From 38b02245fc91fe6b9dabc88315fc5aed5d5e018c Mon Sep 17 00:00:00 2001 From: Omar C Date: Mon, 11 Aug 2014 10:36:18 +0100 Subject: [PATCH 01/40] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 65a9ad7f4..b1b73dee0 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Usage example: ![screenshot of sample code alongside its output with ImGui](/web/code_sample_01.png?raw=true) -ImGui output vertex buffer and simple command-list that you can render in application. Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui within your existing codebase. +ImGui outputs vertex buffers and simple command-lists that you can render in your application. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase. Gallery @@ -25,7 +25,7 @@ Credits Developed by [Omar Cornut](http://www.miracleworld.net). The library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com). -Embeds [proggy_clean font](http://www.proggyfonts.net/) by Tristan Grimmer (also MIT license). +Embeds [proggy_clean](http://www.proggyfonts.net/) font by Tristan Grimmer (also MIT license). Inspiration, feedback, and testing: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Matt Willis. Thanks! From 42419b59c051e30ec5bffabc3dbe9bb9cf8d4221 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 11:10:50 +0100 Subject: [PATCH 02/40] Ignore list for Visual Studio output and temporaries --- .gitignore | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e6df0e49d --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +## Visual Studio files +examples/directx9_example/Debug/* +examples/directx9_example/Release/* +examples/directx9_example/ipch/* +examples/opengl_example/Debug/* +examples/opengl_example/Release/* +examples/opengl_example/ipch/* +*.opensdf +*.sdf +*.suo +*.vcxproj.user From 678f6d3a3db43df96db2f480bc074d6b92f04731 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 12:13:05 +0100 Subject: [PATCH 03/40] Missing includes for some platforms --- imgui.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e5aca50ca..1ef8ad332 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -156,8 +156,10 @@ */ #include "imgui.h" -#include +#include // toupper +#include // INT_MAX #include // sqrt +#include // intptr_t #include // vsnprintf #include // memset From 900dd3bd0fb8a04546dc7a62aa034f80c40527d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 12:45:47 +0100 Subject: [PATCH 04/40] Update README.md Clarifying C++ Added item in todo list --- README.md | 2 +- imgui.cpp | 1 + web/code_sample_01.png | Bin 11345 -> 8005 bytes 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b1b73dee0..876bd29e3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ImGui ===== -ImGui is a bloat-free graphical user interface library for C/C++. It is portable, renderer agnostic and carries minimal amount of dependencies (only 3 files are needed). It is based on an "immediate" graphical user interface paradigm which allows you to build simple user interfaces with ease. +ImGui is a bloat-free graphical user interface library for C++. It is portable, renderer agnostic and carries minimal amount of dependencies (only 3 files are needed). It is based on an "immediate" graphical user interface paradigm which allows you to build simple user interfaces with ease. ImGui is designed to allow programmers to create "content creation" or "debug" tools (as opposed to tools for the average end-user). It favors simplicity and thus lacks certain features normally found in more high-level libraries, such as string localisation. diff --git a/imgui.cpp b/imgui.cpp index 1ef8ad332..1ce8cce14 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -144,6 +144,7 @@ - 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: full keyboard navigation and focus + - clipboard: add a default "local" implementation of clipboard functions (user will only need to override them to connect to OS clipboard) - misc: not thread-safe - optimisation/render: use indexed rendering - optimisation/render: move clip-rect to vertex data? would allow merging all commands diff --git a/web/code_sample_01.png b/web/code_sample_01.png index 6ff370cf2637f35396b6c583e0bfb247458559f9..6178f8d8c2505d265b0bc9329b70f79bb1d2835a 100644 GIT binary patch literal 8005 zcma)Bdpwix-=7pZDBmQNSm%Rcoe;{3N+qO13QH0tMh?T+Dx`x$Duvyu{m$t?(Mnh_j_L7-|P83zvubq-tN7wUH5%`uJ`Btd4Jy53cYS(P_15Zb%a_{NUA6I3(l#eP99Lc+b;_!*c9q#Rhi%HC_q}$k zKCvP{DSDFwYU6LGrch;WmGq~r;mY=Yn=hrbtvV_xLQ=c=x%?pmHh?774i$3(I72Bh z7#gzUMF&w1QK86z_%dM%4?rn|Q1Jn%zZl_x-n>{Sjo|ML=^-F0pb!PtDntqCA0rGs z(1;#_p&VZp!7`t}!UO)#VU-Z#9=LRK3GzSAEfHm5*zu9=HM3zo;yNU8?!K&=U(Fu- zX!(-9Nd4}K6ye5=8{1V(wO^Y_-2<~e%`uD1`ukCYvHX;=@VyPg=K6%5a&V;@p~R^H zBkGZr4BIp(q}_B@b&{t4%AaGz0fEg~_Wc-eq?s`NzB$NUs&O?-l7)eWan z0W?^L^slZTG1o6A;u!TKc3E2?axvI!seF4PI*Q1Oln9s{`(ufVh0KrLBjQBPT-wUc zoQesOBrxk*@e&QzhXif|gec(zVtXkQk@}gR3ZBPHL{-Wu!X)lxRTU^}qmb+d|6MYf zj-GlS^cX$b=@?~`Oy!rlZs$vWG!uL!kdQeU+|8=h^JC zHwmUbo!Pb9gv_Kcx1iAkdf^EEd@yry4`G64Q@8e`+gA#uiv+JjTk3V8f9_FX=WQrw zRj=?u-bFAIGhL;8MVU@8O4M!`Hx~pjFlCePryKE!WMcmw$;b;*_!j@+H(`7l=$>`0 z!+w;-?M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fp znYRwsU6wyL6v6^gfe$1;r|IHFSGuqA*PW}~gSkPuTsi}uX)`q#9Z&ap$HqtG3WG`i zMO=D29&xAv>E|v|w>iJSEEzGpf$!z`-Ay{ zEG2cnQ~39ye(Xu3K=2bwKj-bmr2M^!fKEG|Uv6Wss?EQQ4DWkd7X>404<$Lfb0IoS z_O~>8Mqm(q`oX3DpI|4~;LB2#nfHGVTr~J@d`Tv*4Yuq!o}x|HNr%9e!HcA=2)zH| qF#pBJACcXE!0j Date: Mon, 11 Aug 2014 14:46:04 +0100 Subject: [PATCH 05/40] Git ignore imgui.ini files --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index e6df0e49d..94f4ef015 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ examples/opengl_example/ipch/* *.sdf *.suo *.vcxproj.user + +## Ini files +imgui.ini From 8ab2942716138c087a9e5b4621d93fc38ea31c11 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 14:51:22 +0100 Subject: [PATCH 06/40] Added PixelCenterOffset for OpenGL/DirectX compatibility. --- examples/directx9_example/main.cpp | 1 + examples/opengl_example/main.cpp | 1 + imgui.cpp | 11 +++++++---- imgui.h | 1 + 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index fd25f0101..017a3a915 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -293,6 +293,7 @@ void InitImGui() io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; + io.PixelCenterOffset = 0.0f; io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index 909ffa98e..2d23a7463 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -297,6 +297,7 @@ void InitImGui() io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; + io.PixelCenterOffset = 0.5f; io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; diff --git a/imgui.cpp b/imgui.cpp index 1ce8cce14..449017792 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -262,6 +262,7 @@ ImGuiIO::ImGuiIO() LogFilename = "imgui_log.txt"; Font = NULL; FontAllowScaling = false; + PixelCenterOffset = 0.5f; MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; @@ -5003,6 +5004,8 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c float line_width = 0.0f; const ImVec4 clip_rect = clip_rect_ref; + const float uv_offset = GImGui.IO.PixelCenterOffset; + float x = pos.x; float y = pos.y; for (const char* s = text_begin; s < text_end; s++) @@ -5039,10 +5042,10 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c continue; } - const float s1 = (0.0f + glyph->X) * tex_scale_x; - const float t1 = (0.0f + glyph->Y) * tex_scale_y; - const float s2 = (0.0f + glyph->X + glyph->Width) * tex_scale_x; - const float t2 = (0.0f + glyph->Y + glyph->Height) * tex_scale_y; + const float s1 = (uv_offset + glyph->X) * tex_scale_x; + const float t1 = (uv_offset + glyph->Y) * tex_scale_y; + const float s2 = (uv_offset + glyph->X + glyph->Width) * tex_scale_x; + const float t2 = (uv_offset + glyph->Y + glyph->Height) * tex_scale_y; out_vertices[0].pos = ImVec2(x1, y1); out_vertices[0].uv = ImVec2(s1, t1); diff --git a/imgui.h b/imgui.h index 3c7505771..d2e904171 100644 --- a/imgui.h +++ b/imgui.h @@ -373,6 +373,7 @@ struct ImGuiIO ImFont Font; // // Gets passed to text functions. Typedef ImFont to the type you want (ImBitmapFont* or your own font). float FontHeight; // // Default font height, must be the vertical distance between two lines of text, aka == CalcTextSize(" ").y bool FontAllowScaling; // = false // Set to allow scaling text with CTRL+Wheel. + float PixelCenterOffset; // = 0.5f // Set to 0.0f for DirectX <= 9, 0.5f for Direct3D >= 10 and OpenGL. // Settings - Functions (fill once) void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); // Required From 86d2c9d232de661212062ab7d184030465e1fbdf Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 15:02:33 +0100 Subject: [PATCH 07/40] Commented samples and shuffled bits of the initialisation based on user's feedback. --- examples/directx9_example/main.cpp | 39 ++++++---- examples/opengl_example/main.cpp | 121 +++++++++++++++-------------- imgui.h | 2 +- 3 files changed, 88 insertions(+), 74 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index 017a3a915..36be8a627 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -203,17 +203,6 @@ HRESULT InitD3D(HWND hWnd) if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice) < 0) return E_FAIL; - // Create the vertex buffer. - if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) - return E_FAIL; - - // Load font texture - const void* png_data; - unsigned int png_size; - ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); - if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0) - return E_FAIL; - return S_OK; } @@ -247,9 +236,11 @@ LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) io.MouseDown[1] = false; return true; case WM_MOUSEWHEEL: + // Mouse wheel: -1,0,+1 io.MouseWheel = GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1 : -1; return true; case WM_MOUSEMOVE: + // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) io.MousePos.x = (signed short)(lParam); io.MousePos.y = (signed short)(lParam >> 16); return true; @@ -274,9 +265,10 @@ void InitImGui() GetClientRect(hWnd, &rect); ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); - io.DeltaTime = 1.0f/60.0f; - io.KeyMap[ImGuiKey_Tab] = VK_TAB; + io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Display size, in pixels. For clamping windows positions. + io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable) + io.PixelCenterOffset = 0.0f; // Align Direct3D Texels + io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; @@ -293,11 +285,28 @@ void InitImGui() io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; - io.PixelCenterOffset = 0.0f; io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; + + + // Create the vertex buffer + if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) + { + IM_ASSERT(0); + return; + } + + // Load font texture + const void* png_data; + unsigned int png_size; + ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); + if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0) + { + IM_ASSERT(0); + return; + } } int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int) diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index 2d23a7463..f6a026deb 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -217,58 +217,6 @@ void InitGL() glewInit(); GLenum err = GL_NO_ERROR; - GLint status = GL_TRUE; - err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); - - // Create and compile the vertex shader - vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, NULL); - glCompileShader(vertexShader); - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); - if (status != GL_TRUE) - { - char buffer[512]; - glGetShaderInfoLog(vertexShader, 1024, NULL, buffer); - printf("%s", buffer); - IM_ASSERT(status == GL_TRUE); - } - - // Create and compile the fragment shader - fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, NULL); - glCompileShader(fragmentShader); - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); - IM_ASSERT(status == GL_TRUE); - - // Link the vertex and fragment shader into a shader program - shaderProgram = glCreateProgram(); - glAttachShader(shaderProgram, vertexShader); - glAttachShader(shaderProgram, fragmentShader); - glBindFragDataLocation(shaderProgram, 0, "o_col"); - glLinkProgram(shaderProgram); - glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); - IM_ASSERT(status == GL_TRUE); - - uniMVP = glGetUniformLocation(shaderProgram, "MVP"); - uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect"); - - // Create Vertex Buffer Objects & Vertex Array Objects - glGenBuffers(1, &vbo); - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glGenVertexArrays(1, &vao); - glBindVertexArray(vao); - - GLint posAttrib = glGetAttribLocation(shaderProgram, "i_pos"); - glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), 0); - glEnableVertexAttribArray(posAttrib); - - GLint uvAttrib = glGetAttribLocation(shaderProgram, "i_uv"); - glEnableVertexAttribArray(uvAttrib); - glVertexAttribPointer(uvAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (void*)(2*sizeof(float))); - - GLint colAttrib = glGetAttribLocation(shaderProgram, "i_col"); - glVertexAttribPointer(colAttrib, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (void*)(4*sizeof(float))); - glEnableVertexAttribArray(colAttrib); err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); } @@ -278,9 +226,10 @@ void InitImGui() glfwGetWindowSize(window, &w, &h); ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize = ImVec2((float)w, (float)h); - io.DeltaTime = 1.0f/60.0f; - io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; + io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions. + io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable) + io.PixelCenterOffset = 0.5f; // Align OpenGL texels + io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; @@ -297,12 +246,68 @@ void InitImGui() io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; - io.PixelCenterOffset = 0.5f; io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; + + // Setup graphics backend + GLint status = GL_TRUE; + GLenum err = GL_NO_ERROR; + err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); + + // Create and compile the vertex shader + vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &vertexSource, NULL); + glCompileShader(vertexShader); + glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); + if (status != GL_TRUE) + { + char buffer[512]; + glGetShaderInfoLog(vertexShader, 1024, NULL, buffer); + printf("%s", buffer); + IM_ASSERT(status == GL_TRUE); + } + + // Create and compile the fragment shader + fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragmentShader, 1, &fragmentSource, NULL); + glCompileShader(fragmentShader); + glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); + IM_ASSERT(status == GL_TRUE); + + // Link the vertex and fragment shader into a shader program + shaderProgram = glCreateProgram(); + glAttachShader(shaderProgram, vertexShader); + glAttachShader(shaderProgram, fragmentShader); + glBindFragDataLocation(shaderProgram, 0, "o_col"); + glLinkProgram(shaderProgram); + glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); + IM_ASSERT(status == GL_TRUE); + + uniMVP = glGetUniformLocation(shaderProgram, "MVP"); + uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect"); + + // Create Vertex Buffer Objects & Vertex Array Objects + glGenBuffers(1, &vbo); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glGenVertexArrays(1, &vao); + glBindVertexArray(vao); + + GLint posAttrib = glGetAttribLocation(shaderProgram, "i_pos"); + glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), 0); + glEnableVertexAttribArray(posAttrib); + + GLint uvAttrib = glGetAttribLocation(shaderProgram, "i_uv"); + glEnableVertexAttribArray(uvAttrib); + glVertexAttribPointer(uvAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (void*)(2*sizeof(float))); + + GLint colAttrib = glGetAttribLocation(shaderProgram, "i_col"); + glVertexAttribPointer(colAttrib, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (void*)(4*sizeof(float))); + glEnableVertexAttribArray(colAttrib); + err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); + // Load font texture glGenTextures(1, &fontTex); glBindTexture(GL_TEXTURE_2D, fontTex); @@ -348,10 +353,10 @@ int main(int argc, char** argv) time = current_time; double mouse_x, mouse_y; glfwGetCursorPos(window, &mouse_x, &mouse_y); - io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); + io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0; - io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; + io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1 mouse_wheel = 0.0f; ImGui::NewFrame(); diff --git a/imgui.h b/imgui.h index d2e904171..8f7bf80ca 100644 --- a/imgui.h +++ b/imgui.h @@ -381,7 +381,7 @@ struct ImGuiIO void (*SetClipboardTextFn)(const char* text, const char* text_end); // Required for clipboard support (nb- the string is *NOT* zero-terminated at 'text_end') // Input - Fill before calling NewFrame() - ImVec2 MousePos; // Mouse position (set to -1,-1 if no mouse / on another screen, etc.) + ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) bool MouseDown[2]; // Mouse buttons int MouseWheel; // Mouse wheel: -1,0,+1 bool KeyCtrl; // Keyboard modifier pressed: Control From 4020ef7b58bd2ffb4779494ff2a29c7780d713bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 16:17:59 +0100 Subject: [PATCH 08/40] Tidying up example applications --- examples/directx9_example/main.cpp | 55 +++++++++----------- examples/opengl_example/main.cpp | 80 ++++++++++++++---------------- 2 files changed, 62 insertions(+), 73 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index 36be8a627..01cb3c6c4 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -12,16 +12,15 @@ static LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices static LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture - struct CUSTOMVERTEX { D3DXVECTOR3 position; D3DCOLOR color; float tu, tv; }; - #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) +// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer) static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { size_t total_vtx_count = 0; @@ -30,31 +29,13 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c if (total_vtx_count == 0) return; - ImVector clip_rect_stack; - clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); - - // Setup orthographic projection - // Set up world matrix - D3DXMATRIXA16 mat; - D3DXMatrixIdentity(&mat); - g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat); - g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat); - D3DXMatrixOrthoOffCenterLH(&mat, 0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f); - g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat); - - D3DSURFACE_DESC texture_desc; - g_pTexture->GetLevelDesc(0, &texture_desc); - - // Fill the vertex buffer + // Copy and convert all vertices into a single contiguous buffer CUSTOMVERTEX* vtx_dst; if (g_pVB->Lock(0, total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) return; - for (int n = 0; n < cmd_lists_count; n++) { const ImDrawList* cmd_list = cmd_lists[n]; - if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty()) - continue; const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0]; for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++) { @@ -73,11 +54,10 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) ); g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX ); - // Setup render state: alpha-blending enabled, no face culling, no depth testing + // Setup render state: alpha-blending, no face culling, no depth testing g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false ); g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false ); - g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true ); g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false ); @@ -94,17 +74,29 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); - int vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those - bool clip_rect_dirty = true; + // Setup orthographic projection matrix + D3DXMATRIXA16 mat; + D3DXMatrixIdentity(&mat); + g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat); + D3DXMatrixOrthoOffCenterLH(&mat, 0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat); + // Render command lists + int vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those for (int n = 0; n < cmd_lists_count; n++) { const ImDrawList* cmd_list = cmd_lists[n]; - if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty()) - continue; + + // Setup stack of clipping rectangles + bool clip_rect_dirty = true; + int clip_rect_buf_consumed = 0; + ImVector clip_rect_stack; + clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); + + // Render command list const ImDrawCmd* pcmd = &cmd_list->commands.front(); const ImDrawCmd* pcmd_end = &cmd_list->commands.back(); - int clip_rect_buf_consumed = 0; // offset in cmd_list->clip_rect_buffer. each PushClipRect command consume 1 of those. while (pcmd <= pcmd_end) { const ImDrawCmd& cmd = *pcmd++; @@ -289,7 +281,6 @@ void InitImGui() io.RenderDrawListsFn = ImImpl_RenderDrawLists; io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; - // Create the vertex buffer if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) @@ -396,13 +387,15 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int) ImGui::End(); } - // 3) Render + // 3) Rendering + // Clear frame buffer g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); - g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0); // Clear the backbuffer and the zbuffer + g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { + // Render ImGui ImGui::Render(); g_pd3dDevice->EndScene(); } diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index f6a026deb..769893203 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -18,6 +18,7 @@ static GLuint fontTex; static GLint uniMVP; static GLint uniClipRect; +// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer) static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { size_t total_vtx_count = 0; @@ -26,12 +27,34 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c if (total_vtx_count == 0) return; - int read_pos_clip_rect_buf = 0; // offset in 'clip_rect_buffer'. each PushClipRect command consume 1 of those. + // Copy all vertices into a single contiguous GL buffer + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBindVertexArray(vao); + glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW); + unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + if (!buffer_data) + return; + int vtx_consumed = 0; + for (int n = 0; n < cmd_lists_count; n++) + { + const ImDrawList* cmd_list = cmd_lists[n]; + memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); + buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); + vtx_consumed += cmd_list->vtx_buffer.size(); + } + glUnmapBuffer(GL_ARRAY_BUFFER); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); - ImVector clip_rect_stack; - clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); + // Bind texture and enable our shader + glBindTexture(GL_TEXTURE_2D, fontTex); + glUseProgram(shaderProgram); - // Setup orthographic projection + // Setup orthographic projection matrix const float L = 0.0f; const float R = ImGui::GetIO().DisplaySize.x; const float B = ImGui::GetIO().DisplaySize.y; @@ -43,48 +66,23 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c { 0.0f, 0.0f, -1.0f, 0.0f }, { -(R+L)/(R-L), -(T+B)/(T-B), 0.0f, 1.0f }, }; - - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glBindVertexArray(vao); - glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW); - unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); - if (!buffer_data) - return; - int vtx_consumed = 0; - for (int n = 0; n < cmd_lists_count; n++) - { - const ImDrawList* cmd_list = cmd_lists[n]; - if (!cmd_list->vtx_buffer.empty()) - { - memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); - buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); - vtx_consumed += cmd_list->vtx_buffer.size(); - } - } - glUnmapBuffer(GL_ARRAY_BUFFER); - - glUseProgram(shaderProgram); glUniformMatrix4fv(uniMVP, 1, GL_FALSE, &mvp[0][0]); - // Setup render state: alpha-blending enabled, no face culling, no depth testing - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - - glBindTexture(GL_TEXTURE_2D, fontTex); - + // Render command lists vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those - bool clip_rect_dirty = true; - for (int n = 0; n < cmd_lists_count; n++) { const ImDrawList* cmd_list = cmd_lists[n]; - if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty()) - continue; + + // Setup stack of clipping rectangles + bool clip_rect_dirty = true; + int clip_rect_buf_consumed = 0; + ImVector clip_rect_stack; + clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); + + // Render command list const ImDrawCmd* pcmd = &cmd_list->commands.front(); const ImDrawCmd* pcmd_end = &cmd_list->commands.back(); - int clip_rect_buf_consumed = 0; // offset in cmd_list->clip_rect_buffer. each PushClipRect command consume 1 of those. while (pcmd <= pcmd_end) { const ImDrawCmd& cmd = *pcmd++; @@ -132,7 +130,6 @@ static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end) } // Shader sources -// FIXME-OPT: clip at vertex level const GLchar* vertexSource = "#version 150 core\n" "uniform mat4 MVP;" @@ -164,6 +161,7 @@ const GLchar* fragmentSource = " o_col.w *= (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w));" // Clipping: branch-less, set alpha 0.0f "}"; +// GLFW callbacks to get events static void glfw_error_callback(int error, const char* description) { fputs(description, stderr); @@ -251,7 +249,6 @@ void InitImGui() io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; - // Setup graphics backend GLint status = GL_TRUE; GLenum err = GL_NO_ERROR; @@ -394,7 +391,7 @@ int main(int argc, char** argv) ImGui::End(); } - // 3) Render + // 3) Rendering glClearColor(0.8f, 0.6f, 0.6f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); @@ -403,6 +400,5 @@ int main(int argc, char** argv) } Shutdown(); - return 0; } From 98a000055e498e3a77d7ca348422d6652c9bd06d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 17:46:54 +0100 Subject: [PATCH 09/40] Tidying up example applications --- examples/directx9_example/main.cpp | 26 +++++-------- examples/opengl_example/main.cpp | 61 +++++++++++++----------------- 2 files changed, 36 insertions(+), 51 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index 01cb3c6c4..a75dd0bcc 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -83,45 +83,37 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat); // Render command lists - int vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those + int vtx_offset = 0; for (int n = 0; n < cmd_lists_count; n++) { - const ImDrawList* cmd_list = cmd_lists[n]; - // Setup stack of clipping rectangles - bool clip_rect_dirty = true; - int clip_rect_buf_consumed = 0; + int clip_rect_buf_offset = 0; ImVector clip_rect_stack; clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); // Render command list - const ImDrawCmd* pcmd = &cmd_list->commands.front(); - const ImDrawCmd* pcmd_end = &cmd_list->commands.back(); - while (pcmd <= pcmd_end) + const ImDrawList* cmd_list = cmd_lists[n]; + const ImDrawCmd* pcmd_end = cmd_list->commands.end(); + for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - const ImDrawCmd& cmd = *pcmd++; - switch (cmd.cmd_type) + switch (pcmd->cmd_type) { case ImDrawCmdType_DrawTriangleList: - if (clip_rect_dirty) { const ImVec4& clip_rect = clip_rect_stack.back(); const RECT r = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w }; g_pd3dDevice->SetScissorRect(&r); - clip_rect_dirty = false; + g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3); + vtx_offset += pcmd->vtx_count; } - g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_consumed, cmd.vtx_count/3); - vtx_consumed += cmd.vtx_count; break; case ImDrawCmdType_PushClipRect: - clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]); - clip_rect_dirty = true; + clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_offset++]); break; case ImDrawCmdType_PopClipRect: clip_rect_stack.pop_back(); - clip_rect_dirty = true; break; } } diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index 769893203..dfad6e345 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -15,8 +15,6 @@ static GLuint vertexShader; static GLuint fragmentShader; static GLuint shaderProgram; static GLuint fontTex; -static GLint uniMVP; -static GLint uniClipRect; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer) static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) @@ -34,13 +32,11 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); if (!buffer_data) return; - int vtx_consumed = 0; for (int n = 0; n < cmd_lists_count; n++) { const ImDrawList* cmd_list = cmd_lists[n]; memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); - vtx_consumed += cmd_list->vtx_buffer.size(); } glUnmapBuffer(GL_ARRAY_BUFFER); @@ -53,63 +49,59 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c // Bind texture and enable our shader glBindTexture(GL_TEXTURE_2D, fontTex); glUseProgram(shaderProgram); + const GLint uniMVP = glGetUniformLocation(shaderProgram, "MVP"); + const GLint uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect"); // Setup orthographic projection matrix - const float L = 0.0f; - const float R = ImGui::GetIO().DisplaySize.x; - const float B = ImGui::GetIO().DisplaySize.y; - const float T = 0.0f; + const float width = ImGui::GetIO().DisplaySize.x; + const float height = ImGui::GetIO().DisplaySize.y; const float mvp[4][4] = { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 2.0f/width, 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/-height, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, - { -(R+L)/(R-L), -(T+B)/(T-B), 0.0f, 1.0f }, + { -1.0f, 1.0f, 0.0f, 1.0f }, }; glUniformMatrix4fv(uniMVP, 1, GL_FALSE, &mvp[0][0]); // Render command lists - vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those + int vtx_offset = 0; for (int n = 0; n < cmd_lists_count; n++) { - const ImDrawList* cmd_list = cmd_lists[n]; - // Setup stack of clipping rectangles - bool clip_rect_dirty = true; - int clip_rect_buf_consumed = 0; + int clip_rect_buf_offset = 0; ImVector clip_rect_stack; clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); // Render command list - const ImDrawCmd* pcmd = &cmd_list->commands.front(); - const ImDrawCmd* pcmd_end = &cmd_list->commands.back(); - while (pcmd <= pcmd_end) + const ImDrawList* cmd_list = cmd_lists[n]; + const ImDrawCmd* pcmd_end = cmd_list->commands.end(); + for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - const ImDrawCmd& cmd = *pcmd++; - switch (cmd.cmd_type) + switch (pcmd->cmd_type) { case ImDrawCmdType_DrawTriangleList: - if (clip_rect_dirty) - { - glUniform4fv(uniClipRect, 1, (float*)&clip_rect_stack.back()); - clip_rect_dirty = false; - } - glDrawArrays(GL_TRIANGLES, vtx_consumed, cmd.vtx_count); - vtx_consumed += cmd.vtx_count; + glUniform4fv(uniClipRect, 1, (float*)&clip_rect_stack.back()); + glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); + vtx_offset += pcmd->vtx_count; break; case ImDrawCmdType_PushClipRect: - clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]); - clip_rect_dirty = true; + clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_offset++]); break; case ImDrawCmdType_PopClipRect: clip_rect_stack.pop_back(); - clip_rect_dirty = true; break; } } } + + // Cleanup GL state + glBindTexture(GL_TEXTURE_2D, 0); + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glUseProgram(0); } static const char* ImImpl_GetClipboardTextFn() @@ -122,6 +114,7 @@ static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end) if (!text_end) text_end = text + strlen(text); + // Add a zero-terminator because glfw function doesn't take a size char* buf = (char*)malloc(text_end - text + 1); memcpy(buf, text, text_end-text); buf[text_end-text] = '\0'; @@ -283,9 +276,6 @@ void InitImGui() glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); IM_ASSERT(status == GL_TRUE); - uniMVP = glGetUniformLocation(shaderProgram, "MVP"); - uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect"); - // Create Vertex Buffer Objects & Vertex Array Objects glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); @@ -305,6 +295,9 @@ void InitImGui() glEnableVertexAttribArray(colAttrib); err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + // Load font texture glGenTextures(1, &fontTex); glBindTexture(GL_TEXTURE_2D, fontTex); From 28df6f39d9fc9e461c3000c9f9c4e5e52c8f0825 Mon Sep 17 00:00:00 2001 From: Mirolyub Hristov Date: Mon, 11 Aug 2014 21:35:27 +0200 Subject: [PATCH 10/40] Added ImGuiCol_CheckHovered to show hovered checkboxes and radio buttons --- imgui.cpp | 8 +++++--- imgui.h | 1 + 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 449017792..4f3428146 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -227,6 +227,7 @@ ImGuiStyle::ImGuiStyle() 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, 1.00f); 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); @@ -2168,6 +2169,7 @@ const char* GetStyleColorName(ImGuiCol idx) case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_ComboBg: return "ComboBg"; + case ImGuiCol_CheckHovered: return "CheckHovered"; case ImGuiCol_CheckActive: return "CheckActive"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; @@ -3304,8 +3306,6 @@ void Checkbox(const char* label, bool* v) if (ClipAdvance(check_bb)) return; - RenderFrame(check_bb.Min, check_bb.Max, window->Color(ImGuiCol_FrameBg)); - const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(check_bb); const bool pressed = hovered && g.IO.MouseClicked[0]; if (hovered) @@ -3316,6 +3316,8 @@ void Checkbox(const char* label, bool* v) g.ActiveId = 0; // Clear focus } + RenderFrame(check_bb.Min, check_bb.Max, window->Color(hovered ? ImGuiCol_CheckHovered : ImGuiCol_FrameBg)); + if (*v) { window->DrawList->AddRectFilled(check_bb.Min+ImVec2(4,4), check_bb.Max-ImVec2(4,4), window->Color(ImGuiCol_CheckActive)); @@ -3368,7 +3370,7 @@ bool RadioButton(const char* label, bool active) if (hovered) g.HoveredId = id; - window->DrawList->AddCircleFilled(center, radius, window->Color(ImGuiCol_FrameBg), 16); + window->DrawList->AddCircleFilled(center, radius, window->Color(hovered ? ImGuiCol_CheckHovered : ImGuiCol_FrameBg), 16); if (active) window->DrawList->AddCircleFilled(center, radius-2, window->Color(ImGuiCol_CheckActive), 16); diff --git a/imgui.h b/imgui.h index 8f7bf80ca..4e3274610 100644 --- a/imgui.h +++ b/imgui.h @@ -302,6 +302,7 @@ enum ImGuiCol_ ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_ComboBg, + ImGuiCol_CheckHovered, ImGuiCol_CheckActive, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, From 1b330f420e5138dbd24049daa4c115f3959e68ec Mon Sep 17 00:00:00 2001 From: Mirolyub Hristov Date: Mon, 11 Aug 2014 21:43:48 +0200 Subject: [PATCH 11/40] Checkboxes and radio buttons can be clicked on their labels as well as their icon --- imgui.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4f3428146..3e6ce0779 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3303,10 +3303,12 @@ void Checkbox(const char* label, bool* v) const ImGuiAabb text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + text_size); ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight())); - if (ClipAdvance(check_bb)) + const ImGuiAabb total_bb(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); + + if (ClipAdvance(total_bb)) return; - const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(check_bb); + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(total_bb); const bool pressed = hovered && g.IO.MouseClicked[0]; if (hovered) g.HoveredId = id; @@ -3357,7 +3359,9 @@ bool RadioButton(const char* label, bool active) const ImGuiAabb text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + text_size); ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight())); - if (ClipAdvance(check_bb)) + const ImGuiAabb total_bb(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); + + if (ClipAdvance(total_bb)) return false; ImVec2 center = check_bb.GetCenter(); @@ -3365,7 +3369,7 @@ bool RadioButton(const char* label, bool active) center.y = (float)(int)center.y + 0.5f; const float radius = check_bb.GetHeight() * 0.5f; - const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(check_bb); + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(total_bb); const bool pressed = hovered && g.IO.MouseClicked[0]; if (hovered) g.HoveredId = id; From 080eb69e68210facf4f94e91e059fb17b3d028b0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 22:31:45 +0100 Subject: [PATCH 12/40] Removed dependency on limits.h --- imgui.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 449017792..740dc3466 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -158,7 +158,6 @@ #include "imgui.h" #include // toupper -#include // INT_MAX #include // sqrt #include // intptr_t #include // vsnprintf @@ -292,6 +291,12 @@ void ImGuiIO::AddInputCharacter(char c) #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); } @@ -907,8 +912,8 @@ ImGuiWindow::ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_si AutoFitFrames = 3; FocusIdxCounter = -1; - FocusIdxRequestCurrent = INT_MAX; - FocusIdxRequestNext = INT_MAX; + FocusIdxRequestCurrent = IM_INT_MAX; + FocusIdxRequestNext = IM_INT_MAX; DrawList = new ImDrawList(); } @@ -949,7 +954,7 @@ bool ImGuiWindow::FocusItemRegister(bool is_active, int* out_idx) return false; // Process input at this point: TAB, Shift-TAB switch focus - if (FocusIdxRequestNext == INT_MAX && is_active && ImGui::IsKeyPressedMap(ImGuiKey_Tab)) + if (FocusIdxRequestNext == IM_INT_MAX && is_active && ImGui::IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. FocusIdxRequestNext = FocusIdxCounter + (g.IO.KeyShift ? -1 : +1); @@ -1826,9 +1831,9 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin window->ItemWidthDefault = (float)(int)(window->Size.x > 0.0f ? window->Size.x * 0.65f : 250.0f); // Prepare for focus requests - if (window->FocusIdxRequestNext == INT_MAX || window->FocusIdxCounter == -1) + if (window->FocusIdxRequestNext == IM_INT_MAX || window->FocusIdxCounter == -1) { - window->FocusIdxRequestCurrent = INT_MAX; + window->FocusIdxRequestCurrent = IM_INT_MAX; } else { @@ -1836,7 +1841,7 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin window->FocusIdxRequestCurrent = (window->FocusIdxRequestNext + mod) % mod; } window->FocusIdxCounter = -1; - window->FocusIdxRequestNext = INT_MAX; + window->FocusIdxRequestNext = IM_INT_MAX; ImGuiAabb title_bar_aabb = window->TitleBarAabb(); From 4fa623c43be07b3591916d6b077b26d62eb632f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2014 23:07:29 +0100 Subject: [PATCH 13/40] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 876bd29e3..efd9fb0ff 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ImGui is a bloat-free graphical user interface library for C++. It is portable, ImGui is designed to allow programmers to create "content creation" or "debug" tools (as opposed to tools for the average end-user). It favors simplicity and thus lacks certain features normally found in more high-level libraries, such as string localisation. -Usage example: +After ImGui is setup in your application, you can use it like in this example: ![screenshot of sample code alongside its output with ImGui](/web/code_sample_01.png?raw=true) From ab8561e6fc6f9a5fc9b346aeecfd0c03516604ab Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 00:04:13 +0100 Subject: [PATCH 14/40] Tweaked checkbox/radio default hover color to be less distracting. Added GetItemWidth(). Added text filter to style editor. --- imgui.cpp | 19 ++++++++++++++----- imgui.h | 1 + 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c466fce8a..0b00b8495 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -226,7 +226,7 @@ ImGuiStyle::ImGuiStyle() 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, 1.00f); + 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); @@ -2123,6 +2123,12 @@ void PopItemWidth() window->DC.ItemWidth.pop_back(); } +float GetItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.ItemWidth.back(); +} + void PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); @@ -3307,7 +3313,6 @@ void Checkbox(const char* label, bool* v) const ImGuiAabb text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + text_size); ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight())); - const ImGuiAabb total_bb(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); if (ClipAdvance(total_bb)) @@ -3324,7 +3329,6 @@ void Checkbox(const char* label, bool* v) } RenderFrame(check_bb.Min, check_bb.Max, window->Color(hovered ? ImGuiCol_CheckHovered : ImGuiCol_FrameBg)); - if (*v) { window->DrawList->AddRectFilled(check_bb.Min+ImVec2(4,4), check_bb.Max-ImVec2(4,4), window->Color(ImGuiCol_CheckActive)); @@ -3363,7 +3367,6 @@ bool RadioButton(const char* label, bool active) const ImGuiAabb text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + text_size); ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight())); - const ImGuiAabb total_bb(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); if (ClipAdvance(total_bb)) @@ -5146,11 +5149,17 @@ void ShowStyleEditor(ImGuiStyle* ref) ImGui::SameLine(); ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + ImGui::ColorEditMode(edit_mode); for (size_t i = 0; i < ImGuiCol_COUNT; i++) { + const char* name = GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; ImGui::PushID(i); - ImGui::ColorEdit4(GetStyleColorName(i), (float*)&style.Colors[i], true); + ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) { ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : def.Colors[i]; diff --git a/imgui.h b/imgui.h index 4e3274610..88cc02c70 100644 --- a/imgui.h +++ b/imgui.h @@ -145,6 +145,7 @@ namespace ImGui void SetTreeStateStorage(ImGuiStorage* tree); void PushItemWidth(float item_width); void PopItemWidth(); + float GetItemWidth(); void PushAllowKeyboardFocus(bool v); void PopAllowKeyboardFocus(); void PushStyleColor(ImGuiCol idx, ImVec4 col); From 150ad95bd6dcc65589fd548f883d8d3121f58d32 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 00:36:13 +0100 Subject: [PATCH 15/40] Missing assert + comments --- imgui.cpp | 1 + imgui.h | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0b00b8495..1f73d5691 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -694,6 +694,7 @@ public: static ImGuiWindow* GetCurrentWindow() { + IM_ASSERT(GImGui.CurrentWindow != NULL); // ImGui::NewFrame() hasn't been called yet? GImGui.CurrentWindow->Accessed = true; return GImGui.CurrentWindow; } diff --git a/imgui.h b/imgui.h index 88cc02c70..42b1f9cc7 100644 --- a/imgui.h +++ b/imgui.h @@ -391,10 +391,13 @@ struct ImGuiIO bool KeysDown[512]; // Keyboard keys that are pressed (in whatever order user naturally has access to keyboard data) char InputCharacters[16]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. - // Output - Retrieve after calling NewFrame(), you can use them to discard inputs for the rest of your application + // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application bool WantCaptureMouse; // ImGui is using your mouse input (= window is being hovered or widget is active). bool WantCaptureKeyboard; // imGui is using your keyboard input (= widget is active). + // Function + void AddInputCharacter(char c); // Helper to add a new character into InputCharacters[] + // [Internal] ImGui will maintain those fields for you ImVec2 MousePosPrev; ImVec2 MouseDelta; @@ -406,7 +409,6 @@ struct ImGuiIO float KeysDownTime[512]; ImGuiIO(); - void AddInputCharacter(char c); // Helper to add a new character into InputCharacters[] }; //----------------------------------------------------------------------------- From 882554565319321ab428338c5f04271e3820c80b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 11:21:47 +0100 Subject: [PATCH 16/40] Portability fixes to OpenGL example application (courtesy of djoshea) --- examples/opengl_example/main.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index dfad6e345..16920a3d2 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -39,7 +39,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); } glUnmapBuffer(GL_ARRAY_BUFFER); - + // Setup render state: alpha-blending enabled, no face culling, no depth testing glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -55,7 +55,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; - const float mvp[4][4] = + const float mvp[4][4] = { { 2.0f/width, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/-height, 0.0f, 0.0f }, @@ -149,7 +149,7 @@ const GLchar* fragmentSource = "out vec4 o_col;" "void main() {" " o_col = texture(Tex, uv) * col;" - //" if (pixel_pos.x < ClipRect.x || pixel_pos.y < ClipRect.y || pixel_pos.x > ClipRect.z || pixel_pos.y > ClipRect.w) discard;" // Clipping: using discard + //" if (pixel_pos.x < ClipRect.x || pixel_pos.y < ClipRect.y || pixel_pos.x > ClipRect.z || pixel_pos.y > ClipRect.w) discard;" // Clipping: using discard //" if (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w) < 1.0f) discard;" // Clipping: using discard and step " o_col.w *= (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w));" // Clipping: branch-less, set alpha 0.0f "}"; @@ -191,13 +191,13 @@ void InitGL() if (!glfwInit()) exit(1); - //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); - //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_REFRESH_RATE, 60); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); - window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", nullptr, nullptr); + window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, glfw_key_callback); @@ -207,8 +207,10 @@ void InitGL() glewExperimental = GL_TRUE; glewInit(); - GLenum err = GL_NO_ERROR; - err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); + // After calling glewInit() our GL error state may be GL_INVALID_ENUM + const GLenum err = glGetError(); + (void)err; + IM_ASSERT(err == GL_NO_ERROR || err == GL_INVALID_ENUM); } void InitImGui() From e2655d104e14f0523d63b0e6f11da0c368b0a487 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Tue, 12 Aug 2014 14:24:23 +0200 Subject: [PATCH 17/40] add a quick and dirty makefile to build on linux --- examples/opengl_example/Makefile | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 examples/opengl_example/Makefile diff --git a/examples/opengl_example/Makefile b/examples/opengl_example/Makefile new file mode 100644 index 000000000..6fd0b97c0 --- /dev/null +++ b/examples/opengl_example/Makefile @@ -0,0 +1,18 @@ +# +# Quick and dirty makefile to build on Linux +# tested on Ubuntu 14.04.1 32bit +# + +SRC = main.cpp ../../imgui.cpp + +OBJ = $(SRC:.cpp=.o) + +CXXFLAGS = -I../../ `pkg-config --cflags glfw3` + +LIBS = `pkg-config --static --libs glfw3` -lGLEW + +all: $(OBJ) + $(CXX) $(OBJ) $(LIBS) + +clean: + $(RM) -f $(OBJ) From f4ee74b3127347c16a25e3d21b02b6cf43879e12 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 13:55:30 +0100 Subject: [PATCH 18/40] Renamed Makefile --- examples/opengl_example/{Makefile => Makefile.Linux} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename examples/opengl_example/{Makefile => Makefile.Linux} (100%) diff --git a/examples/opengl_example/Makefile b/examples/opengl_example/Makefile.Linux similarity index 100% rename from examples/opengl_example/Makefile rename to examples/opengl_example/Makefile.Linux From 901e9890d4427a26f45c51b442ddf2fc95639ed5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 13:55:43 +0100 Subject: [PATCH 19/40] Removed stray debug code --- imgui.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1f73d5691..3349f91e8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2370,10 +2370,6 @@ void TextUnformatted(const char* text, const char* text_end) pos.y += lines_skipped * line_height; } } - else - { - printf(""); - } // lines to render? if (line < text_end) From a1e176fb07b618e3a4daa127dfc3f92e71fe70d4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 13:59:36 +0100 Subject: [PATCH 20/40] Added Makefile for MacOS X (courtesy of djoshea) --- examples/opengl_example/Makefile.Macosx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 examples/opengl_example/Makefile.Macosx diff --git a/examples/opengl_example/Makefile.Macosx b/examples/opengl_example/Makefile.Macosx new file mode 100644 index 000000000..474208345 --- /dev/null +++ b/examples/opengl_example/Makefile.Macosx @@ -0,0 +1,17 @@ +# This makefile currently only works for mac os +# You should install via homebrew: +# brew install glew +# brew install glfw3 +# + +CXXFLAGS=-framework OpenGL -framework Cocoa -framework IOKit +#CXXFLAGS+=-L/usr/local/Cellar/glew/1.10.0/lib -L/usr/local/Cellar/glfw3/3.0.4/lib +CXXFLAGS+=-lglew -lglfw3 +CXXFLAGS+=-I../../ +CXXFLAGS+= -D__APPLE__ + +main: main.cpp ../../imgui.cpp + $(CXX) $(CXXFLAGS) -o $@ $^ + +clean: + rm main From c938affcac2a5414c818137c2fbffa52d477e515 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Aug 2014 15:09:01 +0100 Subject: [PATCH 21/40] Update README.md Added References --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index efd9fb0ff..5edd82642 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ After ImGui is setup in your application, you can use it like in this example: ImGui outputs vertex buffers and simple command-lists that you can render in your application. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase. - Gallery ------- @@ -20,6 +19,16 @@ Gallery ![screenshot 3](/web/test_window_03.png?raw=true) ![screenshot 4](/web/test_window_04.png?raw=true) +References +---------- + +The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works. +- [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html). +- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf). +- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/). +- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861). + + Credits ------- From 2573ffb6fc2b1ad2136d6984f19440183337aa4e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 19:57:46 +0100 Subject: [PATCH 22/40] Fixed warnings for more stringent compilation settings. Added various small helpers. --- imconfig.h | 4 +- imgui.cpp | 150 ++++++++++++++++++++++++++--------------------------- imgui.h | 15 +++--- 3 files changed, 84 insertions(+), 85 deletions(-) diff --git a/imconfig.h b/imconfig.h index 0a340eea4..60229d70c 100644 --- a/imconfig.h +++ b/imconfig.h @@ -28,7 +28,7 @@ /* namespace ImGui { - void Value(const char* prefix, cosnt MyVec2& v, const char* float_format = NULL); - void Value(const char* prefix, cosnt MyVec4& v, const char* float_format = NULL); + void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL); + void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL); }; */ diff --git a/imgui.cpp b/imgui.cpp index 3349f91e8..168b87dcb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -274,7 +274,7 @@ ImGuiIO::ImGuiIO() // - on Windows you can get those using ToAscii+keyboard state, or via the VM_CHAR message void ImGuiIO::AddInputCharacter(char c) { - const int n = strlen(InputCharacters); + const size_t n = strlen(InputCharacters); if (n < sizeof(InputCharacters) / sizeof(InputCharacters[0])) { InputCharacters[n] = c; @@ -287,7 +287,7 @@ void ImGuiIO::AddInputCharacter(char c) //----------------------------------------------------------------------------- #undef ARRAYSIZE -#define ARRAYSIZE(_ARR) (sizeof(_ARR)/sizeof(*_ARR)) +#define ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #undef PI const float PI = 3.14159265358979323846f; @@ -337,7 +337,7 @@ static const char* ImStristr(const char* haystack, const char* needle, const cha if (!needle_end) needle_end = needle + strlen(needle); - const char un0 = toupper(*needle); + const char un0 = (char)toupper(*needle); while (*haystack) { if (toupper(*haystack) == un0) @@ -382,7 +382,7 @@ static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) int w = vsnprintf(buf, buf_size, fmt, args); va_end(args); buf[buf_size-1] = 0; - if (w == -1) w = buf_size; + if (w == -1) w = (int)buf_size; return w; } @@ -390,7 +390,7 @@ static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_li { int w = vsnprintf(buf, buf_size, fmt, args); buf[buf_size-1] = 0; - if (w == -1) w = buf_size; + if (w == -1) w = (int)buf_size; return w; } @@ -541,7 +541,7 @@ struct ImGuiTextEditState { char Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so own buffer. char InitialText[1024]; // backup of end-user buffer at focusing time, to ESC key can do a revert. Also used for arithmetic operations (but could use a pre-parsed float there). - int MaxLength; // end-user buffer size <= 1024 (or increase above) + size_t BufSize; // end-user buffer size, <= 1024 (or increase above) float Width; // widget width float ScrollX; STB_TexteditState StbState; @@ -555,7 +555,7 @@ struct ImGuiTextEditState 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 = strlen(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } + void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)strlen(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } void OnKeyboardPressed(int key); void UpdateScrollOffset(); @@ -717,7 +717,7 @@ static ImVector::iterator LowerBound(ImVector::iterator first = data.begin(); ImVector::iterator last = data.end(); - int count = last - first; + int count = (int)(last - first); while (count > 0) { int count2 = count / 2; @@ -870,18 +870,20 @@ bool ImGuiTextFilter::PassFilter(const char* val) const //----------------------------------------------------------------------------- -void ImGuiTextBuffer::Append(const char* fmt, ...) +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 + len >= Buf.capacity()) Buf.reserve(Buf.capacity() * 2); - Buf.resize(write_off + len); + Buf.resize(write_off + (size_t)len); va_start(args, fmt); ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args); @@ -1165,7 +1167,7 @@ void NewFrame() else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; - for (int i = 0; i < ARRAYSIZE(g.IO.MouseDown); i++) + for (size_t i = 0; i < 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); @@ -1185,7 +1187,7 @@ void NewFrame() } } } - for (int i = 0; i < ARRAYSIZE(g.IO.KeysDown); i++) + for (size_t i = 0; i < 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 @@ -1303,7 +1305,6 @@ static void AddWindowToSortedBuffer(ImGuiWindow* window, ImVector& static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec4 cr = clip_rect; @@ -1320,7 +1321,6 @@ static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) static void PopClipRect() { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); window->ClipRectStack.pop_back(); window->DrawList->PopClipRect(); @@ -1451,9 +1451,9 @@ static void LogText(const ImVec2& ref_pos, const char* text, const char* text_en else { if (log_new_line || !is_first_line) - g.LogClipboard.Append("\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); + g.LogClipboard.append("\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); else - g.LogClipboard.Append(" %.*s", char_count, text_remaining); + g.LogClipboard.append(" %.*s", char_count, text_remaining); } } @@ -1496,7 +1496,6 @@ static void RenderText(ImVec2 pos, const char* text, const char* text_end, const static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); @@ -1509,7 +1508,6 @@ static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale = 1.0f, bool shadow = false) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = window->FontSize() * 1.00f; @@ -1538,7 +1536,6 @@ static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale = 1.0f, static ImVec2 CalcTextSize(const char* text, const char* text_end, const bool hide_text_after_hash) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); const char* text_display_end; @@ -1556,7 +1553,7 @@ 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[i]; + ImGuiWindow* window = g.Windows[(size_t)i]; if (!window->Visible) continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) @@ -1588,6 +1585,11 @@ static bool IsMouseHoveringBox(const ImGuiAabb& box) return box_for_touch.Contains(g.IO.MousePos); } +bool IsMouseHoveringBox(const ImVec2& box_min, const ImVec2& box_max) +{ + return IsMouseHoveringBox(ImGuiAabb(box_min, box_max)); +} + static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { ImGuiState& g = GImGui; @@ -1631,6 +1633,13 @@ bool IsMouseClicked(int button, bool repeat) return false; } +bool IsMouseDoubleClicked(int button) +{ + ImGuiState& g = GImGui; + IM_ASSERT(button >= 0 && button < ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDoubleClicked[button]; +} + ImVec2 GetMousePos() { return GImGui.IO.MousePos; @@ -1681,7 +1690,7 @@ void BeginChild(const char* str_id, ImVec2 size, bool border, ImGuiWindowFlags e ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); - ImU32 flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ChildWindow; + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ChildWindow; const ImVec2 content_max = window->Pos + ImGui::GetWindowContentRegionMax(); const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); @@ -2084,7 +2093,7 @@ void End() } if (g.LogClipboard.size() > 1) { - g.LogClipboard.Append("\n"); + g.LogClipboard.append("\n"); if (g.IO.SetClipboardTextFn) g.IO.SetClipboardTextFn(g.LogClipboard.begin(), g.LogClipboard.end()); g.LogClipboard.clear(); @@ -2296,21 +2305,24 @@ void SetCursorPos(ImVec2 p) void SetScrollPosHere() { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); window->NextScrollY = (window->DC.CursorPos.y + window->ScrollY) - (window->Pos.y + window->SizeFull.y * 0.5f) - (window->TitleBarHeight() + window->WindowPadding().y); } void SetTreeStateStorage(ImGuiStorage* tree) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.StateStorage = tree ? tree : &window->StateStorage; } +ImGuiStorage* GetTreeStateStorage() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.StateStorage; +} + void TextV(const char* fmt, va_list args) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->Collapsed) return; @@ -2577,7 +2589,6 @@ bool SmallButton(const char* label) static bool CloseWindowButton(bool* open) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiID id = window->GetID("##CLOSE"); @@ -2613,7 +2624,8 @@ void LogToTTY(int max_depth) return; g.LogEnabled = true; g.LogFile = stdout; - g.LogAutoExpandMaxDepth = max_depth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; } void LogToFile(int max_depth, const char* filename) @@ -2621,10 +2633,12 @@ void LogToFile(int max_depth, const char* filename) ImGuiState& g = GImGui; if (g.LogEnabled) return; - IM_ASSERT(filename); + if (!filename) + filename = g.IO.LogFilename; g.LogEnabled = true; g.LogFile = fopen(filename, "at"); - g.LogAutoExpandMaxDepth = max_depth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; } void LogToClipboard(int max_depth) @@ -2634,7 +2648,8 @@ void LogToClipboard(int max_depth) return; g.LogEnabled = true; g.LogFile = NULL; - g.LogAutoExpandMaxDepth = max_depth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; } void LogButtons() @@ -2761,7 +2776,7 @@ void BulletText(const char* fmt, ...) const float line_height = window->FontSize(); const ImVec2 text_size = CalcTextSize(text_begin, text_end); - const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height + (text_size.x ? (g.Style.FramePadding.x*2) : 0.0f),0) + text_size); // Empty text doesn't add padding + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height + (text_size.x > 0.0f ? (g.Style.FramePadding.x*2) : 0.0f),0) + text_size); // Empty text doesn't add padding ItemSize(bb); if (ClipAdvance(bb)) @@ -2775,10 +2790,6 @@ void BulletText(const char* fmt, ...) bool TreeNode(const char* str_id, const char* fmt, ...) { - ImGuiState& g = GImGui; - ImGuiWindow* window = GetCurrentWindow(); - ImGuiStorage* tree = window->DC.StateStorage; - static char buf[1024]; va_list args; va_start(args, fmt); @@ -2800,10 +2811,6 @@ bool TreeNode(const char* str_id, const char* fmt, ...) bool TreeNode(const void* ptr_id, const char* fmt, ...) { - ImGuiState& g = GImGui; - ImGuiWindow* window = GetCurrentWindow(); - ImGuiStorage* tree = window->DC.StateStorage; - static char buf[1024]; va_list args; va_start(args, fmt); @@ -3147,7 +3154,6 @@ bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const return false; const ImGuiStyle& style = g.Style; - const ImVec2 text_size = CalcTextSize(label); bool value_changed = false; @@ -3192,7 +3198,6 @@ static void Plot(ImGuiPlotType plot_type, const char* label, const float* values return; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); const ImVec2 text_size = CalcTextSize(label); if (graph_size.x == 0) @@ -3430,17 +3435,17 @@ static bool is_separator(char c) { return c==',' || c==';' || c=='(' || c==')' | #define STB_TEXTEDIT_IS_SPACE(c) (is_white(c) || is_separator(c)) void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int idx, int n) { char* dst = obj->Text+idx; const char* src = obj->Text+idx+n; while (char c = *src++) *dst++ = c; *dst = '\0'; } -bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int idx, const char* new_text, int new_text_size) +bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int idx, const char* new_text, int new_text_len) { - char* buf_end = obj->Text + obj->MaxLength; - int text_size = strlen(obj->Text); + char* buf_end = obj->Text + obj->BufSize; + const int text_len = (int)strlen(obj->Text); - if (new_text_size > buf_end - (obj->Text + text_size + 1)) + if (new_text_len > buf_end - (obj->Text + text_len + 1)) return false; - memmove(obj->Text + idx + new_text_size, obj->Text + idx, text_size - idx); - memcpy(obj->Text + idx, new_text, new_text_size); - obj->Text[text_size + new_text_size] = 0; + memmove(obj->Text + idx + new_text_len, obj->Text + idx, text_len - idx); + memcpy(obj->Text + idx, new_text, new_text_len); + obj->Text[text_len + new_text_len] = 0; return true; } @@ -3522,7 +3527,7 @@ void ImGuiTextEditState::RenderTextScrolledClipped(ImFont font, float font_size, const float clip_end = (text_end[0] != '\0' && text_end > text_start) ? symbol_w : 0.0f; // Draw text - ImGui::RenderText(pos+ImVec2(clip_begin,0), text_start+(clip_begin?1:0), text_end-(clip_end?1:0), false);//, &text_params_with_clipping); + ImGui::RenderText(pos+ImVec2(clip_begin,0), text_start+(clip_begin>0.0f?1:0), text_end-(clip_end>0.0f?1:0), false);//, &text_params_with_clipping); // Draw the clip symbol const char s[2] = {symbol_c,'\0'}; @@ -3549,7 +3554,7 @@ bool InputFloat(const char* label, float *v, float step, float step_fast, int de ImGui::PushID(label); const float button_sz = window->FontSize(); - if (step) + if (step > 0.0f) ImGui::PushItemWidth(ImMax(1.0f, window->DC.ItemWidth.back() - (button_sz+g.Style.FramePadding.x*2.0f+g.Style.ItemInnerSpacing.x)*2)); char buf[64]; @@ -3563,21 +3568,20 @@ bool InputFloat(const char* label, float *v, float step, float step_fast, int de ApplyNumericalTextInput(buf, v); value_changed = true; } - if (step) - ImGui::PopItemWidth(); - if (step) + if (step > 0.0f) { + ImGui::PopItemWidth(); ImGui::SameLine(0, 0); if (ImGui::Button("-", ImVec2(button_sz,button_sz), true)) { - *v -= g.IO.KeyCtrl && step_fast ? step_fast : step; + *v -= g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; value_changed = true; } ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); if (ImGui::Button("+", ImVec2(button_sz,button_sz), true)) { - *v += g.IO.KeyCtrl && step_fast ? step_fast : step; + *v += g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; value_changed = true; } } @@ -3664,7 +3668,7 @@ bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlag bool cancel_edit = false; if (g.ActiveId == id) { - edit_state.MaxLength = buf_size < ARRAYSIZE(edit_state.Text) ? buf_size : ARRAYSIZE(edit_state.Text); + edit_state.BufSize = buf_size < ARRAYSIZE(edit_state.Text) ? buf_size : ARRAYSIZE(edit_state.Text); edit_state.Font = window->Font(); edit_state.FontSize = window->FontSize(); @@ -3729,7 +3733,7 @@ bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlag if (const char* clipboard = g.IO.GetClipboardTextFn()) { // Remove new-line from pasted buffer - int clipboard_len = strlen(clipboard); + size_t clipboard_len = strlen(clipboard); char* clipboard_filtered = (char*)malloc(clipboard_len+1); int clipboard_filtered_len = 0; for (int i = 0; clipboard[i]; i++) @@ -3832,7 +3836,6 @@ bool InputFloat3(const char* label, float v[3], int decimal_precision) return false; const ImGuiStyle& style = g.Style; - const ImVec2 text_size = CalcTextSize(label); bool value_changed = false; @@ -4083,8 +4086,6 @@ bool ColorEdit4(const char* label, float col[4], bool alpha) const float w_full = window->DC.ItemWidth.back(); const float square_sz = (window->FontSize() + style.FramePadding.x * 2.0f); - const ImVec2 text_size = CalcTextSize(label); - ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; @@ -4206,15 +4207,12 @@ bool ColorEdit4(const char* label, float col[4], bool alpha) void ColorEditMode(ImGuiColorEditMode mode) { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); - window->DC.ColorEditMode = mode; } void Separator() { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->Collapsed) return; @@ -4240,7 +4238,6 @@ void Separator() void Spacing() { - ImGuiState& g = GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->Collapsed) return; @@ -4581,7 +4578,7 @@ void ImDrawList::AddCommand(ImDrawCmdType cmd_type, int vtx_count) // Merge commands if we can, turning them into less draw calls ImDrawCmd* prev = commands.empty() ? NULL : &commands.back(); - if (vtx_count > 0 && prev && prev->cmd_type == (ImU32)cmd_type && prev->vtx_count + vtx_count < VTX_COUNT_MAX) + if (vtx_count > 0 && prev && prev->cmd_type == cmd_type && prev->vtx_count + vtx_count < VTX_COUNT_MAX) prev->vtx_count += vtx_count; else commands.push_back(ImDrawCmd(cmd_type, vtx_count)); @@ -4799,14 +4796,14 @@ void ImDrawList::AddText(ImFont font, float font_size, const ImVec2& pos, ImU32 if (text_end == NULL) text_end = text_begin + strlen(text_begin); - int char_count = text_end - text_begin; + int char_count = (int)(text_end - text_begin); int vtx_count_max = char_count * 6; - int vtx_begin = vtx_buffer.size(); + size_t vtx_begin = vtx_buffer.size(); AddCommand(ImDrawCmdType_DrawTriangleList, vtx_count_max); font->RenderText(font_size, pos, col, clip_rect_stack_.back(), text_begin, text_end, vtx_write_); vtx_buffer.resize(vtx_write_ - &vtx_buffer.front()); - int vtx_count = vtx_buffer.size() - vtx_begin; + int vtx_count = (int)(vtx_buffer.size() - vtx_begin); commands.back().vtx_count -= (vtx_count_max - vtx_count); vtx_write_ -= (vtx_count_max - vtx_count); @@ -4858,7 +4855,7 @@ bool ImBitmapFont::LoadFromFile(const char* filename) fclose(f); return false; } - if (fread(Data, 1, DataSize, f) != DataSize) + if ((int)fread(Data, 1, DataSize, f) != DataSize) { fclose(f); free(Data); @@ -4919,7 +4916,7 @@ bool ImBitmapFont::LoadFromMemory(const void* data, int data_size) void ImBitmapFont::BuildLookupTable() { ImU32 max_c = 0; - for (int i = 0; i != GlyphsCount; i++) + for (size_t i = 0; i != GlyphsCount; i++) if (max_c < Glyphs[i].Id) max_c = Glyphs[i].Id; @@ -4969,7 +4966,8 @@ ImVec2 ImBitmapFont::CalcTextSize(float size, float max_width, const char* text_ if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) { const float char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; - const float char_extend = (glyph->XOffset + glyph->Width * scale); + //const float char_extend = (glyph->XOffset + glyph->Width * scale); + if (line_width + char_width >= max_width) break; line_width += char_width; @@ -5011,8 +5009,6 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c pos.x = (float)(int)pos.x + 0.5f; pos.y = (float)(int)pos.y + 0.5f; - ImVec2 text_size = ImVec2(0,0); - float line_width = 0.0f; const ImVec4 clip_rect = clip_rect_ref; const float uv_offset = GImGui.IO.PixelCenterOffset; @@ -5032,7 +5028,7 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) { const float char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; - const float char_extend = (glyph->XOffset + glyph->Width * scale); + //const float char_extend = (glyph->XOffset + glyph->Width * scale); if (c != ' ' && c != '\n') { @@ -5150,7 +5146,7 @@ void ShowStyleEditor(ImGuiStyle* ref) filter.Draw("Filter colors", 200); ImGui::ColorEditMode(edit_mode); - for (size_t i = 0; i < ImGuiCol_COUNT; i++) + for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = GetStyleColorName(i); if (!filter.PassFilter(name)) @@ -5476,7 +5472,7 @@ void ShowTestWindow(bool* open) static float foo = 1.0f; ImGui::InputFloat("red", &foo, 0.05f, 0, 3); ImGui::NextColumn(); static float bar = 1.0f; - ImGui::InputFloat("blue", &foo, 0.05f, 0, 3); ImGui::NextColumn(); + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); @@ -5536,7 +5532,7 @@ void ShowTestWindow(bool* open) if (ImGui::Button("Add 1000 lines")) { for (size_t i = 0; i < 1000; i++) - log.Append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); lines += 1000; } ImGui::BeginChild("Log"); diff --git a/imgui.h b/imgui.h index 42b1f9cc7..30e474843 100644 --- a/imgui.h +++ b/imgui.h @@ -29,8 +29,8 @@ typedef ImU32 ImGuiID; typedef int ImGuiCol; // enum ImGuiCol_ typedef int ImGuiKey; // enum ImGuiKey_ typedef int ImGuiColorEditMode; // enum ImGuiColorEditMode_ -typedef ImU32 ImGuiWindowFlags; // enum ImGuiWindowFlags_ -typedef ImU32 ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ +typedef int ImGuiWindowFlags; // enum ImGuiWindowFlags_ +typedef int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ typedef ImBitmapFont* ImFont; struct ImVec2 @@ -143,6 +143,7 @@ namespace ImGui void SetFontScale(float scale); void SetScrollPosHere(); void SetTreeStateStorage(ImGuiStorage* tree); + ImGuiStorage* GetTreeStateStorage(); void PushItemWidth(float item_width); void PopItemWidth(); float GetItemWidth(); @@ -221,9 +222,9 @@ namespace ImGui // Logging void LogButtons(); - void LogToTTY(int max_depth); - void LogToFile(int max_depth, const char* filename); - void LogToClipboard(int max_depth); + void LogToTTY(int max_depth = -1); + void LogToFile(int max_depth = -1, const char* filename = NULL); + void LogToClipboard(int max_depth = -1); // Utilities void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). (currently no contention handling, last call win) @@ -232,6 +233,8 @@ namespace ImGui bool IsClipped(ImVec2 item_size); // to perform coarse clipping on user's side (as an optimisation) bool IsKeyPressed(int key_index, bool repeat = true); // key_index into the keys_down[512] array, imgui doesn't know the semantic of each entry bool IsMouseClicked(int button, bool repeat = false); + bool IsMouseDoubleClicked(int button); + bool IsMouseHoveringBox(const ImVec2& box_min, const ImVec2& box_max); ImVec2 GetMousePos(); float GetTime(); int GetFrameCount(); @@ -469,7 +472,7 @@ struct ImGuiTextBuffer size_t size() const { return Buf.size()-1; } bool empty() { return Buf.empty(); } void clear() { Buf.clear(); Buf.push_back(0); } - void Append(const char* fmt, ...); + void append(const char* fmt, ...); }; // Helper: Key->value storage From 57ac561ecb2131d050125b8c61c0e66fadc43d54 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 20:05:10 +0100 Subject: [PATCH 23/40] Minor warning fix + removed unused function parameter. --- imgui.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 168b87dcb..6ed134aea 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -184,7 +184,7 @@ 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, bool skip_columns = false); +static bool ClipAdvance(const ImGuiAabb& aabb); static bool IsMouseHoveringBox(const ImGuiAabb& box); static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); @@ -3414,7 +3414,7 @@ bool RadioButton(const char* label, int* v, int v_button) // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, ASCII, fixed-width font) int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return (int)strlen(obj->Text); } char STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return (char)obj->Text[idx]; } -float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { return obj->Font->CalcTextSize(obj->FontSize, 0, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } +float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { (void)line_start_idx; return obj->Font->CalcTextSize(obj->FontSize, 0, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } char STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : (char)key; } char STB_TEXTEDIT_NEWLINE = '\n'; void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) @@ -4223,7 +4223,7 @@ void Separator() const ImGuiAabb bb(ImVec2(window->Pos.x, window->DC.CursorPos.y), ImVec2(window->Pos.x + window->Size.x, window->DC.CursorPos.y)); ItemSize(ImVec2(0.0f, bb.GetSize().y)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit - if (ClipAdvance(bb, true)) + if (ClipAdvance(bb)) { if (window->DC.ColumnsCount > 1) ImGui::PushColumnClipRect(); @@ -4307,7 +4307,7 @@ bool IsClipped(ImVec2 item_size) return IsClipped(ImGuiAabb(window->DC.CursorPos, window->DC.CursorPos + item_size)); } -static bool ClipAdvance(const ImGuiAabb& bb, bool skip_columns) +static bool ClipAdvance(const ImGuiAabb& bb) { ImGuiWindow* window = GetCurrentWindow(); if (ImGui::IsClipped(bb)) From ddc7f8b0b0dc22c6204078c986e6a6857047d287 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 11:34:08 +0100 Subject: [PATCH 24/40] Simplified ImDrawList system (samples are 20 lines shorter) + merged title bar draw bar. --- examples/directx9_example/main.cpp | 29 +------- examples/opengl_example/main.cpp | 25 +------ imgui.cpp | 114 +++++++++++++++++------------ imgui.h | 20 ++--- 4 files changed, 78 insertions(+), 110 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index a75dd0bcc..eb0966672 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -86,36 +86,15 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c int vtx_offset = 0; for (int n = 0; n < cmd_lists_count; n++) { - // Setup stack of clipping rectangles - int clip_rect_buf_offset = 0; - ImVector clip_rect_stack; - clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); - // Render command list const ImDrawList* cmd_list = cmd_lists[n]; const ImDrawCmd* pcmd_end = cmd_list->commands.end(); for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - switch (pcmd->cmd_type) - { - case ImDrawCmdType_DrawTriangleList: - { - const ImVec4& clip_rect = clip_rect_stack.back(); - const RECT r = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w }; - g_pd3dDevice->SetScissorRect(&r); - g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3); - vtx_offset += pcmd->vtx_count; - } - break; - - case ImDrawCmdType_PushClipRect: - clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_offset++]); - break; - - case ImDrawCmdType_PopClipRect: - clip_rect_stack.pop_back(); - break; - } + const RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w }; + g_pd3dDevice->SetScissorRect(&r); + g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3); + vtx_offset += pcmd->vtx_count; } } } diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index 16920a3d2..cb5b8c4e1 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -68,32 +68,13 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c int vtx_offset = 0; for (int n = 0; n < cmd_lists_count; n++) { - // Setup stack of clipping rectangles - int clip_rect_buf_offset = 0; - ImVector clip_rect_stack; - clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999)); - - // Render command list const ImDrawList* cmd_list = cmd_lists[n]; const ImDrawCmd* pcmd_end = cmd_list->commands.end(); for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - switch (pcmd->cmd_type) - { - case ImDrawCmdType_DrawTriangleList: - glUniform4fv(uniClipRect, 1, (float*)&clip_rect_stack.back()); - glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); - vtx_offset += pcmd->vtx_count; - break; - - case ImDrawCmdType_PushClipRect: - clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_offset++]); - break; - - case ImDrawCmdType_PopClipRect: - clip_rect_stack.pop_back(); - break; - } + glUniform4fv(uniClipRect, 1, (float*)&pcmd->clip_rect); + glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); + vtx_offset += pcmd->vtx_count; } } diff --git a/imgui.cpp b/imgui.cpp index 6ed134aea..e0a49b46e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -978,7 +978,11 @@ 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]; @@ -1801,6 +1805,10 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin if (!(flags & ImGuiWindowFlags_ComboBox)) ImGui::PushClipRect(parent_window->ClipRectStack.back()); } + else + { + ImGui::PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); + } // ID stack window->IDStack.resize(0); @@ -2035,12 +2043,10 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin // Title bar if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) { - ImGui::PushClipRect(ImVec4(window->Pos.x-0.5f, window->Pos.y-0.5f, window->Pos.x+window->Size.x-1.5f, window->Pos.y+window->Size.y-1.5f), false); RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); RenderText(window->Pos + style.FramePadding + ImVec2(window->FontSize() + style.ItemInnerSpacing.x, 0), name); if (open) ImGui::CloseWindowButton(open); - ImGui::PopClipRect(); } } @@ -2070,8 +2076,14 @@ void End() ImGui::Columns(1, "#CloseColumns"); ImGui::PopClipRect(); if (window->Flags & ImGuiWindowFlags_ChildWindow) + { if (!(window->Flags & ImGuiWindowFlags_ComboBox)) ImGui::PopClipRect(); + } + else + { + ImGui::PopClipRect(); + } // Select window for move/focus when we're done with all our widgets ImGuiAabb bb(window->Pos, window->Pos+window->Size); @@ -4544,58 +4556,62 @@ void ImDrawList::Clear() { commands.resize(0); vtx_buffer.resize(0); - clip_rect_buffer.resize(0); - vtx_write_ = NULL; - clip_rect_stack_.resize(0); + vtx_write = NULL; + clip_rect_stack.resize(0); } void ImDrawList::PushClipRect(const ImVec4& clip_rect) { - commands.push_back(ImDrawCmd(ImDrawCmdType_PushClipRect)); - clip_rect_buffer.push_back(clip_rect); - clip_rect_stack_.push_back(clip_rect); + if (!commands.empty() && commands.back().vtx_count == 0) + { + // Reuse empty command because high-level clipping may have discarded the other vertices already + commands.back().clip_rect = clip_rect; + } + else + { + ImDrawCmd draw_cmd; + draw_cmd.vtx_count = 0; + draw_cmd.clip_rect = clip_rect; + commands.push_back(draw_cmd); + } + clip_rect_stack.push_back(clip_rect); } void ImDrawList::PopClipRect() { - if (!commands.empty() && commands.back().cmd_type == ImDrawCmdType_PushClipRect) + clip_rect_stack.pop_back(); + const ImVec4 clip_rect = clip_rect_stack.empty() ? ImVec4(-9999.0f,-9999.0f, +9999.0f, +9999.0f) : clip_rect_stack.back(); + if (!commands.empty() && commands.back().vtx_count == 0) { - // Discard push/pop combo because high-level clipping may have discarded the other draw commands already - commands.pop_back(); - clip_rect_buffer.pop_back(); + // Reuse empty command because high-level clipping may have discarded the other vertices already + commands.back().clip_rect = clip_rect; } else { - commands.push_back(ImDrawCmd(ImDrawCmdType_PopClipRect)); + ImDrawCmd draw_cmd; + draw_cmd.vtx_count = 0; + draw_cmd.clip_rect = clip_rect; + commands.push_back(draw_cmd); } - clip_rect_stack_.pop_back(); } -void ImDrawList::AddCommand(ImDrawCmdType cmd_type, int vtx_count) +void ImDrawList::ReserveVertices(unsigned int vtx_count) { - // Maximum value that can fit in our u16 vtx_count member - const int VTX_COUNT_MAX = (1<<16); - - // Merge commands if we can, turning them into less draw calls - ImDrawCmd* prev = commands.empty() ? NULL : &commands.back(); - if (vtx_count > 0 && prev && prev->cmd_type == cmd_type && prev->vtx_count + vtx_count < VTX_COUNT_MAX) - prev->vtx_count += vtx_count; - else - commands.push_back(ImDrawCmd(cmd_type, vtx_count)); - if (vtx_count > 0) { + ImDrawCmd& draw_cmd = commands.back(); + draw_cmd.vtx_count += vtx_count; vtx_buffer.resize(vtx_buffer.size() + vtx_count); - vtx_write_ = &vtx_buffer[vtx_buffer.size() - vtx_count]; + vtx_write = &vtx_buffer[vtx_buffer.size() - vtx_count]; } } void ImDrawList::AddVtx(const ImVec2& pos, ImU32 col) { - vtx_write_->pos = pos; - vtx_write_->col = col; - vtx_write_->uv = IMDRAW_TEX_UV_FOR_WHITE; - vtx_write_++; + vtx_write->pos = pos; + vtx_write->col = col; + vtx_write->uv = IMDRAW_TEX_UV_FOR_WHITE; + vtx_write++; } void ImDrawList::AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col) @@ -4617,7 +4633,7 @@ void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col) if ((col >> 24) == 0) return; - AddCommand(ImDrawCmdType_DrawTriangleList, 6); + ReserveVertices(6); AddVtxLine(a, b, col); } @@ -4638,7 +4654,7 @@ void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, i if (tris) { - AddCommand(ImDrawCmdType_DrawTriangleList, (a_max-a_min) * 3); + ReserveVertices((a_max-a_min) * 3); for (int a = a_min; a < a_max; a++) { AddVtx(center + circle_vtx[a % ARRAYSIZE(circle_vtx)] * rad, col); @@ -4648,7 +4664,7 @@ void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, i } else { - AddCommand(ImDrawCmdType_DrawTriangleList, (a_max-a_min) * 6); + ReserveVertices((a_max-a_min) * 6); for (int a = a_min; a < a_max; a++) AddVtxLine(center + circle_vtx[a % ARRAYSIZE(circle_vtx)] * rad, center + circle_vtx[(a+1) % ARRAYSIZE(circle_vtx)] * rad, col); } @@ -4666,7 +4682,7 @@ void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float roun if (r == 0.0f || rounding_corners == 0) { - AddCommand(ImDrawCmdType_DrawTriangleList, 4*6); + ReserveVertices(4*6); AddVtxLine(ImVec2(a.x,a.y), ImVec2(b.x,a.y), col); AddVtxLine(ImVec2(b.x,a.y), ImVec2(b.x,b.y), col); AddVtxLine(ImVec2(b.x,b.y), ImVec2(a.x,b.y), col); @@ -4674,7 +4690,7 @@ void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float roun } else { - AddCommand(ImDrawCmdType_DrawTriangleList, 4*6); + ReserveVertices(4*6); AddVtxLine(ImVec2(a.x + ((rounding_corners & 1)?r:0), a.y), ImVec2(b.x - ((rounding_corners & 2)?r:0), a.y), col); AddVtxLine(ImVec2(b.x, a.y + ((rounding_corners & 2)?r:0)), ImVec2(b.x, b.y - ((rounding_corners & 4)?r:0)), col); AddVtxLine(ImVec2(b.x - ((rounding_corners & 4)?r:0), b.y), ImVec2(a.x + ((rounding_corners & 8)?r:0), b.y), col); @@ -4700,7 +4716,7 @@ void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, floa if (r == 0.0f || rounding_corners == 0) { // Use triangle so we can merge more draw calls together (at the cost of extra vertices) - AddCommand(ImDrawCmdType_DrawTriangleList, 6); + ReserveVertices(6); AddVtx(ImVec2(a.x,a.y), col); AddVtx(ImVec2(b.x,a.y), col); AddVtx(ImVec2(b.x,b.y), col); @@ -4710,7 +4726,7 @@ void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, floa } else { - AddCommand(ImDrawCmdType_DrawTriangleList, 6+6*2); + ReserveVertices(6+6*2); AddVtx(ImVec2(a.x+r,a.y), col); AddVtx(ImVec2(b.x-r,a.y), col); AddVtx(ImVec2(b.x-r,b.y), col); @@ -4748,7 +4764,7 @@ void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec if ((col >> 24) == 0) return; - AddCommand(ImDrawCmdType_DrawTriangleList, 3); + ReserveVertices(3); AddVtx(a, col); AddVtx(b, col); AddVtx(c, col); @@ -4759,7 +4775,7 @@ void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int nu if ((col >> 24) == 0) return; - AddCommand(ImDrawCmdType_DrawTriangleList, num_segments*6); + ReserveVertices(num_segments*6); const float a_step = 2*PI/(float)num_segments; float a0 = 0.0f; for (int i = 0; i < num_segments; i++) @@ -4775,7 +4791,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, if ((col >> 24) == 0) return; - AddCommand(ImDrawCmdType_DrawTriangleList, num_segments*3); + ReserveVertices(num_segments*3); const float a_step = 2*PI/(float)num_segments; float a0 = 0.0f; for (int i = 0; i < num_segments; i++) @@ -4796,17 +4812,19 @@ void ImDrawList::AddText(ImFont font, float font_size, const ImVec2& pos, ImU32 if (text_end == NULL) text_end = text_begin + strlen(text_begin); - int char_count = (int)(text_end - text_begin); - int vtx_count_max = char_count * 6; - size_t vtx_begin = vtx_buffer.size(); - AddCommand(ImDrawCmdType_DrawTriangleList, vtx_count_max); + // reserve vertices for worse case + const int char_count = (int)(text_end - text_begin); + const int vtx_count_max = char_count * 6; + const size_t vtx_begin = vtx_buffer.size(); + ReserveVertices(vtx_count_max); - font->RenderText(font_size, pos, col, clip_rect_stack_.back(), text_begin, text_end, vtx_write_); - vtx_buffer.resize(vtx_write_ - &vtx_buffer.front()); - int vtx_count = (int)(vtx_buffer.size() - vtx_begin); + font->RenderText(font_size, pos, col, clip_rect_stack.back(), text_begin, text_end, vtx_write); + // give unused vertices + vtx_buffer.resize(vtx_write - &vtx_buffer.front()); + const int vtx_count = (int)(vtx_buffer.size() - vtx_begin); commands.back().vtx_count -= (vtx_count_max - vtx_count); - vtx_write_ -= (vtx_count_max - vtx_count); + vtx_write -= (vtx_count_max - vtx_count); } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 30e474843..a1e2c87b0 100644 --- a/imgui.h +++ b/imgui.h @@ -499,19 +499,10 @@ struct ImGuiStorage // Hold a series of drawing commands. The user provide a renderer for ImDrawList //----------------------------------------------------------------------------- -enum ImDrawCmdType -{ - ImDrawCmdType_DrawTriangleList, - ImDrawCmdType_PushClipRect, - ImDrawCmdType_PopClipRect, -}; - -// sizeof() == 4 struct ImDrawCmd { - ImDrawCmdType cmd_type : 16; - unsigned int vtx_count : 16; - ImDrawCmd(ImDrawCmdType _cmd_type = ImDrawCmdType_DrawTriangleList, unsigned int _vtx_count = 0) { cmd_type = _cmd_type; vtx_count = _vtx_count; } + unsigned int vtx_count; + ImVec4 clip_rect; }; #ifndef IMDRAW_TEX_UV_FOR_WHITE @@ -532,16 +523,15 @@ struct ImDrawList { ImVector commands; ImVector vtx_buffer; // each command consume ImDrawCmd::vtx_count of those - ImVector clip_rect_buffer; // each PushClipRect command consume 1 of those - ImVector clip_rect_stack_; // [internal] clip rect stack while building the command-list (so text command can perform clipping early on) - ImDrawVert* vtx_write_; // [internal] point within vtx_buffer after each add command. allow us to use less [] and .resize on the vector (often slow on windows/debug) + ImVector clip_rect_stack; // [internal] clip rect stack while building the command-list (so text command can perform clipping early on) + ImDrawVert* vtx_write; // [internal] point within vtx_buffer after each add command (to avoid using the ImVector<> operators too much) ImDrawList() { Clear(); } void Clear(); void PushClipRect(const ImVec4& clip_rect); void PopClipRect(); - void AddCommand(ImDrawCmdType cmd_type, int vtx_count); + void ReserveVertices(unsigned int vtx_count); void AddVtx(const ImVec2& pos, ImU32 col); void AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col); From cb3d50394151b6e5fefcf4d0269940144dc675bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 11:43:51 +0100 Subject: [PATCH 25/40] OpenGL example now use the fixed function-pipeline. Code down by 120 lines. --- examples/opengl_example/main.cpp | 209 ++++++------------------------- 1 file changed, 39 insertions(+), 170 deletions(-) diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index cb5b8c4e1..44d77f5ef 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -2,87 +2,63 @@ #include #include #define STB_IMAGE_IMPLEMENTATION -#include "stb_image.h" // for .png loading +#include "stb_image.h" // for .png loading #include "../../imgui.h" #ifdef _MSC_VER -#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif static GLFWwindow* window; -static GLuint vbo; -static GLuint vao; -static GLuint vertexShader; -static GLuint fragmentShader; -static GLuint shaderProgram; static GLuint fontTex; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer) +// We are using the fixed pipeline. +// A faster way would be to collate all vertices from all cmd_lists into a single vertex buffer static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { - size_t total_vtx_count = 0; - for (int n = 0; n < cmd_lists_count; n++) - total_vtx_count += cmd_lists[n]->vtx_buffer.size(); - if (total_vtx_count == 0) + if (cmd_lists_count == 0) return; - // Copy all vertices into a single contiguous GL buffer - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glBindVertexArray(vao); - glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW); - unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); - if (!buffer_data) - return; - for (int n = 0; n < cmd_lists_count; n++) - { - const ImDrawList* cmd_list = cmd_lists[n]; - memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); - buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert); - } - glUnmapBuffer(GL_ARRAY_BUFFER); - // Setup render state: alpha-blending enabled, no face culling, no depth testing glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); + //glEnable(GL_SCISSOR_TEST); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); - // Bind texture and enable our shader + // Bind texture glBindTexture(GL_TEXTURE_2D, fontTex); - glUseProgram(shaderProgram); - const GLint uniMVP = glGetUniformLocation(shaderProgram, "MVP"); - const GLint uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect"); + glEnable(GL_TEXTURE_2D); - // Setup orthographic projection matrix - const float width = ImGui::GetIO().DisplaySize.x; - const float height = ImGui::GetIO().DisplaySize.y; - const float mvp[4][4] = - { - { 2.0f/width, 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/-height, 0.0f, 0.0f }, - { 0.0f, 0.0f, -1.0f, 0.0f }, - { -1.0f, 1.0f, 0.0f, 1.0f }, - }; - glUniformMatrix4fv(uniMVP, 1, GL_FALSE, &mvp[0][0]); + // Setup matrices + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); // Render command lists - int vtx_offset = 0; for (int n = 0; n < cmd_lists_count; n++) { const ImDrawList* cmd_list = cmd_lists[n]; + const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin(); + glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer)); + glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8)); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16)); + + int vtx_offset = 0; const ImDrawCmd* pcmd_end = cmd_list->commands.end(); for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - glUniform4fv(uniClipRect, 1, (float*)&pcmd->clip_rect); + glScissor((int)pcmd->clip_rect.x, (int)pcmd->clip_rect.y, (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y)); glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); vtx_offset += pcmd->vtx_count; } } - - // Cleanup GL state - glBindTexture(GL_TEXTURE_2D, 0); - glBindVertexArray(0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glUseProgram(0); + glDisable(GL_SCISSOR_TEST); } static const char* ImImpl_GetClipboardTextFn() @@ -103,42 +79,10 @@ static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end) free(buf); } -// Shader sources -const GLchar* vertexSource = - "#version 150 core\n" - "uniform mat4 MVP;" - "in vec2 i_pos;" - "in vec2 i_uv;" - "in vec4 i_col;" - "out vec4 col;" - "out vec2 pixel_pos;" - "out vec2 uv;" - "void main() {" - " col = i_col;" - " pixel_pos = i_pos;" - " uv = i_uv;" - " gl_Position = MVP * vec4(i_pos.x, i_pos.y, 0.0f, 1.0f);" - "}"; - -const GLchar* fragmentSource = - "#version 150 core\n" - "uniform sampler2D Tex;" - "uniform vec4 ClipRect;" - "in vec4 col;" - "in vec2 pixel_pos;" - "in vec2 uv;" - "out vec4 o_col;" - "void main() {" - " o_col = texture(Tex, uv) * col;" - //" if (pixel_pos.x < ClipRect.x || pixel_pos.y < ClipRect.y || pixel_pos.x > ClipRect.z || pixel_pos.y > ClipRect.w) discard;" // Clipping: using discard - //" if (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w) < 1.0f) discard;" // Clipping: using discard and step - " o_col.w *= (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w));" // Clipping: branch-less, set alpha 0.0f - "}"; - // GLFW callbacks to get events static void glfw_error_callback(int error, const char* description) { - fputs(description, stderr); + fputs(description, stderr); } static float mouse_wheel = 0.0f; @@ -169,29 +113,17 @@ void InitGL() { glfwSetErrorCallback(glfw_error_callback); - if (!glfwInit()) - exit(1); + if (!glfwInit()) + exit(1); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - glfwWindowHint(GLFW_REFRESH_RATE, 60); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL); glfwMakeContextCurrent(window); - glfwSetKeyCallback(window, glfw_key_callback); glfwSetScrollCallback(window, glfw_scroll_callback); glfwSetCharCallback(window, glfw_char_callback); - glewExperimental = GL_TRUE; glewInit(); - - // After calling glewInit() our GL error state may be GL_INVALID_ENUM - const GLenum err = glGetError(); - (void)err; - IM_ASSERT(err == GL_NO_ERROR || err == GL_INVALID_ENUM); } void InitImGui() @@ -200,10 +132,10 @@ void InitImGui() glfwGetWindowSize(window, &w, &h); ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions. - io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable) - io.PixelCenterOffset = 0.5f; // Align OpenGL texels - io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. + io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions. + io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable) + io.PixelCenterOffset = 0.5f; // Align OpenGL texels + io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; @@ -225,68 +157,11 @@ void InitImGui() io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; - // Setup graphics backend - GLint status = GL_TRUE; - GLenum err = GL_NO_ERROR; - err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); - - // Create and compile the vertex shader - vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, NULL); - glCompileShader(vertexShader); - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); - if (status != GL_TRUE) - { - char buffer[512]; - glGetShaderInfoLog(vertexShader, 1024, NULL, buffer); - printf("%s", buffer); - IM_ASSERT(status == GL_TRUE); - } - - // Create and compile the fragment shader - fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, NULL); - glCompileShader(fragmentShader); - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); - IM_ASSERT(status == GL_TRUE); - - // Link the vertex and fragment shader into a shader program - shaderProgram = glCreateProgram(); - glAttachShader(shaderProgram, vertexShader); - glAttachShader(shaderProgram, fragmentShader); - glBindFragDataLocation(shaderProgram, 0, "o_col"); - glLinkProgram(shaderProgram); - glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); - IM_ASSERT(status == GL_TRUE); - - // Create Vertex Buffer Objects & Vertex Array Objects - glGenBuffers(1, &vbo); - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glGenVertexArrays(1, &vao); - glBindVertexArray(vao); - - GLint posAttrib = glGetAttribLocation(shaderProgram, "i_pos"); - glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), 0); - glEnableVertexAttribArray(posAttrib); - - GLint uvAttrib = glGetAttribLocation(shaderProgram, "i_uv"); - glEnableVertexAttribArray(uvAttrib); - glVertexAttribPointer(uvAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (void*)(2*sizeof(float))); - - GLint colAttrib = glGetAttribLocation(shaderProgram, "i_col"); - glVertexAttribPointer(colAttrib, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (void*)(4*sizeof(float))); - glEnableVertexAttribArray(colAttrib); - err = glGetError(); IM_ASSERT(err == GL_NO_ERROR); - - glBindVertexArray(0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - // Load font texture glGenTextures(1, &fontTex); glBindTexture(GL_TEXTURE_2D, fontTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); @@ -299,13 +174,6 @@ void InitImGui() void Shutdown() { ImGui::Shutdown(); - - glDeleteProgram(shaderProgram); - glDeleteShader(fragmentShader); - glDeleteShader(vertexShader); - glDeleteBuffers(1, &vbo); - glDeleteVertexArrays(1, &vao); - glfwTerminate(); } @@ -326,10 +194,10 @@ int main(int argc, char** argv) time = current_time; double mouse_x, mouse_y; glfwGetCursorPos(window, &mouse_x, &mouse_y); - io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0; - io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1 + io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1 mouse_wheel = 0.0f; ImGui::NewFrame(); @@ -356,7 +224,7 @@ int main(int argc, char** argv) if (show_test_window) { // More example code in ShowTestWindow() - ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! + ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! ImGui::ShowTestWindow(&show_test_window); } @@ -367,9 +235,10 @@ int main(int argc, char** argv) ImGui::End(); } - // 3) Rendering - glClearColor(0.8f, 0.6f, 0.6f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); + // 3) Rendering + glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); + glClearColor(0.8f, 0.6f, 0.6f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); glfwSwapBuffers(window); From d3ad5ce4754b09a5b237f4743b861ad32ca6fe46 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Aug 2014 13:23:37 +0100 Subject: [PATCH 26/40] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5edd82642..c3f7767d6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ ImGui ===== -ImGui is a bloat-free graphical user interface library for C++. It is portable, renderer agnostic and carries minimal amount of dependencies (only 3 files are needed). It is based on an "immediate" graphical user interface paradigm which allows you to build simple user interfaces with ease. +ImGui is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is portable, renderer agnostic and carries minimal amount of dependencies (only 3 files are needed). It is based on an "immediate" graphical user interface paradigm which allows you to build simple user interfaces with ease. -ImGui is designed to allow programmers to create "content creation" or "debug" tools (as opposed to tools for the average end-user). It favors simplicity and thus lacks certain features normally found in more high-level libraries, such as string localisation. +ImGui is designed to enable fast iteration and allow programmers to create "content creation" or "debug" tools (as opposed to tools for the average end-user). It favors simplicity and thus lacks certain features normally found in more high-level libraries, such as string localisation. -After ImGui is setup in your application, you can use it like in this example: +ImGui is particularly suited to integration in 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard. + +After ImGui is setup in your engine, you can use it like in this example: ![screenshot of sample code alongside its output with ImGui](/web/code_sample_01.png?raw=true) From cc9d63b46a666cdee74c62ca66c9f3a20ac0fc20 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 17:07:57 +0100 Subject: [PATCH 27/40] Fixed columns lines not being pixel aligned --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e0a49b46e..69f2496b1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4442,7 +4442,8 @@ void Columns(int columns_count, const char* id, bool border) // Draw before resize so our items positioning are in sync with the line const ImU32 col = window->Color(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); - window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), col); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, y1), ImVec2(xi, y2), col); if (held) { From c52a54ef4341c2435044d872aa3e1da61ca1d044 Mon Sep 17 00:00:00 2001 From: Dale Kim Date: Wed, 13 Aug 2014 11:57:37 -0500 Subject: [PATCH 28/40] Fix for gcc type qualifier warnings. With -Wall -Wextra -Werror, it is not possible to compile against imgui.h due to const correctness violation in ImVector. --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index a1e2c87b0..e22f4740c 100644 --- a/imgui.h +++ b/imgui.h @@ -85,9 +85,9 @@ public: inline void clear() { if (_data) { _size = _capacity = 0; free(_data); _data = NULL; } } inline iterator begin() { return _data; } - inline const iterator begin() const { return _data; } + inline const_iterator begin() const { return _data; } inline iterator end() { return _data + _size; } - inline const iterator end() const { return _data + _size; } + inline const_iterator end() const { return _data + _size; } inline value_type& front() { return at(0); } inline const value_type& front() const { return at(0); } inline value_type& back() { IM_ASSERT(_size > 0); return at(_size-1); } From 9a426faf4f27ef02b04e35e7da5494a8c374f93c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 18:38:24 +0100 Subject: [PATCH 29/40] Added InputFloat2(), SliderFloat2() --- imgui.cpp | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++----- imgui.h | 2 ++ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 69f2496b1..96399b2a1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -121,7 +121,7 @@ - input number: holding [-]/[+] buttons should increase the step non-linearly - input number: rename Input*() to Input(), Slider*() to Slider() ? - layout: clean up the InputFloat3/SliderFloat3/ColorEdit4 horrible layout code. item width should include frame padding, then we can have a generic horizontal layout helper. - - add input2/4 helper (once above layout helpers are in they'll be smaller) + - add input4 helper (once above layout helpers are in they'll be smaller) - 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 @@ -1036,7 +1036,7 @@ static void LoadSettings() if (fseek(f, 0, SEEK_SET)) return; char* f_data = new char[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 + f_size = (long)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) { @@ -3158,6 +3158,38 @@ bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* disp return changed; } +bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->Collapsed) + return false; + + const ImGuiStyle& style = g.Style; + + bool value_changed = false; + ImGui::PushID(label); + + const int components = 2; + const float w_full = window->DC.ItemWidth.back(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f+style.ItemInnerSpacing.x)*(components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one+style.FramePadding.x*2.0f+style.ItemInnerSpacing.x)*(components-1))); + + ImGui::PushItemWidth(w_item_one); + value_changed |= ImGui::SliderFloat("##X", &v[0], v_min, v_max, display_format, power); + ImGui::SameLine(0, 0); + ImGui::PopItemWidth(); + ImGui::PushItemWidth(w_item_last); + value_changed |= ImGui::SliderFloat("##Y", &v[1], v_min, v_max, display_format, power); + ImGui::SameLine(0, 0); + ImGui::PopItemWidth(); + + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + ImGui::PopID(); + return value_changed; +} + bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = GImGui; @@ -3168,7 +3200,6 @@ bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const const ImGuiStyle& style = g.Style; bool value_changed = false; - ImGui::PushID(label); const int components = 3; @@ -3191,7 +3222,6 @@ bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::PopID(); - return value_changed; } @@ -3840,6 +3870,38 @@ bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlag return value_changed; } +bool InputFloat2(const char* label, float v[2], int decimal_precision) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->Collapsed) + return false; + + const ImGuiStyle& style = g.Style; + + bool value_changed = false; + ImGui::PushID(label); + + const int components = 2; + const float w_full = window->DC.ItemWidth.back(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f+style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one+style.FramePadding.x*2.0f+style.ItemInnerSpacing.x) * (components-1))); + + ImGui::PushItemWidth(w_item_one); + value_changed |= ImGui::InputFloat("##X", &v[0], 0, 0, decimal_precision); + ImGui::SameLine(0, 0); + ImGui::PopItemWidth(); + ImGui::PushItemWidth(w_item_last); + value_changed |= ImGui::InputFloat("##Y", &v[1], 0, 0, decimal_precision); + ImGui::SameLine(0, 0); + ImGui::PopItemWidth(); + + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + ImGui::PopID(); + return value_changed; +} + bool InputFloat3(const char* label, float v[3], int decimal_precision) { ImGuiState& g = GImGui; @@ -3850,7 +3912,6 @@ bool InputFloat3(const char* label, float v[3], int decimal_precision) const ImGuiStyle& style = g.Style; bool value_changed = false; - ImGui::PushID(label); const int components = 3; @@ -3873,7 +3934,6 @@ bool InputFloat3(const char* label, float v[3], int decimal_precision) ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::PopID(); - return value_changed; } @@ -5292,6 +5352,9 @@ void ShowTestWindow(bool* open) ImGui::InputInt("input int", &i0); ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + //static float vec2b[3] = { 0.10f, 0.20f }; + //ImGui::InputFloat2("input float2", vec2b); + static float vec3b[3] = { 0.10f, 0.20f, 0.30f }; ImGui::InputFloat3("input float3", vec3b); @@ -5311,6 +5374,9 @@ void ShowTestWindow(bool* open) static float angle = 0.0f; ImGui::SliderAngle("angle", &angle); + //static float vec2a[3] = { 0.10f, 0.20f }; + //ImGui::SliderFloat2("slider float2", vec2a, 0.0f, 1.0f); + static float vec3a[3] = { 0.10f, 0.20f, 0.30f }; ImGui::SliderFloat3("slider float3", vec3a, 0.0f, 1.0f); @@ -5343,7 +5409,7 @@ void ShowTestWindow(bool* open) phase += 0.10f*values_offset; } } - ImGui::PlotLines("Frame Times", &values.front(), values.size(), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,70)); + ImGui::PlotLines("Frame Times", &values.front(), (int)values.size(), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,70)); ImGui::SameLine(); ImGui::Checkbox("pause", &pause); ImGui::PlotHistogram("Histogram", arr, ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,70)); diff --git a/imgui.h b/imgui.h index e22f4740c..6b44fb7e2 100644 --- a/imgui.h +++ b/imgui.h @@ -183,6 +183,7 @@ namespace ImGui bool SmallButton(const char* label); bool CollapsingHeader(const char* label, const char* str_id = NULL, const bool display_frame = true, const bool default_open = false); bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); bool SliderAngle(const char* label, float* v, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); // *v in radians bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); @@ -193,6 +194,7 @@ namespace ImGui bool RadioButton(const char* label, bool active); bool RadioButton(const char* label, int* v, int v_button); bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1); + bool InputFloat2(const char* label, float v[2], int decimal_precision = -1); bool InputFloat3(const char* label, float v[3], int decimal_precision = -1); bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100); bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0); From b6d1d85d86ccf7a61f025f474c1d664414b82490 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 19:12:50 +0100 Subject: [PATCH 30/40] Fixed scissoring in OpenGL example --- examples/opengl_example/main.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index 44d77f5ef..c26f6cf61 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -24,7 +24,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); - //glEnable(GL_SCISSOR_TEST); + glEnable(GL_SCISSOR_TEST); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); @@ -34,9 +34,11 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c glEnable(GL_TEXTURE_2D); // Setup matrices + const float width = ImGui::GetIO().DisplaySize.x; + const float height = ImGui::GetIO().DisplaySize.y; glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f); + glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); @@ -53,7 +55,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c const ImDrawCmd* pcmd_end = cmd_list->commands.end(); for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++) { - glScissor((int)pcmd->clip_rect.x, (int)pcmd->clip_rect.y, (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y)); + glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y)); glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); vtx_offset += pcmd->vtx_count; } From cda3aecc6ae11af70383d99a3ac013293daa5342 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 19:26:25 +0100 Subject: [PATCH 31/40] Fixed combo box (bug introduced earlier today) + adding bit of vertical padding in combo. --- imgui.cpp | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 96399b2a1..7ff6bd02d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -110,12 +110,13 @@ ISSUES AND TODO-LIST - misc: merge ImVec4 / ImGuiAabb, they are essentially duplicate containers - - 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 - window: autofit is losing its purpose when user relies on any dynamic layout (window width multiplier, column). maybe just discard autofit? - window: support horizontal scroll - window: fix resize grip scaling along with Rounding style setting - 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. - input number: optional range min/max - input number: holding [-]/[+] buttons should increase the step non-linearly @@ -1804,6 +1805,8 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin window->SizeFull = size; if (!(flags & ImGuiWindowFlags_ComboBox)) ImGui::PushClipRect(parent_window->ClipRectStack.back()); + else + ImGui::PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); } else { @@ -2074,16 +2077,8 @@ void End() ImGuiWindow* window = g.CurrentWindow; ImGui::Columns(1, "#CloseColumns"); - ImGui::PopClipRect(); - if (window->Flags & ImGuiWindowFlags_ChildWindow) - { - if (!(window->Flags & ImGuiWindowFlags_ComboBox)) - ImGui::PopClipRect(); - } - else - { - ImGui::PopClipRect(); - } + ImGui::PopClipRect(); // inner window clip rectangle + ImGui::PopClipRect(); // outer window clip rectangle // Select window for move/focus when we're done with all our widgets ImGuiAabb bb(window->Pos, window->Pos+window->Size); @@ -4042,6 +4037,7 @@ bool Combo(const char* label, int* current_item, bool (*items_getter)(void*, int ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); ImGui::BeginChild("#ComboBox", popup_aabb.GetSize(), false, flags); ImGuiWindow* child_window = GetCurrentWindow(); + ImGui::Spacing(); bool combo_item_active = false; combo_item_active |= (g.ActiveId == child_window->GetID("#SCROLLY")); From 7a3e6aa38de83211e583b5bd604466bc1d0f99ee Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 19:53:26 +0100 Subject: [PATCH 32/40] Default Clipboard functions on Windows+ renamed ARRAYSIZE to IM_ARRAYSIZE --- examples/directx9_example/main.cpp | 51 ---------- imconfig.h | 13 ++- imgui.cpp | 150 ++++++++++++++++++++++------- 3 files changed, 122 insertions(+), 92 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index eb0966672..0b09c82cd 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -99,55 +99,6 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c } } -// Get text data in Win32 clipboard -static const char* ImImpl_GetClipboardTextFn() -{ - static char* buf_local = NULL; - if (buf_local) - { - free(buf_local); - buf_local = NULL; - } - - if (!OpenClipboard(NULL)) - return NULL; - - HANDLE buf_handle = GetClipboardData(CF_TEXT); - if (buf_handle == NULL) - return NULL; - - if (char* buf_global = (char*)GlobalLock(buf_handle)) - buf_local = strdup(buf_global); - GlobalUnlock(buf_handle); - CloseClipboard(); - - return buf_local; -} - -// Set text data in Win32 clipboard -static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end) -{ - if (!OpenClipboard(NULL)) - return; - - if (!text_end) - text_end = text + strlen(text); - - const int buf_length = (text_end - text) + 1; - HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, buf_length * sizeof(char)); - if (buf_handle == NULL) - return; - - char* buf_global = (char *)GlobalLock(buf_handle); - memcpy(buf_global, text, text_end - text); - buf_global[text_end - text] = 0; - GlobalUnlock(buf_handle); - - EmptyClipboard(); - SetClipboardData(CF_TEXT, buf_handle); - CloseClipboard(); -} - HRESULT InitD3D(HWND hWnd) { if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION))) @@ -250,8 +201,6 @@ void InitImGui() io.KeyMap[ImGuiKey_Z] = 'Z'; io.RenderDrawListsFn = ImImpl_RenderDrawLists; - io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; - io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // Create the vertex buffer if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) diff --git a/imconfig.h b/imconfig.h index 60229d70c..f5d971ee1 100644 --- a/imconfig.h +++ b/imconfig.h @@ -4,15 +4,18 @@ #pragma once -//----- Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h +// Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h //#include //#define ImVector std::vector //#define ImVector MyVector -//----- Define assertion handler. Default to calling assert(). +// Define assertion handler. Default to calling assert(). // #define IM_ASSERT(_EXPR) MyAssert(_EXPR) -//----- Define implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. +// Tell ImGui to not implement default clipboard handlers for Windows (so as not to link with OpenClipboard(), etc.) +// #define IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS + +// Define implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ @@ -23,8 +26,8 @@ operator MyVec4() const { return MyVec4(x,y,z,w); } */ -//----- Freely implement extra functions within the ImGui:: namespace. -//----- e.g. you can create variants of the ImGui::Value() helper for your low-level math types. +// Freely implement extra functions within the ImGui:: namespace. +// e.g. you can create variants of the ImGui::Value() helper for your low-level math types. /* namespace ImGui { diff --git a/imgui.cpp b/imgui.cpp index 7ff6bd02d..adca912f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -196,6 +196,17 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); }; // namespace ImGui +//----------------------------------------------------------------------------- +// Platform dependant helpers +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS +static const char* GetClipboardTextFn_DefaultImplWindows(); +static void SetClipboardTextFn_DefaultImplWindows(const char* text, const char* text_end); +#endif +#endif + //----------------------------------------------------------------------------- // User facing structures //----------------------------------------------------------------------------- @@ -268,6 +279,14 @@ ImGuiIO::ImGuiIO() MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; + + // Platform dependant default implementations +#ifdef _MSC_VER +#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS + GetClipboardTextFn = GetClipboardTextFn_DefaultImplWindows; + SetClipboardTextFn = SetClipboardTextFn_DefaultImplWindows; +#endif +#endif } // Pass in translated ASCII characters for text input. @@ -287,8 +306,7 @@ void ImGuiIO::AddInputCharacter(char c) // Helpers //----------------------------------------------------------------------------- -#undef ARRAYSIZE -#define ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #undef PI const float PI = 3.14159265358979323846f; @@ -795,7 +813,7 @@ void ImGuiTextFilter::Draw(const char* label, float width) width = ImMax(window->Pos.x + ImGui::GetWindowContentRegionMax().x - window->DC.CursorPos.x - (label_size.x + GImGui.Style.ItemSpacing.x*4), 10.0f); } ImGui::PushItemWidth(width); - ImGui::InputText(label, InputBuf, ARRAYSIZE(InputBuf)); + ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); ImGui::PopItemWidth(); Build(); } @@ -1057,7 +1075,7 @@ static void LoadSettings() if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') { char name[64]; - ImFormatString(name, ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); settings = FindWindowSettings(name); } else if (settings) @@ -1172,7 +1190,7 @@ void NewFrame() else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; - for (size_t i = 0; i < ARRAYSIZE(g.IO.MouseDown); i++) + 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); @@ -1192,7 +1210,7 @@ void NewFrame() } } } - for (size_t i = 0; i < ARRAYSIZE(g.IO.KeysDown); i++) + 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 @@ -1605,7 +1623,7 @@ static bool IsKeyPressedMap(ImGuiKey key, bool repeat) bool IsKeyPressed(int key_index, bool repeat) { ImGuiState& g = GImGui; - IM_ASSERT(key_index >= 0 && key_index < ARRAYSIZE(g.IO.KeysDown)); + 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; @@ -1623,7 +1641,7 @@ bool IsKeyPressed(int key_index, bool repeat) bool IsMouseClicked(int button, bool repeat) { ImGuiState& g = GImGui; - IM_ASSERT(button >= 0 && button < ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownTime[button]; if (t == 0.0f) return true; @@ -1641,7 +1659,7 @@ bool IsMouseClicked(int button, bool repeat) bool IsMouseDoubleClicked(int button) { ImGuiState& g = GImGui; - IM_ASSERT(button >= 0 && button < ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } @@ -1661,7 +1679,7 @@ void SetTooltip(const char* fmt, ...) ImGuiState& g = GImGui; va_list args; va_start(args, fmt); - ImFormatStringV(g.Tooltip, ARRAYSIZE(g.Tooltip), fmt, args); + ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); va_end(args); } @@ -1714,7 +1732,7 @@ void BeginChild(const char* str_id, ImVec2 size, bool border, ImGuiWindowFlags e flags |= extra_flags; char title[256]; - ImFormatString(title, ARRAYSIZE(title), "%s.%s", window->Name, str_id); + 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); @@ -2335,7 +2353,7 @@ void TextV(const char* fmt, va_list args) return; static char buf[1024]; - const char* text_end = buf + ImFormatStringV(buf, ARRAYSIZE(buf), fmt, args); + const char* text_end = buf + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); TextUnformatted(buf, text_end); } @@ -2470,7 +2488,7 @@ void LabelText(const char* label, const char* fmt, ...) va_list args; va_start(args, fmt); const char* text_begin = &buf[0]; - const char* text_end = text_begin + ImFormatStringV(buf, ARRAYSIZE(buf), fmt, args); + const char* text_end = text_begin + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); va_end(args); const ImVec2 text_size = CalcTextSize(label); @@ -2778,7 +2796,7 @@ void BulletText(const char* fmt, ...) va_list args; va_start(args, fmt); const char* text_begin = buf; - const char* text_end = text_begin + ImFormatStringV(buf, ARRAYSIZE(buf), fmt, args); + const char* text_end = text_begin + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); va_end(args); const float line_height = window->FontSize(); @@ -2800,7 +2818,7 @@ bool TreeNode(const char* str_id, const char* fmt, ...) static char buf[1024]; va_list args; va_start(args, fmt); - ImFormatStringV(buf, ARRAYSIZE(buf), fmt, args); + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); va_end(args); if (!str_id || !str_id[0]) @@ -2821,7 +2839,7 @@ bool TreeNode(const void* ptr_id, const char* fmt, ...) static char buf[1024]; va_list args; va_start(args, fmt); - ImFormatStringV(buf, ARRAYSIZE(buf), fmt, args); + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); va_end(args); if (!ptr_id) @@ -3014,12 +3032,12 @@ bool SliderFloat(const char* label, float* v, float v_min, float v_max, const ch if (start_text_input || (g.ActiveId == id && id == g.SliderAsInputTextId)) { char text_buf[64]; - ImFormatString(text_buf, ARRAYSIZE(text_buf), "%.*f", decimal_precision, *v); + ImFormatString(text_buf, IM_ARRAYSIZE(text_buf), "%.*f", decimal_precision, *v); g.ActiveId = g.SliderAsInputTextId; g.HoveredId = 0; window->FocusItemUnregister(); // Our replacement slider will override the focus ID (that we needed to declare previously to allow for a TAB focus to happen before we got selected) - value_changed = ImGui::InputText(label, text_buf, ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_AlignCenter); + value_changed = ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_AlignCenter); if (g.SliderAsInputTextId == 0) { // First frame @@ -3127,7 +3145,7 @@ bool SliderFloat(const char* label, float* v, float v_min, float v_max, const ch } char value_buf[64]; - ImFormatString(value_buf, ARRAYSIZE(value_buf), display_format, *v); + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderText(ImVec2(slider_bb.GetCenter().x-CalcTextSize(value_buf).x*0.5f, frame_bb.Min.y + style.FramePadding.y), value_buf); RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, slider_bb.Min.y), label); @@ -3596,11 +3614,11 @@ bool InputFloat(const char* label, float *v, float step, float step_fast, int de char buf[64]; if (decimal_precision < 0) - ImFormatString(buf, ARRAYSIZE(buf), "%f", *v); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? + ImFormatString(buf, IM_ARRAYSIZE(buf), "%f", *v); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? else - ImFormatString(buf, ARRAYSIZE(buf), "%.*f", decimal_precision, *v); + ImFormatString(buf, IM_ARRAYSIZE(buf), "%.*f", decimal_precision, *v); bool value_changed = false; - if (ImGui::InputText("", buf, ARRAYSIZE(buf), ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AlignCenter|ImGuiInputTextFlags_AutoSelectAll)) + if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AlignCenter|ImGuiInputTextFlags_AutoSelectAll)) { ApplyNumericalTextInput(buf, v); value_changed = true; @@ -3705,7 +3723,7 @@ bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlag bool cancel_edit = false; if (g.ActiveId == id) { - edit_state.BufSize = buf_size < ARRAYSIZE(edit_state.Text) ? buf_size : ARRAYSIZE(edit_state.Text); + edit_state.BufSize = buf_size < IM_ARRAYSIZE(edit_state.Text) ? buf_size : IM_ARRAYSIZE(edit_state.Text); edit_state.Font = window->Font(); edit_state.FontSize = window->FontSize(); @@ -3788,7 +3806,7 @@ bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlag else if (g.IO.InputCharacters[0]) { // Text input - for (int n = 0; n < ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) + for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) { const char c = g.IO.InputCharacters[n]; if (c) @@ -4220,7 +4238,7 @@ bool ColorEdit4(const char* label, float col[4], bool alpha) else sprintf(buf, "#%02X%02X%02X", ix, iy, iz); ImGui::PushItemWidth(w_slider_all - g.Style.ItemInnerSpacing.x); - value_changed |= ImGui::InputText("##Text", buf, ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal); + value_changed |= ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal); ImGui::PopItemWidth(); char* p = buf; while (*p == '#' || *p == ' ' || *p == '\t') @@ -4700,9 +4718,9 @@ void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, i static bool circle_vtx_builds = false; if (!circle_vtx_builds) { - for (int i = 0; i < ARRAYSIZE(circle_vtx); i++) + for (int i = 0; i < IM_ARRAYSIZE(circle_vtx); i++) { - const float a = ((float)i / (float)ARRAYSIZE(circle_vtx)) * 2*PI; + const float a = ((float)i / (float)IM_ARRAYSIZE(circle_vtx)) * 2*PI; circle_vtx[i].x = cos(a + PI); circle_vtx[i].y = sin(a + PI); } @@ -4714,8 +4732,8 @@ void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, i ReserveVertices((a_max-a_min) * 3); for (int a = a_min; a < a_max; a++) { - AddVtx(center + circle_vtx[a % ARRAYSIZE(circle_vtx)] * rad, col); - AddVtx(center + circle_vtx[(a+1) % ARRAYSIZE(circle_vtx)] * rad, col); + AddVtx(center + circle_vtx[a % IM_ARRAYSIZE(circle_vtx)] * rad, col); + AddVtx(center + circle_vtx[(a+1) % IM_ARRAYSIZE(circle_vtx)] * rad, col); AddVtx(center + third_point_offset, col); } } @@ -4723,7 +4741,7 @@ void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, i { ReserveVertices((a_max-a_min) * 6); for (int a = a_min; a < a_max; a++) - AddVtxLine(center + circle_vtx[a % ARRAYSIZE(circle_vtx)] * rad, center + circle_vtx[(a+1) % ARRAYSIZE(circle_vtx)] * rad, col); + AddVtxLine(center + circle_vtx[a % IM_ARRAYSIZE(circle_vtx)] * rad, center + circle_vtx[(a+1) % IM_ARRAYSIZE(circle_vtx)] * rad, col); } } @@ -5161,6 +5179,66 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c } } +//----------------------------------------------------------------------------- +// PLATFORM DEPENDANT HELPERS +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS + +#define WIN32_LEAN_AND_MEAN +#include + +static const char* GetClipboardTextFn_DefaultImplWindows() +{ + static char* buf_local = NULL; + if (buf_local) + { + free(buf_local); + buf_local = NULL; + } + + if (!OpenClipboard(NULL)) + return NULL; + + HANDLE buf_handle = GetClipboardData(CF_TEXT); + if (buf_handle == NULL) + return NULL; + + if (char* buf_global = (char*)GlobalLock(buf_handle)) + buf_local = strdup(buf_global); + GlobalUnlock(buf_handle); + CloseClipboard(); + + return buf_local; +} + +static void SetClipboardTextFn_DefaultImplWindows(const char* text, const char* text_end) +{ + if (!OpenClipboard(NULL)) + return; + + if (!text_end) + text_end = text + strlen(text); + + const int buf_length = (text_end - text) + 1; + HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, buf_length * sizeof(char)); + if (buf_handle == NULL) + return; + + char* buf_global = (char *)GlobalLock(buf_handle); + memcpy(buf_global, text, text_end - text); + buf_global[text_end - text] = 0; + GlobalUnlock(buf_handle); + + EmptyClipboard(); + SetClipboardData(CF_TEXT, buf_handle); + CloseClipboard(); +} + +#endif // #ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS +#endif // #ifdef _MSC_VER + //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- @@ -5339,12 +5417,12 @@ void ShowTestWindow(bool* open) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; static int item2 = -1; - ImGui::Combo("combo scroll", &item2, items, ARRAYSIZE(items)); + ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); static char str0[128] = "Hello, world!"; static int i0=123; static float f0=0.001f; - ImGui::InputText("string", str0, ARRAYSIZE(str0)); + ImGui::InputText("string", str0, IM_ARRAYSIZE(str0)); ImGui::InputInt("input int", &i0); ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); @@ -5387,7 +5465,7 @@ void ShowTestWindow(bool* open) if (ImGui::CollapsingHeader("Graphs widgets")) { static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Frame Times", arr, ARRAYSIZE(arr)); + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); static bool pause; static ImVector values; if (values.empty()) { values.resize(100); memset(&values.front(), 0, values.size()*sizeof(float)); } @@ -5408,7 +5486,7 @@ void ShowTestWindow(bool* open) ImGui::PlotLines("Frame Times", &values.front(), (int)values.size(), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,70)); ImGui::SameLine(); ImGui::Checkbox("pause", &pause); - ImGui::PlotHistogram("Histogram", arr, ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,70)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,70)); } if (ImGui::CollapsingHeader("Widgets on same line")) @@ -5498,7 +5576,7 @@ void ShowTestWindow(bool* open) for (int i = 0; i < 100; i++) { char buf[32]; - ImFormatString(buf, ARRAYSIZE(buf), "%08x", i*5731); + ImFormatString(buf, IM_ARRAYSIZE(buf), "%08x", i*5731); ImGui::Button(buf); ImGui::NextColumn(); } @@ -5597,7 +5675,7 @@ void ShowTestWindow(bool* open) static ImGuiTextFilter filter; filter.Draw(); const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (size_t i = 0; i < ARRAYSIZE(lines); i++) + for (size_t i = 0; i < IM_ARRAYSIZE(lines); i++) if (filter.PassFilter(lines[i])) ImGui::BulletText("%s", lines[i]); } From 530f103dfebbeb4af28176e692ba197599c6f21a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2014 23:57:14 +0100 Subject: [PATCH 33/40] Tweak MacOS X Makefile for likely scenario --- examples/opengl_example/Makefile.Macosx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/opengl_example/Makefile.Macosx b/examples/opengl_example/Makefile.Macosx index 474208345..44ffe158d 100644 --- a/examples/opengl_example/Makefile.Macosx +++ b/examples/opengl_example/Makefile.Macosx @@ -5,7 +5,8 @@ # CXXFLAGS=-framework OpenGL -framework Cocoa -framework IOKit -#CXXFLAGS+=-L/usr/local/Cellar/glew/1.10.0/lib -L/usr/local/Cellar/glfw3/3.0.4/lib +CXXFLAGS+=-I/usr/local/Cellar/glew/1.10.0/include -I/usr/local/Cellar/glfw3/3.0.4/include +CXXFLAGS+=-L/usr/local/Cellar/glew/1.10.0/lib -L/usr/local/Cellar/glfw3/3.0.4/lib CXXFLAGS+=-lglew -lglfw3 CXXFLAGS+=-I../../ CXXFLAGS+= -D__APPLE__ From 29863b55efe60be734c266e198481de480f77a1e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2014 23:25:42 +0100 Subject: [PATCH 34/40] Fixed logarithmic sliders and HSV conversions on Mac/Linux Tricky bug, I was calling abs() which resolve to abs(float) under Windows with the include we have, but abs(int) under Mac/Linux --- imgui.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index adca912f6..e2c66f7da 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -439,7 +439,7 @@ static void ImConvertColorRGBtoHSV(float r, float g, float b, float& out_h, floa } const float chroma = r - (g < b ? g : b); - out_h = abs(K + (g - b) / (6.f * chroma + 1e-20f)); + out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } @@ -2999,8 +2999,8 @@ bool SliderFloat(const char* label, float* v, float v_min, float v_max, const ch if (v_min * v_max < 0.0f) { // Different sign - const float linear_dist_min_to_0 = powf(abs(0.0f - v_min), 1.0f/power); - const float linear_dist_max_to_0 = powf(abs(v_max - 0.0f), 1.0f/power); + const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); + const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); } else @@ -3070,7 +3070,7 @@ bool SliderFloat(const char* label, float* v, float v_min, float v_max, const ch if (!is_unbound) { const float normalized_pos = ImClamp((g.IO.MousePos.x - slider_effective_x1) / slider_effective_w, 0.0f, 1.0f); - + // Linear slider //float new_value = ImLerp(v_min, v_max, normalized_pos); @@ -3086,9 +3086,11 @@ bool SliderFloat(const char* label, float* v, float v_min, float v_max, const ch else { // Positive: rescale to the positive range before powering - float a = normalized_pos; - if (abs(linear_zero_pos - 1.0f) > 1.e-6) - a = (a - linear_zero_pos) / (1.0f - linear_zero_pos); + float a; + if (fabsf(linear_zero_pos - 1.0f) > 1.e-6) + a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = normalized_pos; a = powf(a, power); new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); } @@ -4750,10 +4752,10 @@ void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float roun if ((col >> 24) == 0) return; - //const float r = ImMin(rounding, ImMin(abs(b.x-a.x), abs(b.y-a.y))*0.5f); + //const float r = ImMin(rounding, ImMin(fabsf(b.x-a.x), fabsf(b.y-a.y))*0.5f); float r = rounding; - r = ImMin(r, abs(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, abs(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); if (r == 0.0f || rounding_corners == 0) { @@ -4783,10 +4785,10 @@ void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, floa if ((col >> 24) == 0) return; - //const float r = ImMin(rounding, ImMin(abs(b.x-a.x), abs(b.y-a.y))*0.5f); + //const float r = ImMin(rounding, ImMin(fabsf(b.x-a.x), fabsf(b.y-a.y))*0.5f); float r = rounding; - r = ImMin(r, abs(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, abs(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); if (r == 0.0f || rounding_corners == 0) { From 46eee0cee479adc2de442a51eadfe695b8dfd95b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 00:01:41 +0100 Subject: [PATCH 35/40] Tidying up example applications so it looks easier to just grab code --- examples/directx9_example/main.cpp | 181 ++++++++++++++++------------- examples/opengl_example/main.cpp | 85 ++++++++------ 2 files changed, 151 insertions(+), 115 deletions(-) diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp index 0b09c82cd..3036eb759 100644 --- a/examples/directx9_example/main.cpp +++ b/examples/directx9_example/main.cpp @@ -220,6 +220,35 @@ void InitImGui() } } +INT64 ticks_per_second = 0; +INT64 time = 0; + +void UpdateImGui() +{ + ImGuiIO& io = ImGui::GetIO(); + + // Setup timestep + INT64 current_time; + QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); + io.DeltaTime = (float)(current_time - time) / ticks_per_second; + time = current_time; + + // Setup inputs + // (we already got mouse position, buttons, wheel from the window message callback) + BYTE keystate[256]; + GetKeyboardState(keystate); + for (int i = 0; i < 256; i++) + io.KeysDown[i] = (keystate[i] & 0x80) != 0; + io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0; + io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0; + // io.MousePos : filled by WM_MOUSEMOVE event + // io.MouseDown : filled by WM_*BUTTON* events + // io.MouseWheel : filled by WM_MOUSEWHEEL events + + // Start the frame + ImGui::NewFrame(); +} + int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int) { // Register the window class @@ -229,101 +258,91 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int) // Create the application's window hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); - INT64 ticks_per_second, time; if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second)) return 1; if (!QueryPerformanceCounter((LARGE_INTEGER *)&time)) return 1; // Initialize Direct3D - if (InitD3D(hWnd) >= 0) + if (InitD3D(hWnd) < 0) + { + if (g_pVB) + g_pVB->Release(); + UnregisterClass(L"ImGui Example", wc.hInstance); + return 1; + } + + // Show the window + ShowWindow(hWnd, SW_SHOWDEFAULT); + UpdateWindow(hWnd); + + InitImGui(); + + // Enter the message loop + MSG msg; + ZeroMemory(&msg, sizeof(msg)); + while (msg.message != WM_QUIT) { - // Show the window - ShowWindow(hWnd, SW_SHOWDEFAULT); - UpdateWindow(hWnd); - - InitImGui(); - - // Enter the message loop - MSG msg; - ZeroMemory(&msg, sizeof(msg)); - while (msg.message != WM_QUIT) + if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { - if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - continue; - } + TranslateMessage(&msg); + DispatchMessage(&msg); + continue; + } - // 1) ImGui start frame, setup time delta & inputs - ImGuiIO& io = ImGui::GetIO(); - INT64 current_time; - QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); - io.DeltaTime = (float)(current_time - time) / ticks_per_second; - time = current_time; - BYTE keystate[256]; - GetKeyboardState(keystate); - for (int i = 0; i < 256; i++) - io.KeysDown[i] = (keystate[i] & 0x80) != 0; - io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0; - io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0; - // io.MousePos : filled by WM_MOUSEMOVE event - // io.MouseDown : filled by WM_*BUTTON* events - // io.MouseWheel : filled by WM_MOUSEWHEEL events - ImGui::NewFrame(); + UpdateImGui(); - // 2) ImGui usage - static bool show_test_window = true; - static bool show_another_window = false; - static float f; - ImGui::Text("Hello, world!"); - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); - show_test_window ^= ImGui::Button("Test Window"); - show_another_window ^= ImGui::Button("Another Window"); + // Create a simple window + // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" + static bool show_test_window = true; + static bool show_another_window = false; + static float f; + ImGui::Text("Hello, world!"); + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); + show_test_window ^= ImGui::Button("Test Window"); + show_another_window ^= ImGui::Button("Another Window"); - // Calculate and show framerate - static float ms_per_frame[120] = { 0 }; - static int ms_per_frame_idx = 0; - static float ms_per_frame_accum = 0.0f; - ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx]; - ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f; - ms_per_frame_accum += ms_per_frame[ms_per_frame_idx]; - ms_per_frame_idx = (ms_per_frame_idx + 1) % 120; - const float ms_per_frame_avg = ms_per_frame_accum / 120; - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg); + // Calculate and show framerate + static float ms_per_frame[120] = { 0 }; + static int ms_per_frame_idx = 0; + static float ms_per_frame_accum = 0.0f; + ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx]; + ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f; + ms_per_frame_accum += ms_per_frame[ms_per_frame_idx]; + ms_per_frame_idx = (ms_per_frame_idx + 1) % 120; + const float ms_per_frame_avg = ms_per_frame_accum / 120; + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg); - if (show_test_window) - { - // More example code in ShowTestWindow() - ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! - ImGui::ShowTestWindow(&show_test_window); - } - - if (show_another_window) - { - ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100)); - ImGui::Text("Hello"); - ImGui::End(); - } - - // 3) Rendering - // Clear frame buffer - g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); - g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); - g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); - g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0); - if (g_pd3dDevice->BeginScene() >= 0) - { - // Render ImGui - ImGui::Render(); - g_pd3dDevice->EndScene(); - } - g_pd3dDevice->Present(NULL, NULL, NULL, NULL); + // Show the ImGui test window + // Most of user example code is in ImGui::ShowTestWindow() + if (show_test_window) + { + ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! + ImGui::ShowTestWindow(&show_test_window); } - ImGui::Shutdown(); - } + // Show another simple window + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100)); + ImGui::Text("Hello"); + ImGui::End(); + } + + // Rendering + g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); + g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); + g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); + g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0); + if (g_pd3dDevice->BeginScene() >= 0) + { + ImGui::Render(); + g_pd3dDevice->EndScene(); + } + g_pd3dDevice->Present(NULL, NULL, NULL, NULL); + } + + ImGui::Shutdown(); if (g_pVB) g_pVB->Release(); diff --git a/examples/opengl_example/main.cpp b/examples/opengl_example/main.cpp index c26f6cf61..609021eaa 100644 --- a/examples/opengl_example/main.cpp +++ b/examples/opengl_example/main.cpp @@ -19,7 +19,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c if (cmd_lists_count == 0) return; - // Setup render state: alpha-blending enabled, no face culling, no depth testing + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); @@ -29,11 +29,11 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); - // Bind texture + // Setup texture glBindTexture(GL_TEXTURE_2D, fontTex); glEnable(GL_TEXTURE_2D); - // Setup matrices + // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; glMatrixMode(GL_PROJECTION); @@ -73,24 +73,33 @@ static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end) if (!text_end) text_end = text + strlen(text); - // Add a zero-terminator because glfw function doesn't take a size - char* buf = (char*)malloc(text_end - text + 1); - memcpy(buf, text, text_end-text); - buf[text_end-text] = '\0'; - glfwSetClipboardString(window, buf); - free(buf); + if (*text_end == 0) + { + // Already got a zero-terminator at 'text_end', we don't need to add one + glfwSetClipboardString(window, text); + } + else + { + // Add a zero-terminator because glfw function doesn't take a size + char* buf = (char*)malloc(text_end - text + 1); + memcpy(buf, text, text_end-text); + buf[text_end-text] = '\0'; + glfwSetClipboardString(window, buf); + free(buf); + } } + // GLFW callbacks to get events static void glfw_error_callback(int error, const char* description) { fputs(description, stderr); } -static float mouse_wheel = 0.0f; static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { - mouse_wheel = (float)yoffset; + ImGuiIO& io = ImGui::GetIO(); + io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1 } static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) @@ -173,37 +182,43 @@ void InitImGui() stbi_image_free(tex_data); } -void Shutdown() +void UpdateImGui() { - ImGui::Shutdown(); - glfwTerminate(); + ImGuiIO& io = ImGui::GetIO(); + + // Setup timestep + static double time = 0.0f; + const double current_time = glfwGetTime(); + io.DeltaTime = (float)(current_time - time); + time = current_time; + + // Setup inputs + // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) + double mouse_x, mouse_y; + glfwGetCursorPos(window, &mouse_x, &mouse_y); + io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; + io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0; + + // Start the frame + ImGui::NewFrame(); } +// Application code int main(int argc, char** argv) { InitGL(); InitImGui(); - double time = glfwGetTime(); while (!glfwWindowShouldClose(window)) { ImGuiIO& io = ImGui::GetIO(); + io.MouseWheel = 0; glfwPollEvents(); + UpdateImGui(); - // 1) ImGui start frame, setup time delta & inputs - const double current_time = glfwGetTime(); - io.DeltaTime = (float)(current_time - time); - time = current_time; - double mouse_x, mouse_y; - glfwGetCursorPos(window, &mouse_x, &mouse_y); - io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) - io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; - io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0; - io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1 - mouse_wheel = 0.0f; - ImGui::NewFrame(); - - // 2) ImGui usage + // Create a simple window + // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" static bool show_test_window = true; static bool show_another_window = false; static float f; @@ -217,19 +232,21 @@ int main(int argc, char** argv) static int ms_per_frame_idx = 0; static float ms_per_frame_accum = 0.0f; ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx]; - ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f; + ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f; ms_per_frame_accum += ms_per_frame[ms_per_frame_idx]; ms_per_frame_idx = (ms_per_frame_idx + 1) % 120; const float ms_per_frame_avg = ms_per_frame_accum / 120; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg); + // Show the ImGui test window + // Most of user example code is in ImGui::ShowTestWindow() if (show_test_window) { - // More example code in ShowTestWindow() ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! ImGui::ShowTestWindow(&show_test_window); } + // Show another simple window if (show_another_window) { ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100)); @@ -237,15 +254,15 @@ int main(int argc, char** argv) ImGui::End(); } - // 3) Rendering + // Rendering glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(0.8f, 0.6f, 0.6f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); - glfwSwapBuffers(window); } - Shutdown(); + ImGui::Shutdown(); + glfwTerminate(); return 0; } From a905505ccaa4d9ea047aac657d85873993bcddd9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 12:43:30 +0100 Subject: [PATCH 36/40] Added GetItemBoxMin(),GetItemBoxMax(), renamed IsHovered()-->IsItemHovered() --- imgui.cpp | 20 ++++++++++++++++++-- imgui.h | 4 +++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e2c66f7da..48775f683 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -113,6 +113,7 @@ - window: autofit is losing its purpose when user relies on any dynamic layout (window width multiplier, column). maybe just discard autofit? - window: support horizontal scroll - window: fix resize grip scaling along with Rounding style setting + - window/style: add global alpha modifier (not just "fill_alpha") - 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 @@ -516,6 +517,7 @@ struct ImGuiDrawContext float PrevLineHeight; float LogLineHeight; int TreeDepth; + ImGuiAabb LastItemAabb; bool LastItemHovered; ImVector ChildWindows; ImVector AllowKeyboardFocus; @@ -538,6 +540,7 @@ struct ImGuiDrawContext CurrentLineHeight = PrevLineHeight = 0.0f; LogLineHeight = -1.0f; TreeDepth = 0; + LastItemAabb = ImGuiAabb(0.0f,0.0f,0.0f,0.0f); LastItemHovered = false; StateStorage = NULL; OpenNextNode = -1; @@ -1668,12 +1671,24 @@ ImVec2 GetMousePos() return GImGui.IO.MousePos; } -bool IsHovered() +bool IsItemHovered() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemHovered; } +ImVec2 GetItemBoxMin() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemAabb.Min; +} + +ImVec2 GetItemBoxMax() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemAabb.Max; +} + void SetTooltip(const char* fmt, ...) { ImGuiState& g = GImGui; @@ -4398,6 +4413,7 @@ bool IsClipped(ImVec2 item_size) static bool ClipAdvance(const ImGuiAabb& bb) { ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemAabb = bb; if (ImGui::IsClipped(bb)) { window->DC.LastItemHovered = false; @@ -5411,7 +5427,7 @@ void ShowTestWindow(bool* open) ImGui::RadioButton("radio c", &e, 2); ImGui::Text("Hover me"); - if (ImGui::IsHovered()) + if (ImGui::IsItemHovered()) ImGui::SetTooltip("I am a tooltip"); static int item = 1; diff --git a/imgui.h b/imgui.h index 6b44fb7e2..0102911cb 100644 --- a/imgui.h +++ b/imgui.h @@ -231,7 +231,9 @@ namespace ImGui // Utilities void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). (currently no contention handling, last call win) void SetNewWindowDefaultPos(ImVec2 pos); // set position of window that do - bool IsHovered(); // was the last item active area hovered by mouse? + bool IsItemHovered(); // was the last item active area hovered by mouse? + ImVec2 GetItemBoxMin(); // get bounding box of last item + ImVec2 GetItemBoxMax(); // get bounding box of last item bool IsClipped(ImVec2 item_size); // to perform coarse clipping on user's side (as an optimisation) bool IsKeyPressed(int key_index, bool repeat = true); // key_index into the keys_down[512] array, imgui doesn't know the semantic of each entry bool IsMouseClicked(int button, bool repeat = false); From f30d23a502b415e139119274dcff5aa135ca2d0b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 14:31:13 +0100 Subject: [PATCH 37/40] Tweaks, more consistent #define names --- imconfig.h | 20 ++++++++++++-------- imgui.cpp | 4 ++-- imgui.h | 4 ++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/imconfig.h b/imconfig.h index f5d971ee1..4f1deac8b 100644 --- a/imconfig.h +++ b/imconfig.h @@ -4,18 +4,22 @@ #pragma once -// Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h +//---- Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h //#include //#define ImVector std::vector //#define ImVector MyVector -// Define assertion handler. Default to calling assert(). -// #define IM_ASSERT(_EXPR) MyAssert(_EXPR) +//---- Define assertion handler. Defaults to calling assert(). +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) -// Tell ImGui to not implement default clipboard handlers for Windows (so as not to link with OpenClipboard(), etc.) -// #define IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS +//---- Don't implement default clipboard handlers for Windows (so as not to link with OpenClipboard(), etc.) +//#define IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS -// Define implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. +//---- If you are loading a custom font, ImGui expect to find a pure white pixel at (0,0) +// Change it's UV coordinate here if you can't have a white pixel at (0,0) +//#define IMGUI_FONT_TEX_UV_FOR_WHITE ImVec2(0.f/256.f,0.f/256.f) + +//---- Define implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ @@ -26,8 +30,8 @@ operator MyVec4() const { return MyVec4(x,y,z,w); } */ -// Freely implement extra functions within the ImGui:: namespace. -// e.g. you can create variants of the ImGui::Value() helper for your low-level math types. +//---- Freely implement extra functions within the ImGui:: namespace. +//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types. /* namespace ImGui { diff --git a/imgui.cpp b/imgui.cpp index 48775f683..6943ad37e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -101,7 +101,7 @@ - if you want to use a different font than the default - create bitmap font data using BMFont. allocate ImGui::GetIO().Font and use ->LoadFromFile()/LoadFromMemory(), set ImGui::GetIO().FontHeight - - load your texture yourself. texture *MUST* have white pixel at UV coordinate 'IMDRAW_TEX_UV_FOR_WHITE' (you can #define it in imconfig.h), this is used by solid objects. + - load your texture yourself. texture *MUST* have white pixel at UV coordinate 'IMGUI_FONT_TEX_UV_FOR_WHITE' (you can #define it in imconfig.h), this is used by solid objects. - tip: the construct 'if (IMGUI_ONCE_UPON_A_FRAME)' will evaluate to true only once a frame, you can use it to 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. @@ -4703,7 +4703,7 @@ void ImDrawList::AddVtx(const ImVec2& pos, ImU32 col) { vtx_write->pos = pos; vtx_write->col = col; - vtx_write->uv = IMDRAW_TEX_UV_FOR_WHITE; + vtx_write->uv = IMGUI_FONT_TEX_UV_FOR_WHITE; vtx_write++; } diff --git a/imgui.h b/imgui.h index 0102911cb..b3549d9c7 100644 --- a/imgui.h +++ b/imgui.h @@ -509,8 +509,8 @@ struct ImDrawCmd ImVec4 clip_rect; }; -#ifndef IMDRAW_TEX_UV_FOR_WHITE -#define IMDRAW_TEX_UV_FOR_WHITE ImVec2(0,0) +#ifndef IMGUI_FONT_TEX_UV_FOR_WHITE +#define IMGUI_FONT_TEX_UV_FOR_WHITE ImVec2(0.f,0.f) #endif // sizeof() == 20 From 309ff44579c652388a0ac2e2c5da77da3a0cb1ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 14:32:01 +0100 Subject: [PATCH 38/40] Undo IsHovered > IsItemHovered, shorter name wins --- imgui.cpp | 4 ++-- imgui.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6943ad37e..6800dcbf6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1671,7 +1671,7 @@ ImVec2 GetMousePos() return GImGui.IO.MousePos; } -bool IsItemHovered() +bool IsHovered() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemHovered; @@ -5427,7 +5427,7 @@ void ShowTestWindow(bool* open) ImGui::RadioButton("radio c", &e, 2); ImGui::Text("Hover me"); - if (ImGui::IsItemHovered()) + if (ImGui::IsHovered()) ImGui::SetTooltip("I am a tooltip"); static int item = 1; diff --git a/imgui.h b/imgui.h index b3549d9c7..bd92ed5b7 100644 --- a/imgui.h +++ b/imgui.h @@ -231,7 +231,7 @@ namespace ImGui // Utilities void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). (currently no contention handling, last call win) void SetNewWindowDefaultPos(ImVec2 pos); // set position of window that do - bool IsItemHovered(); // was the last item active area hovered by mouse? + bool IsHovered(); // was the last item active area hovered by mouse? ImVec2 GetItemBoxMin(); // get bounding box of last item ImVec2 GetItemBoxMax(); // get bounding box of last item bool IsClipped(ImVec2 item_size); // to perform coarse clipping on user's side (as an optimisation) From a830037eab0fbe617658b16423cd0d33563996a4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 15:03:10 +0100 Subject: [PATCH 39/40] Default "local only" clipboard handler on non-Windows platforms --- imconfig.h | 2 +- imgui.cpp | 72 +++++++++++++++++++++++++++++++----------------------- imgui.h | 19 ++++++++++---- 3 files changed, 57 insertions(+), 36 deletions(-) diff --git a/imconfig.h b/imconfig.h index 4f1deac8b..98b16f1b8 100644 --- a/imconfig.h +++ b/imconfig.h @@ -13,7 +13,7 @@ //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //---- Don't implement default clipboard handlers for Windows (so as not to link with OpenClipboard(), etc.) -//#define IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS //---- If you are loading a custom font, ImGui expect to find a pure white pixel at (0,0) // Change it's UV coordinate here if you can't have a white pixel at (0,0) diff --git a/imgui.cpp b/imgui.cpp index 6800dcbf6..7ad8be84f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -146,7 +146,6 @@ - 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: full keyboard navigation and focus - - clipboard: add a default "local" implementation of clipboard functions (user will only need to override them to connect to OS clipboard) - misc: not thread-safe - optimisation/render: use indexed rendering - optimisation/render: move clip-rect to vertex data? would allow merging all commands @@ -154,8 +153,6 @@ - optimisation: turn some the various stack vectors into statically-sized arrays - optimisation: better clipping for multi-component widgets - optimisation: specialize for height based clipping first (assume widgets never go up + height tests before width tests?) - - optimisation/portability: provide ImVector style implementation - - optimisation/portability: remove dependency on */ #include "imgui.h" @@ -198,15 +195,11 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); }; // namespace ImGui //----------------------------------------------------------------------------- -// Platform dependant helpers +// Platform dependant default implementations //----------------------------------------------------------------------------- -#ifdef _MSC_VER -#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS -static const char* GetClipboardTextFn_DefaultImplWindows(); -static void SetClipboardTextFn_DefaultImplWindows(const char* text, const char* text_end); -#endif -#endif +static const char* GetClipboardTextFn_DefaultImpl(); +static void SetClipboardTextFn_DefaultImpl(const char* text, const char* text_end); //----------------------------------------------------------------------------- // User facing structures @@ -282,12 +275,8 @@ ImGuiIO::ImGuiIO() MouseDoubleClickMaxDist = 6.0f; // Platform dependant default implementations -#ifdef _MSC_VER -#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS - GetClipboardTextFn = GetClipboardTextFn_DefaultImplWindows; - SetClipboardTextFn = SetClipboardTextFn_DefaultImplWindows; -#endif -#endif + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; } // Pass in translated ASCII characters for text input. @@ -630,6 +619,7 @@ struct ImGuiState ImGuiStorage ColorEditModeStorage; // for user selection ImGuiID ActiveComboID; char Tooltip[1024]; + char* PrivateClipboard; // if no custom clipboard handler is defined // Logging bool LogEnabled; @@ -653,6 +643,7 @@ struct ImGuiState SliderAsInputTextId = 0; ActiveComboID = 0; memset(Tooltip, 0, sizeof(Tooltip)); + PrivateClipboard = NULL; LogEnabled = false; LogFile = NULL; LogAutoExpandMaxDepth = 2; @@ -1313,6 +1304,12 @@ void Shutdown() g.IO.Font = NULL; } + if (g.PrivateClipboard) + { + free(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + g.Initialized = false; } @@ -5201,13 +5198,13 @@ void ImBitmapFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& c // PLATFORM DEPENDANT HELPERS //----------------------------------------------------------------------------- -#ifdef _MSC_VER -#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS +#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) #define WIN32_LEAN_AND_MEAN #include -static const char* GetClipboardTextFn_DefaultImplWindows() +// Win32 API clipboard implementation +static const char* GetClipboardTextFn_DefaultImpl() { static char* buf_local = NULL; if (buf_local) @@ -5215,47 +5212,62 @@ static const char* GetClipboardTextFn_DefaultImplWindows() free(buf_local); buf_local = NULL; } - if (!OpenClipboard(NULL)) return NULL; - HANDLE buf_handle = GetClipboardData(CF_TEXT); if (buf_handle == NULL) return NULL; - if (char* buf_global = (char*)GlobalLock(buf_handle)) buf_local = strdup(buf_global); GlobalUnlock(buf_handle); CloseClipboard(); - return buf_local; } -static void SetClipboardTextFn_DefaultImplWindows(const char* text, const char* text_end) +// Win32 API clipboard implementation +static void SetClipboardTextFn_DefaultImpl(const char* text, const char* text_end) { if (!OpenClipboard(NULL)) return; - if (!text_end) text_end = text + strlen(text); - const int buf_length = (text_end - text) + 1; HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, buf_length * sizeof(char)); if (buf_handle == NULL) return; - char* buf_global = (char *)GlobalLock(buf_handle); memcpy(buf_global, text, text_end - text); buf_global[text_end - text] = 0; GlobalUnlock(buf_handle); - EmptyClipboard(); SetClipboardData(CF_TEXT, buf_handle); CloseClipboard(); } -#endif // #ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS -#endif // #ifdef _MSC_VER +#else + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static const char* GetClipboardTextFn_DefaultImpl() +{ + return GImGui.PrivateClipboard; +} + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static void SetClipboardTextFn_DefaultImpl(const char* text, const char* text_end) +{ + if (GImGui.PrivateClipboard) + { + free(GImGui.PrivateClipboard); + GImGui.PrivateClipboard = NULL; + } + if (!text_end) + text_end = text + strlen(text); + GImGui.PrivateClipboard = (char*)malloc(text_end - text + 1); + memcpy(GImGui.PrivateClipboard, text, text_end - text); + GImGui.PrivateClipboard[text_end - text] = 0; +} + +#endif //----------------------------------------------------------------------------- // HELP diff --git a/imgui.h b/imgui.h index bd92ed5b7..b00633047 100644 --- a/imgui.h +++ b/imgui.h @@ -384,10 +384,16 @@ struct ImGuiIO bool FontAllowScaling; // = false // Set to allow scaling text with CTRL+Wheel. float PixelCenterOffset; // = 0.5f // Set to 0.0f for DirectX <= 9, 0.5f for Direct3D >= 10 and OpenGL. - // Settings - Functions (fill once) - void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); // Required - const char* (*GetClipboardTextFn)(); // Required for clipboard support - void (*SetClipboardTextFn)(const char* text, const char* text_end); // Required for clipboard support (nb- the string is *NOT* zero-terminated at 'text_end') + // Settings - Rendering function (REQUIRED) + // See example code if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); + + // Settings - Clipboard Support + // Override to provide your clipboard handlers. + // On Windows architecture, defaults to use the native Win32 clipboard, otherwise default to use a ImGui private clipboard. + // NB- for SetClipboardTextFn, the string is *NOT* zero-terminated at 'text_end' + const char* (*GetClipboardTextFn)(); + void (*SetClipboardTextFn)(const char* text, const char* text_end); // Input - Fill before calling NewFrame() ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) @@ -525,8 +531,11 @@ struct ImDrawVert // User is responsible for providing a renderer for this in ImGuiIO::RenderDrawListFn struct ImDrawList { - ImVector commands; + // This is what you have to render + ImVector commands; // commands ImVector vtx_buffer; // each command consume ImDrawCmd::vtx_count of those + + // [Internal to ImGui] ImVector clip_rect_stack; // [internal] clip rect stack while building the command-list (so text command can perform clipping early on) ImDrawVert* vtx_write; // [internal] point within vtx_buffer after each add command (to avoid using the ImVector<> operators too much) From a8d3b045b739f9090887844d52d34f795a2d642d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 14 Aug 2014 15:18:34 +0100 Subject: [PATCH 40/40] Fix for doing multiple Begin()/End() during the same frame --- imgui.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ad8be84f..05ef8c1fc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1833,15 +1833,13 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin parent_window->DC.ChildWindows.push_back(window); window->Pos = window->PosFloat = parent_window->DC.CursorPos; window->SizeFull = size; - if (!(flags & ImGuiWindowFlags_ComboBox)) - ImGui::PushClipRect(parent_window->ClipRectStack.back()); - else - ImGui::PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); } + + // Outer clipping rectangle + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) + ImGui::PushClipRect(g.CurrentWindowStack[g.CurrentWindowStack.size()-2]->ClipRectStack.back()); else - { ImGui::PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); - } // ID stack window->IDStack.resize(0); @@ -2082,8 +2080,16 @@ bool Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWin ImGui::CloseWindowButton(open); } } + else + { + // Outer clipping rectangle + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) + ImGui::PushClipRect(g.CurrentWindowStack[g.CurrentWindowStack.size()-2]->ClipRectStack.back()); + else + ImGui::PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); + } - // Clip rectangle + // Innter 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, title_bar_aabb.Max.y+0.5f, window->Aabb().Max.x-1.5f, window->Aabb().Max.y-1.5f);