| // ImGui library v1.17 wip |
| // See ImGui::ShowTestWindow() for sample code. |
| // Read 'Programmer guide' below for notes on how to setup ImGui in your codebase. |
| // Get latest version at https://github.com/ocornut/imgui |
| // Developed by Omar Cornut and contributors. |
| |
| /* |
| |
| Index |
| - MISSION STATEMENT |
| - END-USER GUIDE |
| - PROGRAMMER GUIDE |
| - API BREAKING CHANGES |
| - TROUBLESHOOTING & FREQUENTLY ASKED QUESTIONS |
| - ISSUES & TODO-LIST |
| - CODE |
| - SAMPLE CODE |
| - FONT DATA |
| |
| |
| MISSION STATEMENT |
| ================= |
| |
| - easy to use to create code-driven and data-driven tools |
| - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools |
| - easy to hack and improve |
| - minimize screen real-estate usage |
| - minimize setup and maintenance |
| - minimize state storage on user side |
| - portable, minimize dependencies, run on target (consoles, etc.) |
| - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) |
| - read about immediate-mode GUI principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html |
| |
| Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: |
| - doesn't look fancy, doesn't animate |
| - limited layout features, intricate layouts are typically crafted in code |
| - occasionally use statically sized buffers for string manipulations - won't crash, but some long text may be clipped |
| |
| END-USER GUIDE |
| ============== |
| |
| - double-click title bar to collapse window |
| - click upper right corner to close a window, available when 'bool* open' is passed to ImGui::Begin() |
| - click and drag on lower right corner to resize window |
| - click and drag on any empty space to move window |
| - double-click/double-tap on lower right corner grip to auto-fit to content |
| - TAB/SHIFT+TAB to cycle through keyboard editable fields |
| - use mouse wheel to scroll |
| - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) |
| - CTRL+Click on a slider to input value as text |
| - text editor: |
| - Hold SHIFT or use mouse to select text. |
| - CTRL+Left/Right to word jump |
| - CTRL+Shift+Left/Right to select words |
| - CTRL+A our Double-Click to select all |
| - CTRL+X,CTRL+C,CTRL+V to use OS clipboard |
| - CTRL+Z,CTRL+Y to undo/redo |
| - ESCAPE to revert text to its original value |
| - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) |
| |
| PROGRAMMER GUIDE |
| ================ |
| |
| - your code creates the UI, if your code doesn't run the UI is gone! == dynamic UI, no construction step, less data retention on your side, no state duplication, less sync, less errors. |
| - see ImGui::ShowTestWindow() for user-side sample code |
| - see examples/ folder for standalone sample applications. |
| |
| - getting started: |
| - initialisation: call ImGui::GetIO() and fill the 'Settings' data. |
| - every frame: |
| 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame(). |
| 2/ use any ImGui function you want between NewFrame() and Render() |
| 3/ ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure. |
| - all rendering information are stored into command-lists until ImGui::Render() is called. |
| - effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations. |
| - refer to the examples applications in the examples/ folder for instruction on how to setup your code. |
| - a typical application skeleton may be: |
| |
| // Application init |
| // TODO: Fill all settings fields of the io structure |
| ImGuiIO& io = ImGui::GetIO(); |
| io.DisplaySize.x = 1920.0f; |
| io.DisplaySize.y = 1280.0f; |
| io.DeltaTime = 1.0f/60.0f; |
| io.IniFilename = "imgui.ini"; |
| |
| // Application main loop |
| while (true) |
| { |
| // 1/ get low-level input |
| // e.g. on Win32, GetKeyboardState(), or poll your events, etc. |
| |
| // 2/ TODO: Fill all 'Input' fields of io structure and call NewFrame |
| ImGuiIO& io = ImGui::GetIO(); |
| io.MousePos = ... |
| io.KeysDown[i] = ... |
| ImGui::NewFrame(); |
| |
| // 3/ most of your application code here - you can use any of ImGui::* functions between NewFrame() and Render() calls |
| GameUpdate(); |
| GameRender(); |
| |
| // 4/ render & swap video buffers |
| ImGui::Render(); |
| // swap video buffer, etc. |
| } |
| |
| API BREAKING CHANGES |
| ==================== |
| |
| Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. |
| Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. |
| |
| - 2014/11/28 (1.17) moved IO.Font*** options to inside the IO.Font-> structure. |
| - 2014/11/26 (1.17) reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility |
| - 2014/11/07 (1.15) renamed IsHovered() to IsItemHovered() |
| - 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) |
| - 2014/09/25 (1.13) removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) |
| - 2014/09/24 (1.12) renamed SetFontScale() to SetWindowFontScale() |
| - 2014/09/24 (1.12) moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn |
| - 2014/08/30 (1.09) removed IO.FontHeight (now computed automatically) |
| - 2014/08/30 (1.09) moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite |
| - 2014/08/28 (1.09) changed the behavior of IO.PixelCenterOffset following various rendering fixes |
| |
| TROUBLESHOOTING & FREQUENTLY ASKED QUESTIONS |
| ============================================ |
| |
| If text or lines are blurry when integrating ImGui in your engine: |
| - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) |
| - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f |
| |
| If you are confused about the meaning or use of ID in ImGui: |
| - some widgets requires state to be carried over multiple frames (most typically ImGui often wants remember what is the "active" widget). |
| to do so they need an unique ID. unique ID are typically derived from a string label, an indice or a pointer. |
| when you call Button("OK") the button shows "OK" and also use "OK" as an ID. |
| - ID are uniquely scoped within Windows so no conflict can happen if you have two buttons called "OK" in two different Windows. |
| within a same Window, use PushID() / PopID() to easily create scopes and avoid ID conflicts. |
| so if you have a loop creating "multiple" items, you can use PushID() / PopID() with the index of each item, or their pointer, etc. |
| some functions like TreeNode() implicitly creates a scope for you by calling PushID() |
| - when dealing with trees, ID are important because you want to preserve the opened/closed state of tree nodes. |
| depending on your use cases you may want to use strings, indices or pointers as ID. experiment and see what makes more sense! |
| e.g. When displaying a single object, using a static string as ID will preserve your node open/closed state when the targeted object change |
| e.g. When displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state per object |
| - when passing a label you can optionally specify extra unique ID information within the same string using "##". This helps solving the simpler collision cases. |
| e.g. "Label" display "Label" and uses "Label" as ID |
| e.g. "Label##Foobar" display "Label" and uses "Label##Foobar" as ID |
| e.g. "##Foobar" display an empty label and uses "##Foobar" as ID |
| - read articles about the imgui principles (see web links) to understand the requirement and use of ID. |
| |
| If you want to use a different font than the default: |
| - read extra_fonts/README.txt for instructions. Examples fonts are also provided. |
| - if you can only see text but no solid shapes or lines, make sure io.Font->TexUvForWhite is set to the texture coordinates of a pure white pixel in your texture! |
| |
| If you want to input Japanese/Chinese/Korean in the text input widget: |
| - make sure you are using a font that can display the glyphs you want (see above paragraph about fonts) |
| - to have the Microsoft IME cursor appears at the right location in the screen, setup a handler for the io.ImeSetInputScreenPosFn function: |
| |
| #include <Windows.h> |
| #include <Imm.h> |
| static void ImImpl_ImeSetInputScreenPosFn(int x, int y) |
| { |
| // Notify OS Input Method Editor of text input position |
| HWND hwnd = glfwGetWin32Window(window); |
| if (HIMC himc = ImmGetContext(hwnd)) |
| { |
| COMPOSITIONFORM cf; |
| cf.ptCurrentPos.x = x; |
| cf.ptCurrentPos.y = y; |
| cf.dwStyle = CFS_FORCE_POSITION; |
| ImmSetCompositionWindow(himc, &cf); |
| } |
| } |
| |
| // Set pointer to handler in ImGuiIO structure |
| io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn; |
| |
| - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will evaluate to a block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. |
| - tip: you can call Render() multiple times (e.g for VR renders), up to you to communicate the extra state to your RenderDrawListFn function. |
| - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" |
| - tip: read the ShowTestWindow() code for more example of how to use ImGui! |
| |
| ISSUES & TODO-LIST |
| ================== |
| |
| - misc: merge or clarify ImVec4 / ImGuiAabb, they are essentially duplicate containers |
| - window: autofit is losing its purpose when user relies on any dynamic layout (window width multiplier, column). maybe just clearly discard autofit? |
| - window: add horizontal scroll |
| - window: fix resize grip rendering scaling along with Rounding style setting |
| - window: better helpers to set pos/size/collapsed with different options (first-run, session only, current value) (github issue #89) |
| - widgets: switching from "widget-label" to "label-widget" would make it more convenient to integrate widgets in trees |
| - widgets: clip text? hover clipped text shows it in a tooltip or in-place overlay |
| - main: make IsHovered() more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes |
| - main: make IsHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? |
| - scrollbar: use relative mouse movement when first-clicking inside of scroll grab box. |
| - scrollbar: make the grab visible and a minimum size for long scroll regions |
| - input number: optional range min/max |
| - input number: holding [-]/[+] buttons should increase the step non-linearly |
| - input number: use mouse wheel to step up/down |
| - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 horrible layout code. item width should include frame padding, then we can have a generic horizontal layout helper. |
| - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) |
| - columns: columns header to act as button (~sort op) and allow resize/reorder |
| - columns: user specify columns size |
| - combo: turn child handling code into pop up helper |
| - list selection, concept of a selectable "block" (that can be multiple widgets) |
| - menubar, menus |
| - plot: make it easier for user to draw into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) |
| - plot: "smooth" automatic scale, user give an input 0.0(full user scale) 1.0(full derived from value) |
| - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) |
| - file selection widget -> build the tool in our codebase to improve model-dialog idioms (may or not lead to ImGui changes) |
| - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() |
| - slider: initial absolute click is imprecise. change to relative movement slider? hide mouse cursor, allow more precise input using less screen-space. |
| - text edit: clean up the horrible mess caused by converting UTF-8 <> wchar |
| - text edit: centered text for slider or input text to it matches typical positioning. |
| - text edit: flag to disable live update of the user buffer. |
| - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text? |
| - text edit: pasting text into a number box should filter the characters the same way direct input does |
| - text edit: add multi-line text edit |
| - settings: write more decent code to allow saving/loading new fields |
| - settings: api for per-tool simple persistent data (bool,int,float) in .ini file |
| - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) |
| - log: be able to right-click and log a window or tree-node into tty/file/clipboard? |
| - filters: set a current filter that tree node can automatically query to hide themselves |
| - filters: handle wildcards (with implicit leading/trailing *), regexps |
| - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) |
| ! keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing |
| - keyboard: full keyboard navigation and focus. |
| - input: rework IO to be able to pass actual events to fix temporal aliasing issues. |
| - input: support track pad style scrolling & slider edit. |
| - tooltip: move to fit within screen (e.g. when mouse cursor is right of the screen). |
| - clipboard: automatically transform \n into \n\r or equivalent for higher compatibility on windows |
| - portability: big-endian test/support (github issue #81) |
| - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL |
| - misc: not thread-safe |
| - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? |
| - misc: CalcTextSize() could benefit from having 'hide_text_after_double_hash' false by default for external use? |
| - style editor: add a button to output C code. |
| - examples: integrate dx11 example. |
| - examples: integrate opengl 3/4 programmable pipeline example. |
| - optimization/render: use indexed rendering |
| - optimization/render: move clip-rect to vertex data? would allow merging all commands |
| - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? |
| - optimization/render: font exported by bmfont is not tight fit on vertical axis, incur unneeded pixel-shading cost. |
| - optimization: turn some the various stack vectors into statically-sized arrays |
| - optimization: better clipping for multi-component widgets |
| - optimization: specialize for height based clipping first (assume widgets never go up + height tests before width tests?) |
| */ |
| |
| #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) |
| #define _CRT_SECURE_NO_WARNINGS |
| #endif |
| |
| #include "imgui.h" |
| #include <ctype.h> // toupper |
| #include <math.h> // sqrtf |
| #include <stdint.h> // intptr_t |
| #include <stdio.h> // vsnprintf |
| #include <string.h> // memset |
| #include <new> // new (ptr) |
| |
| #ifdef _MSC_VER |
| #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen |
| #endif |
| |
| #ifdef __clang__ |
| #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse and not scary looking. |
| #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. |
| #pragma clang diagnostic ignored "-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, thank you. |
| #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. |
| #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. |
| #endif |
| |
| //------------------------------------------------------------------------- |
| // Forward Declarations |
| //------------------------------------------------------------------------- |
| |
| static bool ButtonBehaviour(const ImGuiAabb& bb, const ImGuiID& id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat = false); |
| static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); |
| |
| static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true, float wrap_width = 0.0f); |
| static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); |
| static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale = 1.0f, bool shadow = false); |
| |
| static void ItemSize(ImVec2 size, ImVec2* adjust_start_offset = NULL); |
| static void ItemSize(const ImGuiAabb& aabb, ImVec2* adjust_start_offset = NULL); |
| static void PushColumnClipRect(int column_index = -1); |
| static bool IsClipped(const ImGuiAabb& aabb); |
| static bool ClipAdvance(const ImGuiAabb& aabb); |
| |
| static bool IsMouseHoveringBox(const ImGuiAabb& box); |
| static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); |
| |
| static bool CloseWindowButton(bool* open = NULL); |
| static void FocusWindow(ImGuiWindow* window); |
| static ImGuiWindow* FindWindow(const char* name); |
| static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); |
| |
| //----------------------------------------------------------------------------- |
| // Platform dependent default implementations |
| //----------------------------------------------------------------------------- |
| |
| static const char* GetClipboardTextFn_DefaultImpl(); |
| static void SetClipboardTextFn_DefaultImpl(const char* text); |
| |
| //----------------------------------------------------------------------------- |
| // User facing structures |
| //----------------------------------------------------------------------------- |
| |
| ImGuiStyle::ImGuiStyle() |
| { |
| Alpha = 1.0f; // Global alpha applies to everything in ImGui |
| WindowPadding = ImVec2(8,8); // Padding within a window |
| WindowMinSize = ImVec2(48,48); // Minimum window size |
| FramePadding = ImVec2(5,4); // Padding within a framed rectangle (used by most widgets) |
| ItemSpacing = ImVec2(10,5); // Horizontal and vertical spacing between widgets/lines |
| ItemInnerSpacing = ImVec2(5,5); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) |
| TouchExtraPadding = ImVec2(0,0); // Expand bounding box for touch-based system where touch position is not accurate enough (unnecessary for mouse inputs). Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget running. So dont grow this too much! |
| AutoFitPadding = ImVec2(8,8); // Extra space after auto-fit (double-clicking on resize grip) |
| WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin() |
| WindowRounding = 10.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows |
| TreeNodeSpacing = 22.0f; // Horizontal spacing when entering a tree node |
| ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns |
| ScrollBarWidth = 16.0f; // Width of the vertical scroll bar |
| |
| Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); |
| Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); |
| Colors[ImGuiCol_Border] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); |
| Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); |
| Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input |
| Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); |
| Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); |
| Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); |
| Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); |
| Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); |
| Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); |
| Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); |
| Colors[ImGuiCol_CheckHovered] = ImVec4(0.60f, 0.40f, 0.40f, 0.45f); |
| Colors[ImGuiCol_CheckActive] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); |
| Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); |
| Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); |
| Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); |
| Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); |
| Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); |
| Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); |
| Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); |
| Colors[ImGuiCol_HeaderActive] = ImVec4(0.60f, 0.60f, 0.80f, 1.00f); |
| Colors[ImGuiCol_Column] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); |
| Colors[ImGuiCol_ColumnHovered] = ImVec4(0.60f, 0.40f, 0.40f, 1.00f); |
| Colors[ImGuiCol_ColumnActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); |
| Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); |
| Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); |
| Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); |
| Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); |
| Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); |
| Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); |
| Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); |
| Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); |
| Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); |
| Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); |
| Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); |
| Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); |
| } |
| |
| ImGuiIO::ImGuiIO() |
| { |
| memset(this, 0, sizeof(*this)); |
| DeltaTime = 1.0f/60.0f; |
| IniSavingRate = 5.0f; |
| IniFilename = "imgui.ini"; |
| LogFilename = "imgui_log.txt"; |
| Font = NULL; |
| FontGlobalScale = 1.0f; |
| FontAllowUserScaling = false; |
| PixelCenterOffset = 0.0f; |
| MousePos = ImVec2(-1,-1); |
| MousePosPrev = ImVec2(-1,-1); |
| MouseDoubleClickTime = 0.30f; |
| MouseDoubleClickMaxDist = 6.0f; |
| UserData = NULL; |
| |
| // User functions |
| RenderDrawListsFn = NULL; |
| MemAllocFn = malloc; |
| MemReallocFn = realloc; |
| MemFreeFn = free; |
| GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependant default implementations |
| SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; |
| ImeSetInputScreenPosFn = NULL; |
| } |
| |
| // Pass in translated ASCII characters for text input. |
| // - with glfw you can get those from the callback set in glfwSetCharCallback() |
| // - on Windows you can get those using ToAscii+keyboard state, or via the VM_CHAR message |
| static size_t ImStrlenW(const ImWchar* str); |
| void ImGuiIO::AddInputCharacter(ImWchar c) |
| { |
| const size_t n = ImStrlenW(InputCharacters); |
| if (n + 1 < sizeof(InputCharacters) / sizeof(InputCharacters[0])) |
| { |
| InputCharacters[n] = c; |
| InputCharacters[n+1] = 0; |
| } |
| } |
| |
| //----------------------------------------------------------------------------- |
| // Helpers |
| //----------------------------------------------------------------------------- |
| |
| #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) |
| |
| #undef PI |
| const float PI = 3.14159265358979323846f; |
| |
| #ifdef INT_MAX |
| #define IM_INT_MAX INT_MAX |
| #else |
| #define IM_INT_MAX 2147483647 |
| #endif |
| |
| // Math bits |
| // We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types. |
| static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } |
| //static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } |
| static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } |
| static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } |
| static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } |
| static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } |
| static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } |
| static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } |
| static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } |
| //static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } |
| |
| static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } |
| static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } |
| static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } |
| static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } |
| static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } |
| static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } |
| static inline float ImClamp(float f, float mn, float mx) { return (f < mn) ? mn : (f > mx) ? mx : f; } |
| static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } |
| static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } |
| static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } |
| //static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return a + (b - a) * t; } |
| static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } |
| static inline float ImLength(const ImVec2& lhs) { return sqrtf(lhs.x*lhs.x + lhs.y*lhs.y); } |
| |
| static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int in_char); // return output UTF-8 bytes count |
| static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count |
| static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count |
| static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count |
| static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) |
| static int ImTextCountUtf8BytesFromWchar(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points |
| |
| static int ImStricmp(const char* str1, const char* str2) |
| { |
| int d; |
| while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } |
| return d; |
| } |
| |
| static int ImStrnicmp(const char* str1, const char* str2, int count) |
| { |
| int d = 0; |
| while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } |
| return d; |
| } |
| |
| static char* ImStrdup(const char *str) |
| { |
| char *buff = (char*)ImGui::MemAlloc(strlen(str) + 1); |
| IM_ASSERT(buff); |
| strcpy(buff, str); |
| return buff; |
| } |
| |
| static size_t ImStrlenW(const ImWchar* str) |
| { |
| size_t n = 0; |
| while (*str++) |
| n++; |
| return n; |
| } |
| |
| static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end) |
| { |
| if (!needle_end) |
| needle_end = needle + strlen(needle); |
| |
| const char un0 = (char)toupper(*needle); |
| while (*haystack) |
| { |
| if (toupper(*haystack) == un0) |
| { |
| const char* b = needle + 1; |
| for (const char* a = haystack + 1; b < needle_end; a++, b++) |
| if (toupper(*a) != toupper(*b)) |
| break; |
| if (b == needle_end) |
| return haystack; |
| } |
| haystack++; |
| } |
| return NULL; |
| } |
| |
| static ImU32 crc32(const void* data, size_t data_size, ImU32 seed = 0) |
| { |
| static ImU32 crc32_lut[256] = { 0 }; |
| if (!crc32_lut[1]) |
| { |
| const ImU32 polynomial = 0xEDB88320; |
| for (ImU32 i = 0; i < 256; i++) |
| { |
| ImU32 crc = i; |
| for (ImU32 j = 0; j < 8; j++) |
| crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); |
| crc32_lut[i] = crc; |
| } |
| } |
| ImU32 crc = ~seed; |
| const unsigned char* current = (const unsigned char*)data; |
| while (data_size--) |
| crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; |
| return ~crc; |
| } |
| |
| static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) |
| { |
| va_list args; |
| va_start(args, fmt); |
| int w = vsnprintf(buf, buf_size, fmt, args); |
| va_end(args); |
| buf[buf_size-1] = 0; |
| return (w == -1) ? buf_size : (size_t)w; |
| } |
| |
| static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) |
| { |
| int w = vsnprintf(buf, buf_size, fmt, args); |
| buf[buf_size-1] = 0; |
| return (w == -1) ? buf_size : (size_t)w; |
| } |
| |
| static ImU32 ImConvertColorFloat4ToU32(const ImVec4& in) |
| { |
| ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f)); |
| out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8); |
| out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16); |
| out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24); |
| return out; |
| } |
| |
| // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 |
| // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv |
| static void ImConvertColorRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) |
| { |
| float K = 0.f; |
| if (g < b) |
| { |
| const float tmp = g; g = b; b = tmp; |
| K = -1.f; |
| } |
| if (r < g) |
| { |
| const float tmp = r; r = g; g = tmp; |
| K = -2.f / 6.f - K; |
| } |
| |
| const float chroma = r - (g < b ? g : b); |
| out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); |
| out_s = chroma / (r + 1e-20f); |
| out_v = r; |
| } |
| |
| // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 |
| // also http://en.wikipedia.org/wiki/HSL_and_HSV |
| static void ImConvertColorHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) |
| { |
| if (s == 0.0f) |
| { |
| // gray |
| out_r = out_g = out_b = v; |
| return; |
| } |
| |
| h = fmodf(h, 1.0f) / (60.0f/360.0f); |
| int i = (int)h; |
| float f = h - (float)i; |
| float p = v * (1.0f - s); |
| float q = v * (1.0f - s * f); |
| float t = v * (1.0f - s * (1.0f - f)); |
| |
| switch (i) |
| { |
| case 0: out_r = v; out_g = t; out_b = p; break; |
| case 1: out_r = q; out_g = v; out_b = p; break; |
| case 2: out_r = p; out_g = v; out_b = t; break; |
| case 3: out_r = p; out_g = q; out_b = v; break; |
| case 4: out_r = t; out_g = p; out_b = v; break; |
| case 5: default: out_r = v; out_g = p; out_b = q; break; |
| } |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| struct ImGuiColMod // Color modifier, backup of modified data so we can restore it |
| { |
| ImGuiCol Col; |
| ImVec4 PreviousValue; |
| }; |
| |
| struct ImGuiStyleMod // Style modifier, backup of modified data so we can restore it |
| { |
| ImGuiStyleVar Var; |
| ImVec2 PreviousValue; |
| }; |
| |
| struct ImGuiAabb // 2D axis aligned bounding-box |
| { |
| ImVec2 Min; |
| ImVec2 Max; |
| |
| ImGuiAabb() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); } |
| ImGuiAabb(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; } |
| ImGuiAabb(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; } |
| ImGuiAabb(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; } |
| |
| ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; } |
| ImVec2 GetSize() const { return Max-Min; } |
| float GetWidth() const { return (Max-Min).x; } |
| float GetHeight() const { return (Max-Min).y; } |
| ImVec2 GetTL() const { return Min; } |
| ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); } |
| ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); } |
| ImVec2 GetBR() const { return Max; } |
| bool Contains(ImVec2 p) const { return p.x >= Min.x && p.y >= Min.y && p.x <= Max.x && p.y <= Max.y; } |
| bool Contains(const ImGuiAabb& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } |
| bool Overlaps(const ImGuiAabb& r) const { return r.Min.y <= Max.y && r.Max.y >= Min.y && r.Min.x <= Max.x && r.Max.x >= Min.x; } |
| void Expand(ImVec2 sz) { Min -= sz; Max += sz; } |
| void Clip(const ImGuiAabb& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); } |
| }; |
| |
| // Temporary per-window data, reset at the beginning of the frame |
| struct ImGuiDrawContext |
| { |
| ImVec2 CursorPos; |
| ImVec2 CursorPosPrevLine; |
| ImVec2 CursorStartPos; |
| float CurrentLineHeight; |
| float PrevLineHeight; |
| float LogLineHeight; |
| int TreeDepth; |
| ImGuiAabb LastItemAabb; |
| bool LastItemHovered; |
| bool LastItemFocused; |
| ImVector<ImGuiWindow*> ChildWindows; |
| ImVector<bool> AllowKeyboardFocus; |
| ImVector<float> ItemWidth; |
| ImVector<float> TextWrapPos; |
| ImGuiColorEditMode ColorEditMode; |
| ImGuiStorage* StateStorage; |
| int OpenNextNode; |
| |
| float ColumnsStartX; // Start position from left of window (increased by TreePush/TreePop, etc.) |
| float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. |
| int ColumnsCurrent; |
| int ColumnsCount; |
| ImVec2 ColumnsStartPos; |
| float ColumnsCellMinY; |
| float ColumnsCellMaxY; |
| bool ColumnsShowBorders; |
| ImGuiID ColumnsSetID; |
| |
| ImGuiDrawContext() |
| { |
| CursorPos = CursorPosPrevLine = CursorStartPos = ImVec2(0.0f, 0.0f); |
| CurrentLineHeight = PrevLineHeight = 0.0f; |
| LogLineHeight = -1.0f; |
| TreeDepth = 0; |
| LastItemAabb = ImGuiAabb(0.0f,0.0f,0.0f,0.0f); |
| LastItemHovered = false; |
| LastItemFocused = true; |
| StateStorage = NULL; |
| OpenNextNode = -1; |
| |
| ColumnsStartX = 0.0f; |
| ColumnsOffsetX = 0.0f; |
| ColumnsCurrent = 0; |
| ColumnsCount = 1; |
| ColumnsStartPos = ImVec2(0.0f, 0.0f); |
| ColumnsCellMinY = ColumnsCellMaxY = 0.0f; |
| ColumnsShowBorders = true; |
| ColumnsSetID = 0; |
| } |
| }; |
| |
| struct ImGuiTextEditState; |
| #define STB_TEXTEDIT_STRING ImGuiTextEditState |
| #define STB_TEXTEDIT_CHARTYPE ImWchar |
| #include "stb_textedit.h" |
| |
| // Internal state of the currently focused/edited text input box |
| struct ImGuiTextEditState |
| { |
| ImWchar Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. |
| char InitialText[1024*3+1]; // backup of end-user buffer at the time of focus (in UTF-8, unconverted) |
| size_t BufSize; // end-user buffer size, <= 1024 (or increase above) |
| float Width; // widget width |
| float ScrollX; |
| STB_TexteditState StbState; |
| float CursorAnim; |
| ImVec2 LastCursorPos; // Cursor position in screen space to be used by IME callback. |
| bool SelectedAllMouseLock; |
| ImFont* Font; |
| float FontSize; |
| |
| ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } |
| |
| void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking |
| bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking |
| bool HasSelection() const { return StbState.select_start != StbState.select_end; } |
| void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)ImStrlenW(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } |
| |
| void OnKeyPressed(int key); |
| void UpdateScrollOffset(); |
| ImVec2 CalcDisplayOffsetFromCharIdx(int i) const; |
| |
| // Static functions because they are used to render non-focused instances of a text input box |
| static const char* GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL); |
| static const ImWchar* GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size = NULL); |
| static void RenderTextScrolledClipped(ImFont* font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x); |
| }; |
| |
| struct ImGuiIniData |
| { |
| char* Name; |
| ImVec2 Pos; |
| ImVec2 Size; |
| bool Collapsed; |
| |
| ImGuiIniData() { memset(this, 0, sizeof(*this)); } |
| ~ImGuiIniData() { if (Name) { ImGui::MemFree(Name); Name = NULL; } } |
| }; |
| |
| struct ImGuiState |
| { |
| bool Initialized; |
| ImGuiIO IO; |
| ImGuiStyle Style; |
| float FontSize; // == IO.FontGlobalScale * IO.Font->Scale * IO.Font->Info->FontSize. Vertical distance between two lines of text, aka == CalcTextSize(" ").y |
| ImVec2 FontTexUvForWhite; // == IO.Font->FontTexUvForWhite (cached copy) |
| |
| float Time; |
| int FrameCount; |
| int FrameCountRendered; |
| ImVector<ImGuiWindow*> Windows; |
| ImGuiWindow* CurrentWindow; // Being drawn into |
| ImVector<ImGuiWindow*> CurrentWindowStack; |
| ImGuiWindow* FocusedWindow; // Will catch keyboard inputs |
| ImGuiWindow* HoveredWindow; // Will catch mouse inputs |
| ImGuiWindow* HoveredWindowExcludingChilds; // Will catch mouse inputs (for focus/move only) |
| ImGuiID HoveredId; |
| ImGuiID ActiveId; |
| ImGuiID ActiveIdPreviousFrame; |
| bool ActiveIdIsAlive; |
| float SettingsDirtyTimer; |
| ImVector<ImGuiIniData*> Settings; |
| ImVec2 NewWindowDefaultPos; |
| ImVector<ImGuiColMod> ColorModifiers; |
| ImVector<ImGuiStyleMod> StyleModifiers; |
| |
| // Render |
| ImVector<ImDrawList*> RenderDrawLists; |
| |
| // Widget state |
| ImGuiTextEditState InputTextState; |
| ImGuiID SliderAsInputTextId; |
| ImGuiStorage ColorEditModeStorage; // for user selection |
| ImGuiID ActiveComboID; |
| char Tooltip[1024]; |
| char* PrivateClipboard; // if no custom clipboard handler is defined |
| |
| // Logging |
| bool LogEnabled; |
| FILE* LogFile; |
| ImGuiTextBuffer* LogClipboard; // pointer so our GImGui static constructor doesn't call heap allocators. |
| int LogAutoExpandMaxDepth; |
| |
| ImGuiState() |
| { |
| Initialized = false; |
| Time = 0.0f; |
| FrameCount = 0; |
| FrameCountRendered = -1; |
| CurrentWindow = NULL; |
| FocusedWindow = NULL; |
| HoveredWindow = NULL; |
| HoveredWindowExcludingChilds = NULL; |
| ActiveIdIsAlive = false; |
| SettingsDirtyTimer = 0.0f; |
| NewWindowDefaultPos = ImVec2(60, 60); |
| SliderAsInputTextId = 0; |
| ActiveComboID = 0; |
| memset(Tooltip, 0, sizeof(Tooltip)); |
| PrivateClipboard = NULL; |
| LogEnabled = false; |
| LogFile = NULL; |
| LogAutoExpandMaxDepth = 2; |
| LogClipboard = NULL; |
| } |
| }; |
| |
| static ImGuiState GImGui; |
| |
| struct ImGuiWindow |
| { |
| char* Name; |
| ImGuiID ID; |
| ImGuiWindowFlags Flags; |
| ImVec2 PosFloat; |
| ImVec2 Pos; // Position rounded-up to nearest pixel |
| ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) |
| ImVec2 SizeFull; // Size when non collapsed |
| ImVec2 SizeContentsFit; // Size of contents (extents reach by the drawing cursor) - may not fit within Size. |
| float ScrollY; |
| float NextScrollY; |
| bool ScrollbarY; |
| bool Visible; // Set to true on Begin() |
| bool Accessed; // Set to true when any widget access the current window |
| bool Collapsed; // Set when collapsing window to become only title-bar |
| bool SkipItems; // == Visible && !Collapsed |
| int AutoFitFrames; |
| bool AutoFitOnlyGrows; |
| |
| ImGuiDrawContext DC; |
| ImVector<ImGuiID> IDStack; |
| ImVector<ImVec4> ClipRectStack; |
| int LastFrameDrawn; |
| float ItemWidthDefault; |
| ImGuiStorage StateStorage; |
| float FontWindowScale; // Scale multipler per-window |
| ImDrawList* DrawList; |
| |
| // Focus |
| int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() |
| int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) |
| int FocusIdxAllRequestCurrent; // Item being requested for focus |
| int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus |
| int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) |
| int FocusIdxTabRequestNext; // " |
| |
| public: |
| ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size); |
| ~ImGuiWindow(); |
| |
| ImGuiID GetID(const char* str); |
| ImGuiID GetID(const void* ptr); |
| |
| void AddToRenderList(); |
| bool FocusItemRegister(bool is_active, bool tab_stop = true); // Return true if focus is requested |
| void FocusItemUnregister(); |
| |
| ImGuiAabb Aabb() const { return ImGuiAabb(Pos, Pos+Size); } |
| ImFont* Font() const { return GImGui.IO.Font; } |
| float FontSize() const { return GImGui.FontSize * FontWindowScale; } |
| ImVec2 CursorPos() const { return DC.CursorPos; } |
| float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : FontSize() + GImGui.Style.FramePadding.y * 2.0f; } |
| ImGuiAabb TitleBarAabb() const { return ImGuiAabb(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); } |
| ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders)) ? ImVec2(1,1) : GImGui.Style.WindowPadding; } |
| ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui.Style.Colors[idx]; c.w *= GImGui.Style.Alpha * a; return ImConvertColorFloat4ToU32(c); } |
| ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui.Style.Alpha; return ImConvertColorFloat4ToU32(c); } |
| }; |
| |
| static ImGuiWindow* GetCurrentWindow() |
| { |
| IM_ASSERT(GImGui.CurrentWindow != NULL); // ImGui::NewFrame() hasn't been called yet? |
| GImGui.CurrentWindow->Accessed = true; |
| return GImGui.CurrentWindow; |
| } |
| |
| static void RegisterAliveId(const ImGuiID& id) |
| { |
| if (GImGui.ActiveId == id) |
| GImGui.ActiveIdIsAlive = true; |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| // Helper: Key->value storage |
| void ImGuiStorage::Clear() |
| { |
| Data.clear(); |
| } |
| |
| // std::lower_bound but without the bullshit |
| static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key) |
| { |
| ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); |
| ImVector<ImGuiStorage::Pair>::iterator last = data.end(); |
| int count = (int)(last - first); |
| while (count > 0) |
| { |
| int count2 = count / 2; |
| ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; |
| if (mid->key < key) |
| { |
| first = ++mid; |
| count -= count2 + 1; |
| } |
| else |
| { |
| count = count2; |
| } |
| } |
| return first; |
| } |
| |
| int* ImGuiStorage::Find(ImU32 key) |
| { |
| ImVector<Pair>::iterator it = LowerBound(Data, key); |
| if (it == Data.end()) |
| return NULL; |
| if (it->key != key) |
| return NULL; |
| return &it->val; |
| } |
| |
| int ImGuiStorage::GetInt(ImU32 key, int default_val) |
| { |
| int* pval = Find(key); |
| if (!pval) |
| return default_val; |
| return *pval; |
| } |
| |
| // FIXME-OPT: We are wasting time because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place. |
| // However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed. |
| void ImGuiStorage::SetInt(ImU32 key, int val) |
| { |
| ImVector<Pair>::iterator it = LowerBound(Data, key); |
| if (it != Data.end() && it->key == key) |
| { |
| it->val = val; |
| } |
| else |
| { |
| Pair pair_key; |
| pair_key.key = key; |
| pair_key.val = val; |
| Data.insert(it, pair_key); |
| } |
| } |
| |
| void ImGuiStorage::SetAllInt(int v) |
| { |
| for (size_t i = 0; i < Data.size(); i++) |
| Data[i].val = v; |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" |
| ImGuiTextFilter::ImGuiTextFilter() |
| { |
| InputBuf[0] = 0; |
| CountGrep = 0; |
| } |
| |
| void ImGuiTextFilter::Draw(const char* label, float width) |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| if (width < 0.0f) |
| { |
| ImVec2 label_size = ImGui::CalcTextSize(label, NULL); |
| width = ImMax(window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x - (label_size.x + GImGui.Style.ItemSpacing.x*4), 10.0f); |
| } |
| ImGui::PushItemWidth(width); |
| ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); |
| ImGui::PopItemWidth(); |
| Build(); |
| } |
| |
| void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out) |
| { |
| out.resize(0); |
| const char* wb = b; |
| const char* we = wb; |
| while (we < e) |
| { |
| if (*we == separator) |
| { |
| out.push_back(TextRange(wb, we)); |
| wb = we + 1; |
| } |
| we++; |
| } |
| if (wb != we) |
| out.push_back(TextRange(wb, we)); |
| } |
| |
| void ImGuiTextFilter::Build() |
| { |
| Filters.resize(0); |
| TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); |
| input_range.split(',', Filters); |
| |
| CountGrep = 0; |
| for (size_t i = 0; i != Filters.size(); i++) |
| { |
| Filters[i].trim_blanks(); |
| if (Filters[i].empty()) |
| continue; |
| if (Filters[i].front() != '-') |
| CountGrep += 1; |
| } |
| } |
| |
| bool ImGuiTextFilter::PassFilter(const char* val) const |
| { |
| if (Filters.empty()) |
| return true; |
| |
| if (val == NULL) |
| val = ""; |
| |
| for (size_t i = 0; i != Filters.size(); i++) |
| { |
| const TextRange& f = Filters[i]; |
| if (f.empty()) |
| continue; |
| if (f.front() == '-') |
| { |
| // Subtract |
| if (ImStristr(val, f.begin()+1, f.end()) != NULL) |
| return false; |
| } |
| else |
| { |
| // Grep |
| if (ImStristr(val, f.begin(), f.end()) != NULL) |
| return true; |
| } |
| } |
| |
| // Implicit * grep |
| if (CountGrep == 0) |
| return true; |
| |
| return false; |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| // Helper: Text buffer for logging/accumulating text |
| void ImGuiTextBuffer::append(const char* fmt, ...) |
| { |
| va_list args; |
| va_start(args, fmt); |
| int len = vsnprintf(NULL, 0, fmt, args); |
| va_end(args); |
| if (len <= 0) |
| return; |
| |
| const size_t write_off = Buf.size(); |
| if (write_off + (size_t)len >= Buf.capacity()) |
| Buf.reserve(Buf.capacity() * 2); |
| |
| Buf.resize(write_off + (size_t)len); |
| |
| va_start(args, fmt); |
| ImFormatStringV(&Buf[write_off] - 1, (size_t)len+1, fmt, args); |
| va_end(args); |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| ImGuiWindow::ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size) |
| { |
| Name = ImStrdup(name); |
| ID = GetID(name); |
| IDStack.push_back(ID); |
| |
| PosFloat = default_pos; |
| Pos = ImVec2((float)(int)PosFloat.x, (float)(int)PosFloat.y); |
| Size = SizeFull = default_size; |
| SizeContentsFit = ImVec2(0.0f, 0.0f); |
| ScrollY = 0.0f; |
| NextScrollY = 0.0f; |
| ScrollbarY = false; |
| Visible = false; |
| Accessed = false; |
| Collapsed = false; |
| SkipItems = false; |
| AutoFitFrames = -1; |
| AutoFitOnlyGrows = false; |
| LastFrameDrawn = -1; |
| ItemWidthDefault = 0.0f; |
| FontWindowScale = 1.0f; |
| |
| if (ImLength(Size) < 0.001f) |
| { |
| AutoFitFrames = 2; |
| AutoFitOnlyGrows = true; |
| } |
| |
| DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); |
| new(DrawList) ImDrawList(); |
| |
| FocusIdxAllCounter = FocusIdxTabCounter = -1; |
| FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX; |
| FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX; |
| } |
| |
| ImGuiWindow::~ImGuiWindow() |
| { |
| DrawList->~ImDrawList(); |
| ImGui::MemFree(DrawList); |
| DrawList = NULL; |
| ImGui::MemFree(Name); |
| Name = NULL; |
| } |
| |
| ImGuiID ImGuiWindow::GetID(const char* str) |
| { |
| const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back(); |
| const ImGuiID id = crc32(str, strlen(str), seed); // FIXME-OPT: crc32 function/variant should handle zero-terminated strings |
| RegisterAliveId(id); |
| return id; |
| } |
| |
| ImGuiID ImGuiWindow::GetID(const void* ptr) |
| { |
| const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back(); |
| const ImGuiID id = crc32(&ptr, sizeof(void*), seed); |
| RegisterAliveId(id); |
| return id; |
| } |
| |
| bool ImGuiWindow::FocusItemRegister(bool is_active, bool tab_stop) |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus.back(); |
| FocusIdxAllCounter++; |
| if (allow_keyboard_focus) |
| FocusIdxTabCounter++; |
| |
| if (is_active) |
| window->DC.LastItemFocused = true; |
| |
| // Process keyboard input at this point: TAB, Shift-TAB switch focus |
| // We can always TAB out of a widget that doesn't allow tabbing in. |
| if (tab_stop && FocusIdxAllRequestNext == IM_INT_MAX && FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) |
| { |
| // Modulo on index will be applied at the end of frame once we've got the total counter of items. |
| FocusIdxTabRequestNext = FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); |
| } |
| |
| if (FocusIdxAllCounter == FocusIdxAllRequestCurrent) |
| return true; |
| |
| if (allow_keyboard_focus) |
| if (FocusIdxTabCounter == FocusIdxTabRequestCurrent) |
| return true; |
| |
| return false; |
| } |
| |
| void ImGuiWindow::FocusItemUnregister() |
| { |
| FocusIdxAllCounter--; |
| FocusIdxTabCounter--; |
| } |
| |
| void ImGuiWindow::AddToRenderList() |
| { |
| ImGuiState& g = GImGui; |
| |
| if (!DrawList->commands.empty() && !DrawList->vtx_buffer.empty()) |
| { |
| if (DrawList->commands.back().vtx_count == 0) |
| DrawList->commands.pop_back(); |
| g.RenderDrawLists.push_back(DrawList); |
| } |
| for (size_t i = 0; i < DC.ChildWindows.size(); i++) |
| { |
| ImGuiWindow* child = DC.ChildWindows[i]; |
| if (child->Visible) // clipped childs may have been marked not Visible |
| child->AddToRenderList(); |
| } |
| } |
| |
| //----------------------------------------------------------------------------- |
| |
| void* ImGui::MemAlloc(size_t sz) |
| { |
| return GImGui.IO.MemAllocFn(sz); |
| } |
| |
| void ImGui::MemFree(void* ptr) |
| { |
| return GImGui.IO.MemFreeFn(ptr); |
| } |
| |
| void* ImGui::MemRealloc(void* ptr, size_t sz) |
| { |
| return GImGui.IO.MemReallocFn(ptr, sz); |
| } |
| |
| static ImGuiIniData* FindWindowSettings(const char* name) |
| { |
| ImGuiState& g = GImGui; |
| |
| for (size_t i = 0; i != g.Settings.size(); i++) |
| { |
| ImGuiIniData* ini = g.Settings[i]; |
| if (ImStricmp(ini->Name, name) == 0) |
| return ini; |
| } |
| ImGuiIniData* ini = (ImGuiIniData*)ImGui::MemAlloc(sizeof(ImGuiIniData)); |
| new(ini) ImGuiIniData(); |
| ini->Name = ImStrdup(name); |
| ini->Collapsed = false; |
| ini->Pos = ImVec2(FLT_MAX,FLT_MAX); |
| ini->Size = ImVec2(0,0); |
| g.Settings.push_back(ini); |
| return ini; |
| } |
| |
| // Zero-tolerance, poor-man .ini parsing |
| // FIXME: Write something less rubbish |
| static void LoadSettings() |
| { |
| ImGuiState& g = GImGui; |
| const char* filename = g.IO.IniFilename; |
| if (!filename) |
| return; |
| |
| // Load file |
| FILE* f; |
| if ((f = fopen(filename, "rt")) == NULL) |
| return; |
| if (fseek(f, 0, SEEK_END)) |
| { |
| fclose(f); |
| return; |
| } |
| const long f_size_signed = ftell(f); |
| if (f_size_signed == -1) |
| { |
| fclose(f); |
| return; |
| } |
| size_t f_size = (size_t)f_size_signed; |
| if (fseek(f, 0, SEEK_SET)) |
| { |
| fclose(f); |
| return; |
| } |
| char* f_data = (char*)ImGui::MemAlloc(f_size+1); |
| f_size = fread(f_data, 1, f_size, f); // Text conversion alter read size so let's not be fussy about return value |
| fclose(f); |
| if (f_size == 0) |
| { |
| ImGui::MemFree(f_data); |
| return; |
| } |
| f_data[f_size] = 0; |
| |
| ImGuiIniData* settings = NULL; |
| const char* buf_end = f_data + f_size; |
| for (const char* line_start = f_data; line_start < buf_end; ) |
| { |
| const char* line_end = line_start; |
| while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') |
| line_end++; |
| |
| if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') |
| { |
| char name[64]; |
| ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); |
| settings = FindWindowSettings(name); |
| } |
| else if (settings) |
| { |
| float x, y; |
| int i; |
| if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) |
| settings->Pos = ImVec2(x, y); |
| else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) |
| settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); |
| else if (sscanf(line_start, "Collapsed=%d", &i) == 1) |
| settings->Collapsed = (i != 0); |
| } |
| |
| line_start = line_end+1; |
| } |
| |
| ImGui::MemFree(f_data); |
| } |
| |
| static void SaveSettings() |
| { |
| ImGuiState& g = GImGui; |
| const char* filename = g.IO.IniFilename; |
| if (!filename) |
| return; |
| |
| // Gather data from windows that were active during this session |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| { |
| ImGuiWindow* window = g.Windows[i]; |
| if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) |
| continue; |
| ImGuiIniData* settings = FindWindowSettings(window->Name); |
| settings->Pos = window->Pos; |
| settings->Size = window->SizeFull; |
| settings->Collapsed = window->Collapsed; |
| } |
| |
| // Write .ini file |
| // If a window wasn't opened in this session we preserve its settings |
| FILE* f = fopen(filename, "wt"); |
| if (!f) |
| return; |
| for (size_t i = 0; i != g.Settings.size(); i++) |
| { |
| const ImGuiIniData* settings = g.Settings[i]; |
| if (settings->Pos.x == FLT_MAX) |
| continue; |
| fprintf(f, "[%s]\n", settings->Name); |
| fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); |
| fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); |
| fprintf(f, "Collapsed=%d\n", settings->Collapsed); |
| fprintf(f, "\n"); |
| } |
| |
| fclose(f); |
| } |
| |
| static void MarkSettingsDirty() |
| { |
| ImGuiState& g = GImGui; |
| |
| if (g.SettingsDirtyTimer <= 0.0f) |
| g.SettingsDirtyTimer = g.IO.IniSavingRate; |
| } |
| |
| ImGuiIO& ImGui::GetIO() |
| { |
| return GImGui.IO; |
| } |
| |
| ImGuiStyle& ImGui::GetStyle() |
| { |
| return GImGui.Style; |
| } |
| |
| void ImGui::NewFrame() |
| { |
| ImGuiState& g = GImGui; |
| |
| // Check user inputs |
| IM_ASSERT(g.IO.DeltaTime > 0.0f); |
| IM_ASSERT(g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f); |
| IM_ASSERT(g.IO.RenderDrawListsFn != NULL); // Must be implemented |
| |
| if (!g.Initialized) |
| { |
| // Initialize on first frame |
| g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); |
| new(g.LogClipboard) ImGuiTextBuffer(); |
| |
| IM_ASSERT(g.Settings.empty()); |
| LoadSettings(); |
| if (!g.IO.Font) |
| { |
| // Default font |
| const void* fnt_data; |
| unsigned int fnt_size; |
| ImGui::GetDefaultFontData(&fnt_data, &fnt_size, NULL, NULL); |
| g.IO.Font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); |
| new(g.IO.Font) ImFont(); |
| g.IO.Font->LoadFromMemory(fnt_data, fnt_size); |
| IM_ASSERT(g.IO.Font->IsLoaded()); // Font failed to load |
| g.IO.Font->DisplayOffset = ImVec2(0.0f, +1.0f); |
| } |
| g.Initialized = true; |
| } |
| |
| IM_ASSERT(g.IO.Font && g.IO.Font->IsLoaded()); // Font not loaded |
| IM_ASSERT(g.IO.Font->Scale > 0.0f); |
| g.FontSize = g.IO.FontGlobalScale * (float)g.IO.Font->Info->FontSize * g.IO.Font->Scale; |
| g.FontTexUvForWhite = g.IO.Font->TexUvForWhite; |
| g.IO.Font->FallbackGlyph = g.IO.Font->FindGlyph(g.IO.Font->FallbackChar); |
| |
| g.Time += g.IO.DeltaTime; |
| g.FrameCount += 1; |
| g.Tooltip[0] = '\0'; |
| |
| // Update inputs state |
| if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) |
| g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); |
| if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta |
| g.IO.MouseDelta = ImVec2(0.0f, 0.0f); |
| else |
| g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; |
| g.IO.MousePosPrev = g.IO.MousePos; |
| for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) |
| { |
| g.IO.MouseDownTime[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownTime[i] < 0.0f ? 0.0f : g.IO.MouseDownTime[i] + g.IO.DeltaTime) : -1.0f; |
| g.IO.MouseClicked[i] = (g.IO.MouseDownTime[i] == 0.0f); |
| g.IO.MouseDoubleClicked[i] = false; |
| if (g.IO.MouseClicked[i]) |
| { |
| if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) |
| { |
| if (ImLength(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist) |
| g.IO.MouseDoubleClicked[i] = true; |
| g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click |
| } |
| else |
| { |
| g.IO.MouseClickedTime[i] = g.Time; |
| g.IO.MouseClickedPos[i] = g.IO.MousePos; |
| } |
| } |
| } |
| for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) |
| g.IO.KeysDownTime[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownTime[i] < 0.0f ? 0.0f : g.IO.KeysDownTime[i] + g.IO.DeltaTime) : -1.0f; |
| |
| // Clear reference to active widget if the widget isn't alive anymore |
| g.HoveredId = 0; |
| if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) |
| g.ActiveId = 0; |
| g.ActiveIdPreviousFrame = g.ActiveId; |
| g.ActiveIdIsAlive = false; |
| |
| // Delay saving settings so we don't spam disk too much |
| if (g.SettingsDirtyTimer > 0.0f) |
| { |
| g.SettingsDirtyTimer -= g.IO.DeltaTime; |
| if (g.SettingsDirtyTimer <= 0.0f) |
| SaveSettings(); |
| } |
| |
| g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false); |
| g.HoveredWindowExcludingChilds = FindHoveredWindow(g.IO.MousePos, true); |
| |
| // Are we using inputs? Tell user so they can capture/discard them. |
| g.IO.WantCaptureMouse = (g.HoveredWindow != NULL) || (g.ActiveId != 0); |
| g.IO.WantCaptureKeyboard = (g.ActiveId != 0); |
| |
| // Scale & Scrolling |
| if (g.HoveredWindow && g.IO.MouseWheel != 0.0f) |
| { |
| ImGuiWindow* window = g.HoveredWindow; |
| if (g.IO.KeyCtrl) |
| { |
| if (g.IO.FontAllowUserScaling) |
| { |
| // Zoom / Scale window |
| float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); |
| float scale = new_font_scale / window->FontWindowScale; |
| window->FontWindowScale = new_font_scale; |
| |
| const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; |
| window->Pos += offset; |
| window->PosFloat += offset; |
| window->Size *= scale; |
| window->SizeFull *= scale; |
| } |
| } |
| else |
| { |
| // Scroll |
| const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; |
| window->NextScrollY -= g.IO.MouseWheel * window->FontSize() * scroll_lines; |
| } |
| } |
| |
| // Pressing TAB activate widget focus |
| // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. |
| if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Visible && IsKeyPressedMap(ImGuiKey_Tab, false)) |
| { |
| g.FocusedWindow->FocusIdxTabRequestNext = 0; |
| } |
| |
| // Mark all windows as not visible |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| { |
| ImGuiWindow* window = g.Windows[i]; |
| window->Visible = false; |
| window->Accessed = false; |
| } |
| |
| // No window should be open at the beginning of the frame. |
| // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. |
| g.CurrentWindowStack.clear(); |
| |
| // Create implicit window - we will only render it if the user has added something to it. |
| ImGui::Begin("Debug", NULL, ImVec2(400,400)); |
| } |
| |
| // NB: behaviour of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. |
| void ImGui::Shutdown() |
| { |
| ImGuiState& g = GImGui; |
| if (!g.Initialized) |
| return; |
| |
| SaveSettings(); |
| |
| for (size_t i = 0; i < g.Windows.size(); i++) |
| { |
| g.Windows[i]->~ImGuiWindow(); |
| ImGui::MemFree(g.Windows[i]); |
| } |
| g.Windows.clear(); |
| g.CurrentWindowStack.clear(); |
| g.RenderDrawLists.clear(); |
| g.FocusedWindow = NULL; |
| g.HoveredWindow = NULL; |
| g.HoveredWindowExcludingChilds = NULL; |
| for (size_t i = 0; i < g.Settings.size(); i++) |
| { |
| g.Settings[i]->~ImGuiIniData(); |
| ImGui::MemFree(g.Settings[i]); |
| } |
| g.Settings.clear(); |
| g.ColorEditModeStorage.Clear(); |
| if (g.LogFile && g.LogFile != stdout) |
| { |
| fclose(g.LogFile); |
| g.LogFile = NULL; |
| } |
| if (g.IO.Font) |
| { |
| g.IO.Font->~ImFont(); |
| ImGui::MemFree(g.IO.Font); |
| g.IO.Font = NULL; |
| } |
| |
| if (g.PrivateClipboard) |
| { |
| ImGui::MemFree(g.PrivateClipboard); |
| g.PrivateClipboard = NULL; |
| } |
| |
| if (g.LogClipboard) |
| { |
| g.LogClipboard->~ImGuiTextBuffer(); |
| ImGui::MemFree(g.LogClipboard); |
| } |
| |
| g.Initialized = false; |
| } |
| |
| static void AddWindowToSortedBuffer(ImGuiWindow* window, ImVector<ImGuiWindow*>& sorted_windows) |
| { |
| sorted_windows.push_back(window); |
| if (window->Visible) |
| { |
| for (size_t i = 0; i < window->DC.ChildWindows.size(); i++) |
| { |
| ImGuiWindow* child = window->DC.ChildWindows[i]; |
| if (child->Visible) |
| AddWindowToSortedBuffer(child, sorted_windows); |
| } |
| } |
| } |
| |
| static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| ImVec4 cr = clip_rect; |
| if (clipped && !window->ClipRectStack.empty()) |
| { |
| // Clip to new clip rect |
| const ImVec4 cur_cr = window->ClipRectStack.back(); |
| cr = ImVec4(ImMax(cr.x, cur_cr.x), ImMax(cr.y, cur_cr.y), ImMin(cr.z, cur_cr.z), ImMin(cr.w, cur_cr.w)); |
| } |
| |
| window->ClipRectStack.push_back(cr); |
| window->DrawList->PushClipRect(cr); |
| } |
| |
| static void PopClipRect() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| window->ClipRectStack.pop_back(); |
| window->DrawList->PopClipRect(); |
| } |
| |
| void ImGui::Render() |
| { |
| ImGuiState& g = GImGui; |
| IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() |
| |
| const bool first_render_of_the_frame = (g.FrameCountRendered != g.FrameCount); |
| g.FrameCountRendered = g.FrameCount; |
| |
| if (first_render_of_the_frame) |
| { |
| // Hide implicit window if it hasn't been used |
| IM_ASSERT(g.CurrentWindowStack.size() == 1); // Mismatched Begin/End |
| if (g.CurrentWindow && !g.CurrentWindow->Accessed) |
| g.CurrentWindow->Visible = false; |
| ImGui::End(); |
| |
| // Sort the window list so that all child windows are after their parent |
| // We cannot do that on FocusWindow() because childs may not exist yet |
| ImVector<ImGuiWindow*> sorted_windows; |
| sorted_windows.reserve(g.Windows.size()); |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| { |
| ImGuiWindow* window = g.Windows[i]; |
| if (window->Flags & ImGuiWindowFlags_ChildWindow) // if a child is visible its parent will add it |
| if (window->Visible) |
| continue; |
| AddWindowToSortedBuffer(window, sorted_windows); |
| } |
| IM_ASSERT(g.Windows.size() == sorted_windows.size()); // We done something wrong |
| g.Windows.swap(sorted_windows); |
| |
| // Clear data for next frame |
| g.IO.MouseWheel = 0.0f; |
| memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); |
| } |
| |
| // Skip render altogether if alpha is 0.0 |
| // Note that vertex buffers have been created, so it is best practice that you don't call Begin/End in the first place. |
| if (g.Style.Alpha > 0.0f) |
| { |
| // Render tooltip |
| if (g.Tooltip[0]) |
| { |
| // Use a dummy window to render the tooltip |
| ImGui::BeginTooltip(); |
| ImGui::TextUnformatted(g.Tooltip); |
| ImGui::EndTooltip(); |
| } |
| |
| // Gather windows to render |
| g.RenderDrawLists.resize(0); |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| { |
| ImGuiWindow* window = g.Windows[i]; |
| if (window->Visible && (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) |
| window->AddToRenderList(); |
| } |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| { |
| ImGuiWindow* window = g.Windows[i]; |
| if (window->Visible && (window->Flags & ImGuiWindowFlags_Tooltip)) |
| window->AddToRenderList(); |
| } |
| |
| // Render |
| if (!g.RenderDrawLists.empty()) |
| g.IO.RenderDrawListsFn(&g.RenderDrawLists[0], (int)g.RenderDrawLists.size()); |
| g.RenderDrawLists.resize(0); |
| } |
| } |
| |
| // Find the optional ## from which we stop displaying text. |
| static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL) |
| { |
| const char* text_display_end = text; |
| while ((!text_end || text_display_end < text_end) && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) |
| text_display_end++; |
| return text_display_end; |
| } |
| |
| // Log ImGui display into text output (tty or file or clipboard) |
| static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end) |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| if (!text_end) |
| text_end = FindTextDisplayEnd(text, text_end); |
| |
| const bool log_new_line = ref_pos.y > window->DC.LogLineHeight+1; |
| window->DC.LogLineHeight = ref_pos.y; |
| |
| const char* text_remaining = text; |
| const int tree_depth = window->DC.TreeDepth; |
| while (true) |
| { |
| const char* line_end = text_remaining; |
| while (line_end < text_end) |
| if (*line_end == '\n') |
| break; |
| else |
| line_end++; |
| if (line_end >= text_end) |
| line_end = NULL; |
| |
| const bool is_first_line = (text == text_remaining); |
| bool is_last_line = false; |
| if (line_end == NULL) |
| { |
| is_last_line = true; |
| line_end = text_end; |
| } |
| if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) |
| { |
| const int char_count = (int)(line_end - text_remaining); |
| if (g.LogFile) |
| { |
| if (log_new_line || !is_first_line) |
| fprintf(g.LogFile, "\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); |
| else |
| fprintf(g.LogFile, " %.*s", char_count, text_remaining); |
| } |
| else |
| { |
| if (log_new_line || !is_first_line) |
| g.LogClipboard->append("\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); |
| else |
| g.LogClipboard->append(" %.*s", char_count, text_remaining); |
| } |
| } |
| |
| if (is_last_line) |
| break; |
| text_remaining = line_end + 1; |
| } |
| } |
| |
| static float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) |
| { |
| if (wrap_pos_x < 0.0f) |
| return 0.0f; |
| |
| ImGuiWindow* window = GetCurrentWindow(); |
| if (wrap_pos_x == 0.0f) |
| wrap_pos_x = ImGui::GetContentRegionMax().x; |
| if (wrap_pos_x > 0.0f) |
| wrap_pos_x += window->Pos.x; // wrap_pos_x is provided is window local space |
| |
| const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; |
| return wrap_width; |
| } |
| |
| // Internal ImGui function to render text (called from ImGui::Text(), ImGui::TextUnformatted(), etc.) |
| // RenderText() calls ImDrawList::AddText() calls ImBitmapFont::RenderText() |
| static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash, float wrap_width) |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| // Hide anything after a '##' string |
| const char* text_display_end; |
| if (hide_text_after_hash) |
| { |
| text_display_end = FindTextDisplayEnd(text, text_end); |
| } |
| else |
| { |
| if (!text_end) |
| text_end = text + strlen(text); // FIXME-OPT |
| text_display_end = text_end; |
| } |
| |
| const int text_len = (int)(text_display_end - text); |
| if (text_len > 0) |
| { |
| // Render |
| window->DrawList->AddText(window->Font(), window->FontSize(), pos, window->Color(ImGuiCol_Text), text, text + text_len, wrap_width); |
| |
| // Log as text. We split text into individual lines to add current tree level padding |
| if (g.LogEnabled) |
| LogText(pos, text, text_display_end); |
| } |
| } |
| |
| // Render a rectangle shaped with optional rounding and borders |
| static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); |
| if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) |
| { |
| // FIXME: This is the best I've found that works on multiple renderer/back ends. Rather dodgy. |
| const float offset = GImGui.IO.PixelCenterOffset; |
| window->DrawList->AddRect(p_min+ImVec2(1.5f-offset,1.5f-offset), p_max+ImVec2(1.0f-offset*2,1.0f-offset*2), window->Color(ImGuiCol_BorderShadow), rounding); |
| window->DrawList->AddRect(p_min+ImVec2(0.5f-offset,0.5f-offset), p_max+ImVec2(0.0f-offset*2,0.0f-offset*2), window->Color(ImGuiCol_Border), rounding); |
| } |
| } |
| |
| // Render a triangle to denote expanded/collapsed state |
| static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale, bool shadow) |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| const float h = window->FontSize() * 1.00f; |
| const float r = h * 0.40f * scale; |
| ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); |
| |
| ImVec2 a, b, c; |
| if (open) |
| { |
| center.y -= r*0.25f; |
| a = center + ImVec2(0,1)*r; |
| b = center + ImVec2(-0.866f,-0.5f)*r; |
| c = center + ImVec2(0.866f,-0.5f)*r; |
| } |
| else |
| { |
| a = center + ImVec2(1,0)*r; |
| b = center + ImVec2(-0.500f,0.866f)*r; |
| c = center + ImVec2(-0.500f,-0.866f)*r; |
| } |
| |
| if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0) |
| window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), window->Color(ImGuiCol_BorderShadow)); |
| window->DrawList->AddTriangleFilled(a, b, c, window->Color(ImGuiCol_Border)); |
| } |
| |
| // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. |
| // CalcTextSize("") should return ImVec2(0.0f, GImGui.FontSize) |
| ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| const char* text_display_end; |
| if (hide_text_after_double_hash) |
| text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string |
| else |
| text_display_end = text_end; |
| |
| const ImVec2 text_size = window->Font()->CalcTextSizeA(window->FontSize(), FLT_MAX, wrap_width, text, text_display_end, NULL); |
| return text_size; |
| } |
| |
| // Find window given position, search front-to-back |
| static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) |
| { |
| ImGuiState& g = GImGui; |
| for (int i = (int)g.Windows.size()-1; i >= 0; i--) |
| { |
| ImGuiWindow* window = g.Windows[(size_t)i]; |
| if (!window->Visible) |
| continue; |
| if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) |
| continue; |
| ImGuiAabb bb(window->Pos - g.Style.TouchExtraPadding, window->Pos+window->Size + g.Style.TouchExtraPadding); |
| if (bb.Contains(pos)) |
| return window; |
| } |
| return NULL; |
| } |
| |
| // Test if mouse cursor is hovering given aabb |
| // NB- Box is clipped by our current clip setting |
| // NB- Expand the aabb to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) |
| static bool IsMouseHoveringBox(const ImGuiAabb& box) |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| // Clip |
| ImGuiAabb box_clipped = box; |
| if (!window->ClipRectStack.empty()) |
| { |
| const ImVec4 clip_rect = window->ClipRectStack.back(); |
| box_clipped.Clip(ImGuiAabb(ImVec2(clip_rect.x, clip_rect.y), ImVec2(clip_rect.z, clip_rect.w))); |
| } |
| |
| // Expand for touch input |
| const ImGuiAabb box_for_touch(box_clipped.Min - g.Style.TouchExtraPadding, box_clipped.Max + g.Style.TouchExtraPadding); |
| return box_for_touch.Contains(g.IO.MousePos); |
| } |
| |
| bool ImGui::IsMouseHoveringBox(const ImVec2& box_min, const ImVec2& box_max) |
| { |
| return IsMouseHoveringBox(ImGuiAabb(box_min, box_max)); |
| } |
| |
| bool ImGui::IsMouseHoveringWindow() |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| return g.HoveredWindow == window; |
| } |
| |
| bool ImGui::IsMouseHoveringAnyWindow() |
| { |
| ImGuiState& g = GImGui; |
| return g.HoveredWindow != NULL; |
| } |
| |
| bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) |
| { |
| return FindHoveredWindow(pos, false) != NULL; |
| } |
| |
| static bool IsKeyPressedMap(ImGuiKey key, bool repeat) |
| { |
| ImGuiState& g = GImGui; |
| const int key_index = g.IO.KeyMap[key]; |
| return ImGui::IsKeyPressed(key_index, repeat); |
| } |
| |
| bool ImGui::IsKeyPressed(int key_index, bool repeat) |
| { |
| ImGuiState& g = GImGui; |
| IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); |
| const float t = g.IO.KeysDownTime[key_index]; |
| if (t == 0.0f) |
| return true; |
| |
| // FIXME: Repeat rate should be provided elsewhere? |
| const float KEY_REPEAT_DELAY = 0.250f; |
| const float KEY_REPEAT_RATE = 0.020f; |
| if (repeat && t > KEY_REPEAT_DELAY) |
| if ((fmodf(t - KEY_REPEAT_DELAY, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f) != (fmodf(t - KEY_REPEAT_DELAY - g.IO.DeltaTime, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f)) |
| return true; |
| |
| return false; |
| } |
| |
| bool ImGui::IsMouseClicked(int button, bool repeat) |
| { |
| ImGuiState& g = GImGui; |
| IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); |
| const float t = g.IO.MouseDownTime[button]; |
| if (t == 0.0f) |
| return true; |
| |
| // FIXME: Repeat rate should be provided elsewhere? |
| const float MOUSE_REPEAT_DELAY = 0.250f; |
| const float MOUSE_REPEAT_RATE = 0.020f; |
| if (repeat && t > MOUSE_REPEAT_DELAY) |
| if ((fmodf(t - MOUSE_REPEAT_DELAY, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f) != (fmodf(t - MOUSE_REPEAT_DELAY - g.IO.DeltaTime, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f)) |
| return true; |
| |
| return false; |
| } |
| |
| bool ImGui::IsMouseDoubleClicked(int button) |
| { |
| ImGuiState& g = GImGui; |
| IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); |
| return g.IO.MouseDoubleClicked[button]; |
| } |
| |
| ImVec2 ImGui::GetMousePos() |
| { |
| return GImGui.IO.MousePos; |
| } |
| |
| bool ImGui::IsItemHovered() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| return window->DC.LastItemHovered; |
| } |
| |
| bool ImGui::IsItemFocused() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| return window->DC.LastItemFocused; |
| } |
| |
| ImVec2 ImGui::GetItemBoxMin() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| return window->DC.LastItemAabb.Min; |
| } |
| |
| ImVec2 ImGui::GetItemBoxMax() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| return window->DC.LastItemAabb.Max; |
| } |
| |
| // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. |
| void ImGui::SetTooltipV(const char* fmt, va_list args) |
| { |
| ImGuiState& g = GImGui; |
| ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); |
| } |
| |
| void ImGui::SetTooltip(const char* fmt, ...) |
| { |
| va_list args; |
| va_start(args, fmt); |
| SetTooltipV(fmt, args); |
| va_end(args); |
| } |
| |
| // Position new window if they don't have position setting in the .ini file. Rarely useful (used by the sample applications). |
| void ImGui::SetNewWindowDefaultPos(const ImVec2& pos) |
| { |
| ImGuiState& g = GImGui; |
| g.NewWindowDefaultPos = pos; |
| } |
| |
| float ImGui::GetTime() |
| { |
| return GImGui.Time; |
| } |
| |
| int ImGui::GetFrameCount() |
| { |
| return GImGui.FrameCount; |
| } |
| |
| static ImGuiWindow* FindWindow(const char* name) |
| { |
| ImGuiState& g = GImGui; |
| for (size_t i = 0; i != g.Windows.size(); i++) |
| if (strcmp(g.Windows[i]->Name, name) == 0) |
| return g.Windows[i]; |
| return NULL; |
| } |
| |
| void ImGui::BeginTooltip() |
| { |
| ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), 0.9f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_Tooltip); |
| } |
| |
| void ImGui::EndTooltip() |
| { |
| IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Tooltip); |
| ImGui::End(); |
| } |
| |
| void ImGui::BeginChild(const char* str_id, ImVec2 size, bool border, ImGuiWindowFlags extra_flags) |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ChildWindow; |
| |
| const ImVec2 content_max = window->Pos + ImGui::GetContentRegionMax(); |
| const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); |
| if (size.x <= 0.0f) |
| { |
| if (size.x == 0.0f) |
| flags |= ImGuiWindowFlags_ChildWindowAutoFitX; |
| size.x = ImMax(content_max.x - cursor_pos.x, g.Style.WindowMinSize.x) - fabsf(size.x); |
| } |
| if (size.y <= 0.0f) |
| { |
| if (size.y == 0.0f) |
| flags |= ImGuiWindowFlags_ChildWindowAutoFitY; |
| size.y = ImMax(content_max.y - cursor_pos.y, g.Style.WindowMinSize.y) - fabsf(size.y); |
| } |
| if (border) |
| flags |= ImGuiWindowFlags_ShowBorders; |
| flags |= extra_flags; |
| |
| char title[256]; |
| ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id); |
| |
| const float alpha = (flags & ImGuiWindowFlags_ComboBox) ? 1.0f : 0.0f; |
| ImGui::Begin(title, NULL, size, alpha, flags); |
| |
| if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) |
| g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; |
| } |
| |
| void ImGui::EndChild() |
| { |
| ImGuiWindow* window = GetCurrentWindow(); |
| |
| if (window->Flags & ImGuiWindowFlags_ComboBox) |
| { |
| ImGui::End(); |
| } |
| else |
| { |
| // When using auto-filling child window, we don't provide the width/height to ItemSize so that it doesn't feed back into automatic size-fitting. |
| ImVec2 sz = ImGui::GetWindowSize(); |
| if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) |
| sz.x = 0; |
| if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) |
| sz.y = 0; |
| |
| ImGui::End(); |
| ItemSize(sz); |
| } |
| } |
| |
| // Push a new ImGui window to add widgets to. This can be called multiple times with the same window to append contents |
| bool ImGui::Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWindowFlags flags) |
| { |
| ImGuiState& g = GImGui; |
| const ImGuiStyle& style = g.Style; |
| IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() |
| |
| ImGuiWindow* window = FindWindow(name); |
| if (!window) |
| { |
| // Create window the first time, and load settings |
| if (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) |
| { |
| // Tooltip and child windows don't store settings |
| window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); |
| new(window) ImGuiWindow(name, ImVec2(0,0), size); |
| } |
| else |
| { |
| // Normal windows store settings in .ini file |
| ImGuiIniData* settings = FindWindowSettings(name); |
| if (settings && ImLength(settings->Size) > 0.0f && !(flags & ImGuiWindowFlags_NoResize))// && ImLengthsize) == 0.0f) |
| size = settings->Size; |
| |
| window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); |
| new(window) ImGuiWindow(name, g.NewWindowDefaultPos, size); |
| |
| if (settings->Pos.x != FLT_MAX) |
| { |
| window->PosFloat = settings->Pos; |
| window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); |
| window->Collapsed = settings->Collapsed; |
| } |
| } |
| g.Windows.push_back(window); |
| } |
| window->Flags = (ImGuiWindowFlags)flags; |
| |
| g.CurrentWindowStack.push_back(window); |
| g.CurrentWindow = window; |
| |
| // Default alpha |
| if (fill_alpha < 0.0f) |
| fill_alpha = style.WindowFillAlphaDefault; |
| |
| // When reusing window again multiple times a frame, just append content (don't need to setup again) |
| const int current_frame = ImGui::GetFrameCount(); |
| const bool first_begin_of_the_frame = (window->LastFrameDrawn != current_frame); |
| if (first_begin_of_the_frame) |
| { |
| window->DrawList->Clear(); |
| window->Visible = true; |
| |
| // New windows appears in front |
| if (window->LastFrameDrawn < current_frame - 1) |
| { |
| FocusWindow(window); |
| if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) |
| { |
| // Hide for 1 frame while resizing |
| window->AutoFitFrames = 2; |
| window->AutoFitOnlyGrows = false; |
| window->Visible = false; |
| } |
| } |
| |
| window->LastFrameDrawn = current_frame; |
| window->ClipRectStack.resize(0); |
| |
| if (flags & ImGuiWindowFlags_ChildWindow) |
| { |
| ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.size()-2]; |
| parent_window->DC.ChildWindows.push_back(window); |
| window->Pos = window->PosFloat = parent_window->DC.CursorPos; |
| window->SizeFull = size; |
| } |
| |
| // Outer clipping rectangle |
| if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) |
| PushClipRect(g.CurrentWindowStack[g.CurrentWindowStack.size()-2]->ClipRectStack.back()); |
| else |
| PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); |
| |
| // Seed ID stack with our window pointer |
| window->IDStack.resize(0); |
| ImGui::PushID(window); |
| |
| // Move window (at the beginning of the frame to avoid lag) |
| const ImGuiID move_id = window->GetID("#MOVE"); |
| RegisterAliveId(move_id); |
| if (g.ActiveId == move_id) |
| { |
| if (g.IO.MouseDown[0]) |
| { |
| if (!(window->Flags & ImGuiWindowFlags_NoMove)) |
| { |
| window->PosFloat += g.IO.MouseDelta; |
| MarkSettingsDirty(); |
| } |
| FocusWindow(window); |
| } |
| else |
| { |
| g.ActiveId = 0; |
| } |
| } |
| |
| // Tooltips always follow mouse |
| if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) |
| { |
| window->PosFloat = g.IO.MousePos + ImVec2(32,16) - g.Style.FramePadding*2; |
| } |
| |
| // Clamp into view |
| if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) |
| { |
| const ImVec2 pad = ImVec2(window->FontSize()*2.0f, window->FontSize()*2.0f); |
| window->PosFloat = ImMax(window->PosFloat + window->Size, pad) - window->Size; |
| window->PosFloat = ImMin(window->PosFloat, ImVec2(g.IO.DisplaySize.x, g.IO.DisplaySize.y) - pad); |
| window->SizeFull = ImMax(window->SizeFull, pad); |
| } |
| window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); |
| |
| // Default item width |
| if (window->Size.x > 0.0f && !(window->Flags & ImGuiWindowFlags_Tooltip) && !(window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) |
| window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); |
| else |
| window->ItemWidthDefault = 200.0f; |
| |
| // Prepare for focus requests |
| if (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) |
| window->FocusIdxAllRequestCurrent = IM_INT_MAX; |
| else |
| window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); |
| if (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) |
| window->FocusIdxTabRequestCurrent = IM_INT_MAX; |
| else |
| window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); |
| window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; |
| window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX; |
| |
| ImGuiAabb title_bar_aabb = window->TitleBarAabb(); |
| |
| // Apply and ImClamp scrolling |
| window->ScrollY = window->NextScrollY; |
| window->ScrollY = ImMax(window->ScrollY, 0.0f); |
| if (!window->Collapsed && !window->SkipItems) |
| window->ScrollY = ImMin(window->ScrollY, ImMax(0.0f, (float)window->SizeContentsFit.y - window->SizeFull.y)); |
| window->NextScrollY = window->ScrollY; |
| |
| // At this point we don't have a clipping rectangle setup yet, so we can test and draw in title bar |
| // Collapse window by double-clicking on title bar |
| if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) |
| { |
| if (g.HoveredWindow == window && IsMouseHoveringBox(title_bar_aabb) && g.IO.MouseDoubleClicked[0]) |
| { |
| window->Collapsed = !window->Collapsed; |
| MarkSettingsDirty(); |
| FocusWindow(window); |
| } |
| } |
| else |
| { |
| window->Collapsed = false; |
| } |
| |
| if (window->Collapsed) |
| { |
| // Draw title bar only |
| window->Size = title_bar_aabb.GetSize(); |
| window->DrawList->AddRectFilled(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_TitleBgCollapsed), g.Style.WindowRounding); |
| if (window->Flags & ImGuiWindowFlags_ShowBorders) |
| { |
| window->DrawList->AddRect(title_bar_aabb.GetTL()+ImVec2(1,1), title_bar_aabb.GetBR()+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), g.Style.WindowRounding); |
| window->DrawList->AddRect(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_Border), g.Style.WindowRounding); |
| } |
| } |
| else |
| { |
| window->Size = window->SizeFull; |
| |
| ImU32 resize_col = 0; |
| if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) |
| { |
| // Tooltip always resize |
| if (window->AutoFitFrames > 0) |
| { |
| window->SizeFull = window->SizeContentsFit + g.Style.WindowPadding - ImVec2(0.0f, g.Style.ItemSpacing.y); |
| } |
| } |
| else |
| { |
| const ImVec2 size_auto_fit = ImClamp(window->SizeContentsFit + style.AutoFitPadding, style.WindowMinSize, g.IO.DisplaySize - style.AutoFitPadding); |
| if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) |
| { |
| // Don't continously mark settings as dirty, the size of the window doesn't need to be stored. |
| window->SizeFull = size_auto_fit; |
| } |
| else if (window->AutoFitFrames > 0) |
| { |
| // Auto-fit only grows during the first few frames |
| if (window->AutoFitOnlyGrows) |
| window->SizeFull = ImMax(window->SizeFull, size_auto_fit); |
| else |
| window->SizeFull = size_auto_fit; |
| MarkSettingsDirty(); |
| } |
| else if (!(window->Flags & ImGuiWindowFlags_NoResize)) |
| { |
| // Resize grip |
| const ImGuiAabb resize_aabb(window->Aabb().GetBR()-ImVec2(18,18), window->Aabb().GetBR()); |
| const ImGuiID resize_id = window->GetID("#RESIZE"); |
| bool hovered, held; |
| ButtonBehaviour(resize_aabb, resize_id, &hovered, &held, true); |
| resize_col = window->Color(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); |
| |
| if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) |
| { |
| // Manual auto-fit |
| window->SizeFull = size_auto_fit; |
| window->Size = window->SizeFull; |
| MarkSettingsDirty(); |
| } |
| else if (held) |
| { |
| // Resize |
| window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize); |
| window->Size = window->SizeFull; |
| MarkSettingsDirty(); |
| } |
| } |
| |
| // Update aabb immediately so that the rendering below isn't one frame late |
| title_bar_aabb = window->TitleBarAabb(); |
| } |
| |
| // Title bar + Window box |
| if (fill_alpha > 0.0f) |
| { |
| if ((window->Flags & ImGuiWindowFlags_ComboBox) != 0) |
| window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_ComboBg, fill_alpha), 0); |
| else |
| window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_WindowBg, fill_alpha), g.Style.WindowRounding); |
| } |
| |
| if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) |
| window->DrawList->AddRectFilled(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_TitleBg), g.Style.WindowRounding, 1|2); |
| |
| // Borders |
| if (window->Flags & ImGuiWindowFlags_ShowBorders) |
| { |
| const float rounding = (window->Flags & ImGuiWindowFlags_ComboBox) ? 0.0f : g.Style.WindowRounding; |
| window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), rounding); |
| window->DrawList->AddRect(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_Border), rounding); |
| if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) |
| window->DrawList->AddLine(title_bar_aabb.GetBL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_Border)); |
| } |
| |
| // Scrollbar |
| window->ScrollbarY = (window->SizeContentsFit.y > window->Size.y) && !(window->Flags & ImGuiWindowFlags_NoScrollbar); |
| if (window->ScrollbarY) |
| { |
| ImGuiAabb scrollbar_bb(window->Aabb().Max.x - style.ScrollBarWidth, title_bar_aabb.Max.y+1, window->Aabb().Max.x, window->Aabb().Max.y-1); |
| //window->DrawList->AddLine(scrollbar_bb.GetTL(), scrollbar_bb.GetBL(), g.Colors[ImGuiCol_Border]); |
| window->DrawList->AddRectFilled(scrollbar_bb.Min, scrollbar_bb.Max, window->Color(ImGuiCol_ScrollbarBg)); |
| scrollbar_bb.Expand(ImVec2(-3,-3)); |
| |
| const float grab_size_y_norm = ImSaturate(window->Size.y / ImMax(window->SizeContentsFit.y, window->Size.y)); |
| const float grab_size_y = scrollbar_bb.GetHeight() * grab_size_y_norm; |
| |
| // Handle input right away (none of the code above is relying on scrolling position) |
| bool held = false; |
| bool hovered = false; |
| if (grab_size_y_norm < 1.0f) |
| { |
| const ImGuiID scrollbar_id = window->GetID("#SCROLLY"); |
| ButtonBehaviour(scrollbar_bb, scrollbar_id, &hovered, &held, true); |
| if (held) |
| { |
| g.HoveredId = scrollbar_id; |
| const float pos_y_norm = ImSaturate((g.IO.MousePos.y - (scrollbar_bb.Min.y + grab_size_y*0.5f)) / (scrollbar_bb.GetHeight() - grab_size_y)) * (1.0f - grab_size_y_norm); |
| window->ScrollY = pos_y_norm * window->SizeContentsFit.y; |
| window->NextScrollY = window->ScrollY; |
| } |
| } |
| |
| // Normalized height of the grab |
| const float pos_y_norm = ImSaturate(window->ScrollY / ImMax(0.0f, window->SizeContentsFit.y)); |
| const ImU32 grab_col = window->Color(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); |
| window->DrawList->AddRectFilled( |
| ImVec2(scrollbar_bb.Min.x, ImLerp(scrollbar_bb.Min.y, scrollbar_bb.Max.y, pos_y_norm)), |
| ImVec2(scrollbar_bb.Max.x, ImLerp(scrollbar_bb.Min.y, scrollbar_bb.Max.y, pos_y_norm + grab_size_y_norm)), grab_col); |
| } |
| |
| // Render resize grip |
| // (after the input handling so we don't have a frame of latency) |
| if (!(window->Flags & ImGuiWindowFlags_NoResize)) |
| { |
| const float r = style.WindowRounding; |
| const ImVec2 br = window->Aabb().GetBR(); |
| if (r == 0.0f) |
| { |
| window->DrawList->AddTriangleFilled(br, br-ImVec2(0,14), br-ImVec2(14,0), resize_col); |
| } |
| else |
| { |
| // FIXME: We should draw 4 triangles and decide on a size that's not dependant on the rounding size (previously used 18) |
| window->DrawList->AddArc(br - ImVec2(r,r), r, resize_col, 6, 9, true); |
| window->DrawList->AddTriangleFilled(br+ImVec2(0,-2*r),br+ImVec2(0,-r),br+ImVec2(-r,-r), resize_col); |
| window->DrawList->AddTriangleFilled(br+ImVec2(-r,-r), br+ImVec2(-r,0),br+ImVec2(-2*r,0), resize_col); |
| } |
| } |
| } |
| |
| // Setup drawing context |
| window->DC.ColumnsStartX = window->WindowPadding().x; |
| window->DC.ColumnsOffsetX = 0.0f; |
| window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.ColumnsStartX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->WindowPadding().y) - ImVec2(0.0f, window->ScrollY); |
| window->DC.CursorPos = window->DC.CursorStartPos; |
| window->DC.CursorPosPrevLine = window->DC.CursorPos; |
| window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; |
| window->DC.LogLineHeight = window->DC.CursorPos.y - 9999.0f; |
| window->DC.ChildWindows.resize(0); |
| window->DC.ItemWidth.resize(0); |
| window->DC.ItemWidth.push_back(window->ItemWidthDefault); |
| window->DC.AllowKeyboardFocus.resize(0); |
| window->DC.AllowKeyboardFocus.push_back(true); |
| window->DC.TextWrapPos.resize(0); |
| window->DC.TextWrapPos.push_back(-1.0f); // disabled |
| window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; |
| window->DC.ColumnsCurrent = 0; |
| window->DC.ColumnsCount = 1; |
| window->DC.ColumnsStartPos = window->DC.CursorPos; |
| window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPos.y; |
| window->DC.TreeDepth = 0; |
| window->DC.StateStorage = &window->StateStorage; |
| window->DC.OpenNextNode = -1; |
| |
| // Reset contents size for auto-fitting |
| window->SizeContentsFit = ImVec2(0.0f, 0.0f); |
| if (window->AutoFitFrames > 0) |
| window->AutoFitFrames--; |
| |
| // Title bar |
| if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) |
| { |
| RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); |
| if (open) |
| CloseWindowButton(open); |
| |
| const ImVec2 text_size = CalcTextSize(name); |
| const ImVec2 text_min = window->Pos + style.FramePadding + ImVec2(window->FontSize() + style.ItemInnerSpacing.x, 0.0f); |
| const ImVec2 text_max = window->Pos + ImVec2(window->Size.x - (open ? (title_bar_aabb.GetHeight()-3) : style.FramePadding.x), style.FramePadding.y + text_size.y); |
| const bool clip_title = text_size.x > (text_max.x - text_min.x); // only push a clip rectangle if we need to, because it may turn into a separate draw call |
| if (clip_title) |
| PushClipRect(ImVec4(text_min.x, text_min.y, text_max.x, text_max.y)); |
| RenderText(text_min, name); |
| if (clip_title) |
| PopClipRect(); |
| } |
| } |
| else |
| { |
| // Outer clipping rectangle |
| if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) |
| { |
| ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.size()-2]; |
| PushClipRect(parent_window->ClipRectStack.back()); |
| } |
| else |
| { |
| PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); |
| } |
| } |
| |
| // Inner clipping rectangle |
| // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame |
| const ImGuiAabb title_bar_aabb = window->TitleBarAabb(); |
| ImVec4 clip_rect(title_bar_aabb.Min.x+0.5f+window->WindowPadding().x*0.5f, title_bar_aabb.Max.y+0.5f, window->Aabb().Max.x+0.5f-window->WindowPadding().x*0.5f, window->Aabb().Max.y-1.5f); |
| if (window->ScrollbarY) |
| clip_rect.z -= g.Style.ScrollBarWidth; |
| PushClipRect(clip_rect); |
| |
| // Clear 'accessed' flag last thing |
| if (first_begin_of_the_frame) |
| window->Accessed = false; |
| |
| // Child window can be out of sight and have "negative" clip windows. |
| // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). |
| if (flags & ImGuiWindowFlags_ChildWindow) |
| { |
| IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); |
| const ImVec4 clip_rect_t = window->ClipRectStack.back(); |
| window->Collapsed = (clip_rect_t.x >= clip_rect_t.z || clip_rect_t.y >= clip_rect_t.w); |
| |
| // We also hide the window from rendering because we've already added its border to the command list. |
| // (we could perform the check earlier in the function but it is simpler at this point) |
| if (window->Collapsed) |
| window->Visible = false; |
| } |
| if (g.Style.Alpha <= 0.0f) |
| window->Visible = false; |
| |
| // Return false if we don't intend to display anything to allow user to perform an early out optimisation |
| window->SkipItems = window->Collapsed || (!window->Visible && window->AutoFitFrames == 0); |
| return !window->SkipItems; |
| } |
| |
| void ImGui::End() |
| { |
| ImGuiState& g = GImGui; |
| ImGuiWindow* window = g.CurrentWindow; |
| |
| ImGui::Columns(1, "#CloseColumns"); |
| PopClipRect(); // inner window clip rectangle |
| PopClipRect(); // outer window clip rectangle |
| |
| // Select window for move/focus when we're done with all our widgets (we only consider non-childs windows here) |
| const ImGuiAabb bb(window->Pos, window->Pos+window->Size); |
| if (g.ActiveId == 0 && g.HoveredId == |