imgui: delete demo file
[mesa.git] / src / imgui / imgui.cpp
1 // dear imgui, v1.68 WIP
2 // (main code and documentation)
3
4 // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
5 // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
6 // Get latest version at https://github.com/ocornut/imgui
7 // Releases change-log at https://github.com/ocornut/imgui/releases
8 // Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
9 // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
10
11 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
12 // See LICENSE.txt for copyright and licensing details (standard MIT License).
13 // This library is free but I need your support to sustain development and maintenance.
14 // Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
15 // Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
16
17 // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
18 // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
19 // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
20 // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
21 // to a better solution or official support for them.
22
23 /*
24
25 Index of this file:
26
27 DOCUMENTATION
28
29 - MISSION STATEMENT
30 - END-USER GUIDE
31 - PROGRAMMER GUIDE (read me!)
32 - Read first.
33 - How to update to a newer version of Dear ImGui.
34 - Getting started with integrating Dear ImGui in your code/engine.
35 - This is how a simple application may look like (2 variations).
36 - This is how a simple rendering function may look like.
37 - Using gamepad/keyboard navigation controls.
38 - API BREAKING CHANGES (read me when you update!)
39 - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
40 - How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
41 - How can I display an image? What is ImTextureID, how does it works?
42 - How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack.
43 - How can I use my own math types instead of ImVec2/ImVec4?
44 - How can I load a different font than the default?
45 - How can I easily use icons in my application?
46 - How can I load multiple fonts?
47 - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
48 - How can I interact with standard C++ types (such as std::string and std::vector)?
49 - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
50 - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
51 - I integrated Dear ImGui in my engine and the text or lines are blurry..
52 - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
53 - How can I help?
54
55 CODE
56 (search for "[SECTION]" in the code to find them)
57
58 // [SECTION] FORWARD DECLARATIONS
59 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
60 // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61 // [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
62 // [SECTION] MISC HELPER/UTILITIES (ImText* functions)
63 // [SECTION] MISC HELPER/UTILITIES (Color functions)
64 // [SECTION] ImGuiStorage
65 // [SECTION] ImGuiTextFilter
66 // [SECTION] ImGuiTextBuffer
67 // [SECTION] ImGuiListClipper
68 // [SECTION] RENDER HELPERS
69 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
70 // [SECTION] TOOLTIPS
71 // [SECTION] POPUPS
72 // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
73 // [SECTION] COLUMNS
74 // [SECTION] DRAG AND DROP
75 // [SECTION] LOGGING/CAPTURING
76 // [SECTION] SETTINGS
77 // [SECTION] PLATFORM DEPENDENT HELPERS
78 // [SECTION] METRICS/DEBUG WINDOW
79
80 */
81
82 //-----------------------------------------------------------------------------
83 // DOCUMENTATION
84 //-----------------------------------------------------------------------------
85
86 /*
87
88 MISSION STATEMENT
89 =================
90
91 - Easy to use to create code-driven and data-driven tools.
92 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
93 - Easy to hack and improve.
94 - Minimize screen real-estate usage.
95 - Minimize setup and maintenance.
96 - Minimize state storage on user side.
97 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
98 - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
99 opening a tree node for the first time, etc. but a typical frame should not allocate anything).
100
101 Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
102 - Doesn't look fancy, doesn't animate.
103 - Limited layout features, intricate layouts are typically crafted in code.
104
105
106 END-USER GUIDE
107 ==============
108
109 - Double-click on title bar to collapse window.
110 - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
111 - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
112 - Click and drag on any empty space to move window.
113 - TAB/SHIFT+TAB to cycle through keyboard editable fields.
114 - CTRL+Click on a slider or drag box to input value as text.
115 - Use mouse wheel to scroll.
116 - Text editor:
117 - Hold SHIFT or use mouse to select text.
118 - CTRL+Left/Right to word jump.
119 - CTRL+Shift+Left/Right to select words.
120 - CTRL+A our Double-Click to select all.
121 - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
122 - CTRL+Z,CTRL+Y to undo/redo.
123 - ESCAPE to revert text to its original value.
124 - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
125 - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
126 - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
127 - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
128
129
130 PROGRAMMER GUIDE
131 ================
132
133 READ FIRST:
134
135 - Read the FAQ below this section!
136 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
137 or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
138 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
139 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
140 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
141 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
142 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
143 For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
144 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
145 - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
146 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
147 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
148 If you get an assert, read the messages and comments around the assert.
149 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
150 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
151 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
152 However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
153 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
154
155 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
156
157 - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
158 - Or maintain your own branch where you have imconfig.h modified.
159 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
160 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
161 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
162 likely be a comment about it. Please report any issue to the GitHub page!
163 - Try to keep your copy of dear imgui reasonably up to date.
164
165 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
166
167 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
168 - Add the Dear ImGui source files to your projects or using your preferred build system.
169 It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
170 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
171 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
172 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
173 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
174 phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
175 - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
176 - 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.
177
178 HOW A SIMPLE APPLICATION MAY LOOK LIKE:
179 EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
180
181 // Application init: create a dear imgui context, setup some options, load fonts
182 ImGui::CreateContext();
183 ImGuiIO& io = ImGui::GetIO();
184 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
185 // TODO: Fill optional fields of the io structure later.
186 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
187
188 // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
189 ImGui_ImplWin32_Init(hwnd);
190 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
191
192 // Application main loop
193 while (true)
194 {
195 // Feed inputs to dear imgui, start new frame
196 ImGui_ImplDX11_NewFrame();
197 ImGui_ImplWin32_NewFrame();
198 ImGui::NewFrame();
199
200 // Any application code here
201 ImGui::Text("Hello, world!");
202
203 // Render dear imgui into screen
204 ImGui::Render();
205 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
206 g_pSwapChain->Present(1, 0);
207 }
208
209 // Shutdown
210 ImGui_ImplDX11_Shutdown();
211 ImGui_ImplWin32_Shutdown();
212 ImGui::DestroyContext();
213
214 HOW A SIMPLE APPLICATION MAY LOOK LIKE:
215 EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
216
217 // Application init: create a dear imgui context, setup some options, load fonts
218 ImGui::CreateContext();
219 ImGuiIO& io = ImGui::GetIO();
220 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
221 // TODO: Fill optional fields of the io structure later.
222 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
223
224 // Build and load the texture atlas into a texture
225 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
226 int width, height;
227 unsigned char* pixels = NULL;
228 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
229
230 // At this point you've got the texture data and you need to upload that your your graphic system:
231 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
232 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
233 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
234 io.Fonts->TexID = (void*)texture;
235
236 // Application main loop
237 while (true)
238 {
239 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
240 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
241 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
242 io.DisplaySize.x = 1920.0f; // set the current display width
243 io.DisplaySize.y = 1280.0f; // set the current display height here
244 io.MousePos = my_mouse_pos; // set the mouse position
245 io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
246 io.MouseDown[1] = my_mouse_buttons[1];
247
248 // Call NewFrame(), after this point you can use ImGui::* functions anytime
249 // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
250 ImGui::NewFrame();
251
252 // Most of your application code here
253 ImGui::Text("Hello, world!");
254 MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
255 MyGameRender(); // may use any ImGui functions as well!
256
257 // Render imgui, swap buffers
258 // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
259 ImGui::EndFrame();
260 ImGui::Render();
261 ImDrawData* draw_data = ImGui::GetDrawData();
262 MyImGuiRenderFunction(draw_data);
263 SwapBuffers();
264 }
265
266 // Shutdown
267 ImGui::DestroyContext();
268
269 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
270
271 void void MyImGuiRenderFunction(ImDrawData* draw_data)
272 {
273 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
274 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
275 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
276 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
277 for (int n = 0; n < draw_data->CmdListsCount; n++)
278 {
279 const ImDrawList* cmd_list = draw_data->CmdLists[n];
280 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
281 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
282 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
283 {
284 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
285 if (pcmd->UserCallback)
286 {
287 pcmd->UserCallback(cmd_list, pcmd);
288 }
289 else
290 {
291 // The texture for the draw call is specified by pcmd->TextureId.
292 // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
293 MyEngineBindTexture((MyTexture*)pcmd->TextureId);
294
295 // We are using scissoring to clip some objects. All low-level graphics API should supports it.
296 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
297 // (some elements visible outside their bounds) but you can fix that once everything else works!
298 // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
299 // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
300 // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
301 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
302 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
303 ImVec2 pos = draw_data->DisplayPos;
304 MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
305
306 // Render 'pcmd->ElemCount/3' indexed triangles.
307 // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
308 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
309 }
310 idx_buffer += pcmd->ElemCount;
311 }
312 }
313 }
314
315 - The examples/ folders contains many actual implementation of the pseudo-codes above.
316 - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
317 They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
318 from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
319 - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
320
321 USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
322
323 - The gamepad/keyboard navigation is fairly functional and keeps being improved.
324 - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
325 - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
326 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
327 - Gamepad:
328 - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
329 - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
330 Note that io.NavInputs[] is cleared by EndFrame().
331 - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
332 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
333 - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
334 Your 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.).
335 - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
336 - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
337 to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
338 - Keyboard:
339 - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
340 NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
341 - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
342 will be set. For more advanced uses, you may want to read from:
343 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
344 - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
345 - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
346 Please reach out if you think the game vs navigation input sharing could be improved.
347 - Mouse:
348 - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
349 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
350 - 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.
351 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
352 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.
353 When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
354 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
355 (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
356 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
357
358
359 API BREAKING CHANGES
360 ====================
361
362 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
363 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.
364 When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
365 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
366
367 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
368 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
369 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
370 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete).
371 - 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.
372 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
373 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
374 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
375 - 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.
376 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
377 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
378 - 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.
379 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
380 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
381 - 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).
382 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
383 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
384 - 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.
385 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
386 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
387 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
388 - 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.).
389 old binding will still work as is, however prefer using the separated bindings as they will be updated to be multi-viewport conformant.
390 when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
391 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
392 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
393 - 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.
394 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
395 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.
396 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.
397 - 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",
398 consistent with other functions. Kept redirection functions (will obsolete).
399 - 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.
400 - 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 binding ahead of merging the Nav branch).
401 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
402 - 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.
403 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
404 - 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.
405 - 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.
406 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
407 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
408 - removed Shutdown() function, as DestroyContext() serve this purpose.
409 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
410 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
411 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
412 - 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.
413 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
414 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
415 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
416 - 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.
417 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
418 - 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
419 - 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.
420 - 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.
421 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
422 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
423 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
424 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
425 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
426 - 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.
427 - 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.
428 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.
429 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
430 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
431 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
432 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
433 - 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.
434 - 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.
435 - 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.
436 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
437 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
438 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
439 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete).
440 - 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).
441 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
442 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
443 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
444 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
445 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
446 - 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.
447 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
448 - 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.
449 - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
450 - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
451 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
452 - 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.
453 - 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.
454 - 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))'
455 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
456 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
457 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
458 - 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().
459 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
460 - 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.
461 - 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.
462 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
463 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
464 If your TitleBg/TitleBgActive alpha was <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.
465 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.
466 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
467 {
468 float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
469 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);
470 }
471 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.
472 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
473 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
474 - 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).
475 - 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.
476 - 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).
477 - 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)
478 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
479 - 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.
480 - 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.
481 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
482 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
483 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
484 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.
485 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!
486 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
487 - 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.
488 - 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
489 - 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.
490 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
491 - 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.
492 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
493 - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
494 - the signature of the io.RenderDrawListsFn handler has changed!
495 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
496 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
497 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
498 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
499 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
500 - 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.
501 - 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!
502 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
503 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
504 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
505 - 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.
506 - 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
507 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
508 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
509 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
510 - 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.
511 - 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.
512 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
513 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
514 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
515 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
516 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
517 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
518 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
519 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
520 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
521 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
522 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
523 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
524 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
525 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
526 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
527 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
528 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
529 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
530 font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
531 became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
532 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
533 it is now recommended that you sample the font texture with bilinear interpolation.
534 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
535 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
536 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
537 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
538 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
539 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
540 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
541 - 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)
542 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
543 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
544 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
545 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
546 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
547 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
548
549
550 FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
551 ======================================
552
553 Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
554 A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
555 - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
556 - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
557 - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
558 Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
559 This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
560 Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
561 It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
562 Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
563 perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
564 Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
565 have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
566 were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
567
568 Q: How can I display an image? What is ImTextureID, how does it works?
569 A: Short explanation:
570 - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
571 - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
572 - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
573 Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
574
575 Long explanation:
576 - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
577 At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
578 to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
579 - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
580 We carry the information to identify a "texture" in the ImTextureID type.
581 ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
582 Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
583 - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
584 an image from the end-user perspective. This is what the _examples_ rendering functions are using:
585
586 OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
587 DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
588 DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
589 DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
590
591 For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
592 Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
593 tying together both the texture and information about its format and how to read it.
594 - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
595 the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
596 is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
597 If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
598 representation suggested by the example bindings is probably the best choice.
599 (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
600
601 User code may do:
602
603 // Cast our texture type to ImTextureID / void*
604 MyTexture* texture = g_CoffeeTableTexture;
605 ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
606
607 The renderer function called after ImGui::Render() will receive that same value that the user code passed:
608
609 // Cast ImTextureID / void* stored in the draw command as our texture type
610 MyTexture* texture = (MyTexture*)pcmd->TextureId;
611 MyEngineBindTexture2D(texture);
612
613 Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
614 This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
615 If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
616
617 Here's a simplified OpenGL example using stb_image.h:
618
619 // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
620 #define STB_IMAGE_IMPLEMENTATION
621 #include <stb_image.h>
622 [...]
623 int my_image_width, my_image_height;
624 unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
625
626 // Turn the RGBA pixel data into an OpenGL texture:
627 GLuint my_opengl_texture;
628 glGenTextures(1, &my_opengl_texture);
629 glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
630 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
631 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
632 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
633 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
634
635 // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
636 ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
637
638 C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa.
639 Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*.
640 Examples:
641
642 GLuint my_tex = XXX;
643 void* my_void_ptr;
644 my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
645 my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
646
647 ID3D11ShaderResourceView* my_dx11_srv = XXX;
648 void* my_void_ptr;
649 my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
650 my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
651
652 Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
653
654 Q: How can I have multiple widgets with the same label or with an empty label?
655 Q: I have multiple widgets with the same label, and only the first one works. Why is that?
656 A: A primer on labels and the ID Stack...
657
658 Dear ImGui internally need to uniquely identify UI elements.
659 Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
660 Interactive widgets (such as calls to Button buttons) need a unique ID.
661 Unique ID are used internally to track active widgets and occasionally associate state to widgets.
662 Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
663
664 - Unique ID are often derived from a string label:
665
666 Button("OK"); // Label = "OK", ID = hash of (..., "OK")
667 Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
668
669 - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
670 two buttons labeled "OK" in different windows or different tree locations is fine.
671 We used "..." above to signify whatever was already pushed to the ID stack previously:
672
673 Begin("MyWindow");
674 Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
675 End();
676 Begin("MyOtherWindow");
677 Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
678 End();
679
680 - If you have a same ID twice in the same location, you'll have a conflict:
681
682 Button("OK");
683 Button("OK"); // ID collision! Interacting with either button will trigger the first one.
684
685 Fear not! this is easy to solve and there are many ways to solve it!
686
687 - Solving ID conflict in a simple/local context:
688 When passing a label you can optionally specify extra ID information within string itself.
689 Use "##" to pass a complement to the ID that won't be visible to the end-user.
690 This helps solving the simple collision cases when you know e.g. at compilation time which items
691 are going to be created:
692
693 Begin("MyWindow");
694 Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
695 Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
696 Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
697 End();
698
699 - If you want to completely hide the label, but still need an ID:
700
701 Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
702
703 - Occasionally/rarely you might want change a label while preserving a constant ID. This allows
704 you to animate labels. For example you may want to include varying information in a window title bar,
705 but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
706
707 Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
708 Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
709
710 sprintf(buf, "My game (%f FPS)###MyGame", fps);
711 Begin(buf); // Variable title, ID = hash of "MyGame"
712
713 - Solving ID conflict in a more general manner:
714 Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
715 within the same window. This is the most convenient way of distinguishing ID when iterating and
716 creating many UI elements programmatically.
717 You can push a pointer, a string or an integer value into the ID stack.
718 Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
719 At each level of the stack we store the seed used for items at this level of the ID stack.
720
721 Begin("Window");
722 for (int i = 0; i < 100; i++)
723 {
724 PushID(i); // Push i to the id tack
725 Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
726 PopID();
727 }
728 for (int i = 0; i < 100; i++)
729 {
730 MyObject* obj = Objects[i];
731 PushID(obj);
732 Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
733 PopID();
734 }
735 for (int i = 0; i < 100; i++)
736 {
737 MyObject* obj = Objects[i];
738 PushID(obj->Name);
739 Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
740 PopID();
741 }
742 End();
743
744 - You can stack multiple prefixes into the ID stack:
745
746 Button("Click"); // Label = "Click", ID = hash of (..., "Click")
747 PushID("node");
748 Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
749 PushID(my_ptr);
750 Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
751 PopID();
752 PopID();
753
754 - Tree nodes implicitly creates a scope for you by calling PushID().
755
756 Button("Click"); // Label = "Click", ID = hash of (..., "Click")
757 if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
758 {
759 Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
760 TreePop();
761 }
762
763 - When working with trees, ID are used to preserve the open/close state of each tree node.
764 Depending on your use cases you may want to use strings, indices or pointers as ID.
765 e.g. when following a single pointer that may change over time, using a static string as ID
766 will preserve your node open/closed state when the targeted object change.
767 e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
768 node open/closed state differently. See what makes more sense in your situation!
769
770 Q: How can I use my own math types instead of ImVec2/ImVec4?
771 A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
772 This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2.
773
774 Q: How can I load a different font than the default?
775 A: Use the font atlas to load the TTF/OTF file you want:
776 ImGuiIO& io = ImGui::GetIO();
777 io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
778 io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
779 Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
780 (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
781 (Read the 'misc/fonts/README.txt' file for more details about font loading.)
782
783 New programmers: remember that in C/C++ and most programming languages if you want to use a
784 backslash \ within a string literal, you need to write it double backslash "\\":
785 io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
786 io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
787 io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
788
789 Q: How can I easily use icons in my application?
790 A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
791 main font. Then you can refer to icons within your strings.
792 You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
793 (Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
794
795 Q: How can I load multiple fonts?
796 A: Use the font atlas to pack them into a single texture:
797 (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
798
799 ImGuiIO& io = ImGui::GetIO();
800 ImFont* font0 = io.Fonts->AddFontDefault();
801 ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
802 ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
803 io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
804 // the first loaded font gets used by default
805 // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
806
807 // Options
808 ImFontConfig config;
809 config.OversampleH = 2;
810 config.OversampleV = 1;
811 config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up
812 config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
813 io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
814
815 // Combine multiple fonts into one (e.g. for icon fonts)
816 static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
817 ImFontConfig config;
818 config.MergeMode = true;
819 io.Fonts->AddFontDefault();
820 io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
821 io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
822
823 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
824 A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
825
826 // Add default Japanese ranges
827 io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
828
829 // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
830 ImVector<ImWchar> ranges;
831 ImFontGlyphRangesBuilder builder;
832 builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
833 builder.AddChar(0x7262); // Add a specific character
834 builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
835 builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
836 io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
837
838 All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
839 by using the u8"hello" syntax. Specifying literal in your source code using a local code page
840 (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
841 Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
842
843 Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
844 The applications in examples/ are doing that.
845 Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
846 You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
847 Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
848 the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
849
850 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
851 A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers),
852 and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use
853 any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases.
854 - To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h.
855 - To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API
856 lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API.
857 Prefer using them over the old and awkward Combo()/ListBox() api.
858 - Generally for most high-level types you should be able to access the underlying data type.
859 You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code).
860 - Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass
861 to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application.
862 Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances.
863 Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those
864 are not configurable and not the same across implementations.
865 - If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount
866 of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern
867 is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead.
868 One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str
869 This is a small helper where you can instance strings with configurable local buffers length. Many game engines will
870 provide similar or better string helpers.
871
872 Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
873 A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
874 (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
875 Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
876 - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
877 - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create
878 your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data.
879
880 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
881 A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
882 (short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
883 - You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
884 This is the preferred solution for developer productivity.
885 In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
886 and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
887 to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
888 Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
889 - You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
890 the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
891 - For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
892 for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
893 for screen real-estate and precision.
894
895 Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
896 A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
897 Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
898
899 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
900 A: You are probably mishandling the clipping rectangles in your render function.
901 Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
902
903 Q: How can I help?
904 A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
905 and see how you want to help and can help!
906 - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
907 - Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
908 - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
909 You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers.
910 But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
911 - 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).
912
913 - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
914 this is also useful to set yourself in the context of another window (to get/set other settings)
915 - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
916 - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
917 of a deep nested inner loop in your code.
918 - tip: you can call Render() multiple times (e.g for VR renders).
919 - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
920
921 */
922
923 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
924 #define _CRT_SECURE_NO_WARNINGS
925 #endif
926
927 #include "imgui.h"
928 #ifndef IMGUI_DEFINE_MATH_OPERATORS
929 #define IMGUI_DEFINE_MATH_OPERATORS
930 #endif
931 #include "imgui_internal.h"
932
933 #include <ctype.h> // toupper, isprint
934 #include <stdio.h> // vsnprintf, sscanf, printf
935 #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
936 #include <stddef.h> // intptr_t
937 #else
938 #include <stdint.h> // intptr_t
939 #endif
940
941 // Debug options
942 #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
943 #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
944
945 // Visual Studio warnings
946 #ifdef _MSC_VER
947 #pragma warning (disable: 4127) // condition expression is constant
948 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
949 #endif
950
951 // Clang/GCC warnings with -Weverything
952 #ifdef __clang__
953 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
954 #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
955 #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.
956 #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.
957 #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.
958 #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
959 #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
960 #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.
961 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
962 #if __has_warning("-Wzero-as-null-pointer-constant")
963 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
964 #endif
965 #if __has_warning("-Wdouble-promotion")
966 #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.
967 #endif
968 #elif defined(__GNUC__)
969 #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
970 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
971 #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
972 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
973 #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
974 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
975 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
976 #if __GNUC__ >= 8
977 #pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
978 #endif
979 #endif
980
981 // 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.
982 static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
983 static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
984
985 // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
986 static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
987 static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
988
989 //-------------------------------------------------------------------------
990 // [SECTION] FORWARD DECLARATIONS
991 //-------------------------------------------------------------------------
992
993 static void SetCurrentWindow(ImGuiWindow* window);
994 static void FindHoveredWindow();
995 static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
996 static void CheckStacksSize(ImGuiWindow* window, bool write);
997 static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
998
999 static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
1000 static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1001
1002 static ImRect GetViewportRect();
1003
1004 // Settings
1005 static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1006 static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1007 static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
1008
1009 // Platform Dependents default implementation for IO functions
1010 static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
1011 static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
1012 static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
1013
1014 namespace ImGui
1015 {
1016 static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
1017
1018 // Navigation
1019 static void NavUpdate();
1020 static void NavUpdateWindowing();
1021 static void NavUpdateWindowingList();
1022 static void NavUpdateMoveResult();
1023 static float NavUpdatePageUpPageDown(int allowed_dir_flags);
1024 static inline void NavUpdateAnyRequestFlag();
1025 static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
1026 static ImVec2 NavCalcPreferredRefPos();
1027 static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window);
1028 static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1029
1030 // Misc
1031 static void UpdateMouseInputs();
1032 static void UpdateMouseWheel();
1033 static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
1034 static void RenderOuterBorders(ImGuiWindow* window);
1035
1036 }
1037
1038 //-----------------------------------------------------------------------------
1039 // [SECTION] CONTEXT AND MEMORY ALLOCATORS
1040 //-----------------------------------------------------------------------------
1041
1042 // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1043 // ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
1044 // 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
1045 // SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
1046 // In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
1047 // 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
1048 // If you want thread-safety to allow N threads to access N different contexts, you can:
1049 // - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
1050 // struct ImGuiContext;
1051 // extern thread_local ImGuiContext* MyImGuiTLS;
1052 // #define GImGui MyImGuiTLS
1053 // And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1054 // - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1055 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
1056 #ifndef GImGui
1057 ImGuiContext* GImGui = NULL;
1058 #endif
1059
1060 // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1061 // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
1062 // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1063 #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1064 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
1065 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
1066 #else
1067 static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1068 static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1069 #endif
1070
1071 static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
1072 static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
1073 static void* GImAllocatorUserData = NULL;
1074
1075 //-----------------------------------------------------------------------------
1076 // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1077 //-----------------------------------------------------------------------------
1078
1079 ImGuiStyle::ImGuiStyle()
1080 {
1081 Alpha = 1.0f; // Global alpha applies to everything in ImGui
1082 WindowPadding = ImVec2(8,8); // Padding within a window
1083 WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
1084 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1085 WindowMinSize = ImVec2(32,32); // Minimum window size
1086 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1087 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1088 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1089 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1090 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1091 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1092 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1093 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1094 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1095 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1096 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!
1097 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1098 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
1099 ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1100 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1101 GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
1102 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1103 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1104 TabBorderSize = 0.0f; // Thickness of border around tabs.
1105 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1106 SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
1107 DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
1108 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.
1109 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1110 AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
1111 AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
1112 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.
1113
1114 // Default theme
1115 ImGui::StyleColorsDark(this);
1116 }
1117
1118 // 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.
1119 // 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.
1120 void ImGuiStyle::ScaleAllSizes(float scale_factor)
1121 {
1122 WindowPadding = ImFloor(WindowPadding * scale_factor);
1123 WindowRounding = ImFloor(WindowRounding * scale_factor);
1124 WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1125 ChildRounding = ImFloor(ChildRounding * scale_factor);
1126 PopupRounding = ImFloor(PopupRounding * scale_factor);
1127 FramePadding = ImFloor(FramePadding * scale_factor);
1128 FrameRounding = ImFloor(FrameRounding * scale_factor);
1129 ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1130 ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1131 TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1132 IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1133 ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1134 ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1135 ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1136 GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1137 GrabRounding = ImFloor(GrabRounding * scale_factor);
1138 TabRounding = ImFloor(TabRounding * scale_factor);
1139 DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1140 DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1141 MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1142 }
1143
1144 ImGuiIO::ImGuiIO()
1145 {
1146 // Most fields are initialized with zero
1147 memset(this, 0, sizeof(*this));
1148
1149 // Settings
1150 ConfigFlags = ImGuiConfigFlags_None;
1151 BackendFlags = ImGuiBackendFlags_None;
1152 DisplaySize = ImVec2(-1.0f, -1.0f);
1153 DeltaTime = 1.0f/60.0f;
1154 IniSavingRate = 5.0f;
1155 IniFilename = "imgui.ini";
1156 LogFilename = "imgui_log.txt";
1157 MouseDoubleClickTime = 0.30f;
1158 MouseDoubleClickMaxDist = 6.0f;
1159 for (int i = 0; i < ImGuiKey_COUNT; i++)
1160 KeyMap[i] = -1;
1161 KeyRepeatDelay = 0.250f;
1162 KeyRepeatRate = 0.050f;
1163 UserData = NULL;
1164
1165 Fonts = NULL;
1166 FontGlobalScale = 1.0f;
1167 FontDefault = NULL;
1168 FontAllowUserScaling = false;
1169 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1170
1171 // Miscellaneous options
1172 MouseDrawCursor = false;
1173 #ifdef __APPLE__
1174 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1175 #else
1176 ConfigMacOSXBehaviors = false;
1177 #endif
1178 ConfigInputTextCursorBlink = true;
1179 ConfigWindowsResizeFromEdges = true;
1180 ConfigWindowsMoveFromTitleBarOnly = false;
1181
1182 // Platform Functions
1183 BackendPlatformName = BackendRendererName = NULL;
1184 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1185 GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
1186 SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1187 ClipboardUserData = NULL;
1188 ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
1189 ImeWindowHandle = NULL;
1190
1191 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1192 RenderDrawListsFn = NULL;
1193 #endif
1194
1195 // Input (NB: we already have memset zero the entire structure!)
1196 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1197 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1198 MouseDragThreshold = 6.0f;
1199 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1200 for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
1201 for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
1202 }
1203
1204 // Pass in translated ASCII characters for text input.
1205 // - with glfw you can get those from the callback set in glfwSetCharCallback()
1206 // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1207 void ImGuiIO::AddInputCharacter(ImWchar c)
1208 {
1209 InputQueueCharacters.push_back(c);
1210 }
1211
1212 void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1213 {
1214 while (*utf8_chars != 0)
1215 {
1216 unsigned int c = 0;
1217 utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1218 if (c > 0 && c <= 0xFFFF)
1219 InputQueueCharacters.push_back((ImWchar)c);
1220 }
1221 }
1222
1223 void ImGuiIO::ClearInputCharacters()
1224 {
1225 InputQueueCharacters.resize(0);
1226 }
1227
1228 //-----------------------------------------------------------------------------
1229 // [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
1230 //-----------------------------------------------------------------------------
1231
1232 ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1233 {
1234 ImVec2 ap = p - a;
1235 ImVec2 ab_dir = b - a;
1236 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1237 if (dot < 0.0f)
1238 return a;
1239 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1240 if (dot > ab_len_sqr)
1241 return b;
1242 return a + ab_dir * dot / ab_len_sqr;
1243 }
1244
1245 bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1246 {
1247 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1248 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1249 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1250 return ((b1 == b2) && (b2 == b3));
1251 }
1252
1253 void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1254 {
1255 ImVec2 v0 = b - a;
1256 ImVec2 v1 = c - a;
1257 ImVec2 v2 = p - a;
1258 const float denom = v0.x * v1.y - v1.x * v0.y;
1259 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1260 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1261 out_u = 1.0f - out_v - out_w;
1262 }
1263
1264 ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1265 {
1266 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1267 ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1268 ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1269 float dist2_ab = ImLengthSqr(p - proj_ab);
1270 float dist2_bc = ImLengthSqr(p - proj_bc);
1271 float dist2_ca = ImLengthSqr(p - proj_ca);
1272 float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1273 if (m == dist2_ab)
1274 return proj_ab;
1275 if (m == dist2_bc)
1276 return proj_bc;
1277 return proj_ca;
1278 }
1279
1280 // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1281 int ImStricmp(const char* str1, const char* str2)
1282 {
1283 int d;
1284 while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
1285 return d;
1286 }
1287
1288 int ImStrnicmp(const char* str1, const char* str2, size_t count)
1289 {
1290 int d = 0;
1291 while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1292 return d;
1293 }
1294
1295 void ImStrncpy(char* dst, const char* src, size_t count)
1296 {
1297 if (count < 1)
1298 return;
1299 if (count > 1)
1300 strncpy(dst, src, count - 1);
1301 dst[count - 1] = 0;
1302 }
1303
1304 char* ImStrdup(const char* str)
1305 {
1306 size_t len = strlen(str);
1307 void* buf = ImGui::MemAlloc(len + 1);
1308 return (char*)memcpy(buf, (const void*)str, len + 1);
1309 }
1310
1311 char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1312 {
1313 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1314 size_t src_size = strlen(src) + 1;
1315 if (dst_buf_size < src_size)
1316 {
1317 ImGui::MemFree(dst);
1318 dst = (char*)ImGui::MemAlloc(src_size);
1319 if (p_dst_size)
1320 *p_dst_size = src_size;
1321 }
1322 return (char*)memcpy(dst, (const void*)src, src_size);
1323 }
1324
1325 const char* ImStrchrRange(const char* str, const char* str_end, char c)
1326 {
1327 const char* p = (const char*)memchr(str, (int)c, str_end - str);
1328 return p;
1329 }
1330
1331 int ImStrlenW(const ImWchar* str)
1332 {
1333 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
1334 int n = 0;
1335 while (*str++) n++;
1336 return n;
1337 }
1338
1339 // Find end-of-line. Return pointer will point to either first \n, either str_end.
1340 const char* ImStreolRange(const char* str, const char* str_end)
1341 {
1342 const char* p = (const char*)memchr(str, '\n', str_end - str);
1343 return p ? p : str_end;
1344 }
1345
1346 const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1347 {
1348 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1349 buf_mid_line--;
1350 return buf_mid_line;
1351 }
1352
1353 const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1354 {
1355 if (!needle_end)
1356 needle_end = needle + strlen(needle);
1357
1358 const char un0 = (char)toupper(*needle);
1359 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1360 {
1361 if (toupper(*haystack) == un0)
1362 {
1363 const char* b = needle + 1;
1364 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1365 if (toupper(*a) != toupper(*b))
1366 break;
1367 if (b == needle_end)
1368 return haystack;
1369 }
1370 haystack++;
1371 }
1372 return NULL;
1373 }
1374
1375 // 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.
1376 void ImStrTrimBlanks(char* buf)
1377 {
1378 char* p = buf;
1379 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1380 p++;
1381 char* p_start = p;
1382 while (*p != 0) // Find end of string
1383 p++;
1384 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1385 p--;
1386 if (p_start != buf) // Copy memory if we had leading blanks
1387 memmove(buf, p_start, p - p_start);
1388 buf[p - p_start] = 0; // Zero terminate
1389 }
1390
1391 // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1392 // 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.
1393 // B) When buf==NULL vsnprintf() will return the output size.
1394 #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
1395
1396 //#define IMGUI_USE_STB_SPRINTF
1397 #ifdef IMGUI_USE_STB_SPRINTF
1398 #define STB_SPRINTF_IMPLEMENTATION
1399 #include "imstb_sprintf.h"
1400 #endif
1401
1402 #if defined(_MSC_VER) && !defined(vsnprintf)
1403 #define vsnprintf _vsnprintf
1404 #endif
1405
1406 int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1407 {
1408 va_list args;
1409 va_start(args, fmt);
1410 #ifdef IMGUI_USE_STB_SPRINTF
1411 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1412 #else
1413 int w = vsnprintf(buf, buf_size, fmt, args);
1414 #endif
1415 va_end(args);
1416 if (buf == NULL)
1417 return w;
1418 if (w == -1 || w >= (int)buf_size)
1419 w = (int)buf_size - 1;
1420 buf[w] = 0;
1421 return w;
1422 }
1423
1424 int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1425 {
1426 #ifdef IMGUI_USE_STB_SPRINTF
1427 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1428 #else
1429 int w = vsnprintf(buf, buf_size, fmt, args);
1430 #endif
1431 if (buf == NULL)
1432 return w;
1433 if (w == -1 || w >= (int)buf_size)
1434 w = (int)buf_size - 1;
1435 buf[w] = 0;
1436 return w;
1437 }
1438 #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
1439
1440 // CRC32 needs a 1KB lookup table (not cache friendly)
1441 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1442 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1443 static const ImU32 GCrc32LookupTable[256] =
1444 {
1445 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1446 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1447 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1448 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1449 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1450 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1451 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1452 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1453 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1454 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1455 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1456 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1457 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1458 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1459 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1460 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1461 };
1462
1463 // Known size hash
1464 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1465 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1466 ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
1467 {
1468 ImU32 crc = ~seed;
1469 const unsigned char* data = (const unsigned char*)data_p;
1470 const ImU32* crc32_lut = GCrc32LookupTable;
1471 while (data_size-- != 0)
1472 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1473 return ~crc;
1474 }
1475
1476 // Zero-terminated string hash, with support for ### to reset back to seed value
1477 // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1478 // Because this syntax is rarely used we are optimizing for the common case.
1479 // - If we reach ### in the string we discard the hash so far and reset to the seed.
1480 // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1481 // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1482 ImU32 ImHashStr(const char* data, size_t data_size, ImU32 seed)
1483 {
1484 seed = ~seed;
1485 ImU32 crc = seed;
1486 const unsigned char* src = (const unsigned char*)data;
1487 const ImU32* crc32_lut = GCrc32LookupTable;
1488 if (data_size != 0)
1489 {
1490 while (data_size-- != 0)
1491 {
1492 unsigned char c = *src++;
1493 if (c == '#' && src[0] == '#' && src[1] == '#')
1494 crc = seed;
1495 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1496 }
1497 }
1498 else
1499 {
1500 while (unsigned char c = *src++)
1501 {
1502 if (c == '#' && src[0] == '#' && src[1] == '#')
1503 crc = seed;
1504 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1505 }
1506 }
1507 return ~crc;
1508 }
1509
1510 FILE* ImFileOpen(const char* filename, const char* mode)
1511 {
1512 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
1513 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
1514 const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
1515 const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
1516 ImVector<ImWchar> buf;
1517 buf.resize(filename_wsize + mode_wsize);
1518 ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
1519 ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
1520 return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
1521 #else
1522 return fopen(filename, mode);
1523 #endif
1524 }
1525
1526 // Load file content into memory
1527 // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
1528 void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
1529 {
1530 IM_ASSERT(filename && file_open_mode);
1531 if (out_file_size)
1532 *out_file_size = 0;
1533
1534 FILE* f;
1535 if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
1536 return NULL;
1537
1538 long file_size_signed;
1539 if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
1540 {
1541 fclose(f);
1542 return NULL;
1543 }
1544
1545 size_t file_size = (size_t)file_size_signed;
1546 void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
1547 if (file_data == NULL)
1548 {
1549 fclose(f);
1550 return NULL;
1551 }
1552 if (fread(file_data, 1, file_size, f) != file_size)
1553 {
1554 fclose(f);
1555 ImGui::MemFree(file_data);
1556 return NULL;
1557 }
1558 if (padding_bytes > 0)
1559 memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
1560
1561 fclose(f);
1562 if (out_file_size)
1563 *out_file_size = file_size;
1564
1565 return file_data;
1566 }
1567
1568 //-----------------------------------------------------------------------------
1569 // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
1570 //-----------------------------------------------------------------------------
1571
1572 // Convert UTF-8 to 32-bits character, process single character input.
1573 // Based on stb_from_utf8() from github.com/nothings/stb/
1574 // We handle UTF-8 decoding error by skipping forward.
1575 int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
1576 {
1577 unsigned int c = (unsigned int)-1;
1578 const unsigned char* str = (const unsigned char*)in_text;
1579 if (!(*str & 0x80))
1580 {
1581 c = (unsigned int)(*str++);
1582 *out_char = c;
1583 return 1;
1584 }
1585 if ((*str & 0xe0) == 0xc0)
1586 {
1587 *out_char = 0xFFFD; // will be invalid but not end of string
1588 if (in_text_end && in_text_end - (const char*)str < 2) return 1;
1589 if (*str < 0xc2) return 2;
1590 c = (unsigned int)((*str++ & 0x1f) << 6);
1591 if ((*str & 0xc0) != 0x80) return 2;
1592 c += (*str++ & 0x3f);
1593 *out_char = c;
1594 return 2;
1595 }
1596 if ((*str & 0xf0) == 0xe0)
1597 {
1598 *out_char = 0xFFFD; // will be invalid but not end of string
1599 if (in_text_end && in_text_end - (const char*)str < 3) return 1;
1600 if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
1601 if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
1602 c = (unsigned int)((*str++ & 0x0f) << 12);
1603 if ((*str & 0xc0) != 0x80) return 3;
1604 c += (unsigned int)((*str++ & 0x3f) << 6);
1605 if ((*str & 0xc0) != 0x80) return 3;
1606 c += (*str++ & 0x3f);
1607 *out_char = c;
1608 return 3;
1609 }
1610 if ((*str & 0xf8) == 0xf0)
1611 {
1612 *out_char = 0xFFFD; // will be invalid but not end of string
1613 if (in_text_end && in_text_end - (const char*)str < 4) return 1;
1614 if (*str > 0xf4) return 4;
1615 if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
1616 if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
1617 c = (unsigned int)((*str++ & 0x07) << 18);
1618 if ((*str & 0xc0) != 0x80) return 4;
1619 c += (unsigned int)((*str++ & 0x3f) << 12);
1620 if ((*str & 0xc0) != 0x80) return 4;
1621 c += (unsigned int)((*str++ & 0x3f) << 6);
1622 if ((*str & 0xc0) != 0x80) return 4;
1623 c += (*str++ & 0x3f);
1624 // utf-8 encodings of values used in surrogate pairs are invalid
1625 if ((c & 0xFFFFF800) == 0xD800) return 4;
1626 *out_char = c;
1627 return 4;
1628 }
1629 *out_char = 0;
1630 return 0;
1631 }
1632
1633 int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
1634 {
1635 ImWchar* buf_out = buf;
1636 ImWchar* buf_end = buf + buf_size;
1637 while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
1638 {
1639 unsigned int c;
1640 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
1641 if (c == 0)
1642 break;
1643 if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
1644 *buf_out++ = (ImWchar)c;
1645 }
1646 *buf_out = 0;
1647 if (in_text_remaining)
1648 *in_text_remaining = in_text;
1649 return (int)(buf_out - buf);
1650 }
1651
1652 int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
1653 {
1654 int char_count = 0;
1655 while ((!in_text_end || in_text < in_text_end) && *in_text)
1656 {
1657 unsigned int c;
1658 in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
1659 if (c == 0)
1660 break;
1661 if (c < 0x10000)
1662 char_count++;
1663 }
1664 return char_count;
1665 }
1666
1667 // Based on stb_to_utf8() from github.com/nothings/stb/
1668 static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
1669 {
1670 if (c < 0x80)
1671 {
1672 buf[0] = (char)c;
1673 return 1;
1674 }
1675 if (c < 0x800)
1676 {
1677 if (buf_size < 2) return 0;
1678 buf[0] = (char)(0xc0 + (c >> 6));
1679 buf[1] = (char)(0x80 + (c & 0x3f));
1680 return 2;
1681 }
1682 if (c >= 0xdc00 && c < 0xe000)
1683 {
1684 return 0;
1685 }
1686 if (c >= 0xd800 && c < 0xdc00)
1687 {
1688 if (buf_size < 4) return 0;
1689 buf[0] = (char)(0xf0 + (c >> 18));
1690 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
1691 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
1692 buf[3] = (char)(0x80 + ((c ) & 0x3f));
1693 return 4;
1694 }
1695 //else if (c < 0x10000)
1696 {
1697 if (buf_size < 3) return 0;
1698 buf[0] = (char)(0xe0 + (c >> 12));
1699 buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
1700 buf[2] = (char)(0x80 + ((c ) & 0x3f));
1701 return 3;
1702 }
1703 }
1704
1705 // Not optimal but we very rarely use this function.
1706 int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
1707 {
1708 unsigned int dummy = 0;
1709 return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
1710 }
1711
1712 static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
1713 {
1714 if (c < 0x80) return 1;
1715 if (c < 0x800) return 2;
1716 if (c >= 0xdc00 && c < 0xe000) return 0;
1717 if (c >= 0xd800 && c < 0xdc00) return 4;
1718 return 3;
1719 }
1720
1721 int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
1722 {
1723 char* buf_out = buf;
1724 const char* buf_end = buf + buf_size;
1725 while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
1726 {
1727 unsigned int c = (unsigned int)(*in_text++);
1728 if (c < 0x80)
1729 *buf_out++ = (char)c;
1730 else
1731 buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
1732 }
1733 *buf_out = 0;
1734 return (int)(buf_out - buf);
1735 }
1736
1737 int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
1738 {
1739 int bytes_count = 0;
1740 while ((!in_text_end || in_text < in_text_end) && *in_text)
1741 {
1742 unsigned int c = (unsigned int)(*in_text++);
1743 if (c < 0x80)
1744 bytes_count++;
1745 else
1746 bytes_count += ImTextCountUtf8BytesFromChar(c);
1747 }
1748 return bytes_count;
1749 }
1750
1751 //-----------------------------------------------------------------------------
1752 // [SECTION] MISC HELPER/UTILTIES (Color functions)
1753 // Note: The Convert functions are early design which are not consistent with other API.
1754 //-----------------------------------------------------------------------------
1755
1756 ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
1757 {
1758 float s = 1.0f/255.0f;
1759 return ImVec4(
1760 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
1761 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
1762 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
1763 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
1764 }
1765
1766 ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
1767 {
1768 ImU32 out;
1769 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
1770 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
1771 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
1772 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
1773 return out;
1774 }
1775
1776 // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
1777 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
1778 void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
1779 {
1780 float K = 0.f;
1781 if (g < b)
1782 {
1783 ImSwap(g, b);
1784 K = -1.f;
1785 }
1786 if (r < g)
1787 {
1788 ImSwap(r, g);
1789 K = -2.f / 6.f - K;
1790 }
1791
1792 const float chroma = r - (g < b ? g : b);
1793 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
1794 out_s = chroma / (r + 1e-20f);
1795 out_v = r;
1796 }
1797
1798 // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
1799 // also http://en.wikipedia.org/wiki/HSL_and_HSV
1800 void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
1801 {
1802 if (s == 0.0f)
1803 {
1804 // gray
1805 out_r = out_g = out_b = v;
1806 return;
1807 }
1808
1809 h = ImFmod(h, 1.0f) / (60.0f/360.0f);
1810 int i = (int)h;
1811 float f = h - (float)i;
1812 float p = v * (1.0f - s);
1813 float q = v * (1.0f - s * f);
1814 float t = v * (1.0f - s * (1.0f - f));
1815
1816 switch (i)
1817 {
1818 case 0: out_r = v; out_g = t; out_b = p; break;
1819 case 1: out_r = q; out_g = v; out_b = p; break;
1820 case 2: out_r = p; out_g = v; out_b = t; break;
1821 case 3: out_r = p; out_g = q; out_b = v; break;
1822 case 4: out_r = t; out_g = p; out_b = v; break;
1823 case 5: default: out_r = v; out_g = p; out_b = q; break;
1824 }
1825 }
1826
1827 ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
1828 {
1829 ImGuiStyle& style = GImGui->Style;
1830 ImVec4 c = style.Colors[idx];
1831 c.w *= style.Alpha * alpha_mul;
1832 return ColorConvertFloat4ToU32(c);
1833 }
1834
1835 ImU32 ImGui::GetColorU32(const ImVec4& col)
1836 {
1837 ImGuiStyle& style = GImGui->Style;
1838 ImVec4 c = col;
1839 c.w *= style.Alpha;
1840 return ColorConvertFloat4ToU32(c);
1841 }
1842
1843 const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
1844 {
1845 ImGuiStyle& style = GImGui->Style;
1846 return style.Colors[idx];
1847 }
1848
1849 ImU32 ImGui::GetColorU32(ImU32 col)
1850 {
1851 float style_alpha = GImGui->Style.Alpha;
1852 if (style_alpha >= 1.0f)
1853 return col;
1854 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
1855 a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
1856 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
1857 }
1858
1859 //-----------------------------------------------------------------------------
1860 // [SECTION] ImGuiStorage
1861 // Helper: Key->value storage
1862 //-----------------------------------------------------------------------------
1863
1864 // std::lower_bound but without the bullshit
1865 static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
1866 {
1867 ImGuiStorage::Pair* first = data.Data;
1868 ImGuiStorage::Pair* last = data.Data + data.Size;
1869 size_t count = (size_t)(last - first);
1870 while (count > 0)
1871 {
1872 size_t count2 = count >> 1;
1873 ImGuiStorage::Pair* mid = first + count2;
1874 if (mid->key < key)
1875 {
1876 first = ++mid;
1877 count -= count2 + 1;
1878 }
1879 else
1880 {
1881 count = count2;
1882 }
1883 }
1884 return first;
1885 }
1886
1887 // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
1888 void ImGuiStorage::BuildSortByKey()
1889 {
1890 struct StaticFunc
1891 {
1892 static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
1893 {
1894 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
1895 if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
1896 if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
1897 return 0;
1898 }
1899 };
1900 if (Data.Size > 1)
1901 ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
1902 }
1903
1904 int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
1905 {
1906 ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
1907 if (it == Data.end() || it->key != key)
1908 return default_val;
1909 return it->val_i;
1910 }
1911
1912 bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
1913 {
1914 return GetInt(key, default_val ? 1 : 0) != 0;
1915 }
1916
1917 float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
1918 {
1919 ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
1920 if (it == Data.end() || it->key != key)
1921 return default_val;
1922 return it->val_f;
1923 }
1924
1925 void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
1926 {
1927 ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
1928 if (it == Data.end() || it->key != key)
1929 return NULL;
1930 return it->val_p;
1931 }
1932
1933 // 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.
1934 int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
1935 {
1936 ImGuiStorage::Pair* it = LowerBound(Data, key);
1937 if (it == Data.end() || it->key != key)
1938 it = Data.insert(it, Pair(key, default_val));
1939 return &it->val_i;
1940 }
1941
1942 bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
1943 {
1944 return (bool*)GetIntRef(key, default_val ? 1 : 0);
1945 }
1946
1947 float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
1948 {
1949 ImGuiStorage::Pair* it = LowerBound(Data, key);
1950 if (it == Data.end() || it->key != key)
1951 it = Data.insert(it, Pair(key, default_val));
1952 return &it->val_f;
1953 }
1954
1955 void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
1956 {
1957 ImGuiStorage::Pair* it = LowerBound(Data, key);
1958 if (it == Data.end() || it->key != key)
1959 it = Data.insert(it, Pair(key, default_val));
1960 return &it->val_p;
1961 }
1962
1963 // 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)
1964 void ImGuiStorage::SetInt(ImGuiID key, int val)
1965 {
1966 ImGuiStorage::Pair* it = LowerBound(Data, key);
1967 if (it == Data.end() || it->key != key)
1968 {
1969 Data.insert(it, Pair(key, val));
1970 return;
1971 }
1972 it->val_i = val;
1973 }
1974
1975 void ImGuiStorage::SetBool(ImGuiID key, bool val)
1976 {
1977 SetInt(key, val ? 1 : 0);
1978 }
1979
1980 void ImGuiStorage::SetFloat(ImGuiID key, float val)
1981 {
1982 ImGuiStorage::Pair* it = LowerBound(Data, key);
1983 if (it == Data.end() || it->key != key)
1984 {
1985 Data.insert(it, Pair(key, val));
1986 return;
1987 }
1988 it->val_f = val;
1989 }
1990
1991 void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
1992 {
1993 ImGuiStorage::Pair* it = LowerBound(Data, key);
1994 if (it == Data.end() || it->key != key)
1995 {
1996 Data.insert(it, Pair(key, val));
1997 return;
1998 }
1999 it->val_p = val;
2000 }
2001
2002 void ImGuiStorage::SetAllInt(int v)
2003 {
2004 for (int i = 0; i < Data.Size; i++)
2005 Data[i].val_i = v;
2006 }
2007
2008 //-----------------------------------------------------------------------------
2009 // [SECTION] ImGuiTextFilter
2010 //-----------------------------------------------------------------------------
2011
2012 // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2013 ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
2014 {
2015 if (default_filter)
2016 {
2017 ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2018 Build();
2019 }
2020 else
2021 {
2022 InputBuf[0] = 0;
2023 CountGrep = 0;
2024 }
2025 }
2026
2027 bool ImGuiTextFilter::Draw(const char* label, float width)
2028 {
2029 if (width != 0.0f)
2030 ImGui::PushItemWidth(width);
2031 bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2032 if (width != 0.0f)
2033 ImGui::PopItemWidth();
2034 if (value_changed)
2035 Build();
2036 return value_changed;
2037 }
2038
2039 void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const
2040 {
2041 out->resize(0);
2042 const char* wb = b;
2043 const char* we = wb;
2044 while (we < e)
2045 {
2046 if (*we == separator)
2047 {
2048 out->push_back(TextRange(wb, we));
2049 wb = we + 1;
2050 }
2051 we++;
2052 }
2053 if (wb != we)
2054 out->push_back(TextRange(wb, we));
2055 }
2056
2057 void ImGuiTextFilter::Build()
2058 {
2059 Filters.resize(0);
2060 TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
2061 input_range.split(',', &Filters);
2062
2063 CountGrep = 0;
2064 for (int i = 0; i != Filters.Size; i++)
2065 {
2066 TextRange& f = Filters[i];
2067 while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2068 f.b++;
2069 while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2070 f.e--;
2071 if (f.empty())
2072 continue;
2073 if (Filters[i].b[0] != '-')
2074 CountGrep += 1;
2075 }
2076 }
2077
2078 bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2079 {
2080 if (Filters.empty())
2081 return true;
2082
2083 if (text == NULL)
2084 text = "";
2085
2086 for (int i = 0; i != Filters.Size; i++)
2087 {
2088 const TextRange& f = Filters[i];
2089 if (f.empty())
2090 continue;
2091 if (f.b[0] == '-')
2092 {
2093 // Subtract
2094 if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
2095 return false;
2096 }
2097 else
2098 {
2099 // Grep
2100 if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
2101 return true;
2102 }
2103 }
2104
2105 // Implicit * grep
2106 if (CountGrep == 0)
2107 return true;
2108
2109 return false;
2110 }
2111
2112 //-----------------------------------------------------------------------------
2113 // [SECTION] ImGuiTextBuffer
2114 //-----------------------------------------------------------------------------
2115
2116 // On some platform vsnprintf() takes va_list by reference and modifies it.
2117 // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2118 #ifndef va_copy
2119 #if defined(__GNUC__) || defined(__clang__)
2120 #define va_copy(dest, src) __builtin_va_copy(dest, src)
2121 #else
2122 #define va_copy(dest, src) (dest = src)
2123 #endif
2124 #endif
2125
2126 char ImGuiTextBuffer::EmptyString[1] = { 0 };
2127
2128 void ImGuiTextBuffer::append(const char* str, const char* str_end)
2129 {
2130 int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2131
2132 // Add zero-terminator the first time
2133 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2134 const int needed_sz = write_off + len;
2135 if (write_off + len >= Buf.Capacity)
2136 {
2137 int new_capacity = Buf.Capacity * 2;
2138 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2139 }
2140
2141 Buf.resize(needed_sz);
2142 memcpy(&Buf[write_off - 1], str, (size_t)len);
2143 Buf[write_off - 1 + len] = 0;
2144 }
2145
2146 void ImGuiTextBuffer::appendf(const char* fmt, ...)
2147 {
2148 va_list args;
2149 va_start(args, fmt);
2150 appendfv(fmt, args);
2151 va_end(args);
2152 }
2153
2154 // Helper: Text buffer for logging/accumulating text
2155 void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2156 {
2157 va_list args_copy;
2158 va_copy(args_copy, args);
2159
2160 int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2161 if (len <= 0)
2162 {
2163 va_end(args_copy);
2164 return;
2165 }
2166
2167 // Add zero-terminator the first time
2168 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2169 const int needed_sz = write_off + len;
2170 if (write_off + len >= Buf.Capacity)
2171 {
2172 int new_capacity = Buf.Capacity * 2;
2173 Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2174 }
2175
2176 Buf.resize(needed_sz);
2177 ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2178 va_end(args_copy);
2179 }
2180
2181 //-----------------------------------------------------------------------------
2182 // [SECTION] ImGuiListClipper
2183 // This is currently not as flexible/powerful as it should be, needs some rework (see TODO)
2184 //-----------------------------------------------------------------------------
2185
2186 static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
2187 {
2188 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2189 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2190 // The clipper should probably have a 4th step to display the last item in a regular manner.
2191 ImGui::SetCursorPosY(pos_y);
2192 ImGuiWindow* window = ImGui::GetCurrentWindow();
2193 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.
2194 window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2195 if (window->DC.ColumnsSet)
2196 window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2197 }
2198
2199 // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
2200 // Use case B: Begin() called from constructor with items_height>0
2201 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
2202 void ImGuiListClipper::Begin(int count, float items_height)
2203 {
2204 StartPosY = ImGui::GetCursorPosY();
2205 ItemsHeight = items_height;
2206 ItemsCount = count;
2207 StepNo = 0;
2208 DisplayEnd = DisplayStart = -1;
2209 if (ItemsHeight > 0.0f)
2210 {
2211 ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
2212 if (DisplayStart > 0)
2213 SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
2214 StepNo = 2;
2215 }
2216 }
2217
2218 void ImGuiListClipper::End()
2219 {
2220 if (ItemsCount < 0)
2221 return;
2222 // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
2223 if (ItemsCount < INT_MAX)
2224 SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
2225 ItemsCount = -1;
2226 StepNo = 3;
2227 }
2228
2229 bool ImGuiListClipper::Step()
2230 {
2231 if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
2232 {
2233 ItemsCount = -1;
2234 return false;
2235 }
2236 if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
2237 {
2238 DisplayStart = 0;
2239 DisplayEnd = 1;
2240 StartPosY = ImGui::GetCursorPosY();
2241 StepNo = 1;
2242 return true;
2243 }
2244 if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
2245 {
2246 if (ItemsCount == 1) { ItemsCount = -1; return false; }
2247 float items_height = ImGui::GetCursorPosY() - StartPosY;
2248 IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
2249 Begin(ItemsCount-1, items_height);
2250 DisplayStart++;
2251 DisplayEnd++;
2252 StepNo = 3;
2253 return true;
2254 }
2255 if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
2256 {
2257 IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
2258 StepNo = 3;
2259 return true;
2260 }
2261 if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
2262 End();
2263 return false;
2264 }
2265
2266 //-----------------------------------------------------------------------------
2267 // [SECTION] RENDER HELPERS
2268 // Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
2269 // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
2270 //-----------------------------------------------------------------------------
2271
2272 const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
2273 {
2274 const char* text_display_end = text;
2275 if (!text_end)
2276 text_end = (const char*)-1;
2277
2278 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
2279 text_display_end++;
2280 return text_display_end;
2281 }
2282
2283 // Internal ImGui functions to render text
2284 // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
2285 void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
2286 {
2287 ImGuiContext& g = *GImGui;
2288 ImGuiWindow* window = g.CurrentWindow;
2289
2290 // Hide anything after a '##' string
2291 const char* text_display_end;
2292 if (hide_text_after_hash)
2293 {
2294 text_display_end = FindRenderedTextEnd(text, text_end);
2295 }
2296 else
2297 {
2298 if (!text_end)
2299 text_end = text + strlen(text); // FIXME-OPT
2300 text_display_end = text_end;
2301 }
2302
2303 if (text != text_display_end)
2304 {
2305 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
2306 if (g.LogEnabled)
2307 LogRenderedText(&pos, text, text_display_end);
2308 }
2309 }
2310
2311 void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
2312 {
2313 ImGuiContext& g = *GImGui;
2314 ImGuiWindow* window = g.CurrentWindow;
2315
2316 if (!text_end)
2317 text_end = text + strlen(text); // FIXME-OPT
2318
2319 if (text != text_end)
2320 {
2321 window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
2322 if (g.LogEnabled)
2323 LogRenderedText(&pos, text, text_end);
2324 }
2325 }
2326
2327 // Default clip_rect uses (pos_min,pos_max)
2328 // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
2329 void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
2330 {
2331 // Perform CPU side clipping for single clipped element to avoid using scissor state
2332 ImVec2 pos = pos_min;
2333 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
2334
2335 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
2336 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
2337 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
2338 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
2339 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
2340
2341 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
2342 if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
2343 if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
2344
2345 // Render
2346 if (need_clipping)
2347 {
2348 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
2349 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
2350 }
2351 else
2352 {
2353 draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
2354 }
2355 }
2356
2357 void 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)
2358 {
2359 // Hide anything after a '##' string
2360 const char* text_display_end = FindRenderedTextEnd(text, text_end);
2361 const int text_len = (int)(text_display_end - text);
2362 if (text_len == 0)
2363 return;
2364
2365 ImGuiContext& g = *GImGui;
2366 ImGuiWindow* window = g.CurrentWindow;
2367 RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
2368 if (g.LogEnabled)
2369 LogRenderedText(&pos_min, text, text_display_end);
2370 }
2371
2372 // Render a rectangle shaped with optional rounding and borders
2373 void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
2374 {
2375 ImGuiContext& g = *GImGui;
2376 ImGuiWindow* window = g.CurrentWindow;
2377 window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
2378 const float border_size = g.Style.FrameBorderSize;
2379 if (border && border_size > 0.0f)
2380 {
2381 window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
2382 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
2383 }
2384 }
2385
2386 void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
2387 {
2388 ImGuiContext& g = *GImGui;
2389 ImGuiWindow* window = g.CurrentWindow;
2390 const float border_size = g.Style.FrameBorderSize;
2391 if (border_size > 0.0f)
2392 {
2393 window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
2394 window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
2395 }
2396 }
2397
2398 // Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
2399 void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
2400 {
2401 ImGuiContext& g = *GImGui;
2402
2403 const float h = g.FontSize * 1.00f;
2404 float r = h * 0.40f * scale;
2405 ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
2406
2407 ImVec2 a, b, c;
2408 switch (dir)
2409 {
2410 case ImGuiDir_Up:
2411 case ImGuiDir_Down:
2412 if (dir == ImGuiDir_Up) r = -r;
2413 a = ImVec2(+0.000f,+0.750f) * r;
2414 b = ImVec2(-0.866f,-0.750f) * r;
2415 c = ImVec2(+0.866f,-0.750f) * r;
2416 break;
2417 case ImGuiDir_Left:
2418 case ImGuiDir_Right:
2419 if (dir == ImGuiDir_Left) r = -r;
2420 a = ImVec2(+0.750f,+0.000f) * r;
2421 b = ImVec2(-0.750f,+0.866f) * r;
2422 c = ImVec2(-0.750f,-0.866f) * r;
2423 break;
2424 case ImGuiDir_None:
2425 case ImGuiDir_COUNT:
2426 IM_ASSERT(0);
2427 break;
2428 }
2429
2430 g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
2431 }
2432
2433 void ImGui::RenderBullet(ImVec2 pos)
2434 {
2435 ImGuiContext& g = *GImGui;
2436 ImGuiWindow* window = g.CurrentWindow;
2437 window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
2438 }
2439
2440 void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
2441 {
2442 ImGuiContext& g = *GImGui;
2443 ImGuiWindow* window = g.CurrentWindow;
2444
2445 float thickness = ImMax(sz / 5.0f, 1.0f);
2446 sz -= thickness*0.5f;
2447 pos += ImVec2(thickness*0.25f, thickness*0.25f);
2448
2449 float third = sz / 3.0f;
2450 float bx = pos.x + third;
2451 float by = pos.y + sz - third*0.5f;
2452 window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
2453 window->DrawList->PathLineTo(ImVec2(bx, by));
2454 window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
2455 window->DrawList->PathStroke(col, false, thickness);
2456 }
2457
2458 void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
2459 {
2460 ImGuiContext& g = *GImGui;
2461 if (id != g.NavId)
2462 return;
2463 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
2464 return;
2465 ImGuiWindow* window = g.CurrentWindow;
2466 if (window->DC.NavHideHighlightOneFrame)
2467 return;
2468
2469 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
2470 ImRect display_rect = bb;
2471 display_rect.ClipWith(window->ClipRect);
2472 if (flags & ImGuiNavHighlightFlags_TypeDefault)
2473 {
2474 const float THICKNESS = 2.0f;
2475 const float DISTANCE = 3.0f + THICKNESS * 0.5f;
2476 display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
2477 bool fully_visible = window->ClipRect.Contains(display_rect);
2478 if (!fully_visible)
2479 window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
2480 window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
2481 if (!fully_visible)
2482 window->DrawList->PopClipRect();
2483 }
2484 if (flags & ImGuiNavHighlightFlags_TypeThin)
2485 {
2486 window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
2487 }
2488 }
2489
2490 //-----------------------------------------------------------------------------
2491 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
2492 //-----------------------------------------------------------------------------
2493
2494 // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
2495 ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
2496 : DrawListInst(&context->DrawListSharedData)
2497 {
2498 Name = ImStrdup(name);
2499 ID = ImHashStr(name, 0);
2500 IDStack.push_back(ID);
2501 Flags = ImGuiWindowFlags_None;
2502 Pos = ImVec2(0.0f, 0.0f);
2503 Size = SizeFull = ImVec2(0.0f, 0.0f);
2504 SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
2505 WindowPadding = ImVec2(0.0f, 0.0f);
2506 WindowRounding = 0.0f;
2507 WindowBorderSize = 0.0f;
2508 NameBufLen = (int)strlen(name) + 1;
2509 MoveId = GetID("#MOVE");
2510 ChildId = 0;
2511 Scroll = ImVec2(0.0f, 0.0f);
2512 ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
2513 ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
2514 ScrollbarSizes = ImVec2(0.0f, 0.0f);
2515 ScrollbarX = ScrollbarY = false;
2516 Active = WasActive = false;
2517 WriteAccessed = false;
2518 Collapsed = false;
2519 WantCollapseToggle = false;
2520 SkipItems = false;
2521 Appearing = false;
2522 Hidden = false;
2523 HasCloseButton = false;
2524 ResizeBorderHeld = -1;
2525 BeginCount = 0;
2526 BeginOrderWithinParent = -1;
2527 BeginOrderWithinContext = -1;
2528 PopupId = 0;
2529 AutoFitFramesX = AutoFitFramesY = -1;
2530 AutoFitOnlyGrows = false;
2531 AutoFitChildAxises = 0x00;
2532 AutoPosLastDirection = ImGuiDir_None;
2533 HiddenFramesRegular = HiddenFramesForResize = 0;
2534 SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
2535 SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
2536
2537 LastFrameActive = -1;
2538 ItemWidthDefault = 0.0f;
2539 FontWindowScale = 1.0f;
2540 SettingsIdx = -1;
2541
2542 DrawList = &DrawListInst;
2543 DrawList->_OwnerName = Name;
2544 ParentWindow = NULL;
2545 RootWindow = NULL;
2546 RootWindowForTitleBarHighlight = NULL;
2547 RootWindowForNav = NULL;
2548
2549 NavLastIds[0] = NavLastIds[1] = 0;
2550 NavRectRel[0] = NavRectRel[1] = ImRect();
2551 NavLastChildNavWindow = NULL;
2552
2553 FocusIdxAllCounter = FocusIdxTabCounter = -1;
2554 FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
2555 FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
2556 }
2557
2558 ImGuiWindow::~ImGuiWindow()
2559 {
2560 IM_ASSERT(DrawList == &DrawListInst);
2561 IM_DELETE(Name);
2562 for (int i = 0; i != ColumnsStorage.Size; i++)
2563 ColumnsStorage[i].~ImGuiColumnsSet();
2564 }
2565
2566 ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
2567 {
2568 ImGuiID seed = IDStack.back();
2569 ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
2570 ImGui::KeepAliveID(id);
2571 return id;
2572 }
2573
2574 ImGuiID ImGuiWindow::GetID(const void* ptr)
2575 {
2576 ImGuiID seed = IDStack.back();
2577 ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
2578 ImGui::KeepAliveID(id);
2579 return id;
2580 }
2581
2582 ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
2583 {
2584 ImGuiID seed = IDStack.back();
2585 return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
2586 }
2587
2588 ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
2589 {
2590 ImGuiID seed = IDStack.back();
2591 return ImHashData(&ptr, sizeof(void*), seed);
2592 }
2593
2594 // This is only used in rare/specific situations to manufacture an ID out of nowhere.
2595 ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
2596 {
2597 ImGuiID seed = IDStack.back();
2598 const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
2599 ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
2600 ImGui::KeepAliveID(id);
2601 return id;
2602 }
2603
2604 static void SetCurrentWindow(ImGuiWindow* window)
2605 {
2606 ImGuiContext& g = *GImGui;
2607 g.CurrentWindow = window;
2608 if (window)
2609 g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
2610 }
2611
2612 void ImGui::SetNavID(ImGuiID id, int nav_layer)
2613 {
2614 ImGuiContext& g = *GImGui;
2615 IM_ASSERT(g.NavWindow);
2616 IM_ASSERT(nav_layer == 0 || nav_layer == 1);
2617 g.NavId = id;
2618 g.NavWindow->NavLastIds[nav_layer] = id;
2619 }
2620
2621 void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
2622 {
2623 ImGuiContext& g = *GImGui;
2624 SetNavID(id, nav_layer);
2625 g.NavWindow->NavRectRel[nav_layer] = rect_rel;
2626 g.NavMousePosDirty = true;
2627 g.NavDisableHighlight = false;
2628 g.NavDisableMouseHover = true;
2629 }
2630
2631 void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
2632 {
2633 ImGuiContext& g = *GImGui;
2634 g.ActiveIdIsJustActivated = (g.ActiveId != id);
2635 if (g.ActiveIdIsJustActivated)
2636 {
2637 g.ActiveIdTimer = 0.0f;
2638 g.ActiveIdHasBeenPressed = false;
2639 g.ActiveIdHasBeenEdited = false;
2640 if (id != 0)
2641 {
2642 g.LastActiveId = id;
2643 g.LastActiveIdTimer = 0.0f;
2644 }
2645 }
2646 g.ActiveId = id;
2647 g.ActiveIdAllowNavDirFlags = 0;
2648 g.ActiveIdBlockNavInputFlags = 0;
2649 g.ActiveIdAllowOverlap = false;
2650 g.ActiveIdWindow = window;
2651 if (id)
2652 {
2653 g.ActiveIdIsAlive = id;
2654 g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
2655 }
2656 }
2657
2658 // FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
2659 void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
2660 {
2661 ImGuiContext& g = *GImGui;
2662 IM_ASSERT(id != 0);
2663
2664 // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
2665 const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
2666 if (g.NavWindow != window)
2667 g.NavInitRequest = false;
2668 g.NavId = id;
2669 g.NavWindow = window;
2670 g.NavLayer = nav_layer;
2671 window->NavLastIds[nav_layer] = id;
2672 if (window->DC.LastItemId == id)
2673 window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
2674
2675 if (g.ActiveIdSource == ImGuiInputSource_Nav)
2676 g.NavDisableMouseHover = true;
2677 else
2678 g.NavDisableHighlight = true;
2679 }
2680
2681 void ImGui::ClearActiveID()
2682 {
2683 SetActiveID(0, NULL);
2684 }
2685
2686 void ImGui::SetHoveredID(ImGuiID id)
2687 {
2688 ImGuiContext& g = *GImGui;
2689 g.HoveredId = id;
2690 g.HoveredIdAllowOverlap = false;
2691 if (id != 0 && g.HoveredIdPreviousFrame != id)
2692 g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
2693 }
2694
2695 ImGuiID ImGui::GetHoveredID()
2696 {
2697 ImGuiContext& g = *GImGui;
2698 return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
2699 }
2700
2701 void ImGui::KeepAliveID(ImGuiID id)
2702 {
2703 ImGuiContext& g = *GImGui;
2704 if (g.ActiveId == id)
2705 g.ActiveIdIsAlive = id;
2706 if (g.ActiveIdPreviousFrame == id)
2707 g.ActiveIdPreviousFrameIsAlive = true;
2708 }
2709
2710 void ImGui::MarkItemEdited(ImGuiID id)
2711 {
2712 // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
2713 // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
2714 ImGuiContext& g = *GImGui;
2715 IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
2716 IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
2717 //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
2718 g.ActiveIdHasBeenEdited = true;
2719 g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
2720 }
2721
2722 static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
2723 {
2724 // An active popup disable hovering on other windows (apart from its own children)
2725 // FIXME-OPT: This could be cached/stored within the window.
2726 ImGuiContext& g = *GImGui;
2727 if (g.NavWindow)
2728 if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
2729 if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
2730 {
2731 // For the purpose of those flags we differentiate "standard popup" from "modal popup"
2732 // NB: The order of those two tests is important because Modal windows are also Popups.
2733 if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
2734 return false;
2735 if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
2736 return false;
2737 }
2738
2739 return true;
2740 }
2741
2742 // Advance cursor given item size for layout.
2743 void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
2744 {
2745 ImGuiContext& g = *GImGui;
2746 ImGuiWindow* window = g.CurrentWindow;
2747 if (window->SkipItems)
2748 return;
2749
2750 // Always align ourselves on pixel boundaries
2751 const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y);
2752 const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
2753 //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
2754 window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
2755 window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
2756 window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);
2757 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
2758 window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
2759 //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
2760
2761 window->DC.PrevLineSize.y = line_height;
2762 window->DC.PrevLineTextBaseOffset = text_base_offset;
2763 window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f;
2764
2765 // Horizontal layout mode
2766 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
2767 SameLine();
2768 }
2769
2770 void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
2771 {
2772 ItemSize(bb.GetSize(), text_offset_y);
2773 }
2774
2775 // Declare item bounding box for clipping and interaction.
2776 // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
2777 // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
2778 bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
2779 {
2780 ImGuiContext& g = *GImGui;
2781 ImGuiWindow* window = g.CurrentWindow;
2782
2783 if (id != 0)
2784 {
2785 // Navigation processing runs prior to clipping early-out
2786 // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
2787 // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
2788 // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
2789 // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
2790 window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
2791 if (g.NavId == id || g.NavAnyRequest)
2792 if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
2793 if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
2794 NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
2795 }
2796
2797 window->DC.LastItemId = id;
2798 window->DC.LastItemRect = bb;
2799 window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
2800
2801 #ifdef IMGUI_ENABLE_TEST_ENGINE
2802 if (id != 0)
2803 ImGuiTestEngineHook_ItemAdd(&g, nav_bb_arg ? *nav_bb_arg : bb, id);
2804 #endif
2805
2806 // Clipping test
2807 const bool is_clipped = IsClippedEx(bb, id, false);
2808 if (is_clipped)
2809 return false;
2810 //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
2811
2812 // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
2813 if (IsMouseHoveringRect(bb.Min, bb.Max))
2814 window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
2815 return true;
2816 }
2817
2818 // This is roughly matching the behavior of internal-facing ItemHoverable()
2819 // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
2820 // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
2821 bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
2822 {
2823 ImGuiContext& g = *GImGui;
2824 ImGuiWindow* window = g.CurrentWindow;
2825 if (g.NavDisableMouseHover && !g.NavDisableHighlight)
2826 return IsItemFocused();
2827
2828 // Test for bounding box overlap, as updated as ItemAdd()
2829 if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
2830 return false;
2831 IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
2832
2833 // Test if we are hovering the right window (our window could be behind another window)
2834 // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
2835 // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
2836 //if (g.HoveredWindow != window)
2837 // return false;
2838 if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
2839 return false;
2840
2841 // Test if another item is active (e.g. being dragged)
2842 if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
2843 if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
2844 return false;
2845
2846 // Test if interactions on this window are blocked by an active popup or modal
2847 if (!IsWindowContentHoverable(window, flags))
2848 return false;
2849
2850 // Test if the item is disabled
2851 if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
2852 return false;
2853
2854 // Special handling for the dummy item after Begin() which represent the title bar or tab.
2855 // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
2856 if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
2857 return false;
2858 return true;
2859 }
2860
2861 // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
2862 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
2863 {
2864 ImGuiContext& g = *GImGui;
2865 if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
2866 return false;
2867
2868 ImGuiWindow* window = g.CurrentWindow;
2869 if (g.HoveredWindow != window)
2870 return false;
2871 if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
2872 return false;
2873 if (!IsMouseHoveringRect(bb.Min, bb.Max))
2874 return false;
2875 if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
2876 return false;
2877 if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
2878 return false;
2879
2880 SetHoveredID(id);
2881 return true;
2882 }
2883
2884 bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
2885 {
2886 ImGuiContext& g = *GImGui;
2887 ImGuiWindow* window = g.CurrentWindow;
2888 if (!bb.Overlaps(window->ClipRect))
2889 if (id == 0 || id != g.ActiveId)
2890 if (clip_even_when_logged || !g.LogEnabled)
2891 return true;
2892 return false;
2893 }
2894
2895 bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
2896 {
2897 ImGuiContext& g = *GImGui;
2898
2899 const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
2900 window->FocusIdxAllCounter++;
2901 if (is_tab_stop)
2902 window->FocusIdxTabCounter++;
2903
2904 // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
2905 // Note that we can always TAB out of a widget that doesn't allow tabbing in.
2906 if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
2907 window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
2908
2909 if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
2910 return true;
2911 if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
2912 {
2913 g.NavJustTabbedId = id;
2914 return true;
2915 }
2916
2917 return false;
2918 }
2919
2920 void ImGui::FocusableItemUnregister(ImGuiWindow* window)
2921 {
2922 window->FocusIdxAllCounter--;
2923 window->FocusIdxTabCounter--;
2924 }
2925
2926 ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
2927 {
2928 ImGuiContext& g = *GImGui;
2929 ImVec2 content_max;
2930 if (size.x < 0.0f || size.y < 0.0f)
2931 content_max = g.CurrentWindow->Pos + GetContentRegionMax();
2932 if (size.x <= 0.0f)
2933 size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
2934 if (size.y <= 0.0f)
2935 size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
2936 return size;
2937 }
2938
2939 float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
2940 {
2941 if (wrap_pos_x < 0.0f)
2942 return 0.0f;
2943
2944 ImGuiWindow* window = GetCurrentWindowRead();
2945 if (wrap_pos_x == 0.0f)
2946 wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
2947 else if (wrap_pos_x > 0.0f)
2948 wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
2949
2950 return ImMax(wrap_pos_x - pos.x, 1.0f);
2951 }
2952
2953 void* ImGui::MemAlloc(size_t size)
2954 {
2955 if (ImGuiContext* ctx = GImGui)
2956 ctx->IO.MetricsActiveAllocations++;
2957 return GImAllocatorAllocFunc(size, GImAllocatorUserData);
2958 }
2959
2960 void ImGui::MemFree(void* ptr)
2961 {
2962 if (ptr)
2963 if (ImGuiContext* ctx = GImGui)
2964 ctx->IO.MetricsActiveAllocations--;
2965 return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
2966 }
2967
2968 const char* ImGui::GetClipboardText()
2969 {
2970 return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
2971 }
2972
2973 void ImGui::SetClipboardText(const char* text)
2974 {
2975 if (GImGui->IO.SetClipboardTextFn)
2976 GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
2977 }
2978
2979 const char* ImGui::GetVersion()
2980 {
2981 return IMGUI_VERSION;
2982 }
2983
2984 // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
2985 // 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
2986 ImGuiContext* ImGui::GetCurrentContext()
2987 {
2988 return GImGui;
2989 }
2990
2991 void ImGui::SetCurrentContext(ImGuiContext* ctx)
2992 {
2993 #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
2994 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
2995 #else
2996 GImGui = ctx;
2997 #endif
2998 }
2999
3000 // Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
3001 // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic.
3002 bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert)
3003 {
3004 bool error = false;
3005 if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
3006 if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
3007