From a03523aa4f60763b4e1b3e6e1ec87eeaae669dd8 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 00:32:17 +0100 Subject: [PATCH 01/14] First version of imgui integration --- GUI.diff | 105 +++++++++++ include/openspace/engine/gui.h | 46 +++++ include/openspace/rendering/renderengine.h | 2 + src/CMakeLists.txt | 5 + src/engine/gui.cpp | 199 +++++++++++++++++++++ src/rendering/renderengine.cpp | 18 +- 6 files changed, 374 insertions(+), 1 deletion(-) create mode 100644 GUI.diff create mode 100644 include/openspace/engine/gui.h create mode 100644 src/engine/gui.cpp diff --git a/GUI.diff b/GUI.diff new file mode 100644 index 0000000000..9d50202347 --- /dev/null +++ b/GUI.diff @@ -0,0 +1,105 @@ +diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h +index c3d8c9e..8f70641 100644 +--- a/include/openspace/rendering/renderengine.h ++++ b/include/openspace/rendering/renderengine.h +@@ -36,6 +36,7 @@ class SceneGraph; + class ABuffer; + class ABufferVisualizer; + class ScreenLog; ++class GUI; + + class RenderEngine { + public: +@@ -78,6 +79,7 @@ private: + SceneGraph* _sceneGraph; + ABuffer* _abuffer; + ScreenLog* _log; ++ GUI* _gui; + + bool _showInfo; + bool _showScreenLog; +diff --git a/scripts/bind_keys.lua b/scripts/bind_keys.lua +index a0f9442..08a3254 100644 +--- a/scripts/bind_keys.lua ++++ b/scripts/bind_keys.lua +@@ -17,5 +17,6 @@ openspace.bindKey("f5", "loadKeyBindings()") + + openspace.bindKey("U", "openspace.distance(-interaction_speed * openspace.dt(), 13.0)") + openspace.bindKey("J", "openspace.distance(interaction_speed * openspace.dt(), 13.0)") ++openspace.bindKey("K", "openspace.distance(interaction_speed * openspace.dt(), 20.0)") + + openspace.bindKey("PRINT_SCREEN", "openspace.takeScreenshot()") +\ No newline at end of file +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 0dc32c8..4be7f7a 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -130,6 +130,11 @@ source_group(Interface FILES ${INTERFACE_SOURCE} ${INTERFACE_HEADER}) + include_directories(${HEADER_ROOT_DIR}) + include_directories(${GHOUL_ROOT_DIR}/ext/boost) + ++include_directories(${CMAKE_SOURCE_DIR}/ext/imgui) ++set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.h) ++set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.cpp) ++source_group(ext\\imgui FILES ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.h ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.cpp) ++ + if (APPLE) + add_definitions(-D__APPLE__) + set(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++ ${CMAKE_CXX_FLAGS}") +diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp +index 9317b0e..93735eb 100644 +--- a/src/rendering/renderengine.cpp ++++ b/src/rendering/renderengine.cpp +@@ -30,6 +30,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -38,7 +39,6 @@ + #include + #include + #include +- + #include + #include + +@@ -111,6 +111,7 @@ RenderEngine::RenderEngine() + , _sceneGraph(nullptr) + , _abuffer(nullptr) + , _log(nullptr) ++ , _gui(nullptr) + , _showInfo(true) + , _showScreenLog(true) + , _takeScreenshot(false) +@@ -241,6 +242,11 @@ bool RenderEngine::initializeGL() + + _visualizer = new ABufferVisualizer(); + ++ int x,y; ++ sgct::Engine::instance()->getActiveViewportSize(x, y); ++ _gui = new GUI(glm::vec2(glm::ivec2(x,y))); ++ _gui->initializeGL(); ++ + // successful init + return true; + } +@@ -330,6 +336,16 @@ void RenderEngine::render() + else { + _visualizer->render(); + } ++ ++ double posX, posY; ++ sgct::Engine::instance()->getMousePos(0, &posX, &posY); ++ ++ int button0 = sgct::Engine::instance()->getMouseButton(0, 0); ++ int button1 = sgct::Engine::instance()->getMouseButton(0, 1); ++ bool buttons[2] = { button0 != 0, button1 != 0 }; ++ ++ double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); ++ _gui->render(dt, glm::vec2(posX, posY), buttons); + + #if 1 + diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h new file mode 100644 index 0000000000..4c618a1087 --- /dev/null +++ b/include/openspace/engine/gui.h @@ -0,0 +1,46 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __GUI_H__ +#define __GUI_H__ + +#include +#include + +namespace openspace { + +class GUI { +public: + GUI(const glm::vec2& windowSize); + ~GUI(); + + void initializeGL(); + void deinitializeGL(); + + void render(float deltaTime, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); +}; + +} // namespace openspace + +#endif // __GUI_H__ diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index c3d8c9ee35..8f70641b35 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -36,6 +36,7 @@ class SceneGraph; class ABuffer; class ABufferVisualizer; class ScreenLog; +class GUI; class RenderEngine { public: @@ -78,6 +79,7 @@ private: SceneGraph* _sceneGraph; ABuffer* _abuffer; ScreenLog* _log; + GUI* _gui; bool _showInfo; bool _showScreenLog; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0dc32c8a2a..4be7f7a917 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -130,6 +130,11 @@ source_group(Interface FILES ${INTERFACE_SOURCE} ${INTERFACE_HEADER}) include_directories(${HEADER_ROOT_DIR}) include_directories(${GHOUL_ROOT_DIR}/ext/boost) +include_directories(${CMAKE_SOURCE_DIR}/ext/imgui) +set(OPENSPACE_HEADER ${OPENSPACE_HEADER} ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.h) +set(OPENSPACE_SOURCE ${OPENSPACE_SOURCE} ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.cpp) +source_group(ext\\imgui FILES ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.h ${CMAKE_SOURCE_DIR}/ext/imgui/imgui.cpp) + if (APPLE) add_definitions(-D__APPLE__) set(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++ ${CMAKE_CXX_FLAGS}") diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp new file mode 100644 index 0000000000..41237ca1ef --- /dev/null +++ b/src/engine/gui.cpp @@ -0,0 +1,199 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include + +#include +#include +#define STB_IMAGE_IMPLEMENTATION +#include + +namespace { + const std::string _loggerCat = "GUI"; + + GLuint fontTex = 0; + GLint shader_handle = 0; + GLint texture_location = 0; + GLint ortho_location = 0; + GLuint vbo_handle = 0; + size_t vbo_max_size = 20000; + GLuint vao_handle; + + + +static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { + if (cmd_lists_count == 0) + return; + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_SCISSOR_TEST); + + // Setup texture + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, fontTex); + + // Setup orthographic projection matrix + const float width = ImGui::GetIO().DisplaySize.x; + const float height = ImGui::GetIO().DisplaySize.y; + const float ortho_projection[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 }, + }; + glUseProgram(shader_handle); + glUniform1i(texture_location, 0); + glUniformMatrix4fv(ortho_location, 1, GL_FALSE, &ortho_projection[0][0]); + + // Grow our buffer according to what we need + size_t total_vtx_count = 0; + for (int n = 0; n < cmd_lists_count; n++) + total_vtx_count += cmd_lists[n]->vtx_buffer.size(); + glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); + size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert); + if (neededBufferSize > vbo_max_size) + { + vbo_max_size = neededBufferSize + 5000; // Grow buffer + glBufferData(GL_ARRAY_BUFFER, neededBufferSize, NULL, GL_STREAM_DRAW); + } + + // Copy and convert all vertices into a single contiguous buffer + 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); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(vao_handle); + + int cmd_offset = 0; + for (int n = 0; n < cmd_lists_count; n++) + { + const ImDrawList* cmd_list = cmd_lists[n]; + int vtx_offset = cmd_offset; + 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)(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; + } + cmd_offset = vtx_offset; + } + + // Restore modified state + glBindVertexArray(0); + glUseProgram(0); + glDisable(GL_SCISSOR_TEST); + glBindTexture(GL_TEXTURE_2D, 0); +} +} + +namespace openspace { + +GUI::GUI(const glm::vec2& windowSize) { + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(windowSize.x, windowSize.y); + io.DeltaTime = 1.f / 60.f; + io.PixelCenterOffset = 0.5f; + io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. + io.KeyMap[ImGuiKey_LeftArrow] = SGCT_KEY_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = SGCT_KEY_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = SGCT_KEY_UP; + io.KeyMap[ImGuiKey_DownArrow] = SGCT_KEY_DOWN; + io.KeyMap[ImGuiKey_Home] = SGCT_KEY_HOME; + io.KeyMap[ImGuiKey_End] = SGCT_KEY_END; + io.KeyMap[ImGuiKey_Delete] = SGCT_KEY_DELETE; + io.KeyMap[ImGuiKey_Backspace] = SGCT_KEY_BACKSPACE; + io.KeyMap[ImGuiKey_Enter] = SGCT_KEY_ENTER; + io.KeyMap[ImGuiKey_Escape] = SGCT_KEY_ESCAPE; + io.KeyMap[ImGuiKey_A] = SGCT_KEY_A; + io.KeyMap[ImGuiKey_C] = SGCT_KEY_C; + io.KeyMap[ImGuiKey_V] = SGCT_KEY_V; + io.KeyMap[ImGuiKey_X] = SGCT_KEY_X; + io.KeyMap[ImGuiKey_Y] = SGCT_KEY_Y; + io.KeyMap[ImGuiKey_Z] = SGCT_KEY_Z; + + io.RenderDrawListsFn = ImImpl_RenderDrawLists; + //io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; // @TODO implement? ---abock + //io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // @TODO implement? ---abock +} + +GUI::~GUI() { + ImGui::Shutdown(); +} + +void GUI::initializeGL() { + 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); + int tex_x, tex_y, tex_comp; + void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); + stbi_image_free(tex_data); +} + +void GUI::deinitializeGL() { + if (vao_handle) glDeleteVertexArrays(1, &vao_handle); + if (vbo_handle) glDeleteBuffers(1, &vbo_handle); + glDeleteProgram(shader_handle); +} + +void GUI::render(float deltaTime, + const glm::vec2& mousePos, + bool mouseButtonsPressed[2]) +{ + ImGuiIO& io = ImGui::GetIO(); + io.DeltaTime = deltaTime; + io.MousePos = ImVec2(mousePos.x, mousePos.y); + io.MouseDown[0] = mouseButtonsPressed[0]; + io.MouseDown[1] = mouseButtonsPressed[1]; + + ImGui::NewFrame(); + static bool show = true; + //if (show) { + ImGui::ShowTestWindow(&show); + //} + + ImGui::Render(); +} + +} // namespace openspace diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 9317b0e550..93735eb28e 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -38,7 +39,6 @@ #include #include #include - #include #include @@ -111,6 +111,7 @@ RenderEngine::RenderEngine() , _sceneGraph(nullptr) , _abuffer(nullptr) , _log(nullptr) + , _gui(nullptr) , _showInfo(true) , _showScreenLog(true) , _takeScreenshot(false) @@ -241,6 +242,11 @@ bool RenderEngine::initializeGL() _visualizer = new ABufferVisualizer(); + int x,y; + sgct::Engine::instance()->getActiveViewportSize(x, y); + _gui = new GUI(glm::vec2(glm::ivec2(x,y))); + _gui->initializeGL(); + // successful init return true; } @@ -330,6 +336,16 @@ void RenderEngine::render() else { _visualizer->render(); } + + double posX, posY; + sgct::Engine::instance()->getMousePos(0, &posX, &posY); + + int button0 = sgct::Engine::instance()->getMouseButton(0, 0); + int button1 = sgct::Engine::instance()->getMouseButton(0, 1); + bool buttons[2] = { button0 != 0, button1 != 0 }; + + double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); + _gui->render(dt, glm::vec2(posX, posY), buttons); #if 1 From 9f7e1581de22c2dd0f973c34051706ce44e133ac Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 12:33:06 +0100 Subject: [PATCH 02/14] Allow unique input to the GUI Move GUI from RenderEngine to OpenSpace engine --- include/openspace/engine/gui.h | 7 +- include/openspace/engine/openspaceengine.h | 3 +- include/openspace/rendering/renderengine.h | 2 - openspace-data | 2 +- src/engine/gui.cpp | 101 ++++++++++++++++++++- src/engine/openspaceengine.cpp | 41 +++++++-- src/rendering/renderengine.cpp | 17 ---- 7 files changed, 143 insertions(+), 30 deletions(-) diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h index 4c618a1087..6f36dad686 100644 --- a/include/openspace/engine/gui.h +++ b/include/openspace/engine/gui.h @@ -38,7 +38,12 @@ public: void initializeGL(); void deinitializeGL(); - void render(float deltaTime, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); + bool mouseButtonCallback(int key, int action); + bool keyCallback(int key, int action); + bool charCallback(unsigned int character); + + void startFrame(float deltaTime, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); + void endFrame(); }; } // namespace openspace diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 0fbcbf5eda..83742438c1 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -34,7 +34,7 @@ namespace openspace { -// Forward declare to minimize dependencies +class GUI; class SyncBuffer; class LuaConsole; @@ -95,6 +95,7 @@ private: scripting::ScriptEngine _scriptEngine; ghoul::cmdparser::CommandlineParser _commandlineParser; LuaConsole _console; + GUI* _gui; SyncBuffer* _syncBuffer; diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 8f70641b35..c3d8c9ee35 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -36,7 +36,6 @@ class SceneGraph; class ABuffer; class ABufferVisualizer; class ScreenLog; -class GUI; class RenderEngine { public: @@ -79,7 +78,6 @@ private: SceneGraph* _sceneGraph; ABuffer* _abuffer; ScreenLog* _log; - GUI* _gui; bool _showInfo; bool _showScreenLog; diff --git a/openspace-data b/openspace-data index 07ef85b86b..8a44f44729 160000 --- a/openspace-data +++ b/openspace-data @@ -1 +1 @@ -Subproject commit 07ef85b86b2a65dbce718055f56ddb23a588da3c +Subproject commit 8a44f447292f176e00edeb1f494682ee405577b3 diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 41237ca1ef..223cc945d4 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -36,7 +36,12 @@ namespace { GLuint fontTex = 0; GLint shader_handle = 0; + GLint vert_handle = 0; + GLint frag_handle = 0; GLint texture_location = 0; + GLint position_location = 0; + GLint uv_location = 0; + GLint colour_location = 0; GLint ortho_location = 0; GLuint vbo_handle = 0; size_t vbo_max_size = 20000; @@ -158,6 +163,49 @@ GUI::~GUI() { } void GUI::initializeGL() { + const GLchar *vertex_shader = + "#version 330\n" + "uniform mat4 ortho;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Colour;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Colour;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Colour = Colour;\n" + " gl_Position = ortho*vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* fragment_shader = + "#version 330\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Colour;\n" + "out vec4 FragColor;\n" + "void main()\n" + "{\n" + " FragColor = Frag_Colour * texture( Texture, Frag_UV.st);\n" + "}\n"; + + shader_handle = glCreateProgram(); + vert_handle = glCreateShader(GL_VERTEX_SHADER); + frag_handle = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(vert_handle, 1, &vertex_shader, 0); + glShaderSource(frag_handle, 1, &fragment_shader, 0); + glCompileShader(vert_handle); + glCompileShader(frag_handle); + glAttachShader(shader_handle, vert_handle); + glAttachShader(shader_handle, frag_handle); + glLinkProgram(shader_handle); + + texture_location = glGetUniformLocation(shader_handle, "Texture"); + ortho_location = glGetUniformLocation(shader_handle, "ortho"); + position_location = glGetAttribLocation(shader_handle, "Position"); + uv_location = glGetAttribLocation(shader_handle, "UV"); + colour_location = glGetAttribLocation(shader_handle, "Colour"); + glGenTextures(1, &fontTex); glBindTexture(GL_TEXTURE_2D, fontTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); @@ -169,6 +217,23 @@ void GUI::initializeGL() { void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); stbi_image_free(tex_data); + + glGenBuffers(1, &vbo_handle); + glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); + glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW); + + glGenVertexArrays(1, &vao_handle); + glBindVertexArray(vao_handle); + glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); + glEnableVertexAttribArray(position_location); + glEnableVertexAttribArray(uv_location); + glEnableVertexAttribArray(colour_location); + + glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos)); + glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv)); + glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col)); + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); } void GUI::deinitializeGL() { @@ -177,7 +242,7 @@ void GUI::deinitializeGL() { glDeleteProgram(shader_handle); } -void GUI::render(float deltaTime, +void GUI::startFrame(float deltaTime, const glm::vec2& mousePos, bool mouseButtonsPressed[2]) { @@ -188,6 +253,11 @@ void GUI::render(float deltaTime, io.MouseDown[1] = mouseButtonsPressed[1]; ImGui::NewFrame(); +} + +void GUI::endFrame() +{ + static bool show = true; //if (show) { ImGui::ShowTestWindow(&show); @@ -196,4 +266,33 @@ void GUI::render(float deltaTime, ImGui::Render(); } +bool GUI::mouseButtonCallback(int key, int action) { + ImGuiIO& io = ImGui::GetIO(); + bool consumeEvent = io.WantCaptureMouse; + return consumeEvent; +} + +bool GUI::keyCallback(int key, int action) { + ImGuiIO& io = ImGui::GetIO(); + bool consumeEvent = io.WantCaptureKeyboard; + if (consumeEvent) { + if (action == SGCT_PRESS) + io.KeysDown[key] = true; + if (action == SGCT_RELEASE) + io.KeysDown[key] = false; + } + return consumeEvent; +} + +bool GUI::charCallback(unsigned int character) { + ImGuiIO& io = ImGui::GetIO(); + bool consumeEvent = io.WantCaptureKeyboard; + + if (consumeEvent) { + io.AddInputCharacter((unsigned short)character); + } + + return consumeEvent; +} + } // namespace openspace diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index c6105458c9..439466182a 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -24,7 +24,7 @@ #include -// openspace +#include #include #include #include @@ -83,6 +83,7 @@ OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr; OpenSpaceEngine::OpenSpaceEngine(std::string programName) : _commandlineParser(programName, true) + , _gui(nullptr) , _syncBuffer(nullptr) { // initialize OpenSpace helpers @@ -473,9 +474,14 @@ LuaConsole& OpenSpaceEngine::console() { return _console; } -bool OpenSpaceEngine::initializeGL() -{ - return _renderEngine.initializeGL(); +bool OpenSpaceEngine::initializeGL() { + bool success = _renderEngine.initializeGL(); + int x,y; + sgct::Engine::instance()->getWindowPtr(0)->getFinalFBODimensions(x, y); + _gui = new GUI(glm::vec2(glm::ivec2(x,y))); + _gui->initializeGL(); + + return success; } void OpenSpaceEngine::preSynchronization() { @@ -492,6 +498,16 @@ void OpenSpaceEngine::preSynchronization() { void OpenSpaceEngine::postSynchronizationPreDraw() { _renderEngine.postSynchronizationPreDraw(); + + double posX, posY; + sgct::Engine::instance()->getMousePos(0, &posX, &posY); + + int button0 = sgct::Engine::instance()->getMouseButton(0, 0); + int button1 = sgct::Engine::instance()->getMouseButton(0, 1); + bool buttons[2] = { button0 != 0, button1 != 0 }; + + double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); + _gui->startFrame(dt, glm::vec2(posX, posY), buttons); } void OpenSpaceEngine::render() { @@ -502,9 +518,9 @@ void OpenSpaceEngine::render() { if (sgct::Engine::instance()->isMaster() && !w->isUsingFisheyeRendering() && _console.isVisible()) { _console.render(); } + _gui->endFrame(); } - void OpenSpaceEngine::postDraw() { if (sgct::Engine::instance()->isMaster()) _interactionHandler.unlockControls(); @@ -514,6 +530,10 @@ void OpenSpaceEngine::postDraw() { void OpenSpaceEngine::keyboardCallback(int key, int action) { if (sgct::Engine::instance()->isMaster()) { + bool isConsumed = _gui->keyCallback(key, action); + if (isConsumed) + return; + if (key == _console.commandInputButton() && (action == SGCT_PRESS || action == SGCT_REPEAT)) _console.toggleVisibility(); @@ -527,14 +547,21 @@ void OpenSpaceEngine::keyboardCallback(int key, int action) { } void OpenSpaceEngine::charCallback(unsigned int codepoint) { + bool isConsumed = _gui->charCallback(codepoint); + if (isConsumed) + return; + if (_console.isVisible()) { _console.charCallback(codepoint); } } void OpenSpaceEngine::mouseButtonCallback(int key, int action) { - if (sgct::Engine::instance()->isMaster()) - _interactionHandler.mouseButtonCallback(key, action); + bool isConsumed = _gui->mouseButtonCallback(key, action); + if (isConsumed) + return; + + _interactionHandler.mouseButtonCallback(key, action); } void OpenSpaceEngine::mousePositionCallback(int x, int y) { diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 95f3f9a312..189dd3bc42 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -112,7 +111,6 @@ RenderEngine::RenderEngine() , _sceneGraph(nullptr) , _abuffer(nullptr) , _log(nullptr) - , _gui(nullptr) , _showInfo(true) , _showScreenLog(true) , _takeScreenshot(false) @@ -244,11 +242,6 @@ bool RenderEngine::initializeGL() _visualizer = new ABufferVisualizer(); - int x,y; - sgct::Engine::instance()->getActiveViewportSize(x, y); - _gui = new GUI(glm::vec2(glm::ivec2(x,y))); - _gui->initializeGL(); - // successful init return true; } @@ -338,16 +331,6 @@ void RenderEngine::render() else { _visualizer->render(); } - - double posX, posY; - sgct::Engine::instance()->getMousePos(0, &posX, &posY); - - int button0 = sgct::Engine::instance()->getMouseButton(0, 0); - int button1 = sgct::Engine::instance()->getMouseButton(0, 1); - bool buttons[2] = { button0 != 0, button1 != 0 }; - - double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); - _gui->render(dt, glm::vec2(posX, posY), buttons); #if 1 From 0a0543cc942e3773881ad00fa0398563e2976174 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 12:46:52 +0100 Subject: [PATCH 03/14] More callbacks implemented --- include/openspace/engine/gui.h | 1 + src/engine/gui.cpp | 13 +++++++++++++ src/engine/openspaceengine.cpp | 10 ++++++---- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h index 6f36dad686..8a0908750e 100644 --- a/include/openspace/engine/gui.h +++ b/include/openspace/engine/gui.h @@ -39,6 +39,7 @@ public: void deinitializeGL(); bool mouseButtonCallback(int key, int action); + bool mouseWheelCallback(int position); bool keyCallback(int key, int action); bool charCallback(unsigned int character); diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 223cc945d4..60cafd577a 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -25,6 +25,8 @@ #include #include +#include +#include #include #include @@ -47,6 +49,8 @@ namespace { size_t vbo_max_size = 20000; GLuint vao_handle; + ghoul::opengl::Texture* _texture; + static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { @@ -272,6 +276,15 @@ bool GUI::mouseButtonCallback(int key, int action) { return consumeEvent; } +bool GUI::mouseWheelCallback(int position) { + ImGuiIO& io = ImGui::GetIO(); + bool consumeEvent = io.WantCaptureMouse; + if (consumeEvent) + io.MouseWheel = static_cast(position); + + return consumeEvent; +} + bool GUI::keyCallback(int key, int action) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureKeyboard; diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 439466182a..fa61d4731b 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -569,19 +569,21 @@ void OpenSpaceEngine::mousePositionCallback(int x, int y) { } void OpenSpaceEngine::mouseScrollWheelCallback(int pos) { + bool isConsumed = _gui->mouseWheelCallback(pos); + if (isConsumed) + return; + _interactionHandler.mouseScrollWheelCallback(pos); } -void OpenSpaceEngine::encode() -{ +void OpenSpaceEngine::encode() { if (_syncBuffer) { _renderEngine.serialize(_syncBuffer); _syncBuffer->write(); } } -void OpenSpaceEngine::decode() -{ +void OpenSpaceEngine::decode() { if (_syncBuffer) { _syncBuffer->read(); _renderEngine.deserialize(_syncBuffer); From 0854aa5bcbbe2dedaa0ff1786bbec644043934ba Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 12:48:56 +0100 Subject: [PATCH 04/14] Added imgui library --- ext/imgui/.gitignore | 23 + ext/imgui/LICENSE | 21 + ext/imgui/README.md | 103 + ext/imgui/imconfig.h | 47 + ext/imgui/imgui.cpp | 7568 ++++++++++++++++++++++++++++++++++++++ ext/imgui/imgui.h | 786 ++++ ext/imgui/stb_image.h | 4744 ++++++++++++++++++++++++ ext/imgui/stb_textedit.h | 1254 +++++++ src/engine/gui.cpp | 6 +- 9 files changed, 14547 insertions(+), 5 deletions(-) create mode 100644 ext/imgui/.gitignore create mode 100644 ext/imgui/LICENSE create mode 100644 ext/imgui/README.md create mode 100644 ext/imgui/imconfig.h create mode 100644 ext/imgui/imgui.cpp create mode 100644 ext/imgui/imgui.h create mode 100644 ext/imgui/stb_image.h create mode 100644 ext/imgui/stb_textedit.h diff --git a/ext/imgui/.gitignore b/ext/imgui/.gitignore new file mode 100644 index 0000000000..cc09676fe9 --- /dev/null +++ b/ext/imgui/.gitignore @@ -0,0 +1,23 @@ +## Visual Studio files +examples/Debug/* +examples/Release/* +examples/ipch/* +examples/directx9_example/Debug/* +examples/directx9_example/Release/* +examples/directx9_example/ipch/* +examples/directx11_example/Debug/* +examples/directx11_example/Release/* +examples/directx11_example/ipch/* +examples/opengl_example/Debug/* +examples/opengl_example/Release/* +examples/opengl_example/ipch/* +examples/opengl3_example/Debug/* +examples/opengl3_example/Release/* +examples/opengl3_example/ipch/* +*.opensdf +*.sdf +*.suo +*.vcxproj.user + +## Ini files +imgui.ini diff --git a/ext/imgui/LICENSE b/ext/imgui/LICENSE new file mode 100644 index 0000000000..fa8630078c --- /dev/null +++ b/ext/imgui/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ext/imgui/README.md b/ext/imgui/README.md new file mode 100644 index 0000000000..433f0a6de8 --- /dev/null +++ b/ext/imgui/README.md @@ -0,0 +1,103 @@ +ImGui +===== + +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 user interfaces with ease. + +ImGui is designed to enable fast iteration and allow programmers to create "content creation" or "debug" tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries. + +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) + +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. + +ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc. + +Gallery +------- + +![screenshot 1](/web/test_window_01.png?raw=true) +![screenshot 2](/web/test_window_02.png?raw=true) +![screenshot 3](/web/test_window_03.png?raw=true) +![screenshot 4](/web/test_window_04.png?raw=true) + +UTF-8 is supported for text display and input. Here using M+ font to display Japanese: + +![utf-8 screenshot](/web/utf8_sample_01.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). + +Frequently Asked Question +------------------------- + +How do you use ImGui on a platform that may not have a mouse or keyboard? + +I recommend using [Synergy](http://synergy-project.org). With the uSynergy.c micro client running you can seamlessly use your PC input devices from a video game console or a tablet. ImGui was also designed to function with touch inputs if you increase the padding of widgets to compensate for the lack of precision of touch devices, but it is recommended you use a mouse to allow optimising for screen real-estate. + +I integrated ImGui in my engine and the text or lines are blurry.. + +- Try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f. +- In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + +Can you create elaborate/serious tools with ImGui? + +Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. There's no reason you cannot, and in my experience the simplicity of the API is very empowering. However note that ImGui is programmer centric and the immediate-mode GUI paradigm might requires a bit of adaptation before you can realize its full potential. + +Is ImGui fast? + +Down the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it. + +Mileage may vary but the following screenshot should give you an idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup may be a bottleneck and cause higher variation or throttled framerate. Testing performance as part of a real application is recommended). + +![performance screenshot](/web/performance_01_close_up.png?raw=true) + +This is showing framerate on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M. ([click here for the full-size picture](/web/performance_01.png)). +In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint. + +Can you reskin the look of ImGui? + +Yes, you can alter the look of the interface to some degree: changing colors, sizes and padding, font. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. The example below uses modified settings to create a very compact UI with different colors: + +![skinning screenshot 1](/web/skinning_sample_01.png?raw=true) + +Why using C++ (as opposed to C)? + +ImGui takes advantage of a few C++ features for convenience but nothing in the realm of Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed. + +Shall someone wants to use ImGui from another language, it should be possible to wrap ImGui to be used from a raw C API in the future. + +Support +------- + +Can you develop features xxxx for ImGui? + +Please use GitHub 'Issues' facilities to suggest and discuss improvements. Your questions are often helpul to the community of users. If you represent an organization and would like specific non-trivial features to be implemented, I am available for hire to work on or with ImGui. + +Can I donate to support the development of ImGui? + +If you have the mean to help, I have setup a [**Patreon page**](http://www.patreon.com/imgui) to enable me to spend more time on the development of the library. One-off donations are also greatly appreciated. Thanks! + +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](http://upperbounds.net) font by Tristan Grimmer (MIT license). +Embeds [M+ fonts](http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) font by Coji Morishita (free software license). +Embeds [stb_textedit.h](https://github.com/nothings/stb/) by Sean Barrett. + +Inspiration, feedback, and testing: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Thanks! + +License +------- + +ImGui is licensed under the MIT License, see LICENSE for more information. diff --git a/ext/imgui/imconfig.h b/ext/imgui/imconfig.h new file mode 100644 index 0000000000..02e70da9aa --- /dev/null +++ b/ext/imgui/imconfig.h @@ -0,0 +1,47 @@ +//----------------------------------------------------------------------------- +// USER IMPLEMENTATION +// This file contains compile-time options for ImGui. +// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO(). +//----------------------------------------------------------------------------- + +#pragma once + +//---- 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. Defaults to calling assert(). +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) + +//---- Don't implement default clipboard handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions) +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS + +//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions. +//#define IMGUI_INCLUDE_IMGUI_USER_INL + +//---- Include imgui_user.h at the end of imgui.h +//#define IMGUI_INCLUDE_IMGUI_USER_H + +//---- 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; } \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ + +//---- Freely implement extra functions within the ImGui:: namespace. +//---- Declare helpers or widgets implemented in imgui_user.inl or elsewhere, so end-user doesn't need to include multiple files. +//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types. +/* +namespace ImGui +{ + 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/ext/imgui/imgui.cpp b/ext/imgui/imgui.cpp new file mode 100644 index 0000000000..4db1a5b6fb --- /dev/null +++ b/ext/imgui/imgui.cpp @@ -0,0 +1,7568 @@ +// ImGui library v1.18 wip +// See ImGui::ShowTestWindow() for sample code. +// Read 'Programmer guide' below for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui +// Developed by Omar Cornut and contributors. + +/* + + Index + - MISSION STATEMENT + - END-USER GUIDE + - PROGRAMMER GUIDE + - API BREAKING CHANGES + - TROUBLESHOOTING & FREQUENTLY ASKED QUESTIONS + - ISSUES & TODO-LIST + - CODE + - SAMPLE CODE + - FONT DATA + + + MISSION STATEMENT + ================= + + - easy to use to create code-driven and data-driven tools + - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools + - easy to hack and improve + - minimize screen real-estate usage + - minimize setup and maintenance + - minimize state storage on user side + - portable, minimize dependencies, run on target (consoles, etc.) + - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) + - read about immediate-mode GUI principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html + + Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: + - doesn't look fancy, doesn't animate + - limited layout features, intricate layouts are typically crafted in code + - occasionally use statically sized buffers for string manipulations - won't crash, but some long text may be clipped + + + END-USER GUIDE + ============== + + - double-click title bar to collapse window + - click upper right corner to close a window, available when 'bool* open' is passed to ImGui::Begin() + - click and drag on lower right corner to resize window + - click and drag on any empty space to move window + - double-click/double-tap on lower right corner grip to auto-fit to content + - TAB/SHIFT+TAB to cycle through keyboard editable fields + - use mouse wheel to scroll + - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) + - CTRL+Click on a slider to input value as text + - text editor: + - Hold SHIFT or use mouse to select text. + - CTRL+Left/Right to word jump + - CTRL+Shift+Left/Right to select words + - CTRL+A our Double-Click to select all + - CTRL+X,CTRL+C,CTRL+V to use OS clipboard + - CTRL+Z,CTRL+Y to undo/redo + - ESCAPE to revert text to its original value + - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) + + + PROGRAMMER GUIDE + ================ + + - your code creates the UI, if your code doesn't run the UI is gone! == dynamic UI, no construction step, less data retention on your side, no state duplication, less sync, less errors. + - see ImGui::ShowTestWindow() for user-side sample code + - see examples/ folder for standalone sample applications. + + - getting started: + - initialisation: call ImGui::GetIO() and fill the 'Settings' data. + - every frame: + 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame(). + 2/ use any ImGui function you want between NewFrame() and Render() + 3/ ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure. + - all rendering information are stored into command-lists until ImGui::Render() is called. + - effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations. + - refer to the examples applications in the examples/ folder for instruction on how to setup your code. + - a typical application skeleton may be: + + // Application init + // TODO: Fill all settings fields of the io structure + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize.x = 1920.0f; + io.DisplaySize.y = 1280.0f; + io.DeltaTime = 1.0f/60.0f; + io.IniFilename = "imgui.ini"; + + // Application main loop + while (true) + { + // 1/ get low-level input + // e.g. on Win32, GetKeyboardState(), or poll your events, etc. + + // 2/ TODO: Fill all 'Input' fields of io structure and call NewFrame + ImGuiIO& io = ImGui::GetIO(); + io.MousePos = ... + io.KeysDown[i] = ... + ImGui::NewFrame(); + + // 3/ most of your application code here - you can use any of ImGui::* functions between NewFrame() and Render() calls + GameUpdate(); + GameRender(); + + // 4/ render & swap video buffers + ImGui::Render(); + // swap video buffer, etc. + } + + - after calling ImGui::NewFrame() you can read back 'ImGui::GetIO().WantCaptureMouse' and 'ImGui::GetIO().WantCaptureKeyboard' to tell + if ImGui wants to use your inputs. so typically can hide the mouse inputs from the rest of your application if ImGui is using it. + + + API BREAKING CHANGES + ==================== + + Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. + Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. + + - 2014/11/28 (1.17) moved IO.Font*** options to inside the IO.Font-> structure. + - 2014/11/26 (1.17) reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + TROUBLESHOOTING & FREQUENTLY ASKED QUESTIONS + ============================================ + + If text or lines are blurry when integrating ImGui in your engine: + - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) + - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f + + If you are confused about the meaning or use of ID in ImGui: + - some widgets requires state to be carried over multiple frames (most typically ImGui often wants remember what is the "active" widget). + to do so they need an unique ID. unique ID are typically derived from a string label, an indice or a pointer. + when you call Button("OK") the button shows "OK" and also use "OK" as an ID. + - ID are uniquely scoped within Windows so no conflict can happen if you have two buttons called "OK" in two different Windows. + within a same Window, use PushID() / PopID() to easily create scopes and avoid ID conflicts. + so if you have a loop creating "multiple" items, you can use PushID() / PopID() with the index of each item, or their pointer, etc. + some functions like TreeNode() implicitly creates a scope for you by calling PushID() + - when dealing with trees, ID are important because you want to preserve the opened/closed state of tree nodes. + depending on your use cases you may want to use strings, indices or pointers as ID. experiment and see what makes more sense! + e.g. When displaying a single object, using a static string as ID will preserve your node open/closed state when the targeted object change + e.g. When displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state per object + - when passing a label you can optionally specify extra unique ID information within the same string using "##". This helps solving the simpler collision cases. + e.g. "Label" display "Label" and uses "Label" as ID + e.g. "Label##Foobar" display "Label" and uses "Label##Foobar" as ID + e.g. "##Foobar" display an empty label and uses "##Foobar" as ID + - read articles about the imgui principles (see web links) to understand the requirement and use of ID. + + If you want to use a different font than the default: + - read extra_fonts/README.txt for instructions. Examples fonts are also provided. + - if you can only see text but no solid shapes or lines, make sure io.Font->TexUvForWhite is set to the texture coordinates of a pure white pixel in your texture! + + If you want to input Japanese/Chinese/Korean in the text input widget: + - make sure you are using a font that can display the glyphs you want (see above paragraph about fonts) + - to have the Microsoft IME cursor appears at the right location in the screen, setup a handler for the io.ImeSetInputScreenPosFn function: + + #include + #include + static void ImImpl_ImeSetInputScreenPosFn(int x, int y) + { + // Notify OS Input Method Editor of text input position + HWND hwnd = glfwGetWin32Window(window); + if (HIMC himc = ImmGetContext(hwnd)) + { + COMPOSITIONFORM cf; + cf.ptCurrentPos.x = x; + cf.ptCurrentPos.y = y; + cf.dwStyle = CFS_FORCE_POSITION; + ImmSetCompositionWindow(himc, &cf); + } + } + + // Set pointer to handler in ImGuiIO structure + io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn; + + - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will evaluate to a block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. + - tip: you can call Render() multiple times (e.g for VR renders), up to you to communicate the extra state to your RenderDrawListFn function. + - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" + - tip: read the ShowTestWindow() code for more example of how to use ImGui! + + + ISSUES & TODO-LIST + ================== + + - misc: merge or clarify ImVec4 / ImGuiAabb, they are essentially duplicate containers + - window: autofit is losing its purpose when user relies on any dynamic layout (window width multiplier, column). maybe just clearly discard autofit? + - window: add horizontal scroll + - window: fix resize grip rendering scaling along with Rounding style setting + - window: better helpers to set pos/size/collapsed with different options (first-run, session only, current value) (github issue #89) + - widgets: switching from "widget-label" to "label-widget" would make it more convenient to integrate widgets in trees + - widgets: clip text? hover clipped text shows it in a tooltip or in-place overlay + - main: make IsHovered() more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes + - main: make IsHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? + - scrollbar: use relative mouse movement when first-clicking inside of scroll grab box. + - scrollbar: make the grab visible and a minimum size for long scroll regions +!- input number: very large int not reliably supported because of int<>float conversions. + - input number: optional range min/max for Input*() functions + - input number: holding [-]/[+] buttons should increase the step non-linearly + - input number: use mouse wheel to step up/down + - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 horrible layout code. item width should include frame padding, then we can have a generic horizontal layout helper. + - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) + - columns: columns header to act as button (~sort op) and allow resize/reorder + - columns: user specify columns size + - combo: turn child handling code into pop up helper + - list selection, concept of a selectable "block" (that can be multiple widgets) + - menubar, menus + - plot: make it easier for user to draw into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) + - plot: "smooth" automatic scale, user give an input 0.0(full user scale) 1.0(full derived from value) + - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) + - file selection widget -> build the tool in our codebase to improve model-dialog idioms (may or not lead to ImGui changes) + - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() + - slider: initial absolute click is imprecise. change to relative movement slider? hide mouse cursor, allow more precise input using less screen-space. + - text edit: clean up the horrible mess caused by converting UTF-8 <> wchar + - text edit: centered text for slider or input text to it matches typical positioning. + - text edit: flag to disable live update of the user buffer. + - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text? + - text edit: pasting text into a number box should filter the characters the same way direct input does + - text edit: add multi-line text edit + - settings: write more decent code to allow saving/loading new fields + - settings: api for per-tool simple persistent data (bool,int,float) in .ini file + - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) + - log: be able to right-click and log a window or tree-node into tty/file/clipboard? + - filters: set a current filter that tree node can automatically query to hide themselves + - filters: handle wildcards (with implicit leading/trailing *), regexps + - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) + ! keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing + - keyboard: full keyboard navigation and focus. + - input: rework IO to be able to pass actual events to fix temporal aliasing issues. + - input: support track pad style scrolling & slider edit. + - tooltip: move to fit within screen (e.g. when mouse cursor is right of the screen). + - clipboard: automatically transform \n into \n\r or equivalent for higher compatibility on windows + - portability: big-endian test/support (github issue #81) + - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL + - misc: not thread-safe + - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? + - misc: CalcTextSize() could benefit from having 'hide_text_after_double_hash' false by default for external use? + - style editor: add a button to output C code. + - examples: integrate dx11 example. + - examples: integrate opengl 3/4 programmable pipeline example. + - optimization/render: use indexed rendering + - optimization/render: move clip-rect to vertex data? would allow merging all commands + - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? + - optimization/render: font exported by bmfont is not tight fit on vertical axis, incur unneeded pixel-shading cost. + - optimization: turn some the various stack vectors into statically-sized arrays + - optimization: better clipping for multi-component widgets + - optimization: specialize for height based clipping first (assume widgets never go up + height tests before width tests?) +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#include // toupper +#include // sqrtf +#include // intptr_t +#include // vsnprintf +#include // memset +#include // new (ptr) + +#ifdef _MSC_VER +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse and not scary looking. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code, thank you. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#endif + +//------------------------------------------------------------------------- +// Forward Declarations +//------------------------------------------------------------------------- + +static bool ButtonBehaviour(const ImGuiAabb& bb, const ImGuiID& id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat = false); +static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); + +static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true, float wrap_width = 0.0f); +static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); +static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale = 1.0f, bool shadow = false); + +static void ItemSize(ImVec2 size, ImVec2* adjust_start_offset = NULL); +static void ItemSize(const ImGuiAabb& aabb, ImVec2* adjust_start_offset = NULL); +static void PushColumnClipRect(int column_index = -1); +static bool IsClipped(const ImGuiAabb& aabb); +static bool ClipAdvance(const ImGuiAabb& aabb); + +static bool IsMouseHoveringBox(const ImGuiAabb& box); +static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); + +static bool CloseWindowButton(bool* open = NULL); +static void FocusWindow(ImGuiWindow* window); +static ImGuiWindow* FindWindow(const char* name); +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); + +//----------------------------------------------------------------------------- +// Platform dependent default implementations +//----------------------------------------------------------------------------- + +static const char* GetClipboardTextFn_DefaultImpl(); +static void SetClipboardTextFn_DefaultImpl(const char* text); + +//----------------------------------------------------------------------------- +// User facing structures +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + Alpha = 1.0f; // Global alpha applies to everything in ImGui + WindowPadding = ImVec2(8,8); // Padding within a window + WindowMinSize = ImVec2(48,48); // Minimum window size + FramePadding = ImVec2(5,4); // Padding within a framed rectangle (used by most widgets) + ItemSpacing = ImVec2(10,5); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(5,5); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + TouchExtraPadding = ImVec2(0,0); // Expand bounding box for touch-based system where touch position is not accurate enough (unnecessary for mouse inputs). Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget running. So dont grow this too much! + AutoFitPadding = ImVec2(8,8); // Extra space after auto-fit (double-clicking on resize grip) + WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin() + WindowRounding = 10.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + TreeNodeSpacing = 22.0f; // Horizontal spacing when entering a tree node + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns + ScrollBarWidth = 16.0f; // Width of the vertical scroll bar + + Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + Colors[ImGuiCol_Border] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); + Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input + Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); + Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); + Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); + Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); + Colors[ImGuiCol_CheckHovered] = ImVec4(0.60f, 0.40f, 0.40f, 0.45f); + Colors[ImGuiCol_CheckActive] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); + Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); + Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + Colors[ImGuiCol_HeaderActive] = ImVec4(0.60f, 0.60f, 0.80f, 1.00f); + Colors[ImGuiCol_Column] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + Colors[ImGuiCol_ColumnHovered] = ImVec4(0.60f, 0.40f, 0.40f, 1.00f); + Colors[ImGuiCol_ColumnActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); + Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); + Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); + Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); + Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); + Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); +} + +ImGuiIO::ImGuiIO() +{ + memset(this, 0, sizeof(*this)); + DeltaTime = 1.0f/60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; + LogFilename = "imgui_log.txt"; + Font = NULL; + FontGlobalScale = 1.0f; + FontAllowUserScaling = false; + PixelCenterOffset = 0.0f; + MousePos = ImVec2(-1,-1); + MousePosPrev = ImVec2(-1,-1); + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + UserData = NULL; + + // User functions + RenderDrawListsFn = NULL; + MemAllocFn = malloc; + MemReallocFn = realloc; + MemFreeFn = free; + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependant default implementations + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; + ImeSetInputScreenPosFn = NULL; +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the VM_CHAR message +static size_t ImStrlenW(const ImWchar* str); +void ImGuiIO::AddInputCharacter(ImWchar c) +{ + const size_t n = ImStrlenW(InputCharacters); + if (n + 1 < sizeof(InputCharacters) / sizeof(InputCharacters[0])) + { + InputCharacters[n] = c; + InputCharacters[n+1] = 0; + } +} + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) + +#undef PI +const float PI = 3.14159265358979323846f; + +#ifdef INT_MAX +#define IM_INT_MAX INT_MAX +#else +#define IM_INT_MAX 2147483647 +#endif + +// Math bits +// We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types. +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } +//static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +//static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } + +static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } +static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } +static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } +static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } +static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } +static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } +static inline float ImClamp(float f, float mn, float mx) { return (f < mn) ? mn : (f > mx) ? mx : f; } +static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } +//static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return a + (b - a) * t; } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline float ImLength(const ImVec2& lhs) { return sqrtf(lhs.x*lhs.x + lhs.y*lhs.y); } + +static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int in_char); // return output UTF-8 bytes count +static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count +static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count +static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +static int ImTextCountUtf8BytesFromWchar(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points + +static int ImStricmp(const char* str1, const char* str2) +{ + int d; + while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } + return d; +} + +static int ImStrnicmp(const char* str1, const char* str2, int count) +{ + int d = 0; + while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + return d; +} + +static char* ImStrdup(const char *str) +{ + char *buff = (char*)ImGui::MemAlloc(strlen(str) + 1); + IM_ASSERT(buff); + strcpy(buff, str); + return buff; +} + +static size_t ImStrlenW(const ImWchar* str) +{ + size_t n = 0; + while (*str++) + n++; + return n; +} + +static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end) +{ + if (!needle_end) + needle_end = needle + strlen(needle); + + const char un0 = (char)toupper(*needle); + while (*haystack) + { + if (toupper(*haystack) == un0) + { + const char* b = needle + 1; + for (const char* a = haystack + 1; b < needle_end; a++, b++) + if (toupper(*a) != toupper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + +static ImU32 crc32(const void* data, size_t data_size, ImU32 seed = 0) +{ + static ImU32 crc32_lut[256] = { 0 }; + if (!crc32_lut[1]) + { + const ImU32 polynomial = 0xEDB88320; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; + } + } + ImU32 crc = ~seed; + const unsigned char* current = (const unsigned char*)data; + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + return ~crc; +} + +static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + buf[buf_size-1] = 0; + return (w == -1) ? buf_size : (size_t)w; +} + +static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) +{ + int w = vsnprintf(buf, buf_size, fmt, args); + buf[buf_size-1] = 0; + return (w == -1) ? buf_size : (size_t)w; +} + +static ImU32 ImConvertColorFloat4ToU32(const ImVec4& in) +{ + ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f)); + out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8); + out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16); + out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24); + return out; +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +static void ImConvertColorRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) +{ + float K = 0.f; + if (g < b) + { + const float tmp = g; g = b; b = tmp; + K = -1.f; + } + if (r < g) + { + const float tmp = r; r = g; g = tmp; + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +static void ImConvertColorHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = fmodf(h, 1.0f) / (60.0f/360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: out_r = v; out_g = t; out_b = p; break; + case 1: out_r = q; out_g = v; out_b = p; break; + case 2: out_r = p; out_g = v; out_b = t; break; + case 3: out_r = p; out_g = q; out_b = v; break; + case 4: out_r = t; out_g = p; out_b = v; break; + case 5: default: out_r = v; out_g = p; out_b = q; break; + } +} + +//----------------------------------------------------------------------------- + +struct ImGuiColMod // Color modifier, backup of modified data so we can restore it +{ + ImGuiCol Col; + ImVec4 PreviousValue; +}; + +struct ImGuiStyleMod // Style modifier, backup of modified data so we can restore it +{ + ImGuiStyleVar Var; + ImVec2 PreviousValue; +}; + +struct ImGuiAabb // 2D axis aligned bounding-box +{ + ImVec2 Min; + ImVec2 Max; + + ImGuiAabb() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); } + ImGuiAabb(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; } + ImGuiAabb(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; } + ImGuiAabb(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; } + + ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; } + ImVec2 GetSize() const { return Max-Min; } + float GetWidth() const { return (Max-Min).x; } + float GetHeight() const { return (Max-Min).y; } + ImVec2 GetTL() const { return Min; } + ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); } + ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); } + ImVec2 GetBR() const { return Max; } + bool Contains(ImVec2 p) const { return p.x >= Min.x && p.y >= Min.y && p.x <= Max.x && p.y <= Max.y; } + bool Contains(const ImGuiAabb& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool Overlaps(const ImGuiAabb& r) const { return r.Min.y <= Max.y && r.Max.y >= Min.y && r.Min.x <= Max.x && r.Max.x >= Min.x; } + void Expand(ImVec2 sz) { Min -= sz; Max += sz; } + void Clip(const ImGuiAabb& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); } +}; + +// Temporary per-window data, reset at the beginning of the frame +struct ImGuiDrawContext +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; + float CurrentLineHeight; + float PrevLineHeight; + float LogLineHeight; + int TreeDepth; + ImGuiAabb LastItemAabb; + bool LastItemHovered; + bool LastItemFocused; + ImVector ChildWindows; + ImVector AllowKeyboardFocus; + ImVector ItemWidth; + ImVector TextWrapPos; + ImGuiColorEditMode ColorEditMode; + ImGuiStorage* StateStorage; + int OpenNextNode; + + float ColumnsStartX; // Start position from left of window (increased by TreePush/TreePop, etc.) + float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + int ColumnsCurrent; + int ColumnsCount; + ImVec2 ColumnsStartPos; + float ColumnsCellMinY; + float ColumnsCellMaxY; + bool ColumnsShowBorders; + ImGuiID ColumnsSetID; + + ImGuiDrawContext() + { + CursorPos = CursorPosPrevLine = CursorStartPos = ImVec2(0.0f, 0.0f); + CurrentLineHeight = PrevLineHeight = 0.0f; + LogLineHeight = -1.0f; + TreeDepth = 0; + LastItemAabb = ImGuiAabb(0.0f,0.0f,0.0f,0.0f); + LastItemHovered = false; + LastItemFocused = true; + StateStorage = NULL; + OpenNextNode = -1; + + ColumnsStartX = 0.0f; + ColumnsOffsetX = 0.0f; + ColumnsCurrent = 0; + ColumnsCount = 1; + ColumnsStartPos = ImVec2(0.0f, 0.0f); + ColumnsCellMinY = ColumnsCellMaxY = 0.0f; + ColumnsShowBorders = true; + ColumnsSetID = 0; + } +}; + +struct ImGuiTextEditState; +#define STB_TEXTEDIT_STRING ImGuiTextEditState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#include "stb_textedit.h" + +// Internal state of the currently focused/edited text input box +struct ImGuiTextEditState +{ + ImWchar Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + char InitialText[1024*3+1]; // backup of end-user buffer at the time of focus (in UTF-8, unconverted) + size_t BufSize; // end-user buffer size, <= 1024 (or increase above) + float Width; // widget width + float ScrollX; + STB_TexteditState StbState; + float CursorAnim; + ImVec2 LastCursorPos; // Cursor position in screen space to be used by IME callback. + bool SelectedAllMouseLock; + ImFont* Font; + float FontSize; + + ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } + + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking + bool HasSelection() const { return StbState.select_start != StbState.select_end; } + void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)ImStrlenW(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } + + void OnKeyPressed(int key); + void UpdateScrollOffset(); + ImVec2 CalcDisplayOffsetFromCharIdx(int i) const; + + // Static functions because they are used to render non-focused instances of a text input box + static const char* GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL); + static const ImWchar* GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size = NULL); + static void RenderTextScrolledClipped(ImFont* font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x); +}; + +struct ImGuiIniData +{ + char* Name; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; + + ImGuiIniData() { memset(this, 0, sizeof(*this)); } + ~ImGuiIniData() { if (Name) { ImGui::MemFree(Name); Name = NULL; } } +}; + +struct ImGuiState +{ + bool Initialized; + ImGuiIO IO; + ImGuiStyle Style; + float FontSize; // == IO.FontGlobalScale * IO.Font->Scale * IO.Font->Info->FontSize. Vertical distance between two lines of text, aka == CalcTextSize(" ").y + ImVec2 FontTexUvForWhite; // == IO.Font->FontTexUvForWhite (cached copy) + + float Time; + int FrameCount; + int FrameCountRendered; + ImVector Windows; + ImGuiWindow* CurrentWindow; // Being drawn into + ImVector CurrentWindowStack; + ImGuiWindow* FocusedWindow; // Will catch keyboard inputs + ImGuiWindow* HoveredWindow; // Will catch mouse inputs + ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiID HoveredId; + ImGuiID ActiveId; + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdIsAlive; + float SettingsDirtyTimer; + ImVector Settings; + ImVec2 NewWindowDefaultPos; + ImVector ColorModifiers; + ImVector StyleModifiers; + + // Render + ImVector RenderDrawLists; + + // Widget state + ImGuiTextEditState InputTextState; + ImGuiID SliderAsInputTextId; + ImGuiStorage ColorEditModeStorage; // for user selection + ImGuiID ActiveComboID; + char Tooltip[1024]; + char* PrivateClipboard; // if no custom clipboard handler is defined + + // Logging + bool LogEnabled; + FILE* LogFile; + ImGuiTextBuffer* LogClipboard; // pointer so our GImGui static constructor doesn't call heap allocators. + int LogAutoExpandMaxDepth; + + ImGuiState() + { + Initialized = false; + Time = 0.0f; + FrameCount = 0; + FrameCountRendered = -1; + CurrentWindow = NULL; + FocusedWindow = NULL; + HoveredWindow = NULL; + HoveredRootWindow = NULL; + ActiveIdIsAlive = false; + SettingsDirtyTimer = 0.0f; + NewWindowDefaultPos = ImVec2(60, 60); + SliderAsInputTextId = 0; + ActiveComboID = 0; + memset(Tooltip, 0, sizeof(Tooltip)); + PrivateClipboard = NULL; + LogEnabled = false; + LogFile = NULL; + LogAutoExpandMaxDepth = 2; + LogClipboard = NULL; + } +}; + +static ImGuiState GImGui; + +struct ImGuiWindow +{ + char* Name; + ImGuiID ID; + ImGuiWindowFlags Flags; + ImVec2 PosFloat; + ImVec2 Pos; // Position rounded-up to nearest pixel + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 SizeContentsFit; // Size of contents (extents reach by the drawing cursor) - may not fit within Size. + float ScrollY; + float NextScrollY; + bool ScrollbarY; + bool Visible; // Set to true on Begin() + bool Accessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool SkipItems; // == Visible && !Collapsed + int AutoFitFrames; + bool AutoFitOnlyGrows; + + ImGuiDrawContext DC; + ImVector IDStack; + ImVector ClipRectStack; + int LastFrameDrawn; + float ItemWidthDefault; + ImGuiStorage StateStorage; + float FontWindowScale; // Scale multiplier per-window + ImDrawList* DrawList; + ImGuiWindow* RootWindow; + + // Focus + int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() + int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) + int FocusIdxAllRequestCurrent; // Item being requested for focus + int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus + int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) + int FocusIdxTabRequestNext; // " + +public: + ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str); + ImGuiID GetID(const void* ptr); + + void AddToRenderList(); + bool FocusItemRegister(bool is_active, bool tab_stop = true); // Return true if focus is requested + void FocusItemUnregister(); + + ImGuiAabb Aabb() const { return ImGuiAabb(Pos, Pos+Size); } + ImFont* Font() const { return GImGui.IO.Font; } + float FontSize() const { return GImGui.FontSize * FontWindowScale; } + ImVec2 CursorPos() const { return DC.CursorPos; } + float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : FontSize() + GImGui.Style.FramePadding.y * 2.0f; } + ImGuiAabb TitleBarAabb() const { return ImGuiAabb(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); } + ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders)) ? ImVec2(1,1) : GImGui.Style.WindowPadding; } + ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui.Style.Colors[idx]; c.w *= GImGui.Style.Alpha * a; return ImConvertColorFloat4ToU32(c); } + ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui.Style.Alpha; return ImConvertColorFloat4ToU32(c); } +}; + +static ImGuiWindow* GetCurrentWindow() +{ + IM_ASSERT(GImGui.CurrentWindow != NULL); // ImGui::NewFrame() hasn't been called yet? + GImGui.CurrentWindow->Accessed = true; + return GImGui.CurrentWindow; +} + +static void RegisterAliveId(const ImGuiID& id) +{ + if (GImGui.ActiveId == id) + GImGui.ActiveIdIsAlive = true; +} + +//----------------------------------------------------------------------------- + +// Helper: Key->value storage +void ImGuiStorage::Clear() +{ + Data.clear(); +} + +// std::lower_bound but without the bullshit +static ImVector::iterator LowerBound(ImVector& data, ImU32 key) +{ + ImVector::iterator first = data.begin(); + ImVector::iterator last = data.end(); + int count = (int)(last - first); + while (count > 0) + { + int count2 = count / 2; + ImVector::iterator mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return first; +} + +int* ImGuiStorage::Find(ImU32 key) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end()) + return NULL; + if (it->key != key) + return NULL; + return &it->val; +} + +int ImGuiStorage::GetInt(ImU32 key, int default_val) +{ + int* pval = Find(key); + if (!pval) + return default_val; + return *pval; +} + +// FIXME-OPT: We are wasting time because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place. +// However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed. +void ImGuiStorage::SetInt(ImU32 key, int val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it != Data.end() && it->key == key) + { + it->val = val; + } + else + { + Pair pair_key; + pair_key.key = key; + pair_key.val = val; + Data.insert(it, pair_key); + } +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (size_t i = 0; i < Data.size(); i++) + Data[i].val = v; +} + +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter() +{ + InputBuf[0] = 0; + CountGrep = 0; +} + +void ImGuiTextFilter::Draw(const char* label, float width) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (width < 0.0f) + { + ImVec2 label_size = ImGui::CalcTextSize(label, NULL); + width = ImMax(window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x - (label_size.x + GImGui.Style.ItemSpacing.x*4), 10.0f); + } + ImGui::PushItemWidth(width); + ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + ImGui::PopItemWidth(); + Build(); +} + +void ImGuiTextFilter::TextRange::split(char separator, ImVector& out) +{ + out.resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out.push_back(TextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out.push_back(TextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); + input_range.split(',', Filters); + + CountGrep = 0; + for (size_t i = 0; i != Filters.size(); i++) + { + Filters[i].trim_blanks(); + if (Filters[i].empty()) + continue; + if (Filters[i].front() != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char* val) const +{ + if (Filters.empty()) + return true; + + if (val == NULL) + val = ""; + + for (size_t i = 0; i != Filters.size(); i++) + { + const TextRange& f = Filters[i]; + if (f.empty()) + continue; + if (f.front() == '-') + { + // Subtract + if (ImStristr(val, f.begin()+1, f.end()) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(val, f.begin(), f.end()) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::append(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + int len = vsnprintf(NULL, 0, fmt, args); + va_end(args); + if (len <= 0) + return; + + const size_t write_off = Buf.size(); + if (write_off + (size_t)len >= Buf.capacity()) + Buf.reserve(Buf.capacity() * 2); + + Buf.resize(write_off + (size_t)len); + + va_start(args, fmt); + ImFormatStringV(&Buf[write_off] - 1, (size_t)len+1, fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- + +ImGuiWindow::ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size) +{ + Name = ImStrdup(name); + ID = GetID(name); + IDStack.push_back(ID); + + PosFloat = default_pos; + Pos = ImVec2((float)(int)PosFloat.x, (float)(int)PosFloat.y); + Size = SizeFull = default_size; + SizeContentsFit = ImVec2(0.0f, 0.0f); + ScrollY = 0.0f; + NextScrollY = 0.0f; + ScrollbarY = false; + Visible = false; + Accessed = false; + Collapsed = false; + SkipItems = false; + AutoFitFrames = -1; + AutoFitOnlyGrows = false; + LastFrameDrawn = -1; + ItemWidthDefault = 0.0f; + FontWindowScale = 1.0f; + + if (ImLength(Size) < 0.001f) + { + AutoFitFrames = 2; + AutoFitOnlyGrows = true; + } + + DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); + new(DrawList) ImDrawList(); + + FocusIdxAllCounter = FocusIdxTabCounter = -1; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX; +} + +ImGuiWindow::~ImGuiWindow() +{ + DrawList->~ImDrawList(); + ImGui::MemFree(DrawList); + DrawList = NULL; + ImGui::MemFree(Name); + Name = NULL; +} + +ImGuiID ImGuiWindow::GetID(const char* str) +{ + const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back(); + const ImGuiID id = crc32(str, strlen(str), seed); // FIXME-OPT: crc32 function/variant should handle zero-terminated strings + RegisterAliveId(id); + return id; +} + +ImGuiID ImGuiWindow::GetID(const void* ptr) +{ + const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back(); + const ImGuiID id = crc32(&ptr, sizeof(void*), seed); + RegisterAliveId(id); + return id; +} + +bool ImGuiWindow::FocusItemRegister(bool is_active, bool tab_stop) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus.back(); + FocusIdxAllCounter++; + if (allow_keyboard_focus) + FocusIdxTabCounter++; + + if (is_active) + window->DC.LastItemFocused = true; + + // Process keyboard input at this point: TAB, Shift-TAB switch focus + // We can always TAB out of a widget that doesn't allow tabbing in. + if (tab_stop && FocusIdxAllRequestNext == IM_INT_MAX && FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) + { + // Modulo on index will be applied at the end of frame once we've got the total counter of items. + FocusIdxTabRequestNext = FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); + } + + if (FocusIdxAllCounter == FocusIdxAllRequestCurrent) + return true; + + if (allow_keyboard_focus) + if (FocusIdxTabCounter == FocusIdxTabRequestCurrent) + return true; + + return false; +} + +void ImGuiWindow::FocusItemUnregister() +{ + FocusIdxAllCounter--; + FocusIdxTabCounter--; +} + +void ImGuiWindow::AddToRenderList() +{ + ImGuiState& g = GImGui; + + if (!DrawList->commands.empty() && !DrawList->vtx_buffer.empty()) + { + if (DrawList->commands.back().vtx_count == 0) + DrawList->commands.pop_back(); + g.RenderDrawLists.push_back(DrawList); + } + for (size_t i = 0; i < DC.ChildWindows.size(); i++) + { + ImGuiWindow* child = DC.ChildWindows[i]; + if (child->Visible) // clipped childs may have been marked not Visible + child->AddToRenderList(); + } +} + +//----------------------------------------------------------------------------- + +void* ImGui::MemAlloc(size_t sz) +{ + return GImGui.IO.MemAllocFn(sz); +} + +void ImGui::MemFree(void* ptr) +{ + return GImGui.IO.MemFreeFn(ptr); +} + +void* ImGui::MemRealloc(void* ptr, size_t sz) +{ + return GImGui.IO.MemReallocFn(ptr, sz); +} + +static ImGuiIniData* FindWindowSettings(const char* name) +{ + ImGuiState& g = GImGui; + + for (size_t i = 0; i != g.Settings.size(); i++) + { + ImGuiIniData* ini = g.Settings[i]; + if (ImStricmp(ini->Name, name) == 0) + return ini; + } + ImGuiIniData* ini = (ImGuiIniData*)ImGui::MemAlloc(sizeof(ImGuiIniData)); + new(ini) ImGuiIniData(); + ini->Name = ImStrdup(name); + ini->Collapsed = false; + ini->Pos = ImVec2(FLT_MAX,FLT_MAX); + ini->Size = ImVec2(0,0); + g.Settings.push_back(ini); + return ini; +} + +// Zero-tolerance, poor-man .ini parsing +// FIXME: Write something less rubbish +static void LoadSettings() +{ + ImGuiState& g = GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + // Load file + FILE* f; + if ((f = fopen(filename, "rt")) == NULL) + return; + if (fseek(f, 0, SEEK_END)) + { + fclose(f); + return; + } + const long f_size_signed = ftell(f); + if (f_size_signed == -1) + { + fclose(f); + return; + } + size_t f_size = (size_t)f_size_signed; + if (fseek(f, 0, SEEK_SET)) + { + fclose(f); + return; + } + char* f_data = (char*)ImGui::MemAlloc(f_size+1); + f_size = fread(f_data, 1, f_size, f); // Text conversion alter read size so let's not be fussy about return value + fclose(f); + if (f_size == 0) + { + ImGui::MemFree(f_data); + return; + } + f_data[f_size] = 0; + + ImGuiIniData* settings = NULL; + const char* buf_end = f_data + f_size; + for (const char* line_start = f_data; line_start < buf_end; ) + { + const char* line_end = line_start; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + + if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') + { + char name[64]; + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); + settings = FindWindowSettings(name); + } + else if (settings) + { + float x, y; + int i; + if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) + settings->Pos = ImVec2(x, y); + else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) + settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + else if (sscanf(line_start, "Collapsed=%d", &i) == 1) + settings->Collapsed = (i != 0); + } + + line_start = line_end+1; + } + + ImGui::MemFree(f_data); +} + +static void SaveSettings() +{ + ImGuiState& g = GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + // Gather data from windows that were active during this session + for (size_t i = 0; i != g.Windows.size(); i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) + continue; + ImGuiIniData* settings = FindWindowSettings(window->Name); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write .ini file + // If a window wasn't opened in this session we preserve its settings + FILE* f = fopen(filename, "wt"); + if (!f) + return; + for (size_t i = 0; i != g.Settings.size(); i++) + { + const ImGuiIniData* settings = g.Settings[i]; + if (settings->Pos.x == FLT_MAX) + continue; + fprintf(f, "[%s]\n", settings->Name); + fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + fprintf(f, "Collapsed=%d\n", settings->Collapsed); + fprintf(f, "\n"); + } + + fclose(f); +} + +static void MarkSettingsDirty() +{ + ImGuiState& g = GImGui; + + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +ImGuiIO& ImGui::GetIO() +{ + return GImGui.IO; +} + +ImGuiStyle& ImGui::GetStyle() +{ + return GImGui.Style; +} + +void ImGui::NewFrame() +{ + ImGuiState& g = GImGui; + + // Check user inputs + IM_ASSERT(g.IO.DeltaTime > 0.0f); + IM_ASSERT(g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f); + IM_ASSERT(g.IO.RenderDrawListsFn != NULL); // Must be implemented + + if (!g.Initialized) + { + // Initialize on first frame + g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); + new(g.LogClipboard) ImGuiTextBuffer(); + + IM_ASSERT(g.Settings.empty()); + LoadSettings(); + if (!g.IO.Font) + { + // Default font + const void* fnt_data; + unsigned int fnt_size; + ImGui::GetDefaultFontData(&fnt_data, &fnt_size, NULL, NULL); + g.IO.Font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); + new(g.IO.Font) ImFont(); + g.IO.Font->LoadFromMemory(fnt_data, fnt_size); + IM_ASSERT(g.IO.Font->IsLoaded()); // Font failed to load + g.IO.Font->DisplayOffset = ImVec2(0.0f, +1.0f); + } + g.Initialized = true; + } + + IM_ASSERT(g.IO.Font && g.IO.Font->IsLoaded()); // Font not loaded + IM_ASSERT(g.IO.Font->Scale > 0.0f); + g.FontSize = g.IO.FontGlobalScale * (float)g.IO.Font->Info->FontSize * g.IO.Font->Scale; + g.FontTexUvForWhite = g.IO.Font->TexUvForWhite; + g.IO.Font->FallbackGlyph = g.IO.Font->FindGlyph(g.IO.Font->FallbackChar); + + g.Time += g.IO.DeltaTime; + g.FrameCount += 1; + g.Tooltip[0] = '\0'; + + // Update inputs state + if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) + g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); + if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta + g.IO.MouseDelta = ImVec2(0.0f, 0.0f); + else + g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; + g.IO.MousePosPrev = g.IO.MousePos; + for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + g.IO.MouseDownTime[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownTime[i] < 0.0f ? 0.0f : g.IO.MouseDownTime[i] + g.IO.DeltaTime) : -1.0f; + g.IO.MouseClicked[i] = (g.IO.MouseDownTime[i] == 0.0f); + g.IO.MouseDoubleClicked[i] = false; + if (g.IO.MouseClicked[i]) + { + if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) + { + if (ImLength(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist) + g.IO.MouseDoubleClicked[i] = true; + g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click + } + else + { + g.IO.MouseClickedTime[i] = g.Time; + g.IO.MouseClickedPos[i] = g.IO.MousePos; + } + } + } + for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownTime[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownTime[i] < 0.0f ? 0.0f : g.IO.KeysDownTime[i] + g.IO.DeltaTime) : -1.0f; + + // Clear reference to active widget if the widget isn't alive anymore + g.HoveredId = 0; + if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) + g.ActiveId = 0; + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdIsAlive = false; + + // Delay saving settings so we don't spam disk too much + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + SaveSettings(); + } + + g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false); + g.HoveredRootWindow = FindHoveredWindow(g.IO.MousePos, true); + + // Are we using inputs? Tell user so they can capture/discard them. + g.IO.WantCaptureMouse = (g.HoveredWindow != NULL) || (g.ActiveId != 0); + g.IO.WantCaptureKeyboard = (g.ActiveId != 0); + + // Scale & Scrolling + if (g.HoveredWindow && g.IO.MouseWheel != 0.0f) + { + ImGuiWindow* window = g.HoveredWindow; + if (g.IO.KeyCtrl) + { + if (g.IO.FontAllowUserScaling) + { + // Zoom / Scale window + float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + window->Pos += offset; + window->PosFloat += offset; + window->Size *= scale; + window->SizeFull *= scale; + } + } + else + { + // Scroll + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) + { + const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; + window->NextScrollY -= g.IO.MouseWheel * window->FontSize() * scroll_lines; + } + } + } + + // Pressing TAB activate widget focus + // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. + if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Visible && IsKeyPressedMap(ImGuiKey_Tab, false)) + { + g.FocusedWindow->FocusIdxTabRequestNext = 0; + } + + // Mark all windows as not visible + for (size_t i = 0; i != g.Windows.size(); i++) + { + ImGuiWindow* window = g.Windows[i]; + window->Visible = false; + window->Accessed = false; + } + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.clear(); + + // Create implicit window - we will only render it if the user has added something to it. + ImGui::Begin("Debug", NULL, ImVec2(400,400)); +} + +// NB: behaviour of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. +void ImGui::Shutdown() +{ + ImGuiState& g = GImGui; + if (!g.Initialized) + return; + + SaveSettings(); + + for (size_t i = 0; i < g.Windows.size(); i++) + { + g.Windows[i]->~ImGuiWindow(); + ImGui::MemFree(g.Windows[i]); + } + g.Windows.clear(); + g.CurrentWindowStack.clear(); + g.RenderDrawLists.clear(); + g.FocusedWindow = NULL; + g.HoveredWindow = NULL; + g.HoveredRootWindow = NULL; + for (size_t i = 0; i < g.Settings.size(); i++) + { + g.Settings[i]->~ImGuiIniData(); + ImGui::MemFree(g.Settings[i]); + } + g.Settings.clear(); + g.ColorEditModeStorage.Clear(); + if (g.LogFile && g.LogFile != stdout) + { + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.IO.Font) + { + g.IO.Font->~ImFont(); + ImGui::MemFree(g.IO.Font); + g.IO.Font = NULL; + } + + if (g.PrivateClipboard) + { + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + + if (g.LogClipboard) + { + g.LogClipboard->~ImGuiTextBuffer(); + ImGui::MemFree(g.LogClipboard); + } + + g.Initialized = false; +} + +static void AddWindowToSortedBuffer(ImGuiWindow* window, ImVector& sorted_windows) +{ + sorted_windows.push_back(window); + if (window->Visible) + { + for (size_t i = 0; i < window->DC.ChildWindows.size(); i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (child->Visible) + AddWindowToSortedBuffer(child, sorted_windows); + } + } +} + +static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) +{ + ImGuiWindow* window = GetCurrentWindow(); + + ImVec4 cr = clip_rect; + if (clipped && !window->ClipRectStack.empty()) + { + // Clip to new clip rect + const ImVec4 cur_cr = window->ClipRectStack.back(); + cr = ImVec4(ImMax(cr.x, cur_cr.x), ImMax(cr.y, cur_cr.y), ImMin(cr.z, cur_cr.z), ImMin(cr.w, cur_cr.w)); + } + + window->ClipRectStack.push_back(cr); + window->DrawList->PushClipRect(cr); +} + +static void PopClipRect() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ClipRectStack.pop_back(); + window->DrawList->PopClipRect(); +} + +void ImGui::Render() +{ + ImGuiState& g = GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + const bool first_render_of_the_frame = (g.FrameCountRendered != g.FrameCount); + g.FrameCountRendered = g.FrameCount; + + if (first_render_of_the_frame) + { + // Hide implicit window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.size() == 1); // Mismatched Begin/End + if (g.CurrentWindow && !g.CurrentWindow->Accessed) + g.CurrentWindow->Visible = false; + ImGui::End(); + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + ImVector sorted_windows; + sorted_windows.reserve(g.Windows.size()); + for (size_t i = 0; i != g.Windows.size(); i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_ChildWindow) // if a child is visible its parent will add it + if (window->Visible) + continue; + AddWindowToSortedBuffer(window, sorted_windows); + } + IM_ASSERT(g.Windows.size() == sorted_windows.size()); // We done something wrong + g.Windows.swap(sorted_windows); + + // Clear data for next frame + g.IO.MouseWheel = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + } + + // Skip render altogether if alpha is 0.0 + // Note that vertex buffers have been created, so it is best practice that you don't call Begin/End in the first place. + if (g.Style.Alpha > 0.0f) + { + // Render tooltip + if (g.Tooltip[0]) + { + // Use a dummy window to render the tooltip + ImGui::BeginTooltip(); + ImGui::TextUnformatted(g.Tooltip); + ImGui::EndTooltip(); + } + + // Gather windows to render + g.RenderDrawLists.resize(0); + for (size_t i = 0; i != g.Windows.size(); i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Visible && (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) + window->AddToRenderList(); + } + for (size_t i = 0; i != g.Windows.size(); i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Visible && (window->Flags & ImGuiWindowFlags_Tooltip)) + window->AddToRenderList(); + } + + // Render + if (!g.RenderDrawLists.empty()) + g.IO.RenderDrawListsFn(&g.RenderDrawLists[0], (int)g.RenderDrawLists.size()); + g.RenderDrawLists.resize(0); + } +} + +// Find the optional ## from which we stop displaying text. +static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL) +{ + const char* text_display_end = text; + while ((!text_end || text_display_end < text_end) && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Log ImGui display into text output (tty or file or clipboard) +static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (!text_end) + text_end = FindTextDisplayEnd(text, text_end); + + const bool log_new_line = ref_pos.y > window->DC.LogLineHeight+1; + window->DC.LogLineHeight = ref_pos.y; + + const char* text_remaining = text; + const int tree_depth = window->DC.TreeDepth; + while (true) + { + const char* line_end = text_remaining; + while (line_end < text_end) + if (*line_end == '\n') + break; + else + line_end++; + if (line_end >= text_end) + line_end = NULL; + + const bool is_first_line = (text == text_remaining); + bool is_last_line = false; + if (line_end == NULL) + { + is_last_line = true; + line_end = text_end; + } + if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) + { + const int char_count = (int)(line_end - text_remaining); + if (g.LogFile) + { + if (log_new_line || !is_first_line) + fprintf(g.LogFile, "\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); + else + fprintf(g.LogFile, " %.*s", char_count, text_remaining); + } + else + { + if (log_new_line || !is_first_line) + g.LogClipboard->append("\n%*s%.*s", tree_depth*4, "", char_count, text_remaining); + else + g.LogClipboard->append(" %.*s", char_count, text_remaining); + } + } + + if (is_last_line) + break; + text_remaining = line_end + 1; + } +} + +static float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindow(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = ImGui::GetContentRegionMax().x; + if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x; // wrap_pos_x is provided is window local space + + const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; + return wrap_width; +} + +// Internal ImGui function to render text (called from ImGui::Text(), ImGui::TextUnformatted(), etc.) +// RenderText() calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash, float wrap_width) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindTextDisplayEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + text_display_end = text_end; + } + + const int text_len = (int)(text_display_end - text); + if (text_len > 0) + { + // Render + window->DrawList->AddText(window->Font(), window->FontSize(), pos, window->Color(ImGuiCol_Text), text, text + text_len, wrap_width); + + // Log as text. We split text into individual lines to add current tree level padding + if (g.LogEnabled) + LogText(pos, text, text_display_end); + } +} + +// Render a rectangle shaped with optional rounding and borders +static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +{ + ImGuiWindow* window = GetCurrentWindow(); + + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) + { + // FIXME: This is the best I've found that works on multiple renderer/back ends. Rather dodgy. + const float offset = GImGui.IO.PixelCenterOffset; + window->DrawList->AddRect(p_min+ImVec2(1.5f-offset,1.5f-offset), p_max+ImVec2(1.0f-offset*2,1.0f-offset*2), window->Color(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(p_min+ImVec2(0.5f-offset,0.5f-offset), p_max+ImVec2(0.0f-offset*2,0.0f-offset*2), window->Color(ImGuiCol_Border), rounding); + } +} + +// Render a triangle to denote expanded/collapsed state +static void RenderCollapseTriangle(ImVec2 p_min, bool open, float scale, bool shadow) +{ + ImGuiWindow* window = GetCurrentWindow(); + + const float h = window->FontSize() * 1.00f; + const float r = h * 0.40f * scale; + ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); + + ImVec2 a, b, c; + if (open) + { + center.y -= r*0.25f; + a = center + ImVec2(0,1)*r; + b = center + ImVec2(-0.866f,-0.5f)*r; + c = center + ImVec2(0.866f,-0.5f)*r; + } + else + { + a = center + ImVec2(1,0)*r; + b = center + ImVec2(-0.500f,0.866f)*r; + c = center + ImVec2(-0.500f,-0.866f)*r; + } + + if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0) + window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), window->Color(ImGuiCol_BorderShadow)); + window->DrawList->AddTriangleFilled(a, b, c, window->Color(ImGuiCol_Border)); +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, GImGui.FontSize) +ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + + const char* text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + const ImVec2 text_size = window->Font()->CalcTextSizeA(window->FontSize(), FLT_MAX, wrap_width, text, text_display_end, NULL); + return text_size; +} + +// Find window given position, search front-to-back +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) +{ + ImGuiState& g = GImGui; + for (int i = (int)g.Windows.size()-1; i >= 0; i--) + { + ImGuiWindow* window = g.Windows[(size_t)i]; + if (!window->Visible) + continue; + if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) + continue; + ImGuiAabb bb(window->Pos - g.Style.TouchExtraPadding, window->Pos+window->Size + g.Style.TouchExtraPadding); + if (bb.Contains(pos)) + return window; + } + return NULL; +} + +// Test if mouse cursor is hovering given aabb +// NB- Box is clipped by our current clip setting +// NB- Expand the aabb to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +static bool IsMouseHoveringBox(const ImGuiAabb& box) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Clip + ImGuiAabb box_clipped = box; + if (!window->ClipRectStack.empty()) + { + const ImVec4 clip_rect = window->ClipRectStack.back(); + box_clipped.Clip(ImGuiAabb(ImVec2(clip_rect.x, clip_rect.y), ImVec2(clip_rect.z, clip_rect.w))); + } + + // Expand for touch input + const ImGuiAabb box_for_touch(box_clipped.Min - g.Style.TouchExtraPadding, box_clipped.Max + g.Style.TouchExtraPadding); + return box_for_touch.Contains(g.IO.MousePos); +} + +bool ImGui::IsMouseHoveringBox(const ImVec2& box_min, const ImVec2& box_max) +{ + return IsMouseHoveringBox(ImGuiAabb(box_min, box_max)); +} + +bool ImGui::IsMouseHoveringWindow() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + return g.HoveredWindow == window; +} + +bool ImGui::IsMouseHoveringAnyWindow() +{ + ImGuiState& g = GImGui; + return g.HoveredWindow != NULL; +} + +bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) +{ + return FindHoveredWindow(pos, false) != NULL; +} + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat) +{ + ImGuiState& g = GImGui; + const int key_index = g.IO.KeyMap[key]; + return ImGui::IsKeyPressed(key_index, repeat); +} + +bool ImGui::IsKeyPressed(int key_index, bool repeat) +{ + ImGuiState& g = GImGui; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + const float t = g.IO.KeysDownTime[key_index]; + if (t == 0.0f) + return true; + + // FIXME: Repeat rate should be provided elsewhere? + const float KEY_REPEAT_DELAY = 0.250f; + const float KEY_REPEAT_RATE = 0.020f; + if (repeat && t > KEY_REPEAT_DELAY) + if ((fmodf(t - KEY_REPEAT_DELAY, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f) != (fmodf(t - KEY_REPEAT_DELAY - g.IO.DeltaTime, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f)) + return true; + + return false; +} + +bool ImGui::IsMouseClicked(int button, bool repeat) +{ + ImGuiState& g = GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float t = g.IO.MouseDownTime[button]; + if (t == 0.0f) + return true; + + // FIXME: Repeat rate should be provided elsewhere? + const float MOUSE_REPEAT_DELAY = 0.250f; + const float MOUSE_REPEAT_RATE = 0.020f; + if (repeat && t > MOUSE_REPEAT_DELAY) + if ((fmodf(t - MOUSE_REPEAT_DELAY, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f) != (fmodf(t - MOUSE_REPEAT_DELAY - g.IO.DeltaTime, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f)) + return true; + + return false; +} + +bool ImGui::IsMouseDoubleClicked(int button) +{ + ImGuiState& g = GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDoubleClicked[button]; +} + +ImVec2 ImGui::GetMousePos() +{ + return GImGui.IO.MousePos; +} + +bool ImGui::IsItemHovered() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemHovered; +} + +bool ImGui::IsItemFocused() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemFocused; +} + +ImVec2 ImGui::GetItemBoxMin() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemAabb.Min; +} + +ImVec2 ImGui::GetItemBoxMax() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.LastItemAabb.Max; +} + +// Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. +void ImGui::SetTooltipV(const char* fmt, va_list args) +{ + ImGuiState& g = GImGui; + ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); +} + +void ImGui::SetTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +// Position new window if they don't have position setting in the .ini file. Rarely useful (used by the sample applications). +void ImGui::SetNewWindowDefaultPos(const ImVec2& pos) +{ + ImGuiState& g = GImGui; + g.NewWindowDefaultPos = pos; +} + +float ImGui::GetTime() +{ + return GImGui.Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui.FrameCount; +} + +static ImGuiWindow* FindWindow(const char* name) +{ + ImGuiState& g = GImGui; + for (size_t i = 0; i != g.Windows.size(); i++) + if (strcmp(g.Windows[i]->Name, name) == 0) + return g.Windows[i]; + return NULL; +} + +void ImGui::BeginTooltip() +{ + ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), 0.9f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_Tooltip); +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Tooltip); + ImGui::End(); +} + +void ImGui::BeginChild(const char* str_id, ImVec2 size, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_ChildWindow; + + const ImVec2 content_max = window->Pos + ImGui::GetContentRegionMax(); + const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); + if (size.x <= 0.0f) + { + if (size.x == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitX; + size.x = ImMax(content_max.x - cursor_pos.x, g.Style.WindowMinSize.x) - fabsf(size.x); + } + if (size.y <= 0.0f) + { + if (size.y == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitY; + size.y = ImMax(content_max.y - cursor_pos.y, g.Style.WindowMinSize.y) - fabsf(size.y); + } + if (border) + flags |= ImGuiWindowFlags_ShowBorders; + flags |= extra_flags; + + char title[256]; + ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id); + + const float alpha = (flags & ImGuiWindowFlags_ComboBox) ? 1.0f : 0.0f; + ImGui::Begin(title, NULL, size, alpha, flags); + + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; +} + +void ImGui::EndChild() +{ + ImGuiWindow* window = GetCurrentWindow(); + + if (window->Flags & ImGuiWindowFlags_ComboBox) + { + ImGui::End(); + } + else + { + // When using auto-filling child window, we don't provide the width/height to ItemSize so that it doesn't feed back into automatic size-fitting. + ImVec2 sz = ImGui::GetWindowSize(); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) + sz.x = 0; + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) + sz.y = 0; + + ImGui::End(); + ItemSize(sz); + } +} + +// Push a new ImGui window to add widgets to. This can be called multiple times with the same window to append contents +bool ImGui::Begin(const char* name, bool* open, ImVec2 size, float fill_alpha, ImGuiWindowFlags flags) +{ + ImGuiState& g = GImGui; + const ImGuiStyle& style = g.Style; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + ImGuiWindow* window = FindWindow(name); + if (!window) + { + // Create window the first time, and load settings + if (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) + { + // Tooltip and child windows don't store settings + window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); + new(window) ImGuiWindow(name, ImVec2(0,0), size); + } + else + { + // Normal windows store settings in .ini file + ImGuiIniData* settings = FindWindowSettings(name); + if (settings && ImLength(settings->Size) > 0.0f && !(flags & ImGuiWindowFlags_NoResize))// && ImLengthsize) == 0.0f) + size = settings->Size; + + window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); + new(window) ImGuiWindow(name, g.NewWindowDefaultPos, size); + + if (settings->Pos.x != FLT_MAX) + { + window->PosFloat = settings->Pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + window->Collapsed = settings->Collapsed; + } + } + g.Windows.push_back(window); + } + window->Flags = (ImGuiWindowFlags)flags; + + g.CurrentWindowStack.push_back(window); + g.CurrentWindow = window; + + // Find root + size_t root_idx = g.CurrentWindowStack.size() - 1; + while (root_idx > 0) + { + if ((g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow) == 0) + break; + root_idx--; + } + window->RootWindow = g.CurrentWindowStack[root_idx]; + + // Default alpha + if (fill_alpha < 0.0f) + fill_alpha = style.WindowFillAlphaDefault; + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + const int current_frame = ImGui::GetFrameCount(); + const bool first_begin_of_the_frame = (window->LastFrameDrawn != current_frame); + if (first_begin_of_the_frame) + { + window->DrawList->Clear(); + window->Visible = true; + + // New windows appears in front + if (window->LastFrameDrawn < current_frame - 1) + { + FocusWindow(window); + if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) + { + // Hide for 1 frame while resizing + window->AutoFitFrames = 2; + window->AutoFitOnlyGrows = false; + window->Visible = false; + } + } + + window->LastFrameDrawn = current_frame; + window->ClipRectStack.resize(0); + + if (flags & ImGuiWindowFlags_ChildWindow) + { + ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.size()-2]; + parent_window->DC.ChildWindows.push_back(window); + window->Pos = window->PosFloat = parent_window->DC.CursorPos; + window->SizeFull = size; + } + + // Outer clipping rectangle + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) + PushClipRect(g.CurrentWindowStack[g.CurrentWindowStack.size()-2]->ClipRectStack.back()); + else + PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); + + // Seed ID stack with our window pointer + window->IDStack.resize(0); + ImGui::PushID(window); + + // Move window (at the beginning of the frame to avoid lag) + const ImGuiID move_id = window->GetID("#MOVE"); + RegisterAliveId(move_id); + if (g.ActiveId == move_id) + { + if (g.IO.MouseDown[0]) + { + if (!(window->Flags & ImGuiWindowFlags_NoMove)) + { + window->PosFloat += g.IO.MouseDelta; + MarkSettingsDirty(); + } + FocusWindow(window); + } + else + { + g.ActiveId = 0; + } + } + + // Tooltips always follow mouse + if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) + { + window->PosFloat = g.IO.MousePos + ImVec2(32,16) - g.Style.FramePadding*2; + } + + // Clamp into view + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) + { + const ImVec2 pad = ImVec2(window->FontSize()*2.0f, window->FontSize()*2.0f); + window->PosFloat = ImMax(window->PosFloat + window->Size, pad) - window->Size; + window->PosFloat = ImMin(window->PosFloat, ImVec2(g.IO.DisplaySize.x, g.IO.DisplaySize.y) - pad); + window->SizeFull = ImMax(window->SizeFull, pad); + } + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + // Default item width + if (window->Size.x > 0.0f && !(window->Flags & ImGuiWindowFlags_Tooltip) && !(window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); + else + window->ItemWidthDefault = 200.0f; + + // Prepare for focus requests + if (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) + window->FocusIdxAllRequestCurrent = IM_INT_MAX; + else + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + if (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) + window->FocusIdxTabRequestCurrent = IM_INT_MAX; + else + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX; + + ImGuiAabb title_bar_aabb = window->TitleBarAabb(); + + // Apply and ImClamp scrolling + window->ScrollY = window->NextScrollY; + window->ScrollY = ImMax(window->ScrollY, 0.0f); + if (!window->Collapsed && !window->SkipItems) + window->ScrollY = ImMin(window->ScrollY, ImMax(0.0f, (float)window->SizeContentsFit.y - window->SizeFull.y)); + window->NextScrollY = window->ScrollY; + + // At this point we don't have a clipping rectangle setup yet, so we can test and draw in title bar + // Collapse window by double-clicking on title bar + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + { + if (g.HoveredWindow == window && IsMouseHoveringBox(title_bar_aabb) && g.IO.MouseDoubleClicked[0]) + { + window->Collapsed = !window->Collapsed; + MarkSettingsDirty(); + FocusWindow(window); + } + } + else + { + window->Collapsed = false; + } + + if (window->Collapsed) + { + // Draw title bar only + window->Size = title_bar_aabb.GetSize(); + window->DrawList->AddRectFilled(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_TitleBgCollapsed), g.Style.WindowRounding); + if (window->Flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddRect(title_bar_aabb.GetTL()+ImVec2(1,1), title_bar_aabb.GetBR()+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), g.Style.WindowRounding); + window->DrawList->AddRect(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_Border), g.Style.WindowRounding); + } + } + else + { + window->Size = window->SizeFull; + + ImU32 resize_col = 0; + if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) + { + // Tooltip always resize + if (window->AutoFitFrames > 0) + { + window->SizeFull = window->SizeContentsFit + g.Style.WindowPadding - ImVec2(0.0f, g.Style.ItemSpacing.y); + } + } + else + { + const ImVec2 size_auto_fit = ImClamp(window->SizeContentsFit + style.AutoFitPadding, style.WindowMinSize, g.IO.DisplaySize - style.AutoFitPadding); + if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + // Don't continuously mark settings as dirty, the size of the window doesn't need to be stored. + window->SizeFull = size_auto_fit; + } + else if (window->AutoFitFrames > 0) + { + // Auto-fit only grows during the first few frames + if (window->AutoFitOnlyGrows) + window->SizeFull = ImMax(window->SizeFull, size_auto_fit); + else + window->SizeFull = size_auto_fit; + MarkSettingsDirty(); + } + else if (!(window->Flags & ImGuiWindowFlags_NoResize)) + { + // Resize grip + const ImGuiAabb resize_aabb(window->Aabb().GetBR()-ImVec2(18,18), window->Aabb().GetBR()); + const ImGuiID resize_id = window->GetID("##RESIZE"); + bool hovered, held; + ButtonBehaviour(resize_aabb, resize_id, &hovered, &held, true); + resize_col = window->Color(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + + if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) + { + // Manual auto-fit + window->SizeFull = size_auto_fit; + window->Size = window->SizeFull; + MarkSettingsDirty(); + } + else if (held) + { + // Resize + window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize); + window->Size = window->SizeFull; + MarkSettingsDirty(); + } + } + + // Update aabb immediately so that the rendering below isn't one frame late + title_bar_aabb = window->TitleBarAabb(); + } + + // Title bar + Window box + if (fill_alpha > 0.0f) + { + if ((window->Flags & ImGuiWindowFlags_ComboBox) != 0) + window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_ComboBg, fill_alpha), 0); + else + window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_WindowBg, fill_alpha), g.Style.WindowRounding); + } + + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddRectFilled(title_bar_aabb.GetTL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_TitleBg), g.Style.WindowRounding, 1|2); + + // Borders + if (window->Flags & ImGuiWindowFlags_ShowBorders) + { + const float rounding = (window->Flags & ImGuiWindowFlags_ComboBox) ? 0.0f : g.Style.WindowRounding; + window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_Border), rounding); + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_aabb.GetBL(), title_bar_aabb.GetBR(), window->Color(ImGuiCol_Border)); + } + + // Scrollbar + window->ScrollbarY = (window->SizeContentsFit.y > window->Size.y) && !(window->Flags & ImGuiWindowFlags_NoScrollbar); + if (window->ScrollbarY) + { + ImGuiAabb scrollbar_bb(window->Aabb().Max.x - style.ScrollBarWidth, title_bar_aabb.Max.y+1, window->Aabb().Max.x, window->Aabb().Max.y-1); + //window->DrawList->AddLine(scrollbar_bb.GetTL(), scrollbar_bb.GetBL(), g.Colors[ImGuiCol_Border]); + window->DrawList->AddRectFilled(scrollbar_bb.Min, scrollbar_bb.Max, window->Color(ImGuiCol_ScrollbarBg)); + scrollbar_bb.Expand(ImVec2(-3,-3)); + + const float grab_size_y_norm = ImSaturate(window->Size.y / ImMax(window->SizeContentsFit.y, window->Size.y)); + const float grab_size_y = scrollbar_bb.GetHeight() * grab_size_y_norm; + + // Handle input right away (none of the code above is relying on scrolling position) + bool held = false; + bool hovered = false; + if (grab_size_y_norm < 1.0f) + { + const ImGuiID scrollbar_id = window->GetID("#SCROLLY"); + ButtonBehaviour(scrollbar_bb, scrollbar_id, &hovered, &held, true); + if (held) + { + g.HoveredId = scrollbar_id; + const float pos_y_norm = ImSaturate((g.IO.MousePos.y - (scrollbar_bb.Min.y + grab_size_y*0.5f)) / (scrollbar_bb.GetHeight() - grab_size_y)) * (1.0f - grab_size_y_norm); + window->ScrollY = pos_y_norm * window->SizeContentsFit.y; + window->NextScrollY = window->ScrollY; + } + } + + // Normalized height of the grab + const float pos_y_norm = ImSaturate(window->ScrollY / ImMax(0.0f, window->SizeContentsFit.y)); + const ImU32 grab_col = window->Color(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + window->DrawList->AddRectFilled( + ImVec2(scrollbar_bb.Min.x, ImLerp(scrollbar_bb.Min.y, scrollbar_bb.Max.y, pos_y_norm)), + ImVec2(scrollbar_bb.Max.x, ImLerp(scrollbar_bb.Min.y, scrollbar_bb.Max.y, pos_y_norm + grab_size_y_norm)), grab_col); + } + + // Render resize grip + // (after the input handling so we don't have a frame of latency) + if (!(window->Flags & ImGuiWindowFlags_NoResize)) + { + const float r = style.WindowRounding; + const ImVec2 br = window->Aabb().GetBR(); + if (r == 0.0f) + { + window->DrawList->AddTriangleFilled(br, br-ImVec2(0,14), br-ImVec2(14,0), resize_col); + } + else + { + // FIXME: We should draw 4 triangles and decide on a size that's not dependant on the rounding size (previously used 18) + window->DrawList->AddArc(br - ImVec2(r,r), r, resize_col, 6, 9, true); + window->DrawList->AddTriangleFilled(br+ImVec2(0,-2*r),br+ImVec2(0,-r),br+ImVec2(-r,-r), resize_col); + window->DrawList->AddTriangleFilled(br+ImVec2(-r,-r), br+ImVec2(-r,0),br+ImVec2(-2*r,0), resize_col); + } + } + } + + // Setup drawing context + window->DC.ColumnsStartX = window->WindowPadding().x; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.ColumnsStartX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->WindowPadding().y) - ImVec2(0.0f, window->ScrollY); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; + window->DC.LogLineHeight = window->DC.CursorPos.y - 9999.0f; + window->DC.ChildWindows.resize(0); + window->DC.ItemWidth.resize(0); + window->DC.ItemWidth.push_back(window->ItemWidthDefault); + window->DC.AllowKeyboardFocus.resize(0); + window->DC.AllowKeyboardFocus.push_back(true); + window->DC.TextWrapPos.resize(0); + window->DC.TextWrapPos.push_back(-1.0f); // disabled + window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = 1; + window->DC.ColumnsStartPos = window->DC.CursorPos; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPos.y; + window->DC.TreeDepth = 0; + window->DC.StateStorage = &window->StateStorage; + window->DC.OpenNextNode = -1; + + // Reset contents size for auto-fitting + window->SizeContentsFit = ImVec2(0.0f, 0.0f); + if (window->AutoFitFrames > 0) + window->AutoFitFrames--; + + // Title bar + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + { + RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); + if (open) + CloseWindowButton(open); + + const ImVec2 text_size = CalcTextSize(name); + const ImVec2 text_min = window->Pos + style.FramePadding + ImVec2(window->FontSize() + style.ItemInnerSpacing.x, 0.0f); + const ImVec2 text_max = window->Pos + ImVec2(window->Size.x - (open ? (title_bar_aabb.GetHeight()-3) : style.FramePadding.x), style.FramePadding.y + text_size.y); + const bool clip_title = text_size.x > (text_max.x - text_min.x); // only push a clip rectangle if we need to, because it may turn into a separate draw call + if (clip_title) + PushClipRect(ImVec4(text_min.x, text_min.y, text_max.x, text_max.y)); + RenderText(text_min, name); + if (clip_title) + PopClipRect(); + } + } + else + { + // Outer clipping rectangle + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) + { + ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.size()-2]; + PushClipRect(parent_window->ClipRectStack.back()); + } + else + { + PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); + } + } + + // Inner clipping rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + const ImGuiAabb title_bar_aabb = window->TitleBarAabb(); + ImVec4 clip_rect(title_bar_aabb.Min.x+0.5f+window->WindowPadding().x*0.5f, title_bar_aabb.Max.y+0.5f, window->Aabb().Max.x+0.5f-window->WindowPadding().x*0.5f, window->Aabb().Max.y-1.5f); + if (window->ScrollbarY) + clip_rect.z -= g.Style.ScrollBarWidth; + PushClipRect(clip_rect); + + // Clear 'accessed' flag last thing + if (first_begin_of_the_frame) + window->Accessed = false; + + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). + if (flags & ImGuiWindowFlags_ChildWindow) + { + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); + const ImVec4 clip_rect_t = window->ClipRectStack.back(); + window->Collapsed = (clip_rect_t.x >= clip_rect_t.z || clip_rect_t.y >= clip_rect_t.w); + + // We also hide the window from rendering because we've already added its border to the command list. + // (we could perform the check earlier in the function but it is simpler at this point) + if (window->Collapsed) + window->Visible = false; + } + if (g.Style.Alpha <= 0.0f) + window->Visible = false; + + // Return false if we don't intend to display anything to allow user to perform an early out optimisation + window->SkipItems = window->Collapsed || (!window->Visible && window->AutoFitFrames == 0); + return !window->SkipItems; +} + +void ImGui::End() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = g.CurrentWindow; + + ImGui::Columns(1, "#CloseColumns"); + PopClipRect(); // inner window clip rectangle + PopClipRect(); // outer window clip rectangle + + // Select window for move/focus when we're done with all our widgets (we only consider non-childs windows here) + const ImGuiAabb bb(window->Pos, window->Pos+window->Size); + if (g.ActiveId == 0 && g.HoveredId == 0 && g.HoveredRootWindow == window && IsMouseHoveringBox(bb) && g.IO.MouseClicked[0]) + g.ActiveId = window->GetID("#MOVE"); + + // Stop logging + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging + { + g.LogEnabled = false; + if (g.LogFile != NULL) + { + fprintf(g.LogFile, "\n"); + if (g.LogFile == stdout) + fflush(g.LogFile); + else + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard->size() > 1) + { + g.LogClipboard->append("\n"); + if (g.IO.SetClipboardTextFn) + g.IO.SetClipboardTextFn(g.LogClipboard->begin()); + g.LogClipboard->clear(); + } + } + + // Pop + window->RootWindow = NULL; + g.CurrentWindowStack.pop_back(); + g.CurrentWindow = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back(); +} + +// Moving window to front +static void FocusWindow(ImGuiWindow* window) +{ + ImGuiState& g = GImGui; + g.FocusedWindow = window; + + for (size_t i = 0; i < g.Windows.size(); i++) + if (g.Windows[i] == window) + { + g.Windows.erase(g.Windows.begin() + i); + break; + } + g.Windows.push_back(window); +} + +void ImGui::PushItemWidth(float item_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + item_width = (float)(int)item_width; + window->DC.ItemWidth.push_back(item_width > 0.0f ? item_width : window->ItemWidthDefault); +} + +void ImGui::PopItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidth.pop_back(); +} + +float ImGui::GetItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.ItemWidth.back(); +} + +void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocus.push_back(allow_keyboard_focus); +} + +void ImGui::PopAllowKeyboardFocus() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocus.pop_back(); +} + +void ImGui::PushTextWrapPos(float wrap_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos.push_back(wrap_x); +} + +void ImGui::PopTextWrapPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos.pop_back(); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) +{ + ImGuiState& g = GImGui; + + ImGuiColMod backup; + backup.Col = idx; + backup.PreviousValue = g.Style.Colors[idx]; + g.ColorModifiers.push_back(backup); + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiState& g = GImGui; + + while (count > 0) + { + ImGuiColMod& backup = g.ColorModifiers.back(); + g.Style.Colors[backup.Col] = backup.PreviousValue; + g.ColorModifiers.pop_back(); + count--; + } +} + +static float* GetStyleVarFloatAddr(ImGuiStyleVar idx) +{ + ImGuiState& g = GImGui; + switch (idx) + { + case ImGuiStyleVar_Alpha: return &g.Style.Alpha; + case ImGuiStyleVar_TreeNodeSpacing: return &g.Style.TreeNodeSpacing; + case ImGuiStyleVar_ColumnsMinSpacing: return &g.Style.ColumnsMinSpacing; + } + return NULL; +} + +static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx) +{ + ImGuiState& g = GImGui; + switch (idx) + { + case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding; + case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding; + case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing; + case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing; + } + return NULL; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + ImGuiState& g = GImGui; + + float* pvar = GetStyleVarFloatAddr(idx); + IM_ASSERT(pvar != NULL); // Called wrong function? + ImGuiStyleMod backup; + backup.Var = idx; + backup.PreviousValue = ImVec2(*pvar, 0.0f); + g.StyleModifiers.push_back(backup); + *pvar = val; +} + + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + ImGuiState& g = GImGui; + + ImVec2* pvar = GetStyleVarVec2Addr(idx); + IM_ASSERT(pvar != NULL); // Called wrong function? + ImGuiStyleMod backup; + backup.Var = idx; + backup.PreviousValue = *pvar; + g.StyleModifiers.push_back(backup); + *pvar = val; +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiState& g = GImGui; + + while (count > 0) + { + ImGuiStyleMod& backup = g.StyleModifiers.back(); + if (float* pvar_f = GetStyleVarFloatAddr(backup.Var)) + *pvar_f = backup.PreviousValue.x; + else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var)) + *pvar_v = backup.PreviousValue; + g.StyleModifiers.pop_back(); + count--; + } +} + +const char* ImGui::GetStyleColorName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: return "Text"; + case ImGuiCol_WindowBg: return "WindowBg"; + case ImGuiCol_Border: return "Border"; + case ImGuiCol_BorderShadow: return "BorderShadow"; + case ImGuiCol_FrameBg: return "FrameBg"; + case ImGuiCol_TitleBg: return "TitleBg"; + case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; + 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"; + case ImGuiCol_Button: return "Button"; + case ImGuiCol_ButtonHovered: return "ButtonHovered"; + case ImGuiCol_ButtonActive: return "ButtonActive"; + case ImGuiCol_Header: return "Header"; + case ImGuiCol_HeaderHovered: return "HeaderHovered"; + case ImGuiCol_HeaderActive: return "HeaderActive"; + case ImGuiCol_Column: return "Column"; + case ImGuiCol_ColumnHovered: return "ColumnHovered"; + case ImGuiCol_ColumnActive: return "ColumnActive"; + case ImGuiCol_ResizeGrip: return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_CloseButton: return "CloseButton"; + case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; + case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_TooltipBg: return "TooltipBg"; + } + IM_ASSERT(0); + return "Unknown"; +} + +bool ImGui::GetWindowIsFocused() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + return g.FocusedWindow == window; +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->Size.x; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->Pos; +} + +void ImGui::SetWindowPos(const ImVec2& pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + const ImVec2 old_pos = window->Pos; + window->PosFloat = pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + // If we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorPos += (window->Pos - old_pos); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->Size; +} + +void ImGui::SetWindowSize(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (ImLength(size) < 0.001f) + { + window->AutoFitFrames = 2; + window->AutoFitOnlyGrows = false; + } + else + { + window->SizeFull = size; + } +} + +ImVec2 ImGui::GetContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindow(); + + ImVec2 m = window->Size - window->WindowPadding(); + if (window->DC.ColumnsCount != 1) + { + m.x = GetColumnOffset(window->DC.ColumnsCurrent + 1); + m.x -= GImGui.Style.WindowPadding.x; + } + else + { + if (window->ScrollbarY) + m.x -= GImGui.Style.ScrollBarWidth; + } + + return m; +} + +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow* window = GetCurrentWindow(); + return ImVec2(0, window->TitleBarHeight()) + window->WindowPadding(); +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindow(); + ImVec2 m = window->Size - window->WindowPadding(); + if (window->ScrollbarY) + m.x -= GImGui.Style.ScrollBarWidth; + return m; +} + +float ImGui::GetTextLineHeight() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->FontSize(); +} + +float ImGui::GetTextLineSpacing() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + return window->FontSize() + g.Style.ItemSpacing.y; +} + +ImDrawList* ImGui::GetWindowDrawList() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DrawList; +} + +ImFont* ImGui::GetWindowFont() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->Font(); +} + +float ImGui::GetWindowFontSize() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->FontSize(); +} + +void ImGui::SetWindowFontScale(float scale) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->FontWindowScale = scale; +} + +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.CursorPos - window->Pos; +} + +void ImGui::SetCursorPos(const ImVec2& pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos + pos; +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x + x; +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y + y; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.CursorPos; +} + +void ImGui::SetScrollPosHere() +{ + 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 ImGui::SetKeyboardFocusHere(int offset) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; + window->FocusIdxTabRequestNext = IM_INT_MAX; +} + +void ImGui::SetTreeStateStorage(ImGuiStorage* tree) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage* ImGui::GetTreeStateStorage() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DC.StateStorage; +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + static char buf[1024]; + const char* text_end = buf + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + TextUnformatted(buf, text_end); +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + ImGui::PushStyleColor(ImGuiCol_Text, col); + TextV(fmt, args); + ImGui::PopStyleColor(); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + ImGui::PushTextWrapPos(0.0f); + TextV(fmt, args); + ImGui::PopTextWrapPos(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + IM_ASSERT(text != NULL); + const char* text_begin = text; + if (text_end == NULL) + text_end = text + strlen(text); // FIXME-OPT + + const float wrap_pos_x = window->DC.TextWrapPos.back(); + const bool wrap_enabled = wrap_pos_x >= 0.0f; + if (text_end - text > 2000 && !wrap_enabled) + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // From this point we will only compute the width of lines that are visible. + // Optimization only available when word-wrapping is disabled. + const char* line = text; + const float line_height = ImGui::GetTextLineHeight(); + const ImVec2 start_pos = window->DC.CursorPos; + const ImVec4 clip_rect = window->ClipRectStack.back(); + ImVec2 text_size(0,0); + + if (start_pos.y <= clip_rect.w) + { + ImVec2 pos = start_pos; + + // Lines to skip (can't skip when logging text) + if (!g.LogEnabled) + { + int lines_skippable = (int)((clip_rect.y - start_pos.y) / line_height) - 1; + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped <= lines_skippable) + { + const char* line_end = strchr(line, '\n'); + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImGuiAabb line_box(pos, pos + ImVec2(ImGui::GetWindowWidth(), line_height)); + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (IsClipped(line_box)) + break; + + const ImVec2 line_size = CalcTextSize(line, line_end, false); + text_size.x = ImMax(text_size.x, line_size.x); + RenderText(pos, line, line_end, false); + if (!line_end) + line_end = text_end; + line = line_end + 1; + line_box.Min.y += line_height; + line_box.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + + text_size.y += (pos - start_pos).y; + } + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + text_size); + ItemSize(bb); + ClipAdvance(bb); + } + else + { + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + text_size); + ItemSize(bb.GetSize(), &bb.Min); + + if (ClipAdvance(bb)) + return; + + // Render + // We don't hide text after ## in this end-user function. + RenderText(bb.Min, text_begin, text_end, false, wrap_width); + } +} + +void ImGui::AlignFirstTextHeightToWidgets() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. + ItemSize(ImVec2(0, window->FontSize() + g.Style.FramePadding.y*2)); + ImGui::SameLine(0, 0); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + const ImGuiStyle& style = g.Style; + const float w = window->DC.ItemWidth.back(); + + static char buf[1024]; + const char* text_begin = &buf[0]; + const char* text_end = text_begin + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + + const ImVec2 text_size = CalcTextSize(label); + const ImGuiAabb value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2, text_size.y)); + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2 + style.ItemInnerSpacing.x, 0.0f) + text_size); + ItemSize(bb); + + if (ClipAdvance(value_bb)) + return; + + // Render + RenderText(value_bb.Min, text_begin, text_end); + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y), label); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +static bool ButtonBehaviour(const ImGuiAabb& bb, const ImGuiID& id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + const bool hovered = (g.HoveredRootWindow == window->RootWindow) && (g.HoveredId == 0) && IsMouseHoveringBox(bb); + bool pressed = false; + if (hovered) + { + g.HoveredId = id; + if (allow_key_modifiers || (!g.IO.KeyCtrl && !g.IO.KeyShift)) + { + if (g.IO.MouseClicked[0]) + { + g.ActiveId = id; + } + else if (repeat && g.ActiveId && ImGui::IsMouseClicked(0, true)) + { + pressed = true; + } + } + } + + bool held = false; + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + held = true; + } + else + { + if (hovered) + pressed = true; + g.ActiveId = 0; + } + } + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::Button(const char* label, ImVec2 size, bool repeat_when_held) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 text_size = CalcTextSize(label); + if (size.x == 0.0f) + size.x = text_size.x; + if (size.y == 0.0f) + size.y = text_size.y; + + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos+size + style.FramePadding*2.0f); + ItemSize(bb); + + if (ClipAdvance(bb)) + return false; + + bool hovered, held; + bool pressed = ButtonBehaviour(bb, id, &hovered, &held, true, repeat_when_held); + + // Render + const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col); + + if (size.x < text_size.x || size.y < text_size.y) + PushClipRect(ImVec4(bb.Min.x+style.FramePadding.x, bb.Min.y+style.FramePadding.y, bb.Max.x, bb.Max.y-style.FramePadding.y)); // Allow extra to draw over the horizontal padding to make it visible that text doesn't fit + const ImVec2 off = ImVec2(ImMax(0.0f, size.x - text_size.x) * 0.5f, ImMax(0.0f, size.y - text_size.y) * 0.5f); + RenderText(bb.Min + style.FramePadding + off, label); + if (size.x < text_size.x || size.y < text_size.y) + PopClipRect(); + + return pressed; +} + +// Small buttons fits within text without additional spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos+CalcTextSize(label) + ImVec2(style.FramePadding.x*2,0)); + ItemSize(bb); + + if (ClipAdvance(bb)) + return false; + + bool hovered, held; + bool pressed = ButtonBehaviour(bb, id, &hovered, &held, true); + + // Render + const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col); + RenderText(bb.Min + ImVec2(style.FramePadding.x,0), label); + + return pressed; +} + +// Upper-right button to close a window. +static bool CloseWindowButton(bool* open) +{ + ImGuiWindow* window = GetCurrentWindow(); + + const ImGuiID id = window->GetID("##CLOSE"); + const float size = window->TitleBarHeight() - 4.0f; + const ImGuiAabb bb(window->Aabb().GetTR() + ImVec2(-3.0f-size,2.0f), window->Aabb().GetTR() + ImVec2(-3.0f,2.0f+size)); + + bool hovered, held; + bool pressed = ButtonBehaviour(bb, id, &hovered, &held, true); + + // Render + const ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); + const ImVec2 center = bb.GetCenter(); + window->DrawList->AddCircleFilled(center, ImMax(2.0f,size*0.5f), col, 16); + + const float cross_extent = (size * 0.5f * 0.7071f) - 1.0f; + if (hovered) + { + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), window->Color(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), window->Color(ImGuiCol_Text)); + } + + if (open != NULL && pressed) + *open = !*open; + + return pressed; +} + +// Start logging ImGui output to TTY +void ImGui::LogToTTY(int max_depth) +{ + ImGuiState& g = GImGui; + if (g.LogEnabled) + return; + g.LogEnabled = true; + g.LogFile = stdout; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to given file +void ImGui::LogToFile(int max_depth, const char* filename) +{ + ImGuiState& g = GImGui; + if (g.LogEnabled) + return; + if (!filename) + filename = g.IO.LogFilename; + g.LogEnabled = true; + g.LogFile = fopen(filename, "at"); + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to clipboard +void ImGui::LogToClipboard(int max_depth) +{ + ImGuiState& g = GImGui; + if (g.LogEnabled) + return; + g.LogEnabled = true; + g.LogFile = NULL; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Helper to display logging buttons +void ImGui::LogButtons() +{ + ImGuiState& g = GImGui; + + ImGui::PushID("LogButtons"); + const bool log_to_tty = ImGui::Button("Log To TTY"); + ImGui::SameLine(); + const bool log_to_file = ImGui::Button("Log To File"); + ImGui::SameLine(); + const bool log_to_clipboard = ImGui::Button("Log To Clipboard"); + ImGui::SameLine(); + + ImGui::PushItemWidth(80.0f); + ImGui::PushAllowKeyboardFocus(false); + ImGui::SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + ImGui::PopAllowKeyboardFocus(); + ImGui::PopItemWidth(); + ImGui::PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(g.LogAutoExpandMaxDepth); + if (log_to_file) + LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); + if (log_to_clipboard) + LogToClipboard(g.LogAutoExpandMaxDepth); +} + +bool ImGui::CollapsingHeader(const char* label, const char* str_id, const bool display_frame, const bool default_open) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + + IM_ASSERT(str_id != NULL || label != NULL); + if (str_id == NULL) + str_id = label; + if (label == NULL) + label = str_id; + const ImGuiID id = window->GetID(str_id); + + // We only write to the tree storage if the user clicks + ImGuiStorage* tree = window->DC.StateStorage; + bool opened; + if (window->DC.OpenNextNode != -1) + { + opened = window->DC.OpenNextNode > 0; + tree->SetInt(id, opened); + window->DC.OpenNextNode = -1; + } + else + { + opened = tree->GetInt(id, default_open) != 0; + } + + // Framed header expand a little outside the default padding + const ImVec2 window_padding = window->WindowPadding(); + const ImVec2 text_size = CalcTextSize(label); + const ImVec2 pos_min = window->DC.CursorPos; + const ImVec2 pos_max = window->Pos + GetContentRegionMax(); + ImGuiAabb bb = ImGuiAabb(pos_min, ImVec2(pos_max.x, pos_min.y + text_size.y)); + if (display_frame) + { + bb.Min.x -= window_padding.x*0.5f - 1; + bb.Max.x += window_padding.x*0.5f - 1; + bb.Max.y += style.FramePadding.y * 2; + } + + const ImGuiAabb text_bb(bb.Min, bb.Min + ImVec2(window->FontSize() + style.FramePadding.x*2*2,0) + text_size); + ItemSize(ImVec2(text_bb.GetSize().x, bb.GetSize().y)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit + + // When logging is enabled, if automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behaviour). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (!display_frame) + if (g.LogEnabled && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + opened = true; + + if (ClipAdvance(bb)) + return opened; + + bool hovered, held; + bool pressed = ButtonBehaviour(display_frame ? bb : text_bb, id, &hovered, &held, false); + if (pressed) + { + opened = !opened; + tree->SetInt(id, opened); + } + + // Render + const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + if (display_frame) + { + // Framed type + RenderFrame(bb.Min, bb.Max, col, true); + RenderCollapseTriangle(bb.Min + style.FramePadding, opened, 1.0f, true); + RenderText(bb.Min + style.FramePadding + ImVec2(window->FontSize() + style.FramePadding.x*2,0), label); + } + else + { + // Unframed typed for tree nodes + if ((held && hovered) || hovered) + RenderFrame(bb.Min, bb.Max, col, false); + RenderCollapseTriangle(bb.Min + ImVec2(style.FramePadding.x, window->FontSize()*0.15f), opened, 0.70f, false); + RenderText(bb.Min + ImVec2(window->FontSize() + style.FramePadding.x*2,0), label); + } + + return opened; +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + static char buf[1024]; + const char* text_begin = buf; + const char* text_end = text_begin + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + + 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 > 0.0f ? (g.Style.FramePadding.x*2) : 0.0f),0) + text_size); // Empty text doesn't add padding + ItemSize(bb); + + if (ClipAdvance(bb)) + return; + + // Render + const float bullet_size = line_height*0.15f; + window->DrawList->AddCircleFilled(bb.Min + ImVec2(g.Style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); + RenderText(bb.Min+ImVec2(window->FontSize()+g.Style.FramePadding.x*2,0), text_begin, text_end); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +// If returning 'true' the node is open and the user is responsible for calling TreePop +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + static char buf[1024]; + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + + if (!str_id || !str_id[0]) + str_id = fmt; + + ImGui::PushID(str_id); + const bool opened = ImGui::CollapsingHeader(buf, "", false); // do not add to the ID so that TreeNodeSetOpen can access + ImGui::PopID(); + + if (opened) + ImGui::TreePush(str_id); + + return opened; +} + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool s = TreeNodeV(str_id, fmt, args); + va_end(args); + return s; +} + +// If returning 'true' the node is open and the user is responsible for calling TreePop +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + static char buf[1024]; + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + + if (!ptr_id) + ptr_id = fmt; + + ImGui::PushID(ptr_id); + const bool opened = ImGui::CollapsingHeader(buf, "", false); + ImGui::PopID(); + + if (opened) + ImGui::TreePush(ptr_id); + + return opened; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool s = TreeNodeV(ptr_id, fmt, args); + va_end(args); + return s; +} + +bool ImGui::TreeNode(const char* str_label_id) +{ + return TreeNode(str_label_id, "%s", str_label_id); +} + +void ImGui::OpenNextNode(bool open) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.OpenNextNode = open ? 1 : 0; +} + +void ImGui::PushID(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id)); +} + +void ImGui::PushID(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PushID(const int int_id) +{ + const void* ptr_id = (void*)(intptr_t)int_id; + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PopID() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.pop_back(); +} + +// User can input math operators (e.g. +100) to edit a numerical values. +// NB: only call right after InputText because we are using its InitialValue storage +static void ApplyNumericalTextInput(const char* buf, float *v) +{ + while (*buf == ' ' || *buf == '\t') + buf++; + + // We don't support '-' op because it would conflict with inputing negative value. + // Instead you can use +-100 to subtract from an existing value + char op = buf[0]; + if (op == '+' || op == '*' || op == '/') + { + buf++; + while (*buf == ' ' || *buf == '\t') + buf++; + } + else + { + op = 0; + } + if (!buf[0]) + return; + + float ref_v = *v; + if (op) + if (sscanf(GImGui.InputTextState.InitialText, "%f", &ref_v) < 1) + return; + + float op_v = 0.0f; + if (sscanf(buf, "%f", &op_v) < 1) + return; + + if (op == '+') + *v = ref_v + op_v; + else if (op == '*') + *v = ref_v * op_v; + else if (op == '/') + { + if (op_v == 0.0f) + return; + *v = ref_v / op_v; + } + else + *v = op_v; +} + +// Use power!=1.0 for logarithmic sliders. +// Adjust display_format to decorate the value with a prefix or a suffix. +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = window->DC.ItemWidth.back(); + + if (!display_format) + display_format = "%.3f"; + + // Parse display precision back from the display format string + int decimal_precision = 3; + if (const char* p = strchr(display_format, '%')) + { + p++; + while (*p >= '0' && *p <= '9') + p++; + if (*p == '.') + { + decimal_precision = atoi(p+1); + if (decimal_precision < 0 || decimal_precision > 10) + decimal_precision = 3; + } + } + + const ImVec2 text_size = CalcTextSize(label); + const ImGuiAabb frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, text_size.y) + style.FramePadding*2.0f); + const ImGuiAabb slider_bb(frame_bb.Min+g.Style.FramePadding, frame_bb.Max-g.Style.FramePadding); + const ImGuiAabb bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + text_size.x, 0.0f)); + + if (IsClipped(slider_bb)) + { + // NB- we don't use ClipAdvance() in the if() statement because we don't want to submit ItemSize() because we may change into a text edit later which may submit an ItemSize itself + ItemSize(bb); + return false; + } + + const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); + + const bool is_unbound = v_min == -FLT_MAX || v_min == FLT_MAX || v_max == -FLT_MAX || v_max == FLT_MAX; + + const float grab_size_in_units = 1.0f; // In 'v' units. Probably needs to be parametrized, based on a 'v_step' value? decimal precision? + float grab_size_in_pixels; + if (decimal_precision > 0 || is_unbound) + grab_size_in_pixels = 10.0f; + else + grab_size_in_pixels = ImMax(grab_size_in_units * (w / (v_max-v_min+1.0f)), 8.0f); // Integer sliders + const float slider_effective_w = slider_bb.GetWidth() - grab_size_in_pixels; + const float slider_effective_x1 = slider_bb.Min.x + grab_size_in_pixels*0.5f; + const float slider_effective_x2 = slider_bb.Max.x - grab_size_in_pixels*0.5f; + + // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f + float linear_zero_pos = 0.0f; // 0.0->1.0f + if (!is_unbound) + { + if (v_min * v_max < 0.0f) + { + // Different sign + 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 + { + // Same sign + linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; + } + } + + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(slider_bb); + if (hovered) + g.HoveredId = id; + + bool start_text_input = false; + if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) + { + g.ActiveId = id; + + const bool is_ctrl_down = g.IO.KeyCtrl; + if (tab_focus_requested || is_ctrl_down || is_unbound) + { + start_text_input = true; + g.SliderAsInputTextId = 0; + } + } + + // Tabbing or CTRL-clicking through slider turns into an input box + bool value_changed = false; + if (start_text_input || (g.ActiveId == id && id == g.SliderAsInputTextId)) + { + char text_buf[64]; + 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 (registered previously to allow for a TAB focus to happen) + value_changed = ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); + if (g.SliderAsInputTextId == 0) + { + // First frame + IM_ASSERT(g.ActiveId == id); // InputText ID should match the Slider ID (else we'd need to store them both which is also possible) + g.SliderAsInputTextId = g.ActiveId; + g.ActiveId = id; + g.HoveredId = id; + } + else + { + if (g.ActiveId == g.SliderAsInputTextId) + g.ActiveId = id; + else + g.ActiveId = g.SliderAsInputTextId = 0; + } + if (value_changed) + { + ApplyNumericalTextInput(text_buf, v); + } + return value_changed; + } + + ItemSize(bb); + RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg)); + + // Process clicking on the slider + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + 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); + + // Account for logarithmic scale on both sides of the zero + float new_value; + if (normalized_pos < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (normalized_pos / linear_zero_pos); + a = powf(a, power); + new_value = ImLerp(ImMin(v_max,0.f), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + 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); + } + + // Round past decimal precision + // 0->1, 1->0.1, 2->0.01, etc. + // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 + const float min_step = 1.0f / powf(10.0f, (float)decimal_precision); + const float remainder = fmodf(new_value, min_step); + if (remainder <= min_step*0.5f) + new_value -= remainder; + else + new_value += (min_step - remainder); + + if (*v != new_value) + { + *v = new_value; + value_changed = true; + } + } + } + else + { + g.ActiveId = 0; + } + } + + if (!is_unbound) + { + // Linear slider + // const float grab_t = (ImClamp(*v, v_min, v_max) - v_min) / (v_max - v_min); + + // Calculate slider grab positioning + float grab_t; + float v_clamped = ImClamp(*v, v_min, v_max); + if (v_clamped < 0.0f) + { + const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); + grab_t = (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; + } + else + { + const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); + grab_t = linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); + } + + // Draw + const float grab_x = ImLerp(slider_effective_x1, slider_effective_x2, grab_t); + const ImGuiAabb grab_bb(ImVec2(grab_x-grab_size_in_pixels*0.5f,frame_bb.Min.y+2.0f), ImVec2(grab_x+grab_size_in_pixels*0.5f,frame_bb.Max.y-2.0f)); + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, window->Color(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab)); + } + + // Draw value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + 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); + + return value_changed; +} + +bool ImGui::SliderAngle(const char* label, float* v, float v_degrees_min, float v_degrees_max) +{ + float v_deg = *v * 360.0f / (2*PI); + bool value_changed = ImGui::SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); + *v = v_deg * (2*PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = ImGui::SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + *v = (int)v_f; + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +static bool SliderFloatN(const char* label, float v[3], int components, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + 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))); + + bool value_changed = false; + ImGui::PushID(label); + ImGui::PushItemWidth(w_item_one); + for (int i = 0; i < components; i++) + { + ImGui::PushID(i); + if (i + 1 == components) + { + ImGui::PopItemWidth(); + ImGui::PushItemWidth(w_item_last); + } + value_changed |= ImGui::SliderFloat("##v", &v[i], v_min, v_max, display_format, power); + ImGui::SameLine(0, 0); + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::PopID(); + + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + return value_changed; +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); +} + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImGuiStyle& style = g.Style; + + const ImVec2 text_size = ImGui::CalcTextSize(label); + if (graph_size.x == 0.0f) + graph_size.x = window->DC.ItemWidth.back(); + if (graph_size.y == 0.0f) + graph_size.y = text_size.y; + + const ImGuiAabb frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y) + style.FramePadding*2.0f); + const ImGuiAabb graph_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImGuiAabb bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + text_size.x,0)); + ItemSize(bb); + + if (ClipAdvance(bb)) + return; + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg)); + + int res_w = ImMin((int)graph_size.x, values_count); + if (plot_type == ImGuiPlotType_Lines) + res_w -= 1; + + // Tooltip on hover + int v_hovered = -1; + if (IsMouseHoveringBox(graph_bb)) + { + const float t = ImClamp((g.IO.MousePos.x - graph_bb.Min.x) / (graph_bb.Max.x - graph_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * (values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0))); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + ImGui::SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + ImGui::SetTooltip("%d: %8.4g", v_idx, v0); + v_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 p0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); + + const ImU32 col_base = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v_idx = (int)(t0 * values_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + const float v1 = values_getter(data, (v_idx + values_offset + 1) % values_count); + const ImVec2 p1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); + + // NB- Draw calls are merged together by the DrawList system. + if (plot_type == ImGuiPlotType_Lines) + window->DrawList->AddLine(ImLerp(graph_bb.Min, graph_bb.Max, p0), ImLerp(graph_bb.Min, graph_bb.Max, p1), v_hovered == v_idx ? col_hovered : col_base); + else if (plot_type == ImGuiPlotType_Histogram) + window->DrawList->AddRectFilled(ImLerp(graph_bb.Min, graph_bb.Max, p0), ImLerp(graph_bb.Min, graph_bb.Max, ImVec2(p1.x, 1.0f))+ImVec2(-1,0), v_hovered == v_idx ? col_hovered : col_base); + + t0 = t1; + p0 = p1; + } + + // Text overlay + if (overlay_text) + RenderText(ImVec2(graph_bb.GetCenter().x - ImGui::CalcTextSize(overlay_text).x*0.5f, frame_bb.Min.y + style.FramePadding.y), overlay_text); + + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, graph_bb.Min.y), label); +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + size_t Stride; + + ImGuiPlotArrayGetterData(const float* values, size_t stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + Plot(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + Plot(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + Plot(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + Plot(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 text_size = CalcTextSize(label); + + const ImGuiAabb check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(text_size.y + style.FramePadding.y*2, text_size.y + style.FramePadding.y*2)); + ItemSize(check_bb); + SameLine(0, (int)g.Style.ItemInnerSpacing.x); + + 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)) + return false; + + 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; + if (pressed) + { + *v = !(*v); + g.ActiveId = 0; // Clear focus + } + + RenderFrame(check_bb.Min, check_bb.Max, window->Color(hovered ? ImGuiCol_CheckHovered : ImGuiCol_FrameBg)); + if (*v) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; + window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), window->Color(ImGuiCol_CheckActive)); + } + + if (g.LogEnabled) + LogText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + bool v = (*flags & flags_value) ? true : false; + bool pressed = ImGui::Checkbox(label, &v); + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + return pressed; +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 text_size = CalcTextSize(label); + + const ImGuiAabb check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(text_size.y + style.FramePadding.y*2-1, text_size.y + style.FramePadding.y*2-1)); + ItemSize(check_bb); + SameLine(0, (int)style.ItemInnerSpacing.x); + + 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)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = (float)(int)center.x + 0.5f; + 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(total_bb); + const bool pressed = hovered && g.IO.MouseClicked[0]; + if (hovered) + g.HoveredId = id; + + window->DrawList->AddCircleFilled(center, radius, window->Color(hovered ? ImGuiCol_CheckHovered : ImGuiCol_FrameBg), 16); + if (active) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; + window->DrawList->AddCircleFilled(center, radius-pad, window->Color(ImGuiCol_CheckActive), 16); + } + + if (window->Flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddCircle(center+ImVec2(1,1), radius, window->Color(ImGuiCol_BorderShadow), 16); + window->DrawList->AddCircle(center, radius, window->Color(ImGuiCol_Border), 16); + } + + if (g.LogEnabled) + LogText(text_bb.GetTL(), active ? "(x)" : "( )"); + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = ImGui::RadioButton(label, *v == v_button); + if (pressed) + { + *v = v_button; + } + return pressed; +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return (int)ImStrlenW(obj->Text); } +static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { (void)line_start_idx; return obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } +static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } +static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) +{ + const ImWchar* text_remaining = NULL; + const ImVec2 size = obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, obj->Text + line_start_idx, NULL, &text_remaining); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (obj->Text + line_start_idx)); +} + +static bool is_white(unsigned int c) { return c==0 || c==' ' || c=='\t' || c=='\r' || c=='\n'; } +static bool is_separator(unsigned int c) { return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +#define STB_TEXTEDIT_IS_SPACE(CH) ( is_white((unsigned int)CH) || is_separator((unsigned int)CH) ) +static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { ImWchar* dst = obj->Text+pos; const ImWchar* src = obj->Text+pos+n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } +static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) +{ + const size_t text_len = ImStrlenW(obj->Text); + if ((size_t)new_text_len + text_len + 1 >= obj->BufSize) + return false; + + if (pos != (int)text_len) + memmove(obj->Text + (size_t)pos + new_text_len, obj->Text + (size_t)pos, (text_len - (size_t)pos) * sizeof(ImWchar)); + memcpy(obj->Text + (size_t)pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + obj->Text[text_len + (size_t)new_text_len] = '\0'; + + return true; +} + +enum +{ + STB_TEXTEDIT_K_LEFT = 1 << 16, // keyboard input to move cursor left + STB_TEXTEDIT_K_RIGHT, // keyboard input to move cursor right + STB_TEXTEDIT_K_UP, // keyboard input to move cursor up + STB_TEXTEDIT_K_DOWN, // keyboard input to move cursor down + STB_TEXTEDIT_K_LINESTART, // keyboard input to move cursor to start of line + STB_TEXTEDIT_K_LINEEND, // keyboard input to move cursor to end of line + STB_TEXTEDIT_K_TEXTSTART, // keyboard input to move cursor to start of text + STB_TEXTEDIT_K_TEXTEND, // keyboard input to move cursor to end of text + STB_TEXTEDIT_K_DELETE, // keyboard input to delete selection or character under cursor + STB_TEXTEDIT_K_BACKSPACE, // keyboard input to delete selection or character left of cursor + STB_TEXTEDIT_K_UNDO, // keyboard input to perform undo + STB_TEXTEDIT_K_REDO, // keyboard input to perform redo + STB_TEXTEDIT_K_WORDLEFT, // keyboard input to move cursor left one word + STB_TEXTEDIT_K_WORDRIGHT, // keyboard input to move cursor right one word + STB_TEXTEDIT_K_SHIFT = 1 << 17 +}; + +#define STB_TEXTEDIT_IMPLEMENTATION +#include "stb_textedit.h" + +void ImGuiTextEditState::OnKeyPressed(int key) +{ + stb_textedit_key(this, &StbState, key); + CursorAnimReset(); +} + +void ImGuiTextEditState::UpdateScrollOffset() +{ + // Scroll in chunks of quarter width + const float scroll_x_increment = Width * 0.25f; + const float cursor_offset_x = Font->CalcTextSizeW(FontSize, FLT_MAX, Text, Text+StbState.cursor, NULL).x; + if (ScrollX > cursor_offset_x) + ScrollX = ImMax(0.0f, cursor_offset_x - scroll_x_increment); + else if (ScrollX < cursor_offset_x - Width) + ScrollX = cursor_offset_x - Width + scroll_x_increment; +} + +ImVec2 ImGuiTextEditState::CalcDisplayOffsetFromCharIdx(int i) const +{ + const ImWchar* text_start = GetTextPointerClippedW(Font, FontSize, Text, ScrollX, NULL); + const ImWchar* text_end = (Text+i >= text_start) ? Text+i : text_start; // Clip if requested character is outside of display + IM_ASSERT(text_end >= text_start); + + const ImVec2 offset = Font->CalcTextSizeW(FontSize, Width, text_start, text_end, NULL); + return offset; +} + +// [Static] +const char* ImGuiTextEditState::GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size) +{ + if (width <= 0.0f) + return text; + + const char* text_clipped_end = NULL; + const ImVec2 text_size = font->CalcTextSizeA(font_size, width, 0.0f, text, NULL, &text_clipped_end); + if (out_text_size) + *out_text_size = text_size; + return text_clipped_end; +} + +// [Static] +const ImWchar* ImGuiTextEditState::GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size) +{ + if (width <= 0.0f) + return text; + + const ImWchar* text_clipped_end = NULL; + const ImVec2 text_size = font->CalcTextSizeW(font_size, width, text, NULL, &text_clipped_end); + if (out_text_size) + *out_text_size = text_size; + return text_clipped_end; +} + +// [Static] +void ImGuiTextEditState::RenderTextScrolledClipped(ImFont* font, float font_size, const char* buf, ImVec2 pos, float width, float scroll_x) +{ + // NB- We start drawing at character boundary + ImVec2 text_size; + const char* text_start = GetTextPointerClippedA(font, font_size, buf, scroll_x, NULL); + const char* text_end = GetTextPointerClippedA(font, font_size, text_start, width, &text_size); + + // Draw a little clip symbol if we've got text on either left or right of the box + const char symbol_c = '~'; + const float symbol_w = font_size*0.40f; // FIXME: compute correct width + const float clip_begin = (text_start > buf && text_start < text_end) ? symbol_w : 0.0f; + const float clip_end = (text_end[0] != '\0' && text_end > text_start) ? symbol_w : 0.0f; + + // Draw text + 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'}; + if (clip_begin > 0.0f) + RenderText(pos, s); + if (clip_end > 0.0f) + RenderText(pos+ImVec2(width-clip_end,0.0f), s); +} + +bool ImGui::InputFloat(const char* label, float *v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const float w = window->DC.ItemWidth.back(); + const ImVec2 text_size = CalcTextSize(label); + const ImGuiAabb frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, text_size.y) + style.FramePadding*2.0f); + + ImGui::PushID(label); + const float button_sz = window->FontSize(); + 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]; + if (decimal_precision < 0) + 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, IM_ARRAYSIZE(buf), "%.*f", decimal_precision, *v); + bool value_changed = false; + const ImGuiInputTextFlags flags = extra_flags | (ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AutoSelectAll); + if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), flags)) + { + ApplyNumericalTextInput(buf, v); + value_changed = true; + } + + // Step buttons + 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 > 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 > 0.0f ? step_fast : step; + value_changed = true; + } + } + + ImGui::PopID(); + + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + g.Style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::InputInt(const char* label, int *v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + float f = (float)*v; + const bool value_changed = ImGui::InputFloat(label, &f, (float)step, (float)step_fast, 0, extra_flags); + if (value_changed) + *v = (int)f; + return value_changed; +} + +// Public API to manipulate UTF-8 text +// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) +{ + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + while (char c = *src++) + *dst++ = c; + *dst = '\0'; + + BufDirty = true; + if (CursorPos + bytes_count >= pos) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; +} + +void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + const size_t text_len = strlen(Buf); + if (!new_text_end) + new_text_end = new_text + strlen(new_text); + const size_t new_text_len = (size_t)(new_text_end - new_text); + + if (new_text_len + text_len + 1 >= BufSize) + return; + + size_t upos = (size_t)pos; + if (text_len != upos) + memmove(Buf + upos + new_text_len, Buf + upos, text_len - upos); + memcpy(Buf + upos, new_text, new_text_len * sizeof(char)); + Buf[text_len + new_text_len] = '\0'; + + BufDirty = true; + if (CursorPos >= pos) + CursorPos += (int)new_text_len; + SelectionStart = SelectionEnd = CursorPos; +} + +// Edit a string of text +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, void (*callback)(ImGuiTextEditCallbackData*), void* user_data) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const ImGuiID id = window->GetID(label); + const float w = window->DC.ItemWidth.back(); + + const ImVec2 text_size = CalcTextSize(label); + const ImGuiAabb frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, text_size.y) + style.FramePadding*2.0f); + const ImGuiAabb bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + text_size.x, 0.0f)); + ItemSize(bb); + + if (ClipAdvance(frame_bb)) + return false; + + // NB: we are only allowed to access it if we are the active widget. + ImGuiTextEditState& edit_state = g.InputTextState; + + const bool is_ctrl_down = io.KeyCtrl; + const bool is_shift_down = io.KeyShift; + const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id, (flags & ImGuiInputTextFlags_CallbackCompletion) == 0); // Using completion callback disable keyboard tabbing + //const bool align_center = (bool)(flags & ImGuiInputTextFlags_AlignCenter); // FIXME: Unsupported + + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(frame_bb); + if (hovered) + g.HoveredId = id; + + bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; + if (tab_focus_requested || (hovered && io.MouseClicked[0])) + { + if (g.ActiveId != id) + { + // Start edition + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + ImFormatString(edit_state.InitialText, IM_ARRAYSIZE(edit_state.InitialText), "%s", buf); + ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), buf, NULL); + edit_state.ScrollX = 0.0f; + edit_state.Width = w; + stb_textedit_initialize_state(&edit_state.StbState, true); + edit_state.CursorAnimReset(); + edit_state.LastCursorPos = ImVec2(-1.f,-1.f); + + if (tab_focus_requested || is_ctrl_down) + select_all = true; + } + g.ActiveId = id; + } + else if (io.MouseClicked[0]) + { + // Release focus when we click outside + if (g.ActiveId == id) + { + g.ActiveId = 0; + } + } + + bool value_changed = false; + bool cancel_edit = false; + bool enter_pressed = false; + static char text_tmp_utf8[IM_ARRAYSIZE(edit_state.InitialText)]; + if (g.ActiveId == id) + { + // Edit in progress + 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(); + + const float mx = g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x; + const float my = window->FontSize()*0.5f; // Flatten mouse because we are doing a single-line edit + + edit_state.UpdateScrollOffset(); + if (select_all || (hovered && io.MouseDoubleClicked[0])) + { + edit_state.SelectAll(); + edit_state.SelectedAllMouseLock = true; + } + else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) + { + stb_textedit_click(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + edit_state.CursorAnimReset(); + + } + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock) + { + stb_textedit_drag(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + edit_state.CursorAnimReset(); + } + if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) + edit_state.SelectedAllMouseLock = false; + + const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0); + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Enter)) { g.ActiveId = 0; enter_pressed = true; } + else if (IsKeyPressedMap(ImGuiKey_Escape)) { g.ActiveId = 0; cancel_edit = true; } + else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Z)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); } + else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Y)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); } + else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); } + else if (is_ctrl_down && (IsKeyPressedMap(ImGuiKey_X) || IsKeyPressedMap(ImGuiKey_C))) + { + // Cut, Copy + const bool cut = IsKeyPressedMap(ImGuiKey_X); + if (cut && !edit_state.HasSelection()) + edit_state.SelectAll(); + + if (g.IO.SetClipboardTextFn) + { + const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : (int)ImStrlenW(edit_state.Text); + ImTextStrToUtf8(text_tmp_utf8, IM_ARRAYSIZE(text_tmp_utf8), edit_state.Text+ib, edit_state.Text+ie); + g.IO.SetClipboardTextFn(text_tmp_utf8); + } + + if (cut) + stb_textedit_cut(&edit_state, &edit_state.StbState); + } + else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_V)) + { + // Paste + if (g.IO.GetClipboardTextFn) + { + if (const char* clipboard = g.IO.GetClipboardTextFn()) + { + // Remove new-line from pasted buffer + size_t clipboard_len = strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) + { + unsigned int c; + const int bytes_count = ImTextCharFromUtf8(&c, s, NULL); + if (bytes_count <= 0) + break; + s += bytes_count; + if (c == '\n' || c == '\r') + continue; + if (c >= 0x10000) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + ImGui::MemFree(clipboard_filtered); + } + } + } + else if (g.IO.InputCharacters[0]) + { + // Text input + for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) + { + const ImWchar c = g.IO.InputCharacters[n]; + if (c) + { + // Filter + if (c < 256 && !isprint((char)(c & 0xFF)) && c != ' ') + continue; + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + continue; + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + continue; + + // Insert character! + edit_state.OnKeyPressed(c); + } + } + } + + edit_state.CursorAnim += g.IO.DeltaTime; + edit_state.UpdateScrollOffset(); + + if (cancel_edit) + { + // Restore initial value + ImFormatString(buf, buf_size, "%s", edit_state.InitialText); + value_changed = true; + } + else + { + // Apply new value immediately - copy modified buffer back + // Note that as soon as we can focus into the input box, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' in RenderTextScrolledClipped + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks + ImTextStrToUtf8(text_tmp_utf8, IM_ARRAYSIZE(text_tmp_utf8), edit_state.Text, NULL); + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiKey event_key = ImGuiKey_COUNT; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) + event_key = ImGuiKey_Tab; + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) + event_key = ImGuiKey_UpArrow; + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) + event_key = ImGuiKey_DownArrow; + + if (event_key != ImGuiKey_COUNT || (flags & ImGuiInputTextFlags_CallbackAlways) != 0) + { + ImGuiTextEditCallbackData callback_data; + callback_data.EventKey = event_key; + callback_data.Buf = text_tmp_utf8; + callback_data.BufSize = edit_state.BufSize; + callback_data.BufDirty = false; + callback_data.Flags = flags; + callback_data.UserData = user_data; + + // We have to convert from position from wchar to UTF-8 positions + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromWchar(edit_state.Text, edit_state.Text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromWchar(edit_state.Text, edit_state.Text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromWchar(edit_state.Text, edit_state.Text + edit_state.StbState.select_end); + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + IM_ASSERT(callback_data.Buf == text_tmp_utf8); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == edit_state.BufSize); + IM_ASSERT(callback_data.Flags == flags); + if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); + if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); + if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); + if (callback_data.BufDirty) + { + ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), text_tmp_utf8, NULL); + edit_state.CursorAnimReset(); + } + } + } + + if (strcmp(text_tmp_utf8, buf) != 0) + { + ImFormatString(buf, buf_size, "%s", text_tmp_utf8); + value_changed = true; + } + } + } + + RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true); + + const ImVec2 font_off_up = ImVec2(0.0f,window->FontSize()+1.0f); // FIXME: those offsets are part of the style or font API + const ImVec2 font_off_dn = ImVec2(0.0f,2.0f); + + if (g.ActiveId == id) + { + // Draw selection + const int select_begin_idx = edit_state.StbState.select_start; + const int select_end_idx = edit_state.StbState.select_end; + if (select_begin_idx != select_end_idx) + { + const ImVec2 select_begin_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMin(select_begin_idx,select_end_idx)); + const ImVec2 select_end_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMax(select_begin_idx,select_end_idx)); + window->DrawList->AddRectFilled(select_begin_pos - font_off_up, select_end_pos + font_off_dn, window->Color(ImGuiCol_TextSelectedBg)); + } + } + + // FIXME: 'align_center' unsupported + ImGuiTextEditState::RenderTextScrolledClipped(window->Font(), window->FontSize(), buf, frame_bb.Min + style.FramePadding, w, (g.ActiveId == id) ? edit_state.ScrollX : 0.0f); + + if (g.ActiveId == id) + { + const ImVec2 cursor_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(edit_state.StbState.cursor); + + // Draw blinking cursor + if (g.InputTextState.CursorIsVisible()) + window->DrawList->AddRect(cursor_pos - font_off_up + ImVec2(0,2), cursor_pos + font_off_dn - ImVec2(0,3), window->Color(ImGuiCol_Text)); + + // Notify OS of text input position + if (io.ImeSetInputScreenPosFn && ImLength(edit_state.LastCursorPos - cursor_pos) > 0.01f) + io.ImeSetInputScreenPosFn((int)cursor_pos.x - 1, (int)(cursor_pos.y - window->FontSize())); // -1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety. + + edit_state.LastCursorPos = cursor_pos; + } + + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return enter_pressed; + else + return value_changed; +} + +static bool InputFloatN(const char* label, float* v, int components, int decimal_precision) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + 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))); + + bool value_changed = false; + ImGui::PushID(label); + ImGui::PushItemWidth(w_item_one); + for (int i = 0; i < components; i++) + { + ImGui::PushID(i); + if (i + 1 == components) + { + ImGui::PopItemWidth(); + ImGui::PushItemWidth(w_item_last); + } + value_changed |= ImGui::InputFloat("##v", &v[i], 0, 0, decimal_precision); + ImGui::SameLine(0, 0); + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::PopID(); + + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + return value_changed; +} + +bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision) +{ + return InputFloatN(label, v, 2, decimal_precision); +} + +bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision) +{ + return InputFloatN(label, v, 3, decimal_precision); +} + +bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision) +{ + return InputFloatN(label, v, 4, decimal_precision); +} + +static bool Combo_ArrayGetter(void* data, int idx, const char** out_text) +{ + const char** items = (const char**)data; + if (out_text) + *out_text = items[idx]; + return true; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char** items, int items_count, int popup_height_items) +{ + const bool value_changed = Combo(label, current_item, Combo_ArrayGetter, (void*)items, items_count, popup_height_items); + return value_changed; +} + +static bool Combo_StringListGetter(void* data, int idx, const char** out_text) +{ + // FIXME-OPT: we could precompute the indices to fasten this. But only 1 active combo means the waste is limited. + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += strlen(p) + 1; + items_count++; + } + if (!*p) + return false; + if (out_text) + *out_text = p; + return true; +} + +// Combo box helper allowing to pass all items in a single string. +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_height_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + p += strlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Combo_StringListGetter, (void*)items_separated_by_zeros, items_count, popup_height_items); + return value_changed; +} + +// Combo box function. +bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_height_items) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 text_size = CalcTextSize(label); + const float arrow_size = (window->FontSize() + style.FramePadding.x * 2.0f); + const ImGuiAabb frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(window->DC.ItemWidth.back(), text_size.y) + style.FramePadding*2.0f); + const ImGuiAabb bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + text_size.x,0)); + + if (ClipAdvance(frame_bb)) + return false; + + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(bb); + + bool value_changed = false; + ItemSize(frame_bb); + RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg)); + RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, window->Color(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button)); + RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); + + if (*current_item >= 0 && *current_item < items_count) + { + const char* item_text; + if (items_getter(data, *current_item, &item_text)) + RenderText(frame_bb.Min + style.FramePadding, item_text, NULL, false); + } + + ImGui::SameLine(0, (int)g.Style.ItemInnerSpacing.x); + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + ImGui::PushID((int)id); + bool menu_toggled = false; + if (hovered) + { + g.HoveredId = id; + if (g.IO.MouseClicked[0]) + { + menu_toggled = true; + g.ActiveComboID = (g.ActiveComboID == id) ? 0 : id; + } + } + + if (g.ActiveComboID == id) + { + const ImVec2 backup_pos = ImGui::GetCursorPos(); + const float popup_off_x = 0.0f;//g.Style.ItemInnerSpacing.x; + const float popup_height = (text_size.y + g.Style.ItemSpacing.y) * ImMin(items_count, popup_height_items) + g.Style.WindowPadding.y; + const ImGuiAabb popup_aabb(ImVec2(frame_bb.Min.x+popup_off_x, frame_bb.Max.y), ImVec2(frame_bb.Max.x+popup_off_x, frame_bb.Max.y + popup_height)); + ImGui::SetCursorPos(popup_aabb.Min - window->Pos); + + const 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")); + + // Display items + for (int item_idx = 0; item_idx < items_count; item_idx++) + { + const float item_h = child_window->FontSize(); + const float spacing_up = (float)(int)(g.Style.ItemSpacing.y/2); + const float spacing_dn = g.Style.ItemSpacing.y - spacing_up; + const ImGuiAabb item_aabb(ImVec2(popup_aabb.Min.x, child_window->DC.CursorPos.y - spacing_up), ImVec2(popup_aabb.Max.x, child_window->DC.CursorPos.y + item_h + spacing_dn)); + const ImGuiID item_id = child_window->GetID((void*)(intptr_t)item_idx); + + bool item_hovered, item_held; + bool item_pressed = ButtonBehaviour(item_aabb, item_id, &item_hovered, &item_held, true); + bool item_selected = (item_idx == *current_item); + + if (item_hovered || item_selected) + { + const ImU32 col = window->Color((item_held && item_hovered) ? ImGuiCol_HeaderActive : item_hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(item_aabb.Min, item_aabb.Max, col, false); + } + + const char* item_text; + if (!items_getter(data, item_idx, &item_text)) + item_text = "*Unknown item*"; + ImGui::Text("%s", item_text); + + if (item_selected) + { + if (menu_toggled) + ImGui::SetScrollPosHere(); + } + if (item_pressed) + { + g.ActiveId = 0; + g.ActiveComboID = 0; + value_changed = true; + *current_item = item_idx; + } + + combo_item_active |= (g.ActiveId == item_id); + } + ImGui::EndChild(); + ImGui::SetCursorPos(backup_pos); + + if (!combo_item_active && g.ActiveId != 0) + g.ActiveComboID = 0; + } + + ImGui::PopID(); + + return value_changed; +} + +// A little colored square. Return true when clicked. +bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const float square_size = window->FontSize(); + const ImGuiAabb bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.x*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); + ItemSize(bb); + + if (ClipAdvance(bb)) + return false; + + const bool hovered = (g.HoveredWindow == window) && (g.HoveredId == 0) && IsMouseHoveringBox(bb); + const bool pressed = hovered && g.IO.MouseClicked[0]; + RenderFrame(bb.Min, bb.Max, window->Color(col), outline_border); + + if (hovered) + { + int ix = (int)(col.x * 255.0f + 0.5f); + int iy = (int)(col.y * 255.0f + 0.5f); + int iz = (int)(col.z * 255.0f + 0.5f); + int iw = (int)(col.w * 255.0f + 0.5f); + ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, ix, iy, iz, iw); + } + + return pressed; +} + +bool ImGui::ColorEdit3(const char* label, float col[3]) +{ + float col4[4]; + col4[0] = col[0]; + col4[1] = col[1]; + col4[2] = col[2]; + col4[3] = 1.0f; + const bool value_changed = ImGui::ColorEdit4(label, col4, false); + col[0] = col4[0]; + col[1] = col4[1]; + col[2] = col4[2]; + return value_changed; +} + +// Edit colors components (each component in 0.0f..1.0f range +// Use CTRL-Click to input value and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w_full = window->DC.ItemWidth.back(); + const float square_sz = (window->FontSize() + style.FramePadding.x * 2.0f); + + ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; + if (edit_mode == ImGuiColorEditMode_UserSelect) + edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; + + float fx = col[0]; + float fy = col[1]; + float fz = col[2]; + float fw = col[3]; + const ImVec4 col_display(fx, fy, fz, 1.0f); + + if (edit_mode == ImGuiColorEditMode_HSV) + ImConvertColorRGBtoHSV(fx, fy, fz, fx, fy, fz); + + int ix = (int)(fx * 255.0f + 0.5f); + int iy = (int)(fy * 255.0f + 0.5f); + int iz = (int)(fz * 255.0f + 0.5f); + int iw = (int)(fw * 255.0f + 0.5f); + + int components = alpha ? 4 : 3; + bool value_changed = false; + + ImGui::PushID(label); + + bool hsv = (edit_mode == 1); + switch (edit_mode) + { + case ImGuiColorEditMode_RGB: + case ImGuiColorEditMode_HSV: + { + // 0: RGB 0..255 + // 1: HSV 0.255 Sliders + const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.FramePadding.x*2.0f+style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one+style.FramePadding.x*2.0f+style.ItemInnerSpacing.x) * (components-1))); + + ImGui::PushItemWidth(w_item_one); + value_changed |= ImGui::SliderInt("##X", &ix, 0, 255, hsv ? "H:%3.0f" : "R:%3.0f"); + ImGui::SameLine(0, 0); + value_changed |= ImGui::SliderInt("##Y", &iy, 0, 255, hsv ? "S:%3.0f" : "G:%3.0f"); + ImGui::SameLine(0, 0); + if (alpha) + { + value_changed |= ImGui::SliderInt("##Z", &iz, 0, 255, hsv ? "V:%3.0f" : "B:%3.0f"); + ImGui::SameLine(0, 0); + ImGui::PushItemWidth(w_item_last); + value_changed |= ImGui::SliderInt("##W", &iw, 0, 255, "A:%3.0f"); + } + else + { + ImGui::PushItemWidth(w_item_last); + value_changed |= ImGui::SliderInt("##Z", &iz, 0, 255, hsv ? "V:%3.0f" : "B:%3.0f"); + } + ImGui::PopItemWidth(); + ImGui::PopItemWidth(); + } + break; + case ImGuiColorEditMode_HEX: + { + // 2: RGB Hexadecimal + const float w_slider_all = w_full - square_sz; + char buf[64]; + if (alpha) + sprintf(buf, "#%02X%02X%02X%02X", ix, iy, iz, iw); + else + sprintf(buf, "#%02X%02X%02X", ix, iy, iz); + ImGui::PushItemWidth(w_slider_all - g.Style.ItemInnerSpacing.x); + value_changed |= ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal); + ImGui::PopItemWidth(); + char* p = buf; + while (*p == '#' || *p == ' ' || *p == '\t') + p++; + + // Treat at unsigned (%X is unsigned) + ix = iy = iz = iw = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&ix, (unsigned int*)&iy, (unsigned int*)&iz, (unsigned int*)&iw); + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&ix, (unsigned int*)&iy, (unsigned int*)&iz); + } + break; + } + + ImGui::SameLine(0, 0); + ImGui::ColorButton(col_display); + + if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelect) + { + ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + const char* button_titles[3] = { "RGB", "HSV", "HEX" }; + if (ImGui::Button(button_titles[edit_mode])) + { + // Don't set local copy of 'edit_mode' right away! + g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); + } + } + + ImGui::SameLine(); + ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); + + // Convert back + fx = ix / 255.0f; + fy = iy / 255.0f; + fz = iz / 255.0f; + fw = iw / 255.0f; + if (edit_mode == 1) + ImConvertColorHSVtoRGB(fx, fy, fz, fx, fy, fz); + + if (value_changed) + { + col[0] = fx; + col[1] = fy; + col[2] = fz; + if (alpha) + col[3] = fw; + } + + ImGui::PopID(); + + return value_changed; +} + +void ImGui::ColorEditMode(ImGuiColorEditMode mode) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColorEditMode = mode; +} + +// Horizontal separating line. +void ImGui::Separator() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + if (window->DC.ColumnsCount > 1) + PopClipRect(); + + 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)) + { + if (window->DC.ColumnsCount > 1) + PushColumnClipRect(); + return; + } + + window->DrawList->AddLine(bb.Min, bb.Max, window->Color(ImGuiCol_Border)); + + if (window->DC.ColumnsCount > 1) + PushColumnClipRect(); +} + +// A little vertical spacing. +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ItemSize(ImVec2(0,0)); +} + +// Advance cursor given item size. +static void ItemSize(ImVec2 size, ImVec2* adjust_start_offset) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); + if (adjust_start_offset) + adjust_start_offset->y = adjust_start_offset->y + (line_height - size.y) * 0.5f; + + // Always align ourselves on pixel boundaries + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + + window->SizeContentsFit = ImMax(window->SizeContentsFit, ImVec2(window->DC.CursorPosPrevLine.x, window->DC.CursorPos.y) - window->Pos + ImVec2(0.0f, window->ScrollY)); + + window->DC.PrevLineHeight = line_height; + window->DC.CurrentLineHeight = 0.0f; +} + +static void ItemSize(const ImGuiAabb& aabb, ImVec2* adjust_start_offset) +{ + ItemSize(aabb.GetSize(), adjust_start_offset); +} + +void ImGui::NextColumn() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + if (window->DC.ColumnsCount > 1) + { + ImGui::PopItemWidth(); + PopClipRect(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) + { + window->DC.ColumnsOffsetX = ImGui::GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.ColumnsStartX + g.Style.ItemSpacing.x; + } + else + { + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.y = window->DC.ColumnsCellMinY; + window->DC.CurrentLineHeight = 0.0f; + + PushColumnClipRect(); + ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); + } +} + +static bool IsClipped(const ImGuiAabb& bb) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (!bb.Overlaps(ImGuiAabb(window->ClipRectStack.back())) && !g.LogEnabled) + return true; + return false; +} + +bool ImGui::IsClipped(const ImVec2& item_size) +{ + ImGuiWindow* window = GetCurrentWindow(); + return IsClipped(ImGuiAabb(window->DC.CursorPos, window->DC.CursorPos + item_size)); +} + +static bool ClipAdvance(const ImGuiAabb& bb) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemAabb = bb; + window->DC.LastItemFocused = false; + if (IsClipped(bb)) + { + window->DC.LastItemHovered = false; + return true; + } + window->DC.LastItemHovered = IsMouseHoveringBox(bb); // this is a sensible default but widgets are free to override it after calling ClipAdvance + return false; +} + +// Gets back to previous line and continue with horizontal layout +// column_x == 0 : follow on previous item +// columm_x != 0 : align to specified column +// spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0 +// spacing_w >= 0 : enforce spacing +void ImGui::SameLine(int column_x, int spacing_w) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + float x, y; + if (column_x != 0) + { + if (spacing_w < 0) spacing_w = 0; + x = window->Pos.x + (float)column_x + (float)spacing_w; + y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0) spacing_w = (int)g.Style.ItemSpacing.x; + x = window->DC.CursorPosPrevLine.x + (float)spacing_w; + y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrentLineHeight = window->DC.PrevLineHeight; + window->DC.CursorPos = ImVec2(x, y); +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); + RegisterAliveId(column_id); + const float default_t = column_index / (float)window->DC.ColumnsCount; + const float t = (float)window->StateStorage.GetInt(column_id, (int)(default_t * 8192)) / 8192; // Cheaply store our floating point value inside the integer (could store an union into the map?) + + const float offset = window->DC.ColumnsStartX + t * (window->Size.x - g.Style.ScrollBarWidth - window->DC.ColumnsStartX); + return offset; +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); + const float t = (offset - window->DC.ColumnsStartX) / (window->Size.x - g.Style.ScrollBarWidth - window->DC.ColumnsStartX); + window->StateStorage.SetInt(column_id, (int)(t*8192)); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + const float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); + return w; +} + +static void PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + const float x1 = window->Pos.x + ImGui::GetColumnOffset(column_index) - 1; + const float x2 = window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1; + PushClipRect(ImVec4(x1,-FLT_MAX,x2,+FLT_MAX)); +} + +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + if (window->DC.ColumnsCount != 1) + { + if (window->DC.ColumnsCurrent != 0) + ItemSize(ImVec2(0,0)); // Advance to column 0 + ImGui::PopItemWidth(); + PopClipRect(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; + } + + // Draw columns borders and handle resize at the time of "closing" a columns set + if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders) + { + const float y1 = window->DC.ColumnsStartPos.y; + const float y2 = window->DC.CursorPos.y; + for (int i = 1; i < window->DC.ColumnsCount; i++) + { + float x = window->Pos.x + GetColumnOffset(i); + + const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i); + const ImGuiAabb column_aabb(ImVec2(x-4,y1),ImVec2(x+4,y2)); + + if (IsClipped(column_aabb)) + continue; + + bool hovered, held; + ButtonBehaviour(column_aabb, column_id, &hovered, &held, true); + + // Draw before resize so our items positioning are in sync with the line being drawn + const ImU32 col = window->Color(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, y1), ImVec2(xi, y2), col); + + if (held) + { + x -= window->Pos.x; + x = ImClamp(x + g.IO.MouseDelta.x, ImGui::GetColumnOffset(i-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(i+1)-g.Style.ColumnsMinSpacing); + SetColumnOffset(i, x); + x += window->Pos.x; + } + } + } + + // Set state for first column + window->DC.ColumnsSetID = window->GetID(id ? id : ""); + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = columns_count; + window->DC.ColumnsShowBorders = border; + window->DC.ColumnsStartPos = window->DC.CursorPos; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); + + if (window->DC.ColumnsCount != 1) + { + PushColumnClipRect(); + ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); + } +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColumnsStartX += g.Style.TreeNodeSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.TreeDepth++; + PushID(str_id ? str_id : "#TreePush"); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColumnsStartX += g.Style.TreeNodeSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.TreeDepth++; + PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); +} + +void ImGui::TreePop() +{ + ImGuiState& g = GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColumnsStartX -= g.Style.TreeNodeSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.TreeDepth--; + PopID(); +} + +void ImGui::Value(const char* prefix, bool b) +{ + ImGui::Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + ImGui::Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + ImGui::Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + sprintf(fmt, "%%s: %s", float_format); + ImGui::Text(fmt, prefix, v); + } + else + { + ImGui::Text("%s: %.3f", prefix, v); + } +} + +void ImGui::Color(const char* prefix, const ImVec4& v) +{ + ImGui::Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); + ImGui::SameLine(); + ImGui::ColorButton(v, true); +} + +void ImGui::Color(const char* prefix, unsigned int v) +{ + ImGui::Text("%s: %08X", prefix, v); + ImGui::SameLine(); + + ImVec4 col; + col.x = (float)((v >> 0) & 0xFF) / 255.0f; + col.y = (float)((v >> 8) & 0xFF) / 255.0f; + col.z = (float)((v >> 16) & 0xFF) / 255.0f; + col.w = (float)((v >> 24) & 0xFF) / 255.0f; + ImGui::ColorButton(col, true); +} + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +void ImDrawList::Clear() +{ + commands.resize(0); + vtx_buffer.resize(0); + vtx_write = NULL; + clip_rect_stack.resize(0); +} + +void ImDrawList::PushClipRect(const ImVec4& 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() +{ + 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) + { + // 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); + } +} + +void ImDrawList::ReserveVertices(unsigned int 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]; + } +} + +void ImDrawList::AddVtx(const ImVec2& pos, ImU32 col) +{ + vtx_write->pos = pos; + vtx_write->col = col; + vtx_write->uv = GImGui.FontTexUvForWhite; + vtx_write++; +} + +void ImDrawList::AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col) +{ + const float offset = GImGui.IO.PixelCenterOffset; + const ImVec2 hn = (b - a) * (0.50f / ImLength(b - a)); // half normal + const ImVec2 hp0 = ImVec2(offset + hn.y, offset - hn.x); // half perpendiculars + user offset + const ImVec2 hp1 = ImVec2(offset - hn.y, offset + hn.x); + + // Two triangles makes up one line. Using triangles allows us to reduce amount of draw calls. + AddVtx(a + hp0, col); + AddVtx(b + hp0, col); + AddVtx(a + hp1, col); + AddVtx(b + hp0, col); + AddVtx(b + hp1, col); + AddVtx(a + hp1, col); +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + ReserveVertices(6); + AddVtxLine(a, b, col); +} + +void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, int a_max, bool tris, const ImVec2& third_point_offset) +{ + if ((col >> 24) == 0) + return; + + static ImVec2 circle_vtx[12]; + static bool circle_vtx_builds = false; + if (!circle_vtx_builds) + { + for (int i = 0; i < IM_ARRAYSIZE(circle_vtx); i++) + { + const float a = ((float)i / (float)IM_ARRAYSIZE(circle_vtx)) * 2*PI; + circle_vtx[i].x = cosf(a + PI); + circle_vtx[i].y = sinf(a + PI); + } + circle_vtx_builds = true; + } + + if (tris) + { + ReserveVertices((unsigned int)(a_max-a_min) * 3); + for (int a = a_min; a < a_max; a++) + { + 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); + } + } + else + { + ReserveVertices((unsigned int)(a_max-a_min) * 6); + for (int a = a_min; a < a_max; a++) + AddVtxLine(center + circle_vtx[a % IM_ARRAYSIZE(circle_vtx)] * rad, center + circle_vtx[(a+1) % IM_ARRAYSIZE(circle_vtx)] * rad, col); + } +} + +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) +{ + if ((col >> 24) == 0) + return; + + float r = rounding; + 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) + { + 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); + AddVtxLine(ImVec2(a.x,b.y), ImVec2(a.x,a.y), col); + } + else + { + 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); + AddVtxLine(ImVec2(a.x, b.y - ((rounding_corners & 8)?r:0)), ImVec2(a.x, a.y + ((rounding_corners & 1)?r:0)), col); + + if (rounding_corners & 1) AddArc(ImVec2(a.x+r,a.y+r), r, col, 0, 3); + if (rounding_corners & 2) AddArc(ImVec2(b.x-r,a.y+r), r, col, 3, 6); + if (rounding_corners & 4) AddArc(ImVec2(b.x-r,b.y-r), r, col, 6, 9); + if (rounding_corners & 8) AddArc(ImVec2(a.x+r,b.y-r), r, col, 9, 12); + } +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) +{ + if ((col >> 24) == 0) + return; + + float r = rounding; + 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) + { + // Use triangle so we can merge more draw calls together (at the cost of extra vertices) + ReserveVertices(6); + AddVtx(ImVec2(a.x,a.y), col); + AddVtx(ImVec2(b.x,a.y), col); + AddVtx(ImVec2(b.x,b.y), col); + AddVtx(ImVec2(a.x,a.y), col); + AddVtx(ImVec2(b.x,b.y), col); + AddVtx(ImVec2(a.x,b.y), col); + } + else + { + 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); + AddVtx(ImVec2(a.x+r,a.y), col); + AddVtx(ImVec2(b.x-r,b.y), col); + AddVtx(ImVec2(a.x+r,b.y), col); + + float top_y = (rounding_corners & 1) ? a.y+r : a.y; + float bot_y = (rounding_corners & 8) ? b.y-r : b.y; + AddVtx(ImVec2(a.x,top_y), col); + AddVtx(ImVec2(a.x+r,top_y), col); + AddVtx(ImVec2(a.x+r,bot_y), col); + AddVtx(ImVec2(a.x,top_y), col); + AddVtx(ImVec2(a.x+r,bot_y), col); + AddVtx(ImVec2(a.x,bot_y), col); + + top_y = (rounding_corners & 2) ? a.y+r : a.y; + bot_y = (rounding_corners & 4) ? b.y-r : b.y; + AddVtx(ImVec2(b.x-r,top_y), col); + AddVtx(ImVec2(b.x,top_y), col); + AddVtx(ImVec2(b.x,bot_y), col); + AddVtx(ImVec2(b.x-r,top_y), col); + AddVtx(ImVec2(b.x,bot_y), col); + AddVtx(ImVec2(b.x-r,bot_y), col); + + if (rounding_corners & 1) AddArc(ImVec2(a.x+r,a.y+r), r, col, 0, 3, true); + if (rounding_corners & 2) AddArc(ImVec2(b.x-r,a.y+r), r, col, 3, 6, true); + if (rounding_corners & 4) AddArc(ImVec2(b.x-r,b.y-r), r, col, 6, 9, true); + if (rounding_corners & 8) AddArc(ImVec2(a.x+r,b.y-r), r, col, 9, 12,true); + } +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + const ImVec2 offset(GImGui.IO.PixelCenterOffset,GImGui.IO.PixelCenterOffset); + + ReserveVertices(3); + AddVtx(a + offset, col); + AddVtx(b + offset, col); + AddVtx(c + offset, col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col >> 24) == 0) + return; + + const ImVec2 offset(GImGui.IO.PixelCenterOffset,GImGui.IO.PixelCenterOffset); + + ReserveVertices((unsigned int)num_segments*6); + const float a_step = 2*PI/(float)num_segments; + float a0 = 0.0f; + for (int i = 0; i < num_segments; i++) + { + const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; + AddVtxLine(centre + offset + ImVec2(cosf(a0), sinf(a0))*radius, centre + ImVec2(cosf(a1), sinf(a1))*radius, col); + a0 = a1; + } +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col >> 24) == 0) + return; + + const ImVec2 offset(GImGui.IO.PixelCenterOffset,GImGui.IO.PixelCenterOffset); + + ReserveVertices((unsigned int)num_segments*3); + const float a_step = 2*PI/(float)num_segments; + float a0 = 0.0f; + for (int i = 0; i < num_segments; i++) + { + const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; + AddVtx(centre + offset + ImVec2(cosf(a0), sinf(a0))*radius, col); + AddVtx(centre + offset + ImVec2(cosf(a1), sinf(a1))*radius, col); + AddVtx(centre + offset, col); + a0 = a1; + } +} + +void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width) +{ + if ((col >> 24) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); // FIXME-OPT + + // reserve vertices for worse case + const unsigned int char_count = (unsigned int)(text_end - text_begin); + const unsigned 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, wrap_width); + + // give back unused vertices + vtx_buffer.resize((size_t)(vtx_write - &vtx_buffer.front())); + const size_t vtx_count = vtx_buffer.size() - vtx_begin; + commands.back().vtx_count -= (unsigned int)(vtx_count_max - vtx_count); + vtx_write -= (vtx_count_max - vtx_count); +} + +//----------------------------------------------------------------------------- +// ImBitmapFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + DisplayOffset = ImVec2(0.0f,0.0f); + TexUvForWhite = ImVec2(0.0f,0.0f); + FallbackChar = (ImWchar)'?'; + + Data = NULL; + DataSize = 0; + DataOwned = false; + Info = NULL; + Common = NULL; + Glyphs = NULL; + GlyphsCount = 0; + Kerning = NULL; + KerningCount = 0; +} + +void ImFont::Clear() +{ + if (Data && DataOwned) + ImGui::MemFree(Data); + Data = NULL; + DataOwned = false; + Info = NULL; + Common = NULL; + Glyphs = NULL; + GlyphsCount = 0; + Filenames.clear(); + IndexLookup.clear(); +} + +bool ImFont::LoadFromFile(const char* filename) +{ + IM_ASSERT(!IsLoaded()); // Call Clear() + + // Load file + FILE* f; + if ((f = fopen(filename, "rb")) == NULL) + return false; + if (fseek(f, 0, SEEK_END)) + { + fclose(f); + return false; + } + const long f_size = ftell(f); + if (f_size == -1) + { + fclose(f); + return false; + } + DataSize = (size_t)f_size; + if (fseek(f, 0, SEEK_SET)) + { + fclose(f); + return false; + } + if ((Data = (unsigned char*)ImGui::MemAlloc(DataSize)) == NULL) + { + fclose(f); + return false; + } + if (fread(Data, 1, DataSize, f) != DataSize) + { + fclose(f); + ImGui::MemFree(Data); + return false; + } + fclose(f); + DataOwned = true; + return LoadFromMemory(Data, DataSize); +} + +bool ImFont::LoadFromMemory(const void* data, size_t data_size) +{ + IM_ASSERT(!IsLoaded()); // Call Clear() + + Data = (unsigned char*)data; + DataSize = data_size; + + // Parse data + if (DataSize < 4 || Data[0] != 'B' || Data[1] != 'M' || Data[2] != 'F' || Data[3] != 0x03) + return false; + for (const unsigned char* p = Data+4; p < Data + DataSize; ) + { + const unsigned char block_type = *(unsigned char*)p; + p += sizeof(unsigned char); + ImU32 block_size; // use memcpy to read 4-byte because they may be unaligned. This seems to break when compiling for Emscripten. + memcpy(&block_size, p, sizeof(ImU32)); + p += sizeof(ImU32); + + switch (block_type) + { + case 1: + IM_ASSERT(Info == NULL); + Info = (FntInfo*)p; + break; + case 2: + IM_ASSERT(Common == NULL); + Common = (FntCommon*)p; + break; + case 3: + for (const unsigned char* s = p; s < p+block_size && s < Data+DataSize; s = s + strlen((const char*)s) + 1) + Filenames.push_back((const char*)s); + break; + case 4: + IM_ASSERT(Glyphs == NULL && GlyphsCount == 0); + Glyphs = (FntGlyph*)p; + GlyphsCount = block_size / sizeof(FntGlyph); + break; + case 5: + IM_ASSERT(Kerning == NULL && KerningCount == 0); + Kerning = (FntKerning*)p; + KerningCount = block_size / sizeof(FntKerning); + break; + default: + break; + } + p += block_size; + } + + BuildLookupTable(); + return true; +} + +void ImFont::BuildLookupTable() +{ + ImU32 max_c = 0; + for (size_t i = 0; i != GlyphsCount; i++) + if (max_c < Glyphs[i].Id) + max_c = Glyphs[i].Id; + + IndexLookup.clear(); + IndexLookup.resize(max_c + 1); + for (size_t i = 0; i < IndexLookup.size(); i++) + IndexLookup[i] = -1; + for (size_t i = 0; i < GlyphsCount; i++) + IndexLookup[Glyphs[i].Id] = (int)i; +} + +const ImFont::FntGlyph* ImFont::FindGlyph(unsigned short c) const +{ + if (c < (int)IndexLookup.size()) + { + const int i = IndexLookup[c]; + if (i >= 0 && i < (int)GlyphsCount) + return &Glyphs[i]; + } + return FallbackGlyph; +} + +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) +{ + if (*in_text != 0) + { + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + if (in_text_end && in_text_end - (const char*)str < 2) return -1; + if (*str < 0xc2) return -1; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return -1; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + if (in_text_end && in_text_end - (const char*)str < 3) return -1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return -1; + if (*str == 0xed && str[1] > 0x9f) return -1; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return -1; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return -1; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + if (in_text_end && in_text_end - (const char*)str < 4) return -1; + if (*str > 0xf4) return -1; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return -1; + if (*str == 0xf4 && str[1] > 0x8f) return -1; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return -1; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return -1; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return -1; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return -1; + *out_char = c; + return 4; + } + } + *out_char = 0; + return 0; +} + +static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + return buf_out - buf; +} + +static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int c) +{ + if (c) + { + size_t i = 0; + size_t n = buf_size; + if (c < 0x80) + { + if (i+1 > n) return 0; + buf[i++] = (char)c; + return 1; + } + else if (c < 0x800) + { + if (i+2 > n) return 0; + buf[i++] = (char)(0xc0 + (c >> 6)); + buf[i++] = (char)(0x80 + (c & 0x3f)); + return 2; + } + else if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + else if (c >= 0xd800 && c < 0xdc00) + { + if (i+4 > n) return 0; + buf[i++] = (char)(0xf0 + (c >> 18)); + buf[i++] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[i++] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[i++] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (i+3 > n) return 0; + buf[i++] = (char)(0xe0 + (c >> 12)); + buf[i++] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[i++] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } + } + return 0; +} + +static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + buf_out += ImTextCharToUtf8(buf_out, (uintptr_t)(buf_end-buf_out-1), (unsigned int)*in_text); + in_text++; + } + *buf_out = 0; + return buf_out - buf; +} + +static int ImTextCountUtf8BytesFromWchar(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + char dummy[5]; // FIXME-OPT + bytes_count += ImTextCharToUtf8(dummy, 5, (unsigned int)*in_text); + in_text++; + } + return bytes_count; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" + // --> + // "Hello" + // "world" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width + // --> + // "The tr" + // "opical" + // "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c; + const int bytes_count = ImTextCharFromUtf8(&c, s, text_end); + const char* next_s = s + (bytes_count > 0 ? bytes_count : 1); + + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + + float char_width = 0.0f; + if (c == '\t') + { + if (const FntGlyph* glyph = FindGlyph((unsigned short)' ')) + char_width = (glyph->XAdvance + Info->SpacingHoriz) * 4 * scale; + } + else + { + if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) + char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; + } + + if (c == ' ' || c == '\t') + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT + + const float scale = size / (float)Info->FontSize; + const float line_height = (float)Info->FontSize * scale; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (c == ' ' || c == '\t') { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) + unsigned int c; + const int bytes_count = ImTextCharFromUtf8(&c, s, text_end); + s += bytes_count > 0 ? bytes_count : 1; + + if (c == '\n') + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + continue; + } + + float char_width = 0.0f; + if (c == '\t') + { + // FIXME: Better TAB handling + if (const FntGlyph* glyph = FindGlyph((unsigned short)' ')) + char_width = (glyph->XAdvance + Info->SpacingHoriz) * 4 * scale; + } + else if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; + } + + if (line_width + char_width >= max_width) + break; + + line_width += char_width; + } + + if (line_width > 0 || text_size.y == 0.0f) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + } + + if (remaining) + *remaining = s; + + return text_size; +} + +ImVec2 ImFont::CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining) const +{ + if (!text_end) + text_end = text_begin + ImStrlenW(text_begin); + + const float scale = size / (float)Info->FontSize; + const float line_height = (float)Info->FontSize * scale; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + const unsigned int c = (unsigned int)(*s++); + + if (c == '\n') + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + continue; + } + + float char_width = 0.0f; + if (c == '\t') + { + // FIXME: Better TAB handling + if (const FntGlyph* glyph = FindGlyph((unsigned short)' ')) + char_width = (glyph->XAdvance + Info->SpacingHoriz) * 4 * scale; + } + else + { + if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) + char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; + } + + if (line_width + char_width >= max_width) + break; + + line_width += char_width; + } + + if (line_width > 0 || text_size.y == 0.0f) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + } + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect_ref, const char* text_begin, const char* text_end, ImDrawVert*& out_vertices, float wrap_width) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); + + const float line_height = (float)Info->FontSize; + const float scale = size / (float)Info->FontSize; + const float tex_scale_x = 1.0f / (float)Common->ScaleW; + const float tex_scale_y = 1.0f / (float)(Common->ScaleH); + const float outline = (float)Info->Outline; + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const ImVec4 clip_rect = clip_rect_ref; + float x = pos.x; + float y = pos.y; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height * scale; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (c == ' ' || c == '\t') { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) + unsigned int c; + const int bytes_count = ImTextCharFromUtf8(&c, s, text_end); + s += bytes_count > 0 ? bytes_count : 1; + + if (c == '\n') + { + x = pos.x; + y += line_height * scale; + continue; + } + + float char_width = 0.0f; + if (c == '\t') + { + // FIXME: Better TAB handling + if (const FntGlyph* glyph = FindGlyph((unsigned short)' ')) + char_width += (glyph->XAdvance + Info->SpacingHoriz) * 4 * scale; + } + else if (const FntGlyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = (glyph->XAdvance + Info->SpacingHoriz) * scale; + if (c != ' ') + { + // Clipping on Y is more likely + const float y1 = (float)(y + (glyph->YOffset + outline*2) * scale); + const float y2 = (float)(y1 + glyph->Height * scale); + if (y1 <= clip_rect.w && y2 >= clip_rect.y) + { + const float x1 = (float)(x + (glyph->XOffset + outline) * scale); + const float x2 = (float)(x1 + glyph->Width * scale); + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + const float s1 = (glyph->X) * tex_scale_x; + const float t1 = (glyph->Y) * tex_scale_y; + const float s2 = (glyph->X + glyph->Width) * tex_scale_x; + const float t2 = (glyph->Y + glyph->Height) * tex_scale_y; + + out_vertices[0].pos = ImVec2(x1, y1); + out_vertices[0].uv = ImVec2(s1, t1); + out_vertices[0].col = col; + + out_vertices[1].pos = ImVec2(x2, y1); + out_vertices[1].uv = ImVec2(s2, t1); + out_vertices[1].col = col; + + out_vertices[2].pos = ImVec2(x2, y2); + out_vertices[2].uv = ImVec2(s2, t2); + out_vertices[2].col = col; + + out_vertices[3] = out_vertices[0]; + out_vertices[4] = out_vertices[2]; + + out_vertices[5].pos = ImVec2(x1, y2); + out_vertices[5].uv = ImVec2(s1, t2); + out_vertices[5].col = col; + + out_vertices += 6; + } + } + } + } + + x += char_width; + } +} + +//----------------------------------------------------------------------------- +// PLATFORM DEPENDANT HELPERS +//----------------------------------------------------------------------------- + +#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) + +#define WIN32_LEAN_AND_MEAN +#include + +// Win32 API clipboard implementation +static const char* GetClipboardTextFn_DefaultImpl() +{ + static char* buf_local = NULL; + if (buf_local) + { + ImGui::MemFree(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 = ImStrdup(buf_global); + GlobalUnlock(buf_handle); + CloseClipboard(); + return buf_local; +} + +// Win32 API clipboard implementation +static void SetClipboardTextFn_DefaultImpl(const char* text) +{ + if (!OpenClipboard(NULL)) + return; + const char* text_end = text + strlen(text); + const int buf_length = (int)(text_end - text) + 1; + HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)buf_length * sizeof(char)); + if (buf_handle == NULL) + return; + char* buf_global = (char *)GlobalLock(buf_handle); + memcpy(buf_global, text, (size_t)(text_end - text)); + buf_global[text_end - text] = 0; + GlobalUnlock(buf_handle); + EmptyClipboard(); + SetClipboardData(CF_TEXT, buf_handle); + CloseClipboard(); +} + +#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) +{ + if (GImGui.PrivateClipboard) + { + ImGui::MemFree(GImGui.PrivateClipboard); + GImGui.PrivateClipboard = NULL; + } + const char* text_end = text + strlen(text); + GImGui.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); + memcpy(GImGui.PrivateClipboard, text, (size_t)(text_end - text)); + GImGui.PrivateClipboard[(size_t)(text_end - text)] = 0; +} + +#endif + +//----------------------------------------------------------------------------- +// HELP +//----------------------------------------------------------------------------- + +void ImGui::ShowUserGuide() +{ + ImGuiState& g = GImGui; + + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText("Click and drag on lower right corner to resize window."); + ImGui::BulletText("Click and drag on any empty space to move window."); + ImGui::BulletText("Mouse Wheel to scroll."); + if (g.IO.FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Click on a slider to input text."); + ImGui::BulletText( + "While editing text:\n" + "- Hold SHIFT or use mouse to select text\n" + "- CTRL+Left/Right to word jump\n" + "- CTRL+A select all\n" + "- CTRL+X,CTRL+C,CTRL+V clipboard\n" + "- CTRL+Z,CTRL+Y undo/redo\n" + "- ESCAPE to revert\n" + "- You can apply arithmetic operators +,*,/ on numerical values.\n" + " Use +- to subtract.\n"); +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + ImGuiState& g = GImGui; + ImGuiStyle& style = g.Style; + + const ImGuiStyle def; + + if (ImGui::Button("Revert Style")) + g.Style = ref ? *ref : def; + if (ref) + { + ImGui::SameLine(); + if (ImGui::Button("Save Style")) + *ref = g.Style; + } + + ImGui::PushItemWidth(ImGui::GetWindowWidth()*0.55f); + + if (ImGui::TreeNode("Sizes")) + { + ImGui::SliderFloat("Alpha", &style.Alpha, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI. But application code could have a toggle to switch between zero and non-zero. + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("TreeNodeSpacing", &style.TreeNodeSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ScrollBarWidth", &style.ScrollBarWidth, 0.0f, 20.0f, "%.0f"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colors")) + { + static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; + ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); + ImGui::SameLine(); + ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); + ImGui::SameLine(); + ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + + ImGui::BeginChild("#colors", ImVec2(0, 300), true); + + ImGui::ColorEditMode(edit_mode); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + 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]; + if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } + } + ImGui::PopID(); + } + ImGui::EndChild(); + + ImGui::TreePop(); + } + + /* + // Font scaling options + // Note that those are not actually part of the style. + if (ImGui::TreeNode("Font")) + { + static float window_scale = 1.0f; + ImGui::SliderFloat("window scale", &window_scale, 0.3f, 2.0f, "%.1f"); // scale only this window + ImGui::SliderFloat("font scale", &ImGui::GetIO().Font->Scale, 0.3f, 2.0f, "%.1f"); // scale only this font + ImGui::SliderFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::SetWindowFontScale(window_scale); + ImGui::TreePop(); + } + */ + + ImGui::PopItemWidth(); +} + +//----------------------------------------------------------------------------- +// SAMPLE CODE +//----------------------------------------------------------------------------- + +static void ShowExampleAppConsole(bool* open); +static void ShowExampleAppLongText(bool* open); +static void ShowExampleAppAutoResize(bool* open); + +// Demonstrate ImGui features (unfortunately this makes this function a little bloated!) +void ImGui::ShowTestWindow(bool* open) +{ + static bool no_titlebar = false; + static bool no_border = true; + static bool no_resize = false; + static bool no_move = false; + static bool no_scrollbar = false; + static float fill_alpha = 0.65f; + + const ImGuiWindowFlags layout_flags = (no_titlebar ? ImGuiWindowFlags_NoTitleBar : 0) | (no_border ? 0 : ImGuiWindowFlags_ShowBorders) | (no_resize ? ImGuiWindowFlags_NoResize : 0) | (no_move ? ImGuiWindowFlags_NoMove : 0) | (no_scrollbar ? ImGuiWindowFlags_NoScrollbar : 0); + ImGui::Begin("ImGui Test", open, ImVec2(550,680), fill_alpha, layout_flags); + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); + + ImGui::Text("ImGui says hello."); + //ImGui::Text("MousePos (%g, %g)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); + //ImGui::Text("MouseWheel %d", ImGui::GetIO().MouseWheel); + + ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); + ImGui::ShowUserGuide(); + } + + if (ImGui::CollapsingHeader("Window options")) + { + ImGui::Checkbox("no titlebar", &no_titlebar); ImGui::SameLine(150); + ImGui::Checkbox("no border", &no_border); ImGui::SameLine(300); + ImGui::Checkbox("no resize", &no_resize); + ImGui::Checkbox("no move", &no_move); ImGui::SameLine(150); + ImGui::Checkbox("no scrollbar", &no_scrollbar); + ImGui::SliderFloat("fill alpha", &fill_alpha, 0.0f, 1.0f); + + if (ImGui::TreeNode("Style Editor")) + { + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Logging")) + { + ImGui::LogButtons(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Widgets")) + { + static bool a=false; + if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } + if (a) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + if (ImGui::TreeNode("Tree")) + { + for (size_t i = 0; i < 5; i++) + { + if (ImGui::TreeNode((void*)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("print")) + printf("Child %d pressed", (int)i); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + ImGui::BulletText("Bullet point 3"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colored Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped("This is a long paragraph. The text should automatically wrap on the edge of the window. The current implementation follows simple rules that works for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImGui::Text("Test paragraph 1:"); + ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemBoxMin(), ImGui::GetItemBoxMax(), 0xFF00FFFF); + ImGui::PopTextWrapPos(); + + ImGui::Text("Test paragraph 2:"); + ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemBoxMin(), ImGui::GetItemBoxMax(), 0xFF00FFFF); + ImGui::PopTextWrapPos(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test (need a suitable font, try extra_fonts/mplus* files for example) + // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') + // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. + // In your own application please be reasonable and use UTF-8 in the source or get the data from external files! :) + ImGui::TextWrapped("(CJK text will only appears if the font supports it. Please check in the extra_fonts/ folder if you intend to use non-ASCII characters. Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters.)"); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + ImGui::Text("Hover me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + // Testing IMGUI_ONCE_UPON_A_FRAME macro + //for (int i = 0; i < 5; i++) + //{ + // IMGUI_ONCE_UPON_A_FRAME + // { + // ImGui::Text("This will be displayed only once."); + // } + //} + + ImGui::Separator(); + + static int item = 1; + ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; + static int item2 = -1; + 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, IM_ARRAYSIZE(str0)); + ImGui::InputInt("input int", &i0); + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + + //static float vec2a[3] = { 0.10f, 0.20f }; + //ImGui::InputFloat2("input float2", vec2a); + + static float vec3a[3] = { 0.10f, 0.20f, 0.30f }; + ImGui::InputFloat3("input float3", vec3a); + + //static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + //ImGui::InputFloat4("input float4", vec4a); + + static int i1=0; + static int i2=42; + ImGui::SliderInt("int 0..3", &i1, 0, 3); + ImGui::SliderInt("int -100..100", &i2, -100, 100); + + static float f1=1.123f; + static float f2=0; + static float f3=0; + static float f4=123456789.0f; + ImGui::SliderFloat("float", &f1, 0.0f, 2.0f); + ImGui::SliderFloat("log float", &f2, 0.0f, 10.0f, "%.4f", 2.0f); + ImGui::SliderFloat("signed log float", &f3, -10.0f, 10.0f, "%.4f", 3.0f); + ImGui::SliderFloat("unbound float", &f4, -FLT_MAX, FLT_MAX, "%.4f"); + static float angle = 0.0f; + ImGui::SliderAngle("angle", &angle); + + //static float vec2b[3] = { 0.10f, 0.20f }; + //ImGui::SliderFloat2("slider float2", vec2b, 0.0f, 1.0f); + + static float vec3b[3] = { 0.10f, 0.20f, 0.30f }; + ImGui::SliderFloat3("slider float3", vec3b, 0.0f, 1.0f); + + //static float vec4b[4] = { 0.10f, 0.20f, 0.30f, 0.40f }; + //ImGui::SliderFloat4("slider float4", vec4b, 0.0f, 1.0f); + + static float col1[3] = { 1.0f,0.0f,0.2f }; + static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::ColorEdit4("color 2", col2); + } + + 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, IM_ARRAYSIZE(arr)); + + static bool pause; + static ImVector values; if (values.empty()) { values.resize(100); memset(&values.front(), 0, values.size()*sizeof(float)); } + static size_t values_offset = 0; + if (!pause) + { + // create dummy data at fixed 60 hz rate + static float refresh_time = -1.0f; + if (ImGui::GetTime() > refresh_time + 1.0f/60.0f) + { + refresh_time = ImGui::GetTime(); + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset+1)%values.size(); + phase += 0.10f*values_offset; + } + } + ImGui::PlotLines("Frame Times", &values.front(), (int)values.size(), (int)values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,70)); + + ImGui::SameLine(); ImGui::Checkbox("pause", &pause); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,70)); + } + + if (ImGui::CollapsingHeader("Widgets on same line")) + { + // Text + ImGui::Text("Hello"); + ImGui::SameLine(); + ImGui::Text("World"); + + // Button + if (ImGui::Button("Banana")) printf("Pressed!\n"); + ImGui::SameLine(); + ImGui::Button("Apple"); + ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::SmallButton("Banana"); + ImGui::SameLine(); + ImGui::SmallButton("Apple"); + ImGui::SameLine(); + ImGui::SmallButton("Corniflower"); + ImGui::SameLine(); + ImGui::Text("Small buttons fit in a text block"); + + // Checkbox + static bool c1=false,c2=false,c3=false,c4=false; + ImGui::Checkbox("My", &c1); + ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); + ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); + ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // SliderFloat + static float f0=1.0f, f1=2.0f, f2=3.0f; + ImGui::PushItemWidth(80); + ImGui::SliderFloat("f0", &f0, 0.0f,5.0f); + ImGui::SameLine(); + ImGui::SliderFloat("f1", &f1, 0.0f,5.0f); + ImGui::SameLine(); + ImGui::SliderFloat("f2", &f2, 0.0f,5.0f); + + // InputText + static char s0[128] = "one", s1[128] = "two", s2[128] = "three"; + ImGui::InputText("s0", s0, 128); + ImGui::SameLine(); + ImGui::InputText("s1", s1, 128); + ImGui::SameLine(); + ImGui::InputText("s2", s2, 128); + + // LabelText + ImGui::LabelText("l0", "one"); + ImGui::SameLine(); + ImGui::LabelText("l0", "two"); + ImGui::SameLine(); + ImGui::LabelText("l0", "three"); + ImGui::PopItemWidth(); + } + + if (ImGui::CollapsingHeader("Child regions")) + { + ImGui::Text("Without border"); + static int line = 50; + bool goto_line = ImGui::Button("Goto"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowWidth()*0.5f,300)); + for (int i = 0; i < 100; i++) + { + ImGui::Text("%04d: scrollable region", i); + if (goto_line && line == i) + ImGui::SetScrollPosHere(); + } + if (goto_line && line >= 100) + ImGui::SetScrollPosHere(); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::BeginChild("Sub2", ImVec2(0,300), true); + ImGui::Text("With border"); + ImGui::Columns(2); + for (int i = 0; i < 100; i++) + { + char buf[32]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "%08x", i*5731); + ImGui::Button(buf); + ImGui::NextColumn(); + } + ImGui::EndChild(); + } + + if (ImGui::CollapsingHeader("Columns")) + { + ImGui::Columns(4, "data", true); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Flags"); ImGui::NextColumn(); + ImGui::Separator(); + + ImGui::Text("0000"); ImGui::NextColumn(); + ImGui::Text("Robert"); ImGui::NextColumn(); + ImGui::Text("/path/robert"); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + + ImGui::Text("0001"); ImGui::NextColumn(); + ImGui::Text("Stephanie"); ImGui::NextColumn(); + ImGui::Text("/path/stephanie"); ImGui::NextColumn(); + ImGui::Text("line 1"); ImGui::Text("line 2"); ImGui::NextColumn(); // two lines, two items + + ImGui::Text("0002"); ImGui::NextColumn(); + ImGui::Text("C64"); ImGui::NextColumn(); + ImGui::Text("/path/computer"); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + ImGui::Columns(1); + + ImGui::Separator(); + + ImGui::Columns(3, "mixed"); + + // Create multiple items in a same cell because switching to next column + static int e = 0; + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::RadioButton("radio a", &e, 0); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + ImGui::RadioButton("radio b", &e, 1); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("World!"); + ImGui::Button("Corniflower"); + ImGui::RadioButton("radio c", &e, 2); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + + ImGui::Columns(1); + + ImGui::Separator(); + + ImGui::Columns(2, "multiple components"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, 3); ImGui::NextColumn(); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); ImGui::NextColumn(); + ImGui::Columns(1); + + ImGui::Separator(); + + ImGui::Columns(2, "word wrapping"); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::Text("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::Text("Hello Right"); + ImGui::Columns(1); + + ImGui::Separator(); + + if (ImGui::TreeNode("Inside a tree..")) + { + if (ImGui::TreeNode("node 1 (with borders)")) + { + ImGui::Columns(4); + ImGui::Text("aaa"); ImGui::NextColumn(); + ImGui::Text("bbb"); ImGui::NextColumn(); + ImGui::Text("ccc"); ImGui::NextColumn(); + ImGui::Text("ddd"); ImGui::NextColumn(); + ImGui::Text("eee"); ImGui::NextColumn(); + ImGui::Text("fff"); ImGui::NextColumn(); + ImGui::Text("ggg"); ImGui::NextColumn(); + ImGui::Text("hhh"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::TreePop(); + } + if (ImGui::TreeNode("node 2 (without borders)")) + { + ImGui::Columns(4, NULL, false); + ImGui::Text("aaa"); ImGui::NextColumn(); + ImGui::Text("bbb"); ImGui::NextColumn(); + ImGui::Text("ccc"); ImGui::NextColumn(); + ImGui::Text("ddd"); ImGui::NextColumn(); + ImGui::Text("eee"); ImGui::NextColumn(); + ImGui::Text("fff"); ImGui::NextColumn(); + ImGui::Text("ggg"); ImGui::NextColumn(); + ImGui::Text("hhh"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Filtering")) + { + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + 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 < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + if (ImGui::CollapsingHeader("Keyboard & Focus")) + { + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle thru keyboard editable fields."); + static char buf[32] = "dummy"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + //ImGui::SameLine(); ImGui::Text("(?)"); if (ImGui::IsHovered()) ImGui::SetTooltip("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemFocused()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemFocused()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemFocused()) has_focus = 3; + ImGui::PopAllowKeyboardFocus(); + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + ImGui::TreePop(); + } + } + + static bool show_app_console = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + if (ImGui::CollapsingHeader("App Examples")) + { + ImGui::Checkbox("Console", &show_app_console); + ImGui::Checkbox("Long text display", &show_app_long_text); + ImGui::Checkbox("Auto-resizing window", &show_app_auto_resize); + } + if (show_app_console) + ShowExampleAppConsole(&show_app_console); + if (show_app_long_text) + ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) + ShowExampleAppAutoResize(&show_app_auto_resize); + + ImGui::End(); +} + +static void ShowExampleAppAutoResize(bool* open) +{ + if (!ImGui::Begin("Example: Auto-Resizing Window", open, ImVec2(0,0), -1.0f, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + static int lines = 10; + ImGui::TextWrapped("Window will resize every-frame to the size of its content. Note that you don't want to query the window size to output your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally + + ImGui::End(); +} + +struct ExampleAppConsole +{ + ImVector Items; + bool NewItems; + + void Clear() + { + for (size_t i = 0; i < Items.size(); i++) + ImGui::MemFree(Items[i]); + Items.clear(); + NewItems = true; + } + + void AddLog(const char* fmt, ...) + { + char buf[512]; + va_list args; + va_start(args, fmt); + ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); + va_end(args); + Items.push_back(ImStrdup(buf)); + NewItems = true; + } + + void TextEditCallback(ImGuiTextEditCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventKey) + { + case ImGuiKey_Tab: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + const char* commands[] = { "HELP", "CLEAR", "CLASSIFY" }; + ImVector candidates; + for (size_t i = 0; i < IM_ARRAYSIZE(commands); i++) + if (ImStrnicmp(commands[i], word_start, word_end-word_start) == 0) + candidates.push_back(commands[i]); + + if (candidates.size() == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", word_end-word_start, word_start); + } + else if (candidates.size() == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + data->DeleteChars(word_start-data->Buf, word_end-word_start); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + int match_len = word_end - word_start; + while (true) + { + int c = 0; + bool all_candidates_matches = true; + for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) + { + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + } + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars(word_start - data->Buf, word_end-word_start); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (size_t i = 0; i < candidates.size(); i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + } + } +}; + +static void ShowExampleAppConsole_TextEditCallback(ImGuiTextEditCallbackData* data) +{ + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + console->TextEditCallback(data); +} + +static void ShowExampleAppConsole(bool* open) +{ + if (!ImGui::Begin("Example: Console", open, ImVec2(520,600))) + { + ImGui::End(); + return; + } + + ImGui::TextWrapped("This example implement a simple console. A more elaborate implementation may want to store individual entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Press TAB to use text completion."); + + // TODO: display from bottom + // TODO: clip manually + // TODO: history + + static ExampleAppConsole console; + static char input[256] = ""; + + if (ImGui::SmallButton("Add Dummy Text")) console.AddLog("some text\nsome more text"); + ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Error")) console.AddLog("[error] something went wrong"); + ImGui::SameLine(); + if (ImGui::SmallButton("Clear all")) console.Clear(); + ImGui::Separator(); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + static ImGuiTextFilter filter; + filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + if (ImGui::IsItemHovered()) ImGui::SetKeyboardFocusHere(-1); // Auto focus on hover + ImGui::PopStyleVar(); + ImGui::Separator(); + + ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetTextLineSpacing()*2)); + + // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have lots of text this approach may be too inefficient. You can seek and display only the lines that are on display using a technique similar to what TextUnformatted() does, + // or faster if your entries are already stored into a table. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // tighten spacing + ImGui::GetStyle().ItemSpacing.y = 1; // tighten spacing + for (size_t i = 0; i < console.Items.size(); i++) + { + const char* item = console.Items[i]; + if (!filter.PassFilter(item)) + continue; + ImVec4 col(1,1,1,1); + if (strstr(item, "[error]")) col = ImVec4(1.0f,0.4f,0.4f,1.0f); + else if (strncmp(item, "# ", 2) == 0) col = ImVec4(1.0f,0.8f,0.6f,1.0f); + ImGui::PushStyleColor(ImGuiCol_Text, col); + ImGui::TextUnformatted(item); + ImGui::PopStyleColor(); + } + ImGui::PopStyleVar(); + if (console.NewItems) + { + ImGui::SetScrollPosHere(); + console.NewItems = false; + } + ImGui::EndChild(); + + ImGui::Separator(); + if (ImGui::InputText("Input", input, IM_ARRAYSIZE(input), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion, &ShowExampleAppConsole_TextEditCallback, (void*)&console)) + { + const char* input_trimmed_end = input+strlen(input); + while (input_trimmed_end > input && input_trimmed_end[-1] == ' ') + input_trimmed_end--; + if (input_trimmed_end > input) + { + console.AddLog("# %s\n", input); + console.AddLog("Unknown command: '%.*s'\n", input_trimmed_end-input, input); // NB: we don't actually handle any command in this sample code + } + strcpy(input, ""); + } + if (ImGui::IsItemHovered()) ImGui::SetKeyboardFocusHere(-1); // Auto focus on hover + + ImGui::End(); +} + +static void ShowExampleAppLongText(bool* open) +{ + if (!ImGui::Begin("Example: Long text display", open, ImVec2(520,600))) + { + ImGui::End(); + return; + } + + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + lines += 1000; + } + ImGui::BeginChild("Log"); + ImGui::TextUnformatted(log.begin(), log.end()); + ImGui::EndChild(); + + ImGui::End(); +} + +// End of Sample code + +//----------------------------------------------------------------------------- +// Font data +// Bitmap exported from proggy_clean.fon (c) by Tristan Grimmer http://upperbounds.net/ +// Also available on unofficial ProggyFonts mirror http://www.proggyfonts.net +//----------------------------------------------------------------------------- +/* +// Copyright (c) 2004, 2005 Tristan Grimmer + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +*/ +//----------------------------------------------------------------------------- +// Fonts exported with BMFont http://www.angelcode.com/products/bmfont +// We are using bmfont format and you can load your own font from a file by setting up ImGui::GetIO().Font +// PNG further compressed with pngout.exe http://advsys.net/ken/utils.htm +// Manually converted to C++ array using the following program: +/* +static void binary_to_c(const char* name_in, const char* symbol) +{ + FILE* fi = fopen(name_in, "rb"); fseek(fi, 0, SEEK_END); long sz = ftell(fi); fseek(fi, 0, SEEK_SET); + fprintf(stdout, "static const unsigned int %s_size = %d;\n", symbol, sz); + fprintf(stdout, "static const unsigned int %s_data[%d/4] =\n{", symbol, ((sz+3)/4)*4); + int column = 0; + for (unsigned int data = 0; fread(&data, 1, 4, fi); data = 0) + if ((column++ % 12) == 0) + fprintf(stdout, "\n 0x%08x, ", data); + else + fprintf(stdout, "0x%08x, ", data); + fprintf(stdout, "\n};\n\n"); + fclose(fi); +} + +int main(int argc, char** argv) +{ + binary_to_c("proggy_clean_13.fnt", "proggy_clean_13_fnt"); + binary_to_c("proggy_clean_13.png", "proggy_clean_13_png"); + return 1; +} +*/ +//----------------------------------------------------------------------------- + +static const unsigned int proggy_clean_13_png_size = 1557; +static const unsigned int proggy_clean_13_png_data[1560/4] = +{ + 0x474e5089, 0x0a1a0a0d, 0x0d000000, 0x52444849, 0x00010000, 0x80000000, 0x00000308, 0x476bd300, 0x00000038, 0x544c5006, 0x00000045, 0xa5ffffff, + 0x00dd9fd9, 0x74010000, 0x00534e52, 0x66d8e640, 0xbd050000, 0x54414449, 0x9bed5e78, 0x30e36e51, 0xeef5440c, 0x31fde97f, 0x584ec0f0, 0x681ace39, + 0xca120e6b, 0x1c5a28a6, 0xc5d98a89, 0x1a3d602e, 0x323c0043, 0xf6bc9e68, 0xbe3ad62c, 0x3d60260f, 0x82d60096, 0xe0bfc707, 0xfb9bf1d1, 0xbf0267ac, + 0x1600260f, 0x061229c0, 0x0000c183, 0x37162c58, 0xdfa088fc, 0xde7d5704, 0x77fcbb80, 0x48e5c3f1, 0x73d8b8f8, 0xc4af7802, 0x1ca111ad, 0x0001ed7a, + 0x76eda3ef, 0xb78d3e00, 0x801c7203, 0x0215c0b1, 0x0410b044, 0xa85100d4, 0x07627ec7, 0x0cf83fa8, 0x94001a22, 0xf87347f1, 0xdcb5cfc1, 0x1c3880cc, + 0xd4e034ca, 0xfa928d9d, 0xb0167e31, 0x325cc570, 0x4bbd584b, 0xbd4e6574, 0x70bae084, 0xf0c0008a, 0x3f601ddb, 0x0bba506a, 0xa58a0082, 0x5b46946e, + 0x720a4ccd, 0xdfaaed39, 0x25dc8042, 0x7ee403f4, 0x2ad69cc9, 0x6c4b3009, 0x429037ed, 0x0293f875, 0x1a69dced, 0xab120198, 0x61c01d88, 0xcf2e43dc, + 0xfc3c00ef, 0xc049a270, 0xdbbea582, 0x0d592601, 0xc3c9a8dd, 0x5013d143, 0x19a47bbb, 0xf89253dd, 0x0a9901dc, 0x38900ecd, 0xb2dec9d7, 0xc2b91230, + 0xb8e0106f, 0x976404cb, 0x5d83c3f3, 0x6e8086fd, 0x5c9ab007, 0xf50354f6, 0xe7e72002, 0x4bc870ca, 0xab49736f, 0xc137c6e0, 0xa9aa6ff3, 0xbff84f2f, + 0x673e6e20, 0xf6e3c7e0, 0x618fe05a, 0x39ca2a00, 0x93ca03b4, 0x3a9d2728, 0xbbebba41, 0xce0e3681, 0x6e29ec05, 0x111eca83, 0xfdfe7ec1, 0xa7c8a75b, + 0xac6bc3ab, 0x72a5bc25, 0x9f612c1c, 0x378ec05e, 0x7202b157, 0x789e5a82, 0x5256bc0e, 0xcb900996, 0x10721105, 0x00823ce0, 0x69ab59fb, 0x39c72084, + 0xf5e37b25, 0xd1794700, 0x538d0637, 0x9a2bff4f, 0xce0d43a4, 0xa6da7ed2, 0xd7095132, 0xf5ad6232, 0x9aaa8e9c, 0xd8d1d3ed, 0x058940a1, 0x21f00d64, + 0x89a5c9de, 0x021b3f24, 0x77a97aac, 0x714be65a, 0x5e2d57ae, 0x27e3610f, 0x28809288, 0x36b9559f, 0xd00e347a, 0x0094e385, 0x565d034d, 0x7f52d5f2, + 0x9aea81de, 0x5e804909, 0x010d7f0a, 0x8f0d3fb1, 0xbbce23bc, 0x375e85ac, 0x01fa03b9, 0xc0526c3a, 0xf7866870, 0x9d46d804, 0x158ebf64, 0x7bd534c5, + 0xd80cf202, 0x410ee80f, 0x79419915, 0x74a844ae, 0x94119881, 0xcbbcc0fc, 0xa263d471, 0x013d0269, 0x67f6a0f8, 0x3e4474d0, 0xd1e50cb5, 0x56fd0e60, + 0xc4c0fd4c, 0x940629ff, 0xe18a7a16, 0xcca0330f, 0xb8ed50b7, 0x6935778b, 0x3735c791, 0x3909eb94, 0x0be36620, 0x0ac0d7aa, 0xefe942c9, 0xf0092727, + 0x5c020ee2, 0x0246da53, 0xa24be8bc, 0xa891ab94, 0xd012c7e2, 0x9c115954, 0xde0dac8e, 0x555dc022, 0x59e84f77, 0xbed2cf80, 0xe9af2cda, 0x4b600716, + 0x8955bd80, 0x7098c3f3, 0x25a8466a, 0x4ddbf26a, 0x5f554753, 0xf4890f28, 0x886a27ab, 0x54a00413, 0x0a157ca9, 0x52909a80, 0x7122a312, 0x0024a75c, + 0xe6d72935, 0xecde29cf, 0x025de009, 0x7995a6aa, 0x4a180491, 0x013df0d8, 0xe009edba, 0xd40019dc, 0x45b36b2a, 0x0122eb0d, 0x6e80a79f, 0x746590f5, + 0xd1a6dd49, 0xc05954b6, 0x83d4b957, 0xa00fe5b1, 0x59695ad7, 0xcff8433d, 0x44a0f340, 0xdd226c73, 0x5537f08c, 0xe1e89c32, 0x431056af, 0x233eb000, + 0x60773f40, 0xed7e490a, 0xc160091f, 0x12829db5, 0x43fbe6cf, 0x0a6b26c2, 0xd5f0f35a, 0xfc09fda8, 0x73525f8c, 0x2ea38cf9, 0x32bc410b, 0x94a60a22, + 0x1f62a42b, 0x5f290034, 0x07beaa91, 0x1e8ccb40, 0x17d6b0f9, 0xa2a017c9, 0x4c79a610, 0xa1de6525, 0xe975029f, 0xe063585f, 0x6246cfbb, 0x04acad44, + 0xe6a05138, 0xd03d8434, 0xc9950013, 0x5d4c809e, 0xfd26932d, 0x739213ac, 0xe260d8ef, 0xe4164617, 0x16fc60aa, 0x1d0b21e7, 0x445004b4, 0x13fd1b59, + 0x56b0f804, 0xaa936a3a, 0x335459c1, 0xb37f8caa, 0x06b68e03, 0x14d5eb01, 0x8300c78c, 0x9674792a, 0x20ba791b, 0x4d88024d, 0xef747354, 0x451e673e, + 0xc4dafc9a, 0xe53b9cd1, 0x32b4011a, 0x3d702c0f, 0x09bc0b40, 0x220d277d, 0x47eb7809, 0x8a946500, 0x7a28c4bd, 0x96e00f99, 0xc04365da, 0x05edcf46, + 0x7dee2c27, 0xe6020b7f, 0x159ecedf, 0xcbdb00ff, 0x516bb9e3, 0xd0716161, 0xeba75956, 0xf17fc22b, 0x5c578beb, 0xfe474a09, 0xc1750a87, 0xe384c189, + 0x5df54e26, 0xa6f76b79, 0xd4b172be, 0x3e8d5ceb, 0x832d90ec, 0x180368e7, 0x354c724d, 0x1a8b1412, 0x8de07be9, 0xaf009efe, 0x4616c621, 0x2860eb01, + 0x244f1404, 0xc3de724b, 0x6497a802, 0xab2f4419, 0x4e02910d, 0xe3ecf410, 0x7a6404a8, 0x8c72b112, 0xde5bc706, 0xd4f8ffe9, 0x50176344, 0x7b49fe7d, + 0x02c1d88c, 0x25634a40, 0x194804f7, 0x03b76d84, 0x392bde58, 0xdeebad27, 0xc160c021, 0xa97a72db, 0xa8040b83, 0x78804f3e, 0x046b9433, 0x178cc824, + 0x62800897, 0x7010370b, 0x21cfe7e4, 0x8053ec40, 0xf9d60526, 0xae9d353f, 0x069b40c7, 0x80496f14, 0x57e682b3, 0x6e0273e0, 0x974e2e28, 0x60ab7c3d, + 0x2025ba33, 0x507b3a8c, 0x12b70173, 0xd095c400, 0xee012d96, 0x6e194c9a, 0xe5933f89, 0x43b70102, 0xf30306aa, 0xc5802189, 0x53c077c3, 0x86029009, + 0xa0c1e780, 0xa4c04c1f, 0x93dbd580, 0xf8149809, 0x06021893, 0x3060c183, 0x83060c18, 0x183060c1, 0xc183060c, 0x0c183060, 0x60c18306, 0xfe0c1830, + 0x0cb69501, 0x7a40d9df, 0x000000dd, 0x4e454900, 0x6042ae44, 0x00000082, +}; + +static const unsigned int proggy_clean_13_fnt_size = 4647; +static const unsigned int proggy_clean_13_fnt_data[4648/4] = +{ + 0x03464d42, 0x00001a01, 0x40000d00, 0x01006400, 0x00000000, 0x50000101, 0x67676f72, 0x656c4379, 0x02006e61, 0x0000000f, 0x000a000d, 0x00800100, + 0x01000001, 0x03000000, 0x00000016, 0x676f7270, 0x635f7967, 0x6e61656c, 0x5f33315f, 0x6e702e30, 0xd0040067, 0x00000011, 0x2e000000, 0x07000e00, + 0x00000d00, 0x07000000, 0x010f0000, 0x36000000, 0x05003800, 0x01000d00, 0x07000000, 0x020f0000, 0x86000000, 0x07000e00, 0x00000d00, 0x07000000, + 0x030f0000, 0x07000000, 0x06001c00, 0x01000d00, 0x07000000, 0x040f0000, 0x15000000, 0x06001c00, 0x01000d00, 0x07000000, 0x050f0000, 0x23000000, + 0x06001c00, 0x01000d00, 0x07000000, 0x060f0000, 0x31000000, 0x06001c00, 0x01000d00, 0x07000000, 0x070f0000, 0xfc000000, 0x03003800, 0x02000d00, + 0x07000000, 0x080f0000, 0x54000000, 0x05003800, 0x01000d00, 0x07000000, 0x090f0000, 0x4d000000, 0x06001c00, 0x01000d00, 0x07000000, 0x0a0f0000, + 0xa8000000, 0x06001c00, 0x01000d00, 0x07000000, 0x0b0f0000, 0x6a000000, 0x04004600, 0x00000d00, 0x07000000, 0x0c0f0000, 0x74000000, 0x04004600, + 0x00000d00, 0x07000000, 0x0d0f0000, 0x88000000, 0x04004600, 0x03000d00, 0x07000000, 0x0e0f0000, 0x65000000, 0x04004600, 0x03000d00, 0x07000000, + 0x0f0f0000, 0x36000000, 0x07000e00, 0x00000d00, 0x07000000, 0x100f0000, 0x5a000000, 0x05003800, 0x00000d00, 0x07000000, 0x110f0000, 0x60000000, + 0x05003800, 0x00000d00, 0x07000000, 0x120f0000, 0xe4000000, 0x03004600, 0x01000d00, 0x07000000, 0x130f0000, 0xe0000000, 0x03004600, 0x01000d00, + 0x07000000, 0x140f0000, 0x66000000, 0x05003800, 0x00000d00, 0x07000000, 0x150f0000, 0x6c000000, 0x05003800, 0x00000d00, 0x07000000, 0x160f0000, + 0x72000000, 0x05003800, 0x00000d00, 0x07000000, 0x170f0000, 0xd8000000, 0x03004600, 0x00000d00, 0x07000000, 0x180f0000, 0xcc000000, 0x03004600, + 0x01000d00, 0x07000000, 0x190f0000, 0xc8000000, 0x03004600, 0x02000d00, 0x07000000, 0x1a0f0000, 0x78000000, 0x05003800, 0x00000d00, 0x07000000, + 0x1b0f0000, 0x84000000, 0x05003800, 0x00000d00, 0x07000000, 0x1c0f0000, 0x00000000, 0x15000000, 0xf9000d00, 0x070000ff, 0x1d0f0000, 0xb0000000, + 0x15000000, 0xf9000d00, 0x070000ff, 0x1e0f0000, 0x2c000000, 0x15000000, 0xf9000d00, 0x070000ff, 0x200f0000, 0x9a000000, 0x15000000, 0xf9000d00, + 0x070000ff, 0x210f0000, 0x0c000000, 0x01005400, 0x03000d00, 0x07000000, 0x220f0000, 0xbc000000, 0x03004600, 0x02000d00, 0x07000000, 0x230f0000, + 0x4e000000, 0x07000e00, 0x00000d00, 0x07000000, 0x240f0000, 0x8a000000, 0x05003800, 0x01000d00, 0x07000000, 0x250f0000, 0xa6000000, 0x07000e00, + 0x00000d00, 0x07000000, 0x260f0000, 0xf4000000, 0x06000e00, 0x01000d00, 0x07000000, 0x270f0000, 0x06000000, 0x01005400, 0x03000d00, 0x07000000, + 0x280f0000, 0xb8000000, 0x03004600, 0x02000d00, 0x07000000, 0x290f0000, 0xb4000000, 0x03004600, 0x02000d00, 0x07000000, 0x2a0f0000, 0x90000000, + 0x05003800, 0x01000d00, 0x07000000, 0x2b0f0000, 0x96000000, 0x05003800, 0x01000d00, 0x07000000, 0x2c0f0000, 0xe8000000, 0x02004600, 0x01000d00, + 0x07000000, 0x2d0f0000, 0x9c000000, 0x05003800, 0x01000d00, 0x07000000, 0x2e0f0000, 0x04000000, 0x01005400, 0x02000d00, 0x07000000, 0x2f0f0000, + 0xa2000000, 0x05003800, 0x01000d00, 0x07000000, 0x300f0000, 0xae000000, 0x05003800, 0x01000d00, 0x07000000, 0x310f0000, 0xd8000000, 0x05003800, + 0x01000d00, 0x07000000, 0x320f0000, 0xfa000000, 0x05000000, 0x01000d00, 0x07000000, 0x330f0000, 0x31000000, 0x05002a00, 0x01000d00, 0x07000000, + 0x340f0000, 0x3f000000, 0x06001c00, 0x01000d00, 0x07000000, 0x350f0000, 0x37000000, 0x05002a00, 0x01000d00, 0x07000000, 0x360f0000, 0x3d000000, + 0x05002a00, 0x01000d00, 0x07000000, 0x370f0000, 0x43000000, 0x05002a00, 0x01000d00, 0x07000000, 0x380f0000, 0x49000000, 0x05002a00, 0x01000d00, + 0x07000000, 0x390f0000, 0x4f000000, 0x05002a00, 0x01000d00, 0x07000000, 0x3a0f0000, 0x02000000, 0x01005400, 0x03000d00, 0x07000000, 0x3b0f0000, + 0xfa000000, 0x02004600, 0x01000d00, 0x07000000, 0x3c0f0000, 0x77000000, 0x06001c00, 0x00000d00, 0x07000000, 0x3d0f0000, 0x7e000000, 0x06001c00, + 0x01000d00, 0x07000000, 0x3e0f0000, 0x85000000, 0x06001c00, 0x01000d00, 0x07000000, 0x3f0f0000, 0x55000000, 0x05002a00, 0x01000d00, 0x07000000, + 0x400f0000, 0xae000000, 0x07000e00, 0x00000d00, 0x07000000, 0x410f0000, 0xe0000000, 0x06001c00, 0x01000d00, 0x07000000, 0x420f0000, 0xa1000000, + 0x06001c00, 0x01000d00, 0x07000000, 0x430f0000, 0x5b000000, 0x05002a00, 0x01000d00, 0x07000000, 0x440f0000, 0xaf000000, 0x06001c00, 0x01000d00, + 0x07000000, 0x450f0000, 0x61000000, 0x05002a00, 0x01000d00, 0x07000000, 0x460f0000, 0x67000000, 0x05002a00, 0x01000d00, 0x07000000, 0x470f0000, + 0x38000000, 0x06001c00, 0x01000d00, 0x07000000, 0x480f0000, 0x8c000000, 0x06001c00, 0x01000d00, 0x07000000, 0x490f0000, 0xa0000000, 0x03004600, + 0x02000d00, 0x07000000, 0x4a0f0000, 0x97000000, 0x04004600, 0x01000d00, 0x07000000, 0x4b0f0000, 0xb6000000, 0x06001c00, 0x01000d00, 0x07000000, + 0x4c0f0000, 0x6d000000, 0x05002a00, 0x01000d00, 0x07000000, 0x4d0f0000, 0x1e000000, 0x07000e00, 0x00000d00, 0x07000000, 0x4e0f0000, 0x23000000, + 0x06002a00, 0x01000d00, 0x07000000, 0x4f0f0000, 0xed000000, 0x06000e00, 0x01000d00, 0x07000000, 0x500f0000, 0x73000000, 0x05002a00, 0x01000d00, + 0x07000000, 0x510f0000, 0x00000000, 0x06001c00, 0x01000d00, 0x07000000, 0x520f0000, 0x0e000000, 0x06001c00, 0x01000d00, 0x07000000, 0x530f0000, + 0x1c000000, 0x06001c00, 0x01000d00, 0x07000000, 0x540f0000, 0x66000000, 0x07000e00, 0x00000d00, 0x07000000, 0x550f0000, 0x2a000000, 0x06001c00, + 0x01000d00, 0x07000000, 0x560f0000, 0x6e000000, 0x07000e00, 0x00000d00, 0x07000000, 0x570f0000, 0x76000000, 0x07000e00, 0x00000d00, 0x07000000, + 0x580f0000, 0x46000000, 0x06001c00, 0x01000d00, 0x07000000, 0x590f0000, 0x7e000000, 0x07000e00, 0x00000d00, 0x07000000, 0x5a0f0000, 0x54000000, + 0x06001c00, 0x01000d00, 0x07000000, 0x5b0f0000, 0x9c000000, 0x03004600, 0x02000d00, 0x07000000, 0x5c0f0000, 0x79000000, 0x05002a00, 0x01000d00, + 0x07000000, 0x5d0f0000, 0xdc000000, 0x03004600, 0x02000d00, 0x07000000, 0x5e0f0000, 0x7f000000, 0x05002a00, 0x01000d00, 0x07000000, 0x5f0f0000, + 0xc6000000, 0x07000e00, 0x00000d00, 0x07000000, 0x600f0000, 0xfd000000, 0x02004600, 0x02000d00, 0x07000000, 0x610f0000, 0x85000000, 0x05002a00, + 0x01000d00, 0x07000000, 0x620f0000, 0x8b000000, 0x05002a00, 0x01000d00, 0x07000000, 0x630f0000, 0x91000000, 0x05002a00, 0x01000d00, 0x07000000, + 0x640f0000, 0x97000000, 0x05002a00, 0x01000d00, 0x07000000, 0x650f0000, 0x9d000000, 0x05002a00, 0x01000d00, 0x07000000, 0x660f0000, 0xa3000000, + 0x05002a00, 0x01000d00, 0x07000000, 0x670f0000, 0xa9000000, 0x05002a00, 0x01000d00, 0x07000000, 0x680f0000, 0xaf000000, 0x05002a00, 0x01000d00, + 0x07000000, 0x690f0000, 0xee000000, 0x02004600, 0x02000d00, 0x07000000, 0x6a0f0000, 0x92000000, 0x04004600, 0x01000d00, 0x07000000, 0x6b0f0000, + 0xb5000000, 0x05002a00, 0x01000d00, 0x07000000, 0x6c0f0000, 0xfd000000, 0x02002a00, 0x02000d00, 0x07000000, 0x6d0f0000, 0x8e000000, 0x07000e00, + 0x00000d00, 0x07000000, 0x6e0f0000, 0xbb000000, 0x05002a00, 0x01000d00, 0x07000000, 0x6f0f0000, 0xc1000000, 0x05002a00, 0x01000d00, 0x07000000, + 0x700f0000, 0xc7000000, 0x05002a00, 0x01000d00, 0x07000000, 0x710f0000, 0xcd000000, 0x05002a00, 0x01000d00, 0x07000000, 0x720f0000, 0xd3000000, + 0x05002a00, 0x01000d00, 0x07000000, 0x730f0000, 0xd9000000, 0x05002a00, 0x01000d00, 0x07000000, 0x740f0000, 0x7e000000, 0x04004600, 0x02000d00, + 0x07000000, 0x750f0000, 0xdf000000, 0x05002a00, 0x01000d00, 0x07000000, 0x760f0000, 0xe5000000, 0x05002a00, 0x01000d00, 0x07000000, 0x770f0000, + 0xbe000000, 0x07000e00, 0x00000d00, 0x07000000, 0x780f0000, 0xeb000000, 0x05002a00, 0x01000d00, 0x07000000, 0x790f0000, 0xf1000000, 0x05002a00, + 0x01000d00, 0x07000000, 0x7a0f0000, 0xf7000000, 0x05002a00, 0x01000d00, 0x07000000, 0x7b0f0000, 0x00000000, 0x05003800, 0x01000d00, 0x07000000, + 0x7c0f0000, 0x00000000, 0x01005400, 0x03000d00, 0x07000000, 0x7d0f0000, 0x06000000, 0x05003800, 0x01000d00, 0x07000000, 0x7e0f0000, 0x16000000, + 0x07000e00, 0x00000d00, 0x07000000, 0x7f0f0000, 0x58000000, 0x15000000, 0xf9000d00, 0x070000ff, 0x810f0000, 0x16000000, 0x15000000, 0xf9000d00, + 0x070000ff, 0x8d0f0000, 0x00000000, 0x15000e00, 0xf9000d00, 0x070000ff, 0x8f0f0000, 0xc6000000, 0x15000000, 0xf9000d00, 0x070000ff, 0x900f0000, + 0x6e000000, 0x15000000, 0xf9000d00, 0x070000ff, 0x9d0f0000, 0x84000000, 0x15000000, 0xf9000d00, 0x070000ff, 0xa00f0000, 0xdc000000, 0x15000000, + 0xf9000d00, 0x070000ff, 0xa10f0000, 0x0a000000, 0x01005400, 0x03000d00, 0x07000000, 0xa20f0000, 0x0c000000, 0x05003800, 0x01000d00, 0x07000000, + 0xa30f0000, 0x12000000, 0x05003800, 0x01000d00, 0x07000000, 0xa40f0000, 0x96000000, 0x07000e00, 0x00000d00, 0x07000000, 0xa50f0000, 0x5e000000, + 0x07000e00, 0x00000d00, 0x07000000, 0xa60f0000, 0x08000000, 0x01005400, 0x03000d00, 0x07000000, 0xa70f0000, 0x18000000, 0x05003800, 0x01000d00, + 0x07000000, 0xa80f0000, 0xac000000, 0x03004600, 0x02000d00, 0x07000000, 0xa90f0000, 0x56000000, 0x07000e00, 0x00000d00, 0x07000000, 0xaa0f0000, + 0x8d000000, 0x04004600, 0x01000d00, 0x07000000, 0xab0f0000, 0x1e000000, 0x05003800, 0x01000d00, 0x07000000, 0xac0f0000, 0xfb000000, 0x04000e00, + 0x01000d00, 0x07000000, 0xad0f0000, 0x42000000, 0x15000000, 0xf9000d00, 0x070000ff, 0xae0f0000, 0x3e000000, 0x07000e00, 0x00000d00, 0x07000000, + 0xaf0f0000, 0x26000000, 0x07000e00, 0x00000d00, 0x07000000, 0xb00f0000, 0x6f000000, 0x04004600, 0x01000d00, 0x07000000, 0xb10f0000, 0x24000000, + 0x05003800, 0x01000d00, 0x07000000, 0xb20f0000, 0x79000000, 0x04004600, 0x01000d00, 0x07000000, 0xb30f0000, 0x83000000, 0x04004600, 0x01000d00, + 0x07000000, 0xb40f0000, 0xeb000000, 0x02004600, 0x03000d00, 0x07000000, 0xb50f0000, 0x46000000, 0x07000e00, 0x00000d00, 0x07000000, 0xb60f0000, + 0xe6000000, 0x06000e00, 0x01000d00, 0x07000000, 0xb70f0000, 0xc0000000, 0x03004600, 0x02000d00, 0x07000000, 0xb80f0000, 0xf7000000, 0x02004600, + 0x03000d00, 0x07000000, 0xb90f0000, 0xc4000000, 0x03004600, 0x01000d00, 0x07000000, 0xba0f0000, 0x60000000, 0x04004600, 0x01000d00, 0x07000000, + 0xbb0f0000, 0x2a000000, 0x05003800, 0x01000d00, 0x07000000, 0xbc0f0000, 0x1c000000, 0x06002a00, 0x01000d00, 0x07000000, 0xbd0f0000, 0xc4000000, + 0x06001c00, 0x01000d00, 0x07000000, 0xbe0f0000, 0x9e000000, 0x07000e00, 0x00000d00, 0x07000000, 0xbf0f0000, 0x30000000, 0x05003800, 0x01000d00, + 0x07000000, 0xc00f0000, 0x9a000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc10f0000, 0x93000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc20f0000, + 0x70000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc30f0000, 0x69000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc40f0000, 0x62000000, 0x06001c00, + 0x01000d00, 0x07000000, 0xc50f0000, 0x5b000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc60f0000, 0xf2000000, 0x07000000, 0x00000d00, 0x07000000, + 0xc70f0000, 0xbd000000, 0x06001c00, 0x01000d00, 0x07000000, 0xc80f0000, 0x3c000000, 0x05003800, 0x01000d00, 0x07000000, 0xc90f0000, 0x42000000, + 0x05003800, 0x01000d00, 0x07000000, 0xca0f0000, 0x48000000, 0x05003800, 0x01000d00, 0x07000000, 0xcb0f0000, 0x4e000000, 0x05003800, 0x01000d00, + 0x07000000, 0xcc0f0000, 0xa4000000, 0x03004600, 0x02000d00, 0x07000000, 0xcd0f0000, 0xb0000000, 0x03004600, 0x02000d00, 0x07000000, 0xce0f0000, + 0xa8000000, 0x03004600, 0x02000d00, 0x07000000, 0xcf0f0000, 0xfc000000, 0x03001c00, 0x02000d00, 0x07000000, 0xd00f0000, 0xce000000, 0x07000e00, + 0x00000d00, 0x07000000, 0xd10f0000, 0xcb000000, 0x06001c00, 0x01000d00, 0x07000000, 0xd20f0000, 0xd2000000, 0x06001c00, 0x01000d00, 0x07000000, + 0xd30f0000, 0xd9000000, 0x06001c00, 0x01000d00, 0x07000000, 0xd40f0000, 0x2a000000, 0x06002a00, 0x01000d00, 0x07000000, 0xd50f0000, 0xe7000000, + 0x06001c00, 0x01000d00, 0x07000000, 0xd60f0000, 0xee000000, 0x06001c00, 0x01000d00, 0x07000000, 0xd70f0000, 0x7e000000, 0x05003800, 0x01000d00, + 0x07000000, 0xd80f0000, 0xf5000000, 0x06001c00, 0x01000d00, 0x07000000, 0xd90f0000, 0x00000000, 0x06002a00, 0x01000d00, 0x07000000, 0xda0f0000, + 0x07000000, 0x06002a00, 0x01000d00, 0x07000000, 0xdb0f0000, 0x0e000000, 0x06002a00, 0x01000d00, 0x07000000, 0xdc0f0000, 0x15000000, 0x06002a00, + 0x01000d00, 0x07000000, 0xdd0f0000, 0xd6000000, 0x07000e00, 0x00000d00, 0x07000000, 0xde0f0000, 0xa8000000, 0x05003800, 0x01000d00, 0x07000000, + 0xdf0f0000, 0xde000000, 0x07000e00, 0x00000d00, 0x07000000, 0xe00f0000, 0xb4000000, 0x05003800, 0x01000d00, 0x07000000, 0xe10f0000, 0xba000000, + 0x05003800, 0x01000d00, 0x07000000, 0xe20f0000, 0xc0000000, 0x05003800, 0x01000d00, 0x07000000, 0xe30f0000, 0xc6000000, 0x05003800, 0x01000d00, + 0x07000000, 0xe40f0000, 0xcc000000, 0x05003800, 0x01000d00, 0x07000000, 0xe50f0000, 0xd2000000, 0x05003800, 0x01000d00, 0x07000000, 0xe60f0000, + 0xb6000000, 0x07000e00, 0x00000d00, 0x07000000, 0xe70f0000, 0xde000000, 0x05003800, 0x01000d00, 0x07000000, 0xe80f0000, 0xe4000000, 0x05003800, + 0x01000d00, 0x07000000, 0xe90f0000, 0xea000000, 0x05003800, 0x01000d00, 0x07000000, 0xea0f0000, 0xf0000000, 0x05003800, 0x01000d00, 0x07000000, + 0xeb0f0000, 0xf6000000, 0x05003800, 0x01000d00, 0x07000000, 0xec0f0000, 0xf1000000, 0x02004600, 0x02000d00, 0x07000000, 0xed0f0000, 0xf4000000, + 0x02004600, 0x02000d00, 0x07000000, 0xee0f0000, 0xd0000000, 0x03004600, 0x02000d00, 0x07000000, 0xef0f0000, 0xd4000000, 0x03004600, 0x02000d00, + 0x07000000, 0xf00f0000, 0x00000000, 0x05004600, 0x01000d00, 0x07000000, 0xf10f0000, 0x06000000, 0x05004600, 0x01000d00, 0x07000000, 0xf20f0000, + 0x0c000000, 0x05004600, 0x01000d00, 0x07000000, 0xf30f0000, 0x12000000, 0x05004600, 0x01000d00, 0x07000000, 0xf40f0000, 0x18000000, 0x05004600, + 0x01000d00, 0x07000000, 0xf50f0000, 0x1e000000, 0x05004600, 0x01000d00, 0x07000000, 0xf60f0000, 0x24000000, 0x05004600, 0x01000d00, 0x07000000, + 0xf70f0000, 0x2a000000, 0x05004600, 0x01000d00, 0x07000000, 0xf80f0000, 0x30000000, 0x05004600, 0x01000d00, 0x07000000, 0xf90f0000, 0x36000000, + 0x05004600, 0x01000d00, 0x07000000, 0xfa0f0000, 0x3c000000, 0x05004600, 0x01000d00, 0x07000000, 0xfb0f0000, 0x42000000, 0x05004600, 0x01000d00, + 0x07000000, 0xfc0f0000, 0x48000000, 0x05004600, 0x01000d00, 0x07000000, 0xfd0f0000, 0x4e000000, 0x05004600, 0x01000d00, 0x07000000, 0xfe0f0000, + 0x54000000, 0x05004600, 0x01000d00, 0x07000000, 0xff0f0000, 0x5a000000, 0x05004600, 0x01000d00, 0x07000000, 0x000f0000, +}; + +void ImGui::GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size) +{ + if (fnt_data) *fnt_data = (const void*)proggy_clean_13_fnt_data; + if (fnt_size) *fnt_size = proggy_clean_13_fnt_size; + if (png_data) *png_data = (const void*)proggy_clean_13_png_data; + if (png_size) *png_size = proggy_clean_13_png_size; +} + +//----------------------------------------------------------------------------- + +//---- Include imgui_user.inl at the end of imgui.cpp +//---- So you can include code that extends ImGui using its private data/functions. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- diff --git a/ext/imgui/imgui.h b/ext/imgui/imgui.h new file mode 100644 index 0000000000..6d050a3ccc --- /dev/null +++ b/ext/imgui/imgui.h @@ -0,0 +1,786 @@ +// ImGui library v1.18 wip +// See .cpp file for commentary. +// See ImGui::ShowTestWindow() for sample code. +// Read 'Programmer guide' in .cpp for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui + +#pragma once + +struct ImDrawList; +struct ImFont; +struct ImGuiAabb; +struct ImGuiIO; +struct ImGuiStorage; +struct ImGuiStyle; +struct ImGuiWindow; + +#include "imconfig.h" +#include // FLT_MAX +#include // va_list +#include // ptrdiff_t +#include // NULL, malloc + +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) +#endif + +#ifndef IMGUI_API +#define IMGUI_API +#endif + +typedef unsigned int ImU32; +typedef unsigned short ImWchar; // hold a character for display +typedef ImU32 ImGuiID; // hold widget unique ID +typedef int ImGuiCol; // enum ImGuiCol_ +typedef int ImGuiStyleVar; // enum ImGuiStyleVar_ +typedef int ImGuiKey; // enum ImGuiKey_ +typedef int ImGuiColorEditMode; // enum ImGuiColorEditMode_ +typedef int ImGuiWindowFlags; // enum ImGuiWindowFlags_ +typedef int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ +struct ImGuiTextEditCallbackData; + +struct ImVec2 +{ + float x, y; + ImVec2() {} + ImVec2(float _x, float _y) { x = _x; y = _y; } + +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA +#endif +}; + +struct ImVec4 +{ + float x, y, z, w; + ImVec4() {} + ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } + +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA +#endif +}; + +namespace ImGui +{ + // Proxy functions to access the MemAllocFn/MemFreeFn/MemReallocFn pointers in ImGui::GetIO(). The only reason they exist here is to allow ImVector<> to compile inline. + IMGUI_API void* MemAlloc(size_t sz); + IMGUI_API void MemFree(void* ptr); + IMGUI_API void* MemRealloc(void* ptr, size_t sz); +} + +// std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). +// Use '#define ImVector std::vector' if you want to use the STL type or your own type. +// Our implementation does NOT call c++ constructors! because the data types we use don't need them (but that could be added as well). Only provide the minimum functionalities we need. +#ifndef ImVector +template +class ImVector +{ +protected: + size_t Size; + size_t Capacity; + T* Data; + +public: + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + ImVector() { Size = Capacity = 0; Data = NULL; } + ~ImVector() { if (Data) ImGui::MemFree(Data); } + + inline bool empty() const { return Size == 0; } + inline size_t size() const { return Size; } + inline size_t capacity() const { return Capacity; } + + inline value_type& at(size_t i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& at(size_t i) const { IM_ASSERT(i < Size); return Data[i]; } + inline value_type& operator[](size_t i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& operator[](size_t i) const { IM_ASSERT(i < Size); return Data[i]; } + + inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline iterator begin() { return Data; } + inline const_iterator begin() const { return Data; } + inline iterator end() { 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); } + inline const value_type& back() const { IM_ASSERT(Size > 0); return at(Size-1); } + inline void swap(ImVector& rhs) { const size_t rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; const size_t rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline void reserve(size_t new_capacity) { Data = (value_type*)ImGui::MemRealloc(Data, new_capacity * sizeof(value_type)); Capacity = new_capacity; } + inline void resize(size_t new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } + + inline void push_back(const value_type& v) { if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); Data[Size++] = v; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + + inline iterator erase(const_iterator it) { IM_ASSERT(it >= begin() && it < end()); const ptrdiff_t off = it - begin(); memmove(Data + off, Data + off + 1, (Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline void insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= begin() && it <= end()); const ptrdiff_t off = it - begin(); if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, (Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; } +}; +#endif // #ifndef ImVector + +// Helpers at bottom of the file: +// - IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) +// - struct ImGuiTextFilter // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +// - struct ImGuiTextBuffer // Text buffer for logging/accumulating text +// - struct ImGuiStorage // Custom key value storage (if you need to alter open/close states manually) +// - struct ImDrawList // Draw command list +// - struct ImBitmapFont // Bitmap font loader + +// ImGui End-user API +// In a namespace so that user can add extra functions (e.g. Value() helpers for your vector or common types) +namespace ImGui +{ + // Main + IMGUI_API ImGuiIO& GetIO(); + IMGUI_API ImGuiStyle& GetStyle(); + IMGUI_API void NewFrame(); + IMGUI_API void Render(); + IMGUI_API void Shutdown(); + IMGUI_API void ShowUserGuide(); + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); + IMGUI_API void ShowTestWindow(bool* open = NULL); + + // Window + IMGUI_API bool Begin(const char* name = "Debug", bool* open = NULL, ImVec2 size = ImVec2(0,0), float fill_alpha = -1.0f, ImGuiWindowFlags flags = 0); // return false when window is collapsed, so you can early out in your code. + IMGUI_API void End(); + IMGUI_API void BeginChild(const char* str_id, ImVec2 size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). on each axis. + IMGUI_API void EndChild(); + IMGUI_API bool GetWindowIsFocused(); + IMGUI_API ImVec2 GetWindowSize(); + IMGUI_API float GetWindowWidth(); + IMGUI_API void SetWindowSize(const ImVec2& size); // set to ImVec2(0,0) to force an auto-fit + IMGUI_API ImVec2 GetWindowPos(); // you should rarely need/care about the window position, but it can be useful if you want to use your own drawing. + IMGUI_API void SetWindowPos(const ImVec2& pos); // set current window pos. + IMGUI_API ImVec2 GetContentRegionMax(); // window or current column boundaries + IMGUI_API ImVec2 GetWindowContentRegionMin(); // window boundaries + IMGUI_API ImVec2 GetWindowContentRegionMax(); + IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives. + IMGUI_API ImFont* GetWindowFont(); + IMGUI_API float GetWindowFontSize(); + IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows. + IMGUI_API void SetScrollPosHere(); // adjust scrolling position to center into the current cursor position. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use 'offset' to access sub components of a multiple component widget. + IMGUI_API void SetTreeStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it). + IMGUI_API ImGuiStorage* GetTreeStateStorage(); + + IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case. default to ~2/3 of windows width. + IMGUI_API void PopItemWidth(); + IMGUI_API float GetItemWidth(); + IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets. + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space. + IMGUI_API void PopTextWrapPos(); + + // Tooltip + IMGUI_API void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins. + IMGUI_API void SetTooltipV(const char* fmt, va_list args); + IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text. + IMGUI_API void EndTooltip(); + + // Layout + IMGUI_API void Separator(); // horizontal line + IMGUI_API void SameLine(int column_x = 0, int spacing_w = -1); // call between widgets to layout them horizontally + IMGUI_API void Spacing(); + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border=true); // setup number of columns + IMGUI_API void NextColumn(); // next column + IMGUI_API float GetColumnOffset(int column_index = -1); + IMGUI_API void SetColumnOffset(int column_index, float offset); + IMGUI_API float GetColumnWidth(int column_index = -1); + IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position + IMGUI_API void SetCursorPos(const ImVec2& pos); // " + IMGUI_API void SetCursorPosX(float x); // " + IMGUI_API void SetCursorPosY(float y); // " + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in screen space + IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets. + IMGUI_API float GetTextLineSpacing(); + IMGUI_API float GetTextLineHeight(); + + // ID scopes + IMGUI_API void PushID(const char* str_id); + IMGUI_API void PushID(const void* ptr_id); + IMGUI_API void PushID(const int int_id); + IMGUI_API void PopID(); + + // Widgets + IMGUI_API void Text(const char* fmt, ...); + IMGUI_API void TextV(const char* fmt, va_list args); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); + IMGUI_API void TextWrapped(const char* fmt, ...); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos(); + IMGUI_API void TextWrappedV(const char* fmt, va_list args); + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text. + IMGUI_API void LabelText(const char* label, const char* fmt, ...); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); + IMGUI_API void BulletText(const char* fmt, ...); + IMGUI_API void BulletTextV(const char* fmt, va_list args); + IMGUI_API bool Button(const char* label, ImVec2 size = ImVec2(0,0), bool repeat_when_held = false); + IMGUI_API bool SmallButton(const char* label); + IMGUI_API bool CollapsingHeader(const char* label, const char* str_id = NULL, const bool display_frame = true, const bool default_open = false); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderAngle(const char* label, float* v, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); // *v in radians + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, void (*callback)(ImGuiTextEditCallbackData*) = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1); + IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1); + IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int popup_height_items = 7); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_height_items = 7); // separate items with \0, end item-list with \0\0 + IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_height_items = 7); + IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); + IMGUI_API bool ColorEdit3(const char* label, float col[3]); + IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); + IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); + IMGUI_API bool TreeNode(const char* str_label_id); // if returning 'true' the node is open and the user is responsible for calling TreePop + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...); // " + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " + IMGUI_API void TreePush(const char* str_id = NULL); // already called by TreeNode(), but you can call Push/Pop yourself for layouting purpose + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); + IMGUI_API void OpenNextNode(bool open); // force open/close the next TreeNode or CollapsingHeader + + // Value helper output "name: value". tip: freely declare your own within the ImGui namespace! + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + IMGUI_API void Color(const char* prefix, const ImVec4& v); + IMGUI_API void Color(const char* prefix, unsigned int v); + + // Logging + IMGUI_API void LogButtons(); + IMGUI_API void LogToTTY(int max_depth = -1); + IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); + IMGUI_API void LogToClipboard(int max_depth = -1); + + // Utilities + IMGUI_API void SetNewWindowDefaultPos(const ImVec2& pos); // set position of window that do + IMGUI_API bool IsItemHovered(); // was the last item active area hovered by mouse? + IMGUI_API bool IsItemFocused(); // was the last item focused for keyboard input? + IMGUI_API ImVec2 GetItemBoxMin(); // get bounding box of last item + IMGUI_API ImVec2 GetItemBoxMax(); // get bounding box of last item + IMGUI_API bool IsClipped(const ImVec2& item_size); // to perform coarse clipping on user's side (as an optimization) + IMGUI_API 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 + IMGUI_API bool IsMouseClicked(int button, bool repeat = false); + IMGUI_API bool IsMouseDoubleClicked(int button); + IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window) + IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any active imgui window + IMGUI_API bool IsMouseHoveringBox(const ImVec2& box_min, const ImVec2& box_max); // is mouse hovering given bounding box + IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API float GetTime(); + IMGUI_API int GetFrameCount(); + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); + IMGUI_API void GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size); + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = true, float wrap_width = -1.0f); + +} // namespace ImGui + +// Flags for ImGui::Begin() +enum ImGuiWindowFlags_ +{ + // Default: 0 + ImGuiWindowFlags_ShowBorders = 1 << 0, + ImGuiWindowFlags_NoTitleBar = 1 << 1, + ImGuiWindowFlags_NoResize = 1 << 2, + ImGuiWindowFlags_NoMove = 1 << 3, + ImGuiWindowFlags_NoScrollbar = 1 << 4, + ImGuiWindowFlags_NoScrollWithMouse = 1 << 5, + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, + ImGuiWindowFlags_ChildWindow = 1 << 7, // For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 8, // For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 9, // For internal use by BeginChild() + ImGuiWindowFlags_ComboBox = 1 << 10, // For internal use by ComboBox() + ImGuiWindowFlags_Tooltip = 1 << 11 // For internal use by Render() when using Tooltip +}; + +// Flags for ImGui::InputText() +enum ImGuiInputTextFlags_ +{ + // Default: 0 + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_AutoSelectAll = 1 << 2, // Select entire text when first taking focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 3, // Return 'true' when Enter is pressed (as opposed to when the value was modified) + ImGuiInputTextFlags_CallbackCompletion = 1 << 4, // Call user function on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 5, // Call user function on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 6 // Call user function every time + //ImGuiInputTextFlags_AlignCenter = 1 << 6, +}; + +// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array +enum ImGuiKey_ +{ + ImGuiKey_Tab, + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_A, // for CTRL+A: select all + ImGuiKey_C, // for CTRL+C: copy + ImGuiKey_V, // for CTRL+V: paste + ImGuiKey_X, // for CTRL+X: cut + ImGuiKey_Y, // for CTRL+Y: redo + ImGuiKey_Z, // for CTRL+Z: undo + ImGuiKey_COUNT +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_WindowBg, + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_TitleBg, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_ComboBg, + ImGuiCol_CheckHovered, + ImGuiCol_CheckActive, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Column, + ImGuiCol_ColumnHovered, + ImGuiCol_ColumnActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_CloseButton, + ImGuiCol_CloseButtonHovered, + ImGuiCol_CloseButtonActive, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TextSelectedBg, + ImGuiCol_TooltipBg, + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() +// NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others. +enum ImGuiStyleVar_ +{ + ImGuiStyleVar_Alpha, // float + ImGuiStyleVar_WindowPadding, // ImVec2 + ImGuiStyleVar_FramePadding, // ImVec2 + ImGuiStyleVar_ItemSpacing, // ImVec2 + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 + ImGuiStyleVar_TreeNodeSpacing, // float + ImGuiStyleVar_ColumnsMinSpacing // float +}; + +// Enumeration for ColorEditMode() +enum ImGuiColorEditMode_ +{ + ImGuiColorEditMode_UserSelect = -1, + ImGuiColorEditMode_RGB = 0, + ImGuiColorEditMode_HSV = 1, + ImGuiColorEditMode_HEX = 2 +}; + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in ImGui + ImVec2 WindowPadding; // Padding within a window + ImVec2 WindowMinSize; // Minimum window size + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + ImVec2 TouchExtraPadding; // Expand bounding box for touch-based system where touch position is not accurate enough (unnecessary for mouse inputs). Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget running. So dont grow this too much! + ImVec2 AutoFitPadding; // Extra space after auto-fit (double-clicking on resize grip) + float WindowFillAlphaDefault; // Default alpha of window background, if not specified in ImGui::Begin() + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + float TreeNodeSpacing; // Horizontal spacing when entering a tree node + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns + float ScrollBarWidth; // Width of the vertical scroll bar + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); +}; + +// This is where your app communicate with ImGui. Call ImGui::GetIO() to access. +// Read 'Programmer guide' section in .cpp file for general usage. +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Settings (fill once) // Default value: + //------------------------------------------------------------------ + + ImVec2 DisplaySize; // // Display size, in pixels. For clamping windows positions. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. + float IniSavingRate; // = 5.0f // Maximum time between saving .ini file, in seconds. Set to a negative value to disable .ini saving. + const char* IniFilename; // = "imgui.ini" // Path to .ini file. + const char* LogFilename; // = "imgui_log.txt" // Path to .log file. + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array + ImFont* Font; // // Font (also see 'Settings' fields inside ImFont structure for details) + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + float PixelCenterOffset; // = 0.0f // Try to set to 0.5f or 0.375f if rendering is blurry + + void* UserData; // = NULL // Store your own data for retrieval by callbacks. + + //------------------------------------------------------------------ + // User Functions + //------------------------------------------------------------------ + + // REQUIRED: rendering function. + // See example code if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); + + // Optional: access OS clipboard (default to use native Win32 clipboard on Windows, otherwise use a ImGui private clipboard) + // Override to access OS clipboard on other architectures. + const char* (*GetClipboardTextFn)(); + void (*SetClipboardTextFn)(const char* text); + + // Optional: override memory allocations (default to posix malloc/realloc/free) + void* (*MemAllocFn)(size_t sz); + void* (*MemReallocFn)(void* ptr, size_t sz); + void (*MemFreeFn)(void* ptr); + + // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese inputs in Windows) + void (*ImeSetInputScreenPosFn)(int x, int y); + + //------------------------------------------------------------------ + // Input - Fill before calling NewFrame() + //------------------------------------------------------------------ + + ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + bool MouseDown[5]; // Mouse buttons. ImGui itself only uses button 0 (left button) but you can use others as storage for convenience. + float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. + bool KeyCtrl; // Keyboard modifier pressed: Control + bool KeyShift; // Keyboard modifier pressed: Shift + bool KeysDown[512]; // Keyboard keys that are pressed (in whatever order user naturally has access to keyboard data) + ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. + + // Function + IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] + + //------------------------------------------------------------------ + // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) + bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) + + //------------------------------------------------------------------ + // [Internal] ImGui will maintain those fields for you + //------------------------------------------------------------------ + + ImVec2 MousePosPrev; + ImVec2 MouseDelta; + bool MouseClicked[5]; + ImVec2 MouseClickedPos[5]; + float MouseClickedTime[5]; + bool MouseDoubleClicked[5]; + float MouseDownTime[5]; + float KeysDownTime[512]; + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +// Helper: execute a block of code once a frame only +// Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. +// Usage: +// IMGUI_ONCE_UPON_A_FRAME +// { +// // code block will be executed one per frame +// } +// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. +#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__) +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { const int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + struct TextRange + { + const char* b; + const char* e; + + TextRange() { b = e = NULL; } + TextRange(const char* _b, const char* _e) { b = _b; e = _e; } + const char* begin() const { return b; } + const char* end() const { return e; } + bool empty() const { return b == e; } + char front() const { return *b; } + static bool isblank(char c) { return c == ' ' || c == '\t'; } + void trim_blanks() { while (b < e && isblank(*b)) b++; while (e > b && isblank(*(e-1))) e--; } + IMGUI_API void split(char separator, ImVector& out); + }; + + char InputBuf[256]; + ImVector Filters; + int CountGrep; + + ImGuiTextFilter(); + void Clear() { InputBuf[0] = 0; Build(); } + void Draw(const char* label = "Filter (inc,-exc)", float width = -1.0f); // Helper calling InputText+Build + bool PassFilter(const char* val) const; + bool IsActive() const { return !Filters.empty(); } + IMGUI_API void Build(); +}; + +// Helper: Text buffer for logging/accumulating text +struct ImGuiTextBuffer +{ + ImVector Buf; + + ImGuiTextBuffer() { Buf.push_back(0); } + ~ImGuiTextBuffer() { clear(); } + const char* begin() const { return &Buf.front(); } + const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator + size_t size() const { return Buf.size()-1; } + bool empty() { return Buf.empty(); } + void clear() { Buf.clear(); Buf.push_back(0); } + IMGUI_API void append(const char* fmt, ...); +}; + +// Helper: Key->value storage +// - Store collapse state for a tree +// - Store color edit options, etc. +// Typically you don't have to worry about this since a storage is held within each Window. +// Declare your own storage if you want to manipulate the open/close state of a particular sub-tree in your interface. +struct ImGuiStorage +{ + struct Pair { ImU32 key; int val; }; + ImVector Data; + + IMGUI_API void Clear(); + IMGUI_API int GetInt(ImU32 key, int default_val = 0); + IMGUI_API void SetInt(ImU32 key, int val); + IMGUI_API void SetAllInt(int val); + + IMGUI_API int* Find(ImU32 key); + IMGUI_API void Insert(ImU32 key, int val); +}; + +// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used. +struct ImGuiTextEditCallbackData +{ + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only + char* Buf; // Current text // Read-write (pointed data only) + size_t BufSize; // // Read-only + bool BufDirty; // Set if you modify Buf directly // Write + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + int CursorPos; // // Read-write + int SelectionStart; // // Read-write (== to SelectionEnd when no selection) + int SelectionEnd; // // Read-write + void* UserData; // What user passed to InputText() + + // NB: calling those function loses selection. + void DeleteChars(int pos, int bytes_count); + void InsertChars(int pos, const char* text, const char* text_end = NULL); +}; + +//----------------------------------------------------------------------------- +// Draw List +// Hold a series of drawing commands. The user provide a renderer for ImDrawList +//----------------------------------------------------------------------------- + +struct ImDrawCmd +{ + unsigned int vtx_count; + ImVec4 clip_rect; +}; + +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +// Default vertex layout +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can change the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT. +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described by the #define (you can either declare the struct or use a typedef) +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// Draw command list +// This is the low-level list of polygon that ImGui:: functions are creating. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged. +// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// Note that this only gives you access to rendering polygons. If your intent is to create custom widgets and the publicly exposed functions/data aren't sufficient, you can add code in imgui_user.inl +struct ImDrawList +{ + // 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) + + ImDrawList() { Clear(); } + + IMGUI_API void Clear(); + IMGUI_API void PushClipRect(const ImVec4& clip_rect); + IMGUI_API void PopClipRect(); + IMGUI_API void ReserveVertices(unsigned int vtx_count); + IMGUI_API void AddVtx(const ImVec2& pos, ImU32 col); + IMGUI_API void AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col); + + // Primitives + IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners=0x0F); + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners=0x0F); + IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, int a_max, bool tris = false, const ImVec2& third_point_offset = ImVec2(0,0)); + IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f); +}; + +// Bitmap font data loader & renderer into vertices +// Using the .fnt format exported by BMFont +// - tool: http://www.angelcode.com/products/bmfont +// - file-format: http://www.angelcode.com/products/bmfont/doc/file_format.html +// Assume valid file data (won't handle invalid/malicious data) +// Handle a subset of the options, namely: +// - kerning pair are not supported (because some ImGui code does per-character CalcTextSize calls, need to turn it into something more state-ful to allow for kerning) +struct ImFont +{ + struct FntInfo; + struct FntCommon; + struct FntGlyph; + struct FntKerning; + + // Settings + float Scale; // = 1.0f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.0f,0.0f // Offset font rendering by xx pixels + ImVec2 TexUvForWhite; // = (0.0f,0.0f) // Font texture must have a white pixel at this UV coordinate. Adjust if you are using custom texture. + ImWchar FallbackChar; // = '?' // Replacement glyph is one isn't found. + + // Data + unsigned char* Data; // Raw data, content of .fnt file + size_t DataSize; // + bool DataOwned; // + const FntInfo* Info; // (point into raw data) + const FntCommon* Common; // (point into raw data) + const FntGlyph* Glyphs; // (point into raw data) + size_t GlyphsCount; // + const FntKerning* Kerning; // (point into raw data) - NB: kerning is unsupported + size_t KerningCount; // + ImVector Filenames; // (point into raw data) + ImVector IndexLookup; // (built) + const FntGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) + + IMGUI_API ImFont(); + IMGUI_API ~ImFont() { Clear(); } + + IMGUI_API bool LoadFromMemory(const void* data, size_t data_size); + IMGUI_API bool LoadFromFile(const char* filename); + IMGUI_API void Clear(); + IMGUI_API void BuildLookupTable(); + IMGUI_API const FntGlyph* FindGlyph(unsigned short c) const; + IMGUI_API bool IsLoaded() const { return Info != NULL && Common != NULL && Glyphs != NULL; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API ImVec2 CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL) const; // wchar + IMGUI_API void RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, ImDrawVert*& out_vertices, float wrap_width = 0.0f) const; + + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + +#pragma pack(push, 1) + struct FntInfo + { + signed short FontSize; + unsigned char BitField; // bit 0: smooth, bit 1: unicode, bit 2: italic, bit 3: bold, bit 4: fixedHeight, bits 5-7: reserved + unsigned char CharSet; + unsigned short StretchH; + unsigned char AA; + unsigned char PaddingUp, PaddingRight, PaddingDown, PaddingLeft; + unsigned char SpacingHoriz, SpacingVert, Outline; + //char FontName[]; + }; + + struct FntCommon + { + unsigned short LineHeight, Base; + unsigned short ScaleW, ScaleH; + unsigned short Pages; + unsigned char BitField; + unsigned char Channels[4]; + }; + + struct FntGlyph + { + unsigned int Id; + unsigned short X, Y, Width, Height; + signed short XOffset, YOffset; + signed short XAdvance; + unsigned char Page; + unsigned char Channel; + }; + + struct FntKerning + { + unsigned int IdFirst; + unsigned int IdSecond; + signed short Amount; + }; +#pragma pack(pop) +}; + +//---- Include imgui_user.h at the end of imgui.h +//---- So you can include code that extends ImGui using any of the types declared above. +//---- (also convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif diff --git a/ext/imgui/stb_image.h b/ext/imgui/stb_image.h new file mode 100644 index 0000000000..5ab9c58ec1 --- /dev/null +++ b/ext/imgui/stb_image.h @@ -0,0 +1,4744 @@ +/* stb_image - v1.46 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c + when you control the images you're loading + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + #define STBI_ASSERT(x) to avoid using assert.h. + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline (no JPEG progressive) + PNG 1/2/4/8-bit-per-channel (16 bpc not supported) + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD) + + Latest revisions: + 1.xx (2014-09-26) 1/2/4-bit PNG support (both grayscale and paletted) + 1.46 (2014-08-26) fix broken tRNS chunk in non-paletted PNG + 1.45 (2014-08-16) workaround MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) warnings + 1.43 (2014-07-15) fix MSVC-only bug in 1.42 + 1.42 (2014-07-09) no _CRT_SECURE_NO_WARNINGS; error-path fixes; STBI_ASSERT + 1.41 (2014-06-25) fix search&replace that messed up comments/error messages + 1.40 (2014-06-22) gcc warning + 1.39 (2014-06-15) TGA optimization bugfix, multiple BMP fixes + 1.38 (2014-06-06) suppress MSVC run-time warnings, fix accidental rename of 'skip' + 1.37 (2014-06-04) remove duplicate typedef + 1.36 (2014-06-03) converted to header file, allow reading incorrect iphoned-images without iphone flag + 1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc + + See end of file for full revision history. + + TODO: + stbi_info support for BMP,PSD,HDR,PIC + + + ============================ Contributors ========================= + + Image formats Bug fixes & warning fixes + Sean Barrett (jpeg, png, bmp) Marc LeBlanc + Nicolas Schulz (hdr, psd) Christpher Lloyd + Jonathan Dummer (tga) Dave Moore + Jean-Marc Lienher (gif) Won Chun + Tom Seddon (pic) the Horde3D community + Thatcher Ulrich (psd) Janez Zemva + Jonathan Blow + Laurent Gomila + Extensions, features Aruelien Pocheville + Jetro Lauha (stbi_info) Ryamond Barbiero + James "moose2000" Brown (iPhone PNG) David Woo + Ben "Disch" Wenger (io callbacks) Roy Eltham + Martin "SpartanJ" Golini Luke Graham + Omar Cornut (1/2/4-bit png) Thomas Ruf + John Bartholomew + Optimizations & bugfixes Ken Hamada + Fabian "ryg" Giesen Cort Stratton + Arseny Kapoulkine Blazej Dariusz Roszkowski + Thibault Reuille + Paul Du Bois + Guillaume George + Jerry Jansson + If your name should be here but Hayaki Saito + isn't, let Sean know. Johan Duparc + Ronny Chevalier + Michal Cichon +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// Limitations: +// - no jpeg progressive support +// - non-HDR formats support 8-bit samples only (jpeg, png) +// - no delayed line count (jpeg) -- IJG doesn't support either +// - no 1-bit BMP +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *comp -- outputs # of image components in image file +// int req_comp -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. +// If req_comp is non-zero, *comp has the number of components that _would_ +// have been output otherwise. E.g. if you set req_comp to 4, you will always +// get RGBA output, but you can check *comp to easily see if it's opaque. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *comp will be unchanged. The function stbi_failure_reason() +// can be queried for an extremely brief, end-user unfriendly explanation +// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid +// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB; nominally they +// would silently load as BGR, except the existing code should have just +// failed on such iPhone PNGs. But you can disable this conversion by +// by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through. +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image now supports loading HDR images in general, and currently +// the Radiance .HDR file format, although the support is provided +// generically. You can still load any file through the existing interface; +// if you attempt to load an HDR file, it will be automatically remapped to +// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for req_comp + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +typedef unsigned char stbi_uc; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +STBIDEF stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); + +#ifndef STBI_NO_HDR + STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); + #endif + + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); + + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); + + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_HDR + +// stbi_is_hdr is always defined +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// NOT THREADSAFE +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); + +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +// define faster low-level operations (typically SIMD support) +#ifdef STBI_SIMD +typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize); +// compute an integer IDCT on "input" +// input[x] = data[x] * dequantize[x] +// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride' +// CLAMP results to 0..255 +typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step); +// compute a conversion from YCbCr to RGB +// 'count' pixels +// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B +// y: Y input channel +// cb: Cb input channel; scale/biased to be 0..255 +// cr: Cr input channel; scale/biased to be 0..255 + +STBIDEF void stbi_install_idct(stbi_idct_8x8 func); +STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func); +#endif // STBI_SIMD + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#ifndef STBI_NO_HDR +#include // ldexp +#include // strcmp, strtok +#endif + +#ifndef STBI_NO_STDIO +#include +#endif +#include +#include +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif +#include +#include // ptrdiff_t on osx + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + fseek((FILE*) user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; +} + +static int stbi__jpeg_test(stbi__context *s); +static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_test(stbi__context *s); +static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__bmp_test(stbi__context *s); +static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__tga_test(stbi__context *s); +static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_test(stbi__context *s); +static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +#endif +static int stbi__pic_test(stbi__context *s); +static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__gif_test(stbi__context *s); +static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); + + +// this is not threadsafe +static const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} + +static void *stbi__malloc(size_t size) +{ + return malloc(size); +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + free(retval_from_stbi_load); +} + +#ifndef STBI_NO_HDR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static unsigned char *stbi_load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp); + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp); + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp); + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp); + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp); + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp); + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp); + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +#ifndef STBI_NO_STDIO + +FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi_load_main(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} +#endif //!STBI_NO_STDIO + +STBIDEF unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi_load_main(&s,x,y,comp,req_comp); +} + +unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi_load_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_HDR + +float *stbi_loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) + return stbi__hdr_load(s,x,y,comp,req_comp); + #endif + data = stbi_load_main(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi_loadf_main(&s,x,y,comp,req_comp); +} + +float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi_loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi_loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_HDR + +// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is +// defined, for API simplicity; if STBI_NO_HDR is defined, it always +// reports false! + +int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_file(&s,f); + return stbi__hdr_test(&s); + #else + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + return 0; + #endif +} + +#ifndef STBI_NO_HDR +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + +void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + SCAN_load=0, + SCAN_type, + SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} + +static void stbi__skip(stbi__context *s, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} + +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} + +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} + +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} + +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} + +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} + +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} + +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc(req_comp * x * y); + if (good == NULL) { + free(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define COMBO(a,b) ((a)*8+(b)) + #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (COMBO(img_n, req_comp)) { + CASE(1,2) dest[0]=src[0], dest[1]=255; break; + CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; + CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; + CASE(2,1) dest[0]=src[0]; break; + CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; + CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; + CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; + CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; + CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break; + CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; + CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; + CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; + default: STBI_ASSERT(0); + } + #undef CASE + } + + free(data); + return good; +} + +#ifndef STBI_NO_HDR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output = (float *) stbi__malloc(x * y * comp * sizeof(float)); + if (output == NULL) { free(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; + } + free(data); + return output; +} + +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp); + if (output == NULL) { free(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + free(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation) +// +// simple implementation +// - channel subsampling of at most 2 in each dimension +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - uses a lot of intermediate memory, could cache poorly +// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4 +// stb_jpeg: 1.34 seconds (MSVC6, default release build) +// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro) +// IJL11.dll: 1.08 seconds (compiled by intel) +// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG) +// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro) + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + #ifdef STBI_SIMD + unsigned short dequant2[4][64]; + #endif + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi_uc dequant[4][64]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data; + stbi_uc *linebuf; + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int scan_n, order[4]; + int restart_interval, todo; +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0,code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) + for (j=0; j < count[i]; ++j) + h->size[k++] = (stbi_uc) (i+1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// combined JPEG 'receive' and JPEG 'extend', since baseline +// always extends everything it receives. +stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) +{ + unsigned int m = 1 << (n-1); + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + + #if 1 + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + #else + k = (j->code_buffer >> (32 - n)) & stbi__bmask[n]; + j->code_bits -= n; + j->code_buffer <<= n; + #endif + // the following test is probably a random branch that won't + // predict well. I tried to table accelerate it but failed. + // maybe it's compiling as a conditional move? + if (k < m) + return (-1 << n) + k + 1; + else + return k; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, int b) +{ + int diff,dc,k; + int t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) dc; + + // decode AC components, see JPEG spec + k = 1; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + data[stbi__jpeg_dezigzag[k++]] = (short) stbi__extend_receive(j,s); + } + } while (k < 64); + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) (int) (((x) * 4096 + 0.5)) +#define stbi__fsh(x) ((x) << 12) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +#ifdef STBI_SIMD +typedef unsigned short stbi_dequantize_t; +#else +typedef stbi_uc stbi_dequantize_t; +#endif + +// .344 seconds on 3*anemones.jpg +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64], stbi_dequantize_t *dequantize) +{ + int i,val[64],*v=val; + stbi_dequantize_t *dq = dequantize; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d,++dq, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0] * dq[0] << 2; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24], + d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SIMD +static stbi_idct_8x8 stbi__idct_installed = stbi__idct_block; + +STBIDEF void stbi_install_idct(stbi_idct_8x8 func) +{ + stbi__idct_installed = func; +} +#endif + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (z->scan_n == 1) { + int i,j; + #ifdef STBI_SIMD + __declspec(align(16)) + #endif + short data[64]; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; + #ifdef STBI_SIMD + stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); + #else + stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); + #endif + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + } else { // interleaved! + int i,j,k,x,y; + short data[64]; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; + #ifdef STBI_SIMD + stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); + #else + stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); + #endif + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + } + return 1; +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xC2: // stbi__SOF - progressive + return stbi__err("progressive jpeg","JPEG format not supported (progressive)"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4; + int t = q & 15,i; + if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); + #ifdef STBI_SIMD + for (i=0; i < 64; ++i) + z->dequant2[t][i] = z->dequant[t][i]; + #endif + L -= 65; + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + L -= n; + } + return L==0; + } + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + stbi__skip(z->s, stbi__get16be(z->s)-2); + return 1; + } + return 0; +} + +// after we see stbi__SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad stbi__SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad stbi__SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG"); + stbi__get8(z->s); // should be 63, but might be 0 + if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG"); + + return 1; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad stbi__SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + c = stbi__get8(s); + if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad stbi__SOF len","Corrupt JPEG"); + + for (i=0; i < s->img_n; ++i) { + z->img_comp[i].id = stbi__get8(s); + if (z->img_comp[i].id != i+1) // JFIF requires + if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! + return stbi__err("bad component ID","Corrupt JPEG"); + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != SCAN_load) return 1; + + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); + if (z->img_comp[i].raw_data == NULL) { + for(--i; i >= 0; --i) { + free(z->img_comp[i].raw_data); + z->img_comp[i].data = NULL; + } + return stbi__err("outofmem", "Out of memory"); + } + // align blocks for installable-idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + z->img_comp[i].linebuf = NULL; + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. stbi__SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1) +#define stbi__SOS(x) ((x) == 0xda) + +static int decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no stbi__SOI","Corrupt JPEG"); + if (scan == SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no stbi__SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static int decode_jpeg_image(stbi__jpeg *j) +{ + int m; + j->restart_interval = 0; + if (!decode_jpeg_header(j, SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } else if (x != 0) { + return 0; + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +#define float2fixed(x) ((int) ((x) * 65536 + 0.5)) + +// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro) +// VC6 without processor=Pro is generating multiple LEAs per multiply! +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 16) + 32768; // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr*float2fixed(1.40200f); + g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); + b = y_fixed + cb*float2fixed(1.77200f); + r >>= 16; + g >>= 16; + b >>= 16; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#ifdef STBI_SIMD +static stbi_YCbCr_to_RGB_run stbi__YCbCr_installed = stbi__YCbCr_to_RGB_row; + +STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func) +{ + stbi__YCbCr_installed = func; +} +#endif + + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + int i; + for (i=0; i < j->s->img_n; ++i) { + if (j->img_comp[i].raw_data) { + free(j->img_comp[i].raw_data); + j->img_comp[i].raw_data = NULL; + j->img_comp[i].data = NULL; + } + if (j->img_comp[i].linebuf) { + free(j->img_comp[i].linebuf); + j->img_comp[i].linebuf = NULL; + } + } +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source + if (!decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n; + + if (z->s->img_n == 3 && n < 3) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4]; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = stbi__resample_row_hv_2; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + #ifdef STBI_SIMD + stbi__YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n); + #else + stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n); + #endif + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n; // report original components, not output + return output; + } +} + +static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__jpeg j; + j.s = s; + return load_jpeg_image(&j, x,y,comp,req_comp); +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg j; + j.s = s; + r = decode_jpeg_header(&j, SCAN_type); + stbi__rewind(s); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!decode_jpeg_header(j, SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__jpeg j; + j.s = s; + return stbi__jpeg_info_raw(&j, x, y, comp); +} + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 255, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + STBI_ASSERT(sizes[i] <= (1 << i)); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt JPEG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int k = stbi__bit_reverse(next_code[s],s); + while (k < (1 << STBI__ZFAST_BITS)) { + z->fast[k] = (stbi__uint16) c; + k += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + z->code_buffer |= stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + if (a->num_bits < 16) stbi__fill_bits(a); + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b < 0xffff) { + s = z->size[b]; + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; + } + + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s == 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + STBI_ASSERT(z->size[b] == s); + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +static int stbi__zexpand(stbi__zbuf *z, int n) // need to make room for n bytes +{ + char *q; + int cur, limit; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (int) (z->zout - z->zout_start); + limit = (int) (z->zout_end - z->zout_start); + while (cur + n > limit) + limit *= 2; + q = (char *) realloc(z->zout_start, limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (a->zout >= a->zout_end) if (!stbi__zexpand(a, 1)) return 0; + *a->zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) return 1; + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (a->zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, len)) return 0; + p = (stbi_uc *) (a->zout - dist); + while (len--) + *a->zout++ = *p++; + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < hlit + hdist) { + int c = stbi__zhuffman_decode(a, &z_codelength); + STBI_ASSERT(c >= 0 && c < 19); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else if (c == 16) { + c = stbi__zreceive(a,2)+3; + memset(lencodes+n, lencodes[n-1], c); + n += c; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + memset(lencodes+n, 0, c); + n += c; + } else { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a,7)+11; + memset(lencodes+n, 0, c); + n += c; + } + } + if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncomperssed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + STBI_ASSERT(a->num_bits == 0); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +// @TODO: should statically initialize these for optimal thread safety +static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; +static void stbi__init_zdefaults(void) +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncomperssed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + free(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + free(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + free(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + + +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; +} stbi__png; + + +enum { + STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4, + STBI__F_avg_first, STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n; + stbi__uint32 img_len; + int k; + int img_n = s->img_n; // copy it into a local for later + stbi_uc* line8 = NULL; // point into raw when depth==8 else temporary local buffer + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc(x * y * out_n); + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + img_len = ((((img_n * x * depth) + 7) >> 3) + 1) * y; + if (s->img_x == x && s->img_y == y) { + if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); + } else { // interlaced: + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + } + + if (depth != 8) { + line8 = (stbi_uc *) stbi__malloc((x+7) * out_n); // allocate buffer for one scanline + if (!line8) return stbi__err("outofmem", "Out of memory"); + } + + for (j=0; j < y; ++j) { + stbi_uc *in; + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior = cur - stride; + int filter = *raw++; + if (filter > 4) { + if (depth != 8) free(line8); + return stbi__err("invalid filter","Corrupt PNG"); + } + + if (depth == 8) { + in = raw; + raw += x*img_n; + } + else { + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + in = line8; + stbi_uc* decode_out = line8; + stbi_uc scale = (color == 0) ? 0xFF/((1<= 1; k-=2, raw++) { + *decode_out++ = scale * ((*raw >> 4) ); + *decode_out++ = scale * ((*raw ) & 0x0f); + } + } else if (depth == 2) { + for (k=x*img_n; k >= 1; k-=4, raw++) { + *decode_out++ = scale * ((*raw >> 6) ); + *decode_out++ = scale * ((*raw >> 4) & 0x03); + *decode_out++ = scale * ((*raw >> 2) & 0x03); + *decode_out++ = scale * ((*raw ) & 0x03); + } + } else if (depth == 1) { + for (k=x*img_n; k >= 1; k-=8, raw++) { + *decode_out++ = scale * ((*raw >> 7) ); + *decode_out++ = scale * ((*raw >> 6) & 0x01); + *decode_out++ = scale * ((*raw >> 5) & 0x01); + *decode_out++ = scale * ((*raw >> 4) & 0x01); + *decode_out++ = scale * ((*raw >> 3) & 0x01); + *decode_out++ = scale * ((*raw >> 2) & 0x01); + *decode_out++ = scale * ((*raw >> 1) & 0x01); + *decode_out++ = scale * ((*raw ) & 0x01); + } + } + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first pixel explicitly + for (k=0; k < img_n; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = in[k]; break; + case STBI__F_sub : cur[k] = in[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(in[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(in[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = in[k]; break; + case STBI__F_paeth_first: cur[k] = in[k]; break; + } + } + if (img_n != out_n) cur[img_n] = 255; + in += img_n; + cur += out_n; + prior += out_n; + // this is a little gross, so that we don't switch per-pixel or per-component + if (img_n == out_n) { + #define CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, in+=img_n,cur+=img_n,prior+=img_n) \ + for (k=0; k < img_n; ++k) + switch (filter) { + CASE(STBI__F_none) cur[k] = in[k]; break; + CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(in[k] + cur[k-img_n]); break; + CASE(STBI__F_up) cur[k] = STBI__BYTECAST(in[k] + prior[k]); break; + CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(in[k] + ((prior[k] + cur[k-img_n])>>1)); break; + CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-img_n],prior[k],prior[k-img_n])); break; + CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(in[k] + (cur[k-img_n] >> 1)); break; + CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-img_n],0,0)); break; + } + #undef CASE + } else { + STBI_ASSERT(img_n+1 == out_n); + #define CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[img_n]=255,in+=img_n,cur+=out_n,prior+=out_n) \ + for (k=0; k < img_n; ++k) + switch (filter) { + CASE(STBI__F_none) cur[k] = in[k]; break; + CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(in[k] + cur[k-out_n]); break; + CASE(STBI__F_up) cur[k] = STBI__BYTECAST(in[k] + prior[k]); break; + CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(in[k] + ((prior[k] + cur[k-out_n])>>1)); break; + CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; + CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(in[k] + (cur[k-out_n] >> 1)); break; + CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-out_n],0,0)); break; + } + #undef CASE + } + } + + if (depth != 8) free(line8); + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, int depth, int color, int interlaced) +{ + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((out_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, raw, raw_len, out_n, x, y, depth, color)) { + free(final); + return 0; + } + for (j=0; j < y; ++j) + for (i=0; i < x; ++i) + memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n, + a->out + (j*x+i)*out_n, out_n); + free(a->out); + raw += img_len; + raw_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + free(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + p[0] = p[2] * 255 / a; + p[1] = p[1] * 255 / a; + p[2] = t * 255 / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, depth=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == SCAN_header) return 1; + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + for (k=0; k < s->img_n; ++k) + tc[k] = (stbi_uc) (stbi__get16be(s) & 255); // non 8-bit images will be larger + } + break; + } + + case PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; } + if (ioff + c.length > idata_limit) { + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + p = (stbi_uc *) realloc(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + free(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0; + if (has_trans) + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } + free(z->expanded); z->expanded = NULL; + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp) +{ + unsigned char *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, SCAN_load, req_comp)) { + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_out_n; + } + free(p->out); p->out = NULL; + free(p->expanded); p->expanded = NULL; + free(p->idata); p->idata = NULL; + + return result; +} + +static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +// Microsoft/Windows BMP image +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) n += 16, z >>= 16; + if (z >= 0x00100) n += 8, z >>= 8; + if (z >= 0x00010) n += 4, z >>= 4; + if (z >= 0x00004) n += 2, z >>= 2; + if (z >= 0x00002) n += 1, z >>= 1; + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +static int stbi__shiftsigned(int v, int shift, int bits) +{ + int result; + int z=0; + + if (shift < 0) v <<= -shift; + else v >>= shift; + result = v; + + z = bits; + while (z < 8) { + result += v >> z; + z += bits; + } + return result; +} + +static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0; + stbi_uc pal[256][4]; + int psize=0,i,j,compress=0,width; + int bpp, flip_vertically, pad, target, offset, hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + offset = stbi__get32le(s); + hsz = stbi__get32le(s); + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + bpp = stbi__get16le(s); + if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + if (hsz == 12) { + if (bpp < 24) + psize = (offset - 14 - 24) / 3; + } else { + compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (bpp == 16 || bpp == 32) { + mr = mg = mb = 0; + if (compress == 0) { + if (bpp == 32) { + mr = 0xffu << 16; + mg = 0xffu << 8; + mb = 0xffu << 0; + ma = 0xffu << 24; + fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255 + STBI_NOTUSED(fake_a); + } else { + mr = 31u << 10; + mg = 31u << 5; + mb = 31u << 0; + } + } else if (compress == 3) { + mr = stbi__get32le(s); + mg = stbi__get32le(s); + mb = stbi__get32le(s); + // not documented, but generated by photoshop and handled by mspaint + if (mr == mg && mg == mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + STBI_ASSERT(hsz == 108 || hsz == 124); + mr = stbi__get32le(s); + mg = stbi__get32le(s); + mb = stbi__get32le(s); + ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + if (bpp < 16) + psize = (offset - 14 - hsz) >> 2; + } + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { free(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4)); + if (bpp == 4) width = (s->img_x + 1) >> 1; + else if (bpp == 8) width = s->img_x; + else { free(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, offset - 14 - hsz); + if (bpp == 24) width = 3 * s->img_x; + else if (bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (bpp == 24) { + easy = 1; + } else if (bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { free(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + if (target == 4) out[z++] = a; + } + } else { + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (stbi__uint32) (bpp == 16 ? stbi__get16le(s) : stbi__get32le(s)); + int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i], p1[i] = p2[i], p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} + +// Targa Truevision - TGA +// by Jonathan Dummer + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp; + int sz; + stbi__get8(s); // discard Offset + sz = stbi__get8(s); // color type + if( sz > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + sz = stbi__get8(s); // image type + // only RGB or grey allowed, +/- RLE + if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0; + stbi__skip(s,9); + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + sz = stbi__get8(s); // bits per pixel + // only RGB or RGBA or grey allowed + if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) { + stbi__rewind(s); + return 0; + } + tga_comp = sz; + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp / 8; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res; + int sz; + stbi__get8(s); // discard Offset + sz = stbi__get8(s); // color type + if ( sz > 1 ) return 0; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE + stbi__get16be(s); // discard palette start + stbi__get16be(s); // discard palette length + stbi__get8(s); // discard bits per palette color entry + stbi__get16be(s); // discard x origin + stbi__get16be(s); // discard y origin + if ( stbi__get16be(s) < 1 ) return 0; // test width + if ( stbi__get16be(s) < 1 ) return 0; // test height + sz = stbi__get8(s); // bits per pixel + if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) + res = 0; + else + res = 1; + stbi__rewind(s); + return res; +} + +static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp = tga_bits_per_pixel / 8; + int tga_inverted = stbi__get8(s); + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4]; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + /* int tga_alpha_bits = tga_inverted & 15; */ + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // error check + if ( //(tga_indexed) || + (tga_width < 1) || (tga_height < 1) || + (tga_image_type < 1) || (tga_image_type > 3) || + ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) && + (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)) + ) + { + return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA + } + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) + { + tga_comp = tga_palette_bits / 8; + } + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + tga_data = (unsigned char*)stbi__malloc( tga_width * tga_height * tga_comp ); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE) { + for (i=0; i < tga_height; ++i) { + int y = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + y*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_palette_bits / 8 ); + if (!tga_palette) { + free(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) { + free(tga_data); + free(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in 1 byte, then perform the lookup + int pal_idx = stbi__get8(s); + if ( pal_idx >= tga_palette_len ) + { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_bits_per_pixel / 8; + for (j = 0; j*8 < tga_bits_per_pixel; ++j) + { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else + { + // read in the data raw + for (j = 0; j*8 < tga_bits_per_pixel; ++j) + { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + free( tga_palette ); + } + } + + // swap RGB + if (tga_comp >= 3) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + // OK, done + return tga_data; +} + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + int pixelCount; + int channelCount, compression; + int channel, i, count, len; + int w,h; + stbi_uc *out; + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + // Make sure the depth is 8 bits. + if (stbi__get16be(s) != 8) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Create the destination image. + out = (stbi_uc *) stbi__malloc(4 * w*h); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4; + } else { + // Read the RLE data. + count = 0; + while (count < pixelCount) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len ^= 0x0FF; + len += 2; + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out + channel; + if (channel > channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4; + } else { + // Read the data. + for (i = 0; i < pixelCount; i++) + *p = stbi__get8(s), p += 4; + } + } + } + + if (req_comp && req_comp != 4) { + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = channelCount; + *y = h; + *x = w; + + return out; +} + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + int i; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp) +{ + stbi_uc *result; + int i, x,y; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc(x*y*4); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + free(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[4096]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif g; + if (!stbi__gif_header(s, &g, comp, 1)) { + stbi__rewind( s ); + return 0; + } + if (x) *x = g.w; + if (y) *y = g.h; + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + p = &g->out[g->cur_x + g->cur_y]; + c = &g->color_table[g->codes[code].suffix * 4]; + + if (c[3] >= 128) { + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (code = 0; code < clear; code++) { + g->codes[code].prefix = -1; + g->codes[code].first = (stbi_uc) code; + g->codes[code].suffix = (stbi_uc) code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +static void stbi__fill_gif_background(stbi__gif *g) +{ + int i; + stbi_uc *c = g->pal[g->bgindex]; + // @OPTIMIZE: write a dword at a time + for (i = 0; i < g->w * g->h * 4; i += 4) { + stbi_uc *p = &g->out[i]; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) +{ + int i; + stbi_uc *old_out = 0; + + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + stbi__fill_gif_background(g); + } else { + // animated-gif-only path + if (((g->eflags & 0x1C) >> 2) == 3) { + old_out = g->out; + g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + memcpy(g->out, old_out, g->w*g->h*4); + } + } + + for (;;) { + switch (stbi__get8(s)) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + for (i=0; i < 256; ++i) // @OPTIMIZE: stbi__jpeg_reset only the previous transparent + g->pal[i][3] = 255; + if (g->transparent >= 0 && (g->eflags & 0x01)) + g->pal[g->transparent][3] = 0; + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (o == NULL) return NULL; + + if (req_comp && req_comp != 4) + o = stbi__convert_format(o, 4, req_comp, g->w, g->h); + return o; + } + + case 0x21: // Comment Extension. + { + int len; + if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + stbi__get16le(s); // delay + g->transparent = stbi__get8(s); + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) + stbi__skip(s, len); + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + + u = stbi__gif_load_next(s, &g, comp, req_comp); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + } + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} + + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s) +{ + const char *signature = "#?RADIANCE\n"; + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s); + stbi__rewind(s); + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + + + // Check identifier + if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + // Read data + hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float)); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + free(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { free(hdr_data); free(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4); + + for (k = 0; k < 4; ++k) { + i = 0; + while (i < width) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + free(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + + if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') { + stbi__rewind( s ); + return 0; + } + stbi__skip(s,12); + hsz = stbi__get32le(s); + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) { + stbi__rewind( s ); + return 0; + } + if (hsz == 12) { + *x = stbi__get16le(s); + *y = stbi__get16le(s); + } else { + *x = stbi__get32le(s); + *y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) { + stbi__rewind( s ); + return 0; + } + *comp = stbi__get16le(s) / 8; + return 1; +} + +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + if (stbi__get16be(s) != 8) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained; + stbi__pic_packet packets[10]; + + stbi__skip(s, 92); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) return 0; + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + if (stbi__jpeg_info(s, x, y, comp)) + return 1; + if (stbi__png_info(s, x, y, comp)) + return 1; + if (stbi__gif_info(s, x, y, comp)) + return 1; + if (stbi__bmp_info(s, x, y, comp)) + return 1; + if (stbi__psd_info(s, x, y, comp)) + return 1; + if (stbi__pic_info(s, x, y, comp)) + return 1; + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) + return 1; + #endif + // test tga last because it's a crappy test! + if (stbi__tga_info(s, x, y, comp)) + return 1; + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 2008-08-02 + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 first released version +*/ diff --git a/ext/imgui/stb_textedit.h b/ext/imgui/stb_textedit.h new file mode 100644 index 0000000000..5aa79f02ad --- /dev/null +++ b/ext/imgui/stb_textedit.h @@ -0,0 +1,1254 @@ +// stb_textedit.h - v1.4 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// This software has been placed in the public domain by its author. +// Where that dedication is not recognized, you are granted a perpetual, +// irrevocable license to copy and modify this file as you see fit. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove'. Uses no other functions. +// Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// 1.4 (2014-08-17) fix signed/unsigned warnings +// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +// 1.2 (2014-05-27) fix some RAD types that had crept into the new code +// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +// 1.0 (2012-07-26) improve documentation, initial public release +// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +// 0.2 (2011-11-28) fixes to undo/redo +// 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Scott Graham: mouse selection bugfix in 1.3 +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string being edited, +// typically this is a wrapper object with other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters +// starting from character #n (see discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +// to the xpos of the i+1'th char for a line of characters +// starting at character #n (i.e. accounts for kerning +// with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character +// (return type is int, -1 means not valid to insert) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based +// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +// as manually wordwrapping for end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME +// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END +// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME +// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +// STB_TEXTEDIT_K_UNDO keyboard input to perform undo +// STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for WORDLEFT/WORDRIGHT +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// +// Todo: +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// +// Keyboard input must be encoded as a single integer value; e.g. a character code +// and some bitflags that represent shift states. to simplify the interface, SHIFT must +// be a bitflag, so we can test the shifted state of cursor movements to allow selection, +// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN +// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, +// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the +// API below. The control keys will only match WM_KEYDOWN events because of the +// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute word-wrapping +// here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the cursor +// and reset the selection start/end to the cursor point. the x,y must +// be relative to the text widget, with (0,0) being the top left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste buffer. +// (To copy, just copy the current selection out of the string yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the current +// selection if there is one. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from control +// inputs, set a high bit to distinguish the two; then you can define the +// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit +// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is +// clear. +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_STB_TEXTEDIT_H +#define INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef STB_TEXTEDIT_UNDOSTATECOUNT +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef STB_TEXTEDIT_UNDOCHARCOUNT +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_CHARTYPE int +#endif +#ifndef STB_TEXTEDIT_POSITIONTYPE +#define STB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct +{ + // private data + STB_TEXTEDIT_POSITIONTYPE where; + short insert_length; + short delete_length; + short char_storage; +} StbUndoRecord; + +typedef struct +{ + // private data + StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; + STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + short undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct +{ + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries to seek to along x + StbUndoState undostate; +} STB_TexteditState; + + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct +{ + float x0,x1; // starting x location, end x location (allows for align=right, etc) + float baseline_y_delta; // position of baseline relative to previous row's baseline + float ymin,ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif //INCLUDE_STB_TEXTEDIT_H + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef STB_TEXTEDIT_IMPLEMENTATION + +#include // memmove + + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i=0, k; + + if (y < 0) + return 0; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + return n; + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + k = i; + prev_x = r.x0; + for (i=0; i < r.num_chars; ++i) { + float w = STB_TEXTEDIT_GETWIDTH(str, k, i); + if (x < prev_x+w) { + if (x < prev_x+w/2) + return k+i; + else + return k+i+1; + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line case + } + + // if the last character is a newline, return that. otherwise return 'after' the last character + if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) + return i+r.num_chars-1; + else + return i+r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset the selection +static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + state->cursor = stb_text_locate_coord(str, x, y); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location +static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + int p = stb_text_locate_coord(str, x, y); + state->cursor = state->select_end = p; +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); + +typedef struct +{ + float x,y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous row in +// case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i=0, first; + + if (n == z) { + // if it's at the end, then find the last line -- simpler than trying to + // explicitly handle this case in the regular code + if (single_line) { + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + } else { + find->y = 0; + find->x = 0; + find->height = 1; + while (i < z) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + prev_start = i; + i += r.num_chars; + } + find->first_char = i; + find->length = 0; + find->prev_first = prev_start; + } + return; + } + + // search rows to find the one that straddles character n + find->y = 0; + + for(;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (n < i + r.num_chars) + break; + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + i = 0; + for (i=0; first+i < n; ++i) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) state->select_start = n; + if (state->select_end > n) state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary( STB_TEXTEDIT_STRING *_str, int _idx ) +{ + return _idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str,_idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str, _idx) ) ) : 1; +} + +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +{ + int c = _state->cursor - 1; + while( c >= 0 && !is_word_boundary( _str, c ) ) + --c; + + if( c < 0 ) + c = 0; + + return c; +} + +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +{ + const int len = STB_TEXTEDIT_STRINGLEN(_str); + int c = _state->cursor+1; + while( c < len && !is_word_boundary( _str, c ) ) + ++c; + + if( c > len ) + c = len; + + return c; +} +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str,state); // implicity clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext; + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str,state); + // try to insert the characters + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // remove the undo since we didn't actually insert the characters + if (state->undostate.undo_point) + --state->undostate.undo_point; + return 0; +} + +// API key: process a keyboard input +static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) +{ +retry: + switch (key) { + default: { + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; + + // can't add newline in single-line mode + if (c == '\n' && state->single_line) + break; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + ++state->cursor; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str,state); // implicity clamps + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + stb_text_makeundo_insert(state, state->cursor, 1); + ++state->cursor; + state->has_preferred_x = 0; + } + } + } + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else + if (state->cursor > 0) + --state->cursor; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + ++state->cursor; + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + --state->select_end; + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_IS_SPACE + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = stb_textedit_move_to_word_previous(str, state); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = stb_textedit_move_to_word_next(str, state); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = stb_textedit_move_to_word_previous(str, state); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = stb_textedit_move_to_word_next(str, state); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + ++state->select_end; + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down in single-line behave like left&right + key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str,state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // now find character position down a row + if (find.length) { + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + int start = find.first_char + find.length; + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down become left&right + key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // can only go up if there's a previous row + if (find.prev_first != find.first_char) { + // now find character position up a row + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete(str, state, state->cursor, 1); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + stb_textedit_delete(str, state, state->cursor-1, 1); + --state->cursor; + } + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + + + case STB_TEXTEDIT_K_LINESTART: { + StbFindState find; + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + state->cursor = find.first_char; + state->has_preferred_x = 0; + break; + } + + case STB_TEXTEDIT_K_LINEEND: { + StbFindState find; + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + state->cursor = find.first_char + find.length; + state->has_preferred_x = 0; + break; + } + + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + state->cursor = state->select_end = find.first_char; + state->has_preferred_x = 0; + break; + } + + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + state->cursor = state->select_end = find.first_char + find.length; + state->has_preferred_x = 0; + break; + } + +// @TODO: +// STB_TEXTEDIT_K_PGUP - move cursor up a page +// STB_TEXTEDIT_K_PGDOWN - move cursor down a page + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 + memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it + } + --state->undo_point; + memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // delete n characters from all other records + state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 + memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 + } + ++state->redo_point; + memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't undo + if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to make room + while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (short) insert_len; + r->delete_length = (short) delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point = state->undo_char_point + (short) insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo record + u = s->undo_rec[s->undo_point-1]; + r = &s->undo_rec[s->redo_point-1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo record will + // need to re-insert the characters that get deleted, so we need to store + // them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters eventually + while (s->undo_char_point + u.delete_length > s->redo_char_point) { + // there's currently not enough room, so discard a redo record + stb_textedit_discard_redo(s); + // should never happen: + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + } + r = &s->undo_rec[s->redo_point-1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = s->redo_char_point - (short) u.delete_length; + + // now save the characters + for (i=0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo record + // was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo record + // needs to store the characters + + if (s->undo_char_point + u->insert_length > s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = s->undo_char_point + u->insert_length; + + // now save the characters + for (i=0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + } + + state->cursor = r.where + r.insert_length; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i=0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); + if (p) { + for (i=0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char) is_single_line; + state->insert_mode = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} +#endif//STB_TEXTEDIT_IMPLEMENTATION diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 60cafd577a..fc62d7b93c 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -259,14 +259,10 @@ void GUI::startFrame(float deltaTime, ImGui::NewFrame(); } -void GUI::endFrame() -{ +void GUI::endFrame() { static bool show = true; - //if (show) { ImGui::ShowTestWindow(&show); - //} - ImGui::Render(); } From 8719f98a2315a9e3483ba05dd445dd8ef8cc449f Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:18:05 +0100 Subject: [PATCH 05/14] Allow access to minimum/maximum values of NumericalPropertys --- include/openspace/properties/numericalproperty.h | 3 +++ include/openspace/properties/numericalproperty.inl | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/include/openspace/properties/numericalproperty.h b/include/openspace/properties/numericalproperty.h index 45d15f9d03..5f97c23fcb 100644 --- a/include/openspace/properties/numericalproperty.h +++ b/include/openspace/properties/numericalproperty.h @@ -42,6 +42,9 @@ public: bool setLua(lua_State* state) override; int typeLua() const override; + T minValue() const; + T maxValue() const; + virtual std::string className() const override; using TemplateProperty::operator=; diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index 30ee9ea0d3..be04323787 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -200,5 +200,15 @@ int NumericalProperty::typeLua() const { } +template +T NumericalProperty::minValue() const { + return _minimumValue; +} + +template +T NumericalProperty::maxValue() const { + return _maximumValue; +} + } // namespace properties } // namespace openspace From 9a9c0c0237a9d2e0d1272d8547e84fab4ab72627 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:18:49 +0100 Subject: [PATCH 06/14] Give PropertyOwner a field to remember its owner --- include/openspace/properties/propertyowner.h | 11 +++++++++++ src/properties/propertyowner.cpp | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/include/openspace/properties/propertyowner.h b/include/openspace/properties/propertyowner.h index ad7f136d92..ee747fc174 100644 --- a/include/openspace/properties/propertyowner.h +++ b/include/openspace/properties/propertyowner.h @@ -84,6 +84,12 @@ public: */ const std::vector& properties() const; + /** + * Returns a list of all Propertys directly or indirectly owned by this PropertyOwner. + * \return A list of all Propertys directly or indirectly owned by this PropertyOwner + */ + std::vector propertiesRecursive() const; + /** * Retrieves a Property identified by URI from this PropertyOwner. If * id does not contain a . the identifier must refer to a @@ -108,6 +114,9 @@ public: */ bool hasProperty(const std::string& URI) const; + void setPropertyOwner(PropertyOwner* owner) { _owner = owner; } + PropertyOwner* owner() const { return _owner; } + /** * Returns a list of all sub-owners this PropertyOwner has. Each name of a sub-owner * has to be unique with respect to other sub-owners as well as Property's owned by @@ -201,6 +210,8 @@ protected: private: /// The name of this PropertyOwner std::string _name; + /// The owner of this PropertyOwner + PropertyOwner* _owner; /// A list of all registered Property's std::vector _properties; /// A list of all sub-owners diff --git a/src/properties/propertyowner.cpp b/src/properties/propertyowner.cpp index f2cefb6dac..f6f533cfc4 100644 --- a/src/properties/propertyowner.cpp +++ b/src/properties/propertyowner.cpp @@ -46,6 +46,7 @@ bool subOwnerLess(PropertyOwner* lhs, PropertyOwner* rhs) { PropertyOwner::PropertyOwner() : _name("") + , _owner(nullptr) { } @@ -60,6 +61,18 @@ const std::vector& PropertyOwner::properties() const return _properties; } +std::vector PropertyOwner::propertiesRecursive() const +{ + std::vector props = properties(); + + for (auto owner : _subOwners) { + std::vector p = owner->propertiesRecursive(); + props.insert(props.end(), p.begin(), p.end()); + } + + return std::move(props); +} + Property* PropertyOwner::property(const std::string& id) const { assert(std::is_sorted(_properties.begin(), _properties.end(), propertyLess)); @@ -218,6 +231,7 @@ void PropertyOwner::addPropertySubOwner(openspace::properties::PropertyOwner* ow else { // Otherwise we have found the correct position to add it in _subOwners.insert(it, owner); + owner->setPropertyOwner(this); } } From 4e65aaafe2cef535283018b79d27cb6acf479848 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:19:25 +0100 Subject: [PATCH 07/14] Add method to get fully qualified id to Propertys --- include/openspace/properties/property.h | 11 ++++++++++- src/properties/property.cpp | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index 9b042bbed7..1d5506f9a9 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -167,6 +167,15 @@ public: * \return The unique identifier of this Property */ const std::string& identifier() const; + + /** + * Returns the fully qualified name for this Property that uniquely identifies this + * Property within OpenSpace. It consists of the identifier preceded by + * all levels of PropertyOwner%s separated with .; for example: + * owner1.owner2.identifier. + * \return The fully qualified identifier for this Property + */ + std::string fullyQualifiedIdentifier() const; /** * Returns the PropertyOwner of this Property or nullptr, if it does not @@ -189,7 +198,7 @@ public: * key. * \return The human-readable GUI name for this Property */ - const std::string& guiName() const; + std::string guiName() const; /** * Sets the identifier of the group that this Property belongs to. Property groups can diff --git a/src/properties/property.cpp b/src/properties/property.cpp index 81347f43bd..d634887101 100644 --- a/src/properties/property.cpp +++ b/src/properties/property.cpp @@ -22,7 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "openspace/properties/property.h" +#include + +#include #include @@ -63,6 +65,17 @@ const std::string& Property::identifier() const { return _identifier; } +std::string Property::fullyQualifiedIdentifier() const { + std::string identifier = _identifier; + PropertyOwner* currentOwner = owner(); + while (currentOwner) { + std::string ownerId = currentOwner->name(); + identifier = ownerId + "." + identifier; + currentOwner = currentOwner->owner(); + } + return identifier; +} + boost::any Property::get() const { return boost::any(); } @@ -85,7 +98,7 @@ int Property::typeLua() const { return LUA_TNONE; } -const std::string& Property::guiName() const { +std::string Property::guiName() const { std::string result; _metaData.getValue(_metaDataKeyGuiName, result); return std::move(result); From afa2d4d6a94fd11caa4ba56112b2a42b72f5d014 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:20:59 +0100 Subject: [PATCH 08/14] More work on GUI elements Create GUI for some Properties --- include/openspace/engine/gui.h | 27 +- include/openspace/engine/openspaceengine.h | 2 + shaders/gui_fs.glsl | 34 ++ shaders/gui_vs.glsl | 40 ++ src/engine/gui.cpp | 375 ++++++++++++------ src/engine/openspaceengine.cpp | 11 +- .../planets/simplespheregeometry.cpp | 2 +- src/scenegraph/scenegraph.cpp | 9 + 8 files changed, 382 insertions(+), 118 deletions(-) create mode 100644 shaders/gui_fs.glsl create mode 100644 shaders/gui_vs.glsl diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h index 8a0908750e..673cc9b519 100644 --- a/include/openspace/engine/gui.h +++ b/include/openspace/engine/gui.h @@ -26,25 +26,48 @@ #define __GUI_H__ #include + +#include +#include #include +#include namespace openspace { +namespace properties { + class Property; +} + class GUI { public: - GUI(const glm::vec2& windowSize); + GUI(); ~GUI(); void initializeGL(); void deinitializeGL(); + void registerProperty(properties::Property* prop); + bool mouseButtonCallback(int key, int action); bool mouseWheelCallback(int position); bool keyCallback(int key, int action); bool charCallback(unsigned int character); - void startFrame(float deltaTime, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); + void startFrame(float deltaTime, const glm::vec2& windowSize, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); void endFrame(); + +private: + void renderGuiElements(); + + std::set _boolProperties; + std::set _intProperties; + std::set _floatProperties; + std::set _vec2Properties; + std::set _vec3Properties; + std::set _stringProperties; + std::set _optionProperty; + + std::map> _propertiesByOwner; }; } // namespace openspace diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 83742438c1..6699477ff1 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -59,6 +59,8 @@ public: scripting::ScriptEngine& scriptEngine(); LuaConsole& console(); + GUI* gui() { return _gui; } + // SGCT callbacks bool initializeGL(); void preSynchronization(); diff --git a/shaders/gui_fs.glsl b/shaders/gui_fs.glsl new file mode 100644 index 0000000000..169aa1f0f5 --- /dev/null +++ b/shaders/gui_fs.glsl @@ -0,0 +1,34 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#version __CONTEXT__ + +uniform sampler2D tex; + +layout(location = 1) in vec2 in_uv; +layout(location = 2) in vec4 in_color; +layout(location = 0) out vec4 FragColor; +void main() { + FragColor = in_color * texture(tex, in_uv.st); +} \ No newline at end of file diff --git a/shaders/gui_vs.glsl b/shaders/gui_vs.glsl new file mode 100644 index 0000000000..12a084717a --- /dev/null +++ b/shaders/gui_vs.glsl @@ -0,0 +1,40 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#version __CONTEXT__ + +uniform mat4 ortho; + +layout(location = 0) in vec2 in_position; +layout(location = 1) in vec2 in_uv; +layout(location = 2) in vec4 in_color; + +layout(location = 1) out vec2 out_uv; +layout(location = 2) out vec4 out_color; + +void main() { + out_uv = in_uv; + out_color = in_color; + gl_Position = ortho * vec4(in_position.xy, 0.0, 1.0); +} \ No newline at end of file diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index fc62d7b93c..53de479cc5 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -24,9 +24,18 @@ #include -#include +#include + #include +#include +#include #include +#include + +#include +#include +#include +#include #include #include @@ -37,24 +46,18 @@ namespace { const std::string _loggerCat = "GUI"; GLuint fontTex = 0; - GLint shader_handle = 0; - GLint vert_handle = 0; - GLint frag_handle = 0; - GLint texture_location = 0; - GLint position_location = 0; - GLint uv_location = 0; - GLint colour_location = 0; - GLint ortho_location = 0; - GLuint vbo_handle = 0; - size_t vbo_max_size = 20000; - GLuint vao_handle; + GLint positionLocation = 0; + GLint uvLocation = 0; + GLint colorLocation = 0; + size_t vboMaxSize = 20000; + GLuint vao = 0; + GLuint vbo = 0; - ghoul::opengl::Texture* _texture; + ghoul::opengl::ProgramObject* _program; - -static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) { - if (cmd_lists_count == 0) +static void ImImpl_RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) { + if (nCommandLists == 0) return; // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled @@ -65,33 +68,31 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); - // Setup texture - glActiveTexture(GL_TEXTURE0); + ghoul::opengl::TextureUnit unit; + unit.activate(); glBindTexture(GL_TEXTURE_2D, fontTex); // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; - const float ortho_projection[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 }, - }; - glUseProgram(shader_handle); - glUniform1i(texture_location, 0); - glUniformMatrix4fv(ortho_location, 1, GL_FALSE, &ortho_projection[0][0]); + static const glm::mat4 ortho( + 2.f/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 + ); + _program->activate(); + _program->setUniform("tex", unit.glEnum()); + _program->setUniform("ortho", ortho); // Grow our buffer according to what we need size_t total_vtx_count = 0; - for (int n = 0; n < cmd_lists_count; n++) - total_vtx_count += cmd_lists[n]->vtx_buffer.size(); - glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); + for (int n = 0; n < nCommandLists; n++) + total_vtx_count += commandLists[n]->vtx_buffer.size(); + glBindBuffer(GL_ARRAY_BUFFER, vbo); size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert); - if (neededBufferSize > vbo_max_size) - { - vbo_max_size = neededBufferSize + 5000; // Grow buffer + if (neededBufferSize > vboMaxSize) { + vboMaxSize = neededBufferSize + 5000; // Grow buffer glBufferData(GL_ARRAY_BUFFER, neededBufferSize, NULL, GL_STREAM_DRAW); } @@ -99,34 +100,30 @@ 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; - for (int n = 0; n < cmd_lists_count; n++) - { - const ImDrawList* cmd_list = cmd_lists[n]; + for (int n = 0; n < nCommandLists; ++n) { + const ImDrawList* cmd_list = commandLists[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); glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(vao_handle); + glBindVertexArray(vao); int cmd_offset = 0; - for (int n = 0; n < cmd_lists_count; n++) - { - const ImDrawList* cmd_list = cmd_lists[n]; + for (int n = 0; n < nCommandLists; ++n) { + const ImDrawList* cmd_list = commandLists[n]; int vtx_offset = cmd_offset; 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)(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; + for (auto pcmd : cmd_list->commands) { + 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; } cmd_offset = vtx_offset; } - // Restore modified state glBindVertexArray(0); - glUseProgram(0); + _program->deactivate(); glDisable(GL_SCISSOR_TEST); glBindTexture(GL_TEXTURE_2D, 0); } @@ -134,9 +131,8 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c namespace openspace { -GUI::GUI(const glm::vec2& windowSize) { +GUI::GUI() { ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize = ImVec2(windowSize.x, windowSize.y); io.DeltaTime = 1.f / 60.f; io.PixelCenterOffset = 0.5f; io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. @@ -167,48 +163,12 @@ GUI::~GUI() { } void GUI::initializeGL() { - const GLchar *vertex_shader = - "#version 330\n" - "uniform mat4 ortho;\n" - "in vec2 Position;\n" - "in vec2 UV;\n" - "in vec4 Colour;\n" - "out vec2 Frag_UV;\n" - "out vec4 Frag_Colour;\n" - "void main()\n" - "{\n" - " Frag_UV = UV;\n" - " Frag_Colour = Colour;\n" - " gl_Position = ortho*vec4(Position.xy,0,1);\n" - "}\n"; - - const GLchar* fragment_shader = - "#version 330\n" - "uniform sampler2D Texture;\n" - "in vec2 Frag_UV;\n" - "in vec4 Frag_Colour;\n" - "out vec4 FragColor;\n" - "void main()\n" - "{\n" - " FragColor = Frag_Colour * texture( Texture, Frag_UV.st);\n" - "}\n"; - - shader_handle = glCreateProgram(); - vert_handle = glCreateShader(GL_VERTEX_SHADER); - frag_handle = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(vert_handle, 1, &vertex_shader, 0); - glShaderSource(frag_handle, 1, &fragment_shader, 0); - glCompileShader(vert_handle); - glCompileShader(frag_handle); - glAttachShader(shader_handle, vert_handle); - glAttachShader(shader_handle, frag_handle); - glLinkProgram(shader_handle); - - texture_location = glGetUniformLocation(shader_handle, "Texture"); - ortho_location = glGetUniformLocation(shader_handle, "ortho"); - position_location = glGetAttribLocation(shader_handle, "Position"); - uv_location = glGetAttribLocation(shader_handle, "UV"); - colour_location = glGetAttribLocation(shader_handle, "Colour"); + _program = ghoul::opengl::ProgramObject::Build("GUI", + "${SHADERS}/gui_vs.glsl", "${SHADERS}/gui_fs.glsl"); + + positionLocation = glGetAttribLocation(*_program, "in_position"); + uvLocation = glGetAttribLocation(*_program, "in_uv"); + colorLocation = glGetAttribLocation(*_program, "in_color"); glGenTextures(1, &fontTex); glBindTexture(GL_TEXTURE_2D, fontTex); @@ -222,35 +182,39 @@ void GUI::initializeGL() { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); stbi_image_free(tex_data); - glGenBuffers(1, &vbo_handle); - glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); - glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW); + glGenBuffers(1, &vbo); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_DYNAMIC_DRAW); - glGenVertexArrays(1, &vao_handle); - glBindVertexArray(vao_handle); - glBindBuffer(GL_ARRAY_BUFFER, vbo_handle); - glEnableVertexAttribArray(position_location); - glEnableVertexAttribArray(uv_location); - glEnableVertexAttribArray(colour_location); + glGenVertexArrays(1, &vao); + glBindVertexArray(vao); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glEnableVertexAttribArray(positionLocation); + glEnableVertexAttribArray(uvLocation); + glEnableVertexAttribArray(colorLocation); - glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos)); - glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv)); - glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col)); + glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos)); + glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv)); + glVertexAttribPointer(colorLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col)); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void GUI::deinitializeGL() { - if (vao_handle) glDeleteVertexArrays(1, &vao_handle); - if (vbo_handle) glDeleteBuffers(1, &vbo_handle); - glDeleteProgram(shader_handle); + delete _program; + _program = nullptr; + + if (vao) glDeleteVertexArrays(1, &vao); + if (vbo) glDeleteBuffers(1, &vbo); } void GUI::startFrame(float deltaTime, + const glm::vec2& windowSize, const glm::vec2& mousePos, bool mouseButtonsPressed[2]) { ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(windowSize.x, windowSize.y); io.DeltaTime = deltaTime; io.MousePos = ImVec2(mousePos.x, mousePos.y); io.MouseDown[0] = mouseButtonsPressed[0]; @@ -260,9 +224,11 @@ void GUI::startFrame(float deltaTime, } void GUI::endFrame() { - static bool show = true; - ImGui::ShowTestWindow(&show); + //ImGui::ShowTestWindow(&show); + + renderGuiElements(); + ImGui::Render(); } @@ -297,11 +263,198 @@ bool GUI::charCallback(unsigned int character) { ImGuiIO& io = ImGui::GetIO(); bool consumeEvent = io.WantCaptureKeyboard; - if (consumeEvent) { + if (consumeEvent) io.AddInputCharacter((unsigned short)character); - } return consumeEvent; } +void GUI::registerProperty(properties::Property* prop) { + using namespace properties; + + std::string className = prop->className(); + + if (className == "BoolProperty") + _boolProperties.insert(prop); + else if (className == "IntProperty") + _intProperties.insert(prop); + else if (className == "FloatProperty") + _floatProperties.insert(prop); + else if (className == "StringProperty") + _stringProperties.insert(prop); + else if (className == "Vec2Property") + _vec2Properties.insert(prop); + else if (className == "Vec3Property") + _vec3Properties.insert(prop); + else if (className == "OptionProperty") + _optionProperty.insert(prop); + else { + LWARNING("Class name '" << className << "' not handled in GUI generation"); + return; + } + + std::string fullyQualifiedId = prop->fullyQualifiedIdentifier(); + size_t pos = fullyQualifiedId.find('.'); + std::string owner = fullyQualifiedId.substr(0, pos); + + auto it =_propertiesByOwner.find(owner); + if (it == _propertiesByOwner.end()) + _propertiesByOwner[owner] = { prop }; + else + it->second.push_back(prop); + +} + +void renderBoolProperty(properties::Property* prop) { + properties::BoolProperty* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + //std::string name = p->guiName(); + + properties::BoolProperty::ValueType value = *p; + ImGui::Checkbox(name.c_str(), &value); + p->set(value); +} + +void renderOptionProperty(properties::Property* prop) { + properties::OptionProperty* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + + int value = *p; + std::vector options = p->options(); + for (auto o : options) { + ImGui::RadioButton(name.c_str(), &value, o.value); + ImGui::SameLine(); + ImGui::Text(o.description.c_str()); + } + p->set(value); +} + +void renderIntProperty(properties::Property* prop) { + properties::IntProperty* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + //std::string name = p->guiName(); + + properties::IntProperty::ValueType value = *p; + ImGui::SliderInt(name.c_str(), &value, p->minValue(), p->maxValue()); + p->set(value); +} + +void renderFloatProperty(properties::Property* prop) { + properties::FloatProperty* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + //std::string name = p->guiName(); + + properties::FloatProperty::ValueType value = *p; + ImGui::SliderFloat(name.c_str(), &value, p->minValue(), p->maxValue()); + p->set(value); +} + +void renderVec2Property(properties::Property* prop) { + properties::Vec2Property* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + //std::string name = p->guiName(); + + properties::Vec2Property::ValueType value = *p; + + ImGui::SliderFloat2(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); + p->set(value); +} + + +void renderVec3Property(properties::Property* prop) { + properties::Vec3Property* p = static_cast(prop); + std::string name = p->fullyQualifiedIdentifier(); + //std::string name = p->guiName(); + + properties::Vec3Property::ValueType value = *p; + + ImGui::SliderFloat3(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); + p->set(value); +} + + +void GUI::renderGuiElements() { + using namespace properties; + + ImGui::Begin("Properties"); + + for (auto p : _propertiesByOwner) { + if (ImGui::CollapsingHeader(p.first.c_str())) { + for (auto prop : p.second) { + if (_boolProperties.find(prop) != _boolProperties.end()) { + renderBoolProperty(prop); + continue; + } + + if (_intProperties.find(prop) != _intProperties.end()) { + renderIntProperty(prop); + continue; + } + + if (_floatProperties.find(prop) != _floatProperties.end()) { + renderFloatProperty(prop); + continue; + } + + if (_vec2Properties.find(prop) != _vec2Properties.end()) { + renderVec2Property(prop); + continue; + } + + if (_vec3Properties.find(prop) != _vec3Properties.end()) { + renderVec3Property(prop); + continue; + } + + if (_optionProperty.find(prop) != _optionProperty.end()) { + renderOptionProperty(prop); + continue; + } + + } + } + } + + + //for (auto pair : _propertiesByOwner) { + // auto p = _propertiesByOwner.equal_range(pair); + + // if (ImGui::CollapsingHeader(pair->first.c_str())) { + // for () + // if (_boolProperties.find(p->second) != _boolProperties.end()) { + + // } + // } + //} + + //for (auto prop : _boolProperties) { + // BoolProperty* p = static_cast(prop); + // std::string name = p->fullyQualifiedIdentifier(); + + // BoolProperty::ValueType value = *p; + // ImGui::Checkbox(name.c_str(), &value); + // p->set(value); + + //} + + //for (auto prop : _intProperties) { + // IntProperty* p = static_cast(prop); + // std::string name = p->fullyQualifiedIdentifier(); + + // IntProperty::ValueType value = *p; + // ImGui::SliderInt(name.c_str(), &value, p->minValue(), p->maxValue()); + // p->set(value); + //} + + //for (auto prop : _StringProperties) { + // StringProperty* p = static_cast(prop); + // std::string name = p->fullyQualifiedIdentifier(); + + // //ImGui::TextUnformatted() + //} + + ImGui::End(); + +} + } // namespace openspace diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index fa61d4731b..8db152ce25 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -451,6 +451,8 @@ bool OpenSpaceEngine::initialize() { // Load a light and a monospaced font loadFonts(); + _gui = new GUI; + return true; } @@ -476,9 +478,6 @@ LuaConsole& OpenSpaceEngine::console() { bool OpenSpaceEngine::initializeGL() { bool success = _renderEngine.initializeGL(); - int x,y; - sgct::Engine::instance()->getWindowPtr(0)->getFinalFBODimensions(x, y); - _gui = new GUI(glm::vec2(glm::ivec2(x,y))); _gui->initializeGL(); return success; @@ -502,12 +501,16 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { double posX, posY; sgct::Engine::instance()->getMousePos(0, &posX, &posY); + int x,y; + sgct::Engine::instance()->getWindowPtr(0)->getFinalFBODimensions(x, y); + + int button0 = sgct::Engine::instance()->getMouseButton(0, 0); int button1 = sgct::Engine::instance()->getMouseButton(0, 1); bool buttons[2] = { button0 != 0, button1 != 0 }; double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); - _gui->startFrame(dt, glm::vec2(posX, posY), buttons); + _gui->startFrame(dt, glm::vec2(glm::ivec2(x,y)), glm::vec2(posX, posY), buttons); } void OpenSpaceEngine::render() { diff --git a/src/rendering/planets/simplespheregeometry.cpp b/src/rendering/planets/simplespheregeometry.cpp index f34de92b95..2169af250a 100644 --- a/src/rendering/planets/simplespheregeometry.cpp +++ b/src/rendering/planets/simplespheregeometry.cpp @@ -44,7 +44,7 @@ SimpleSphereGeometry::SimpleSphereGeometry(const ghoul::Dictionary& dictionary) : PlanetGeometry() , _radius("radius", "Radius", glm::vec2(1.f, 0.f), glm::vec2(-10.f, -20.f), glm::vec2(10.f, 20.f)) - , _segments("segments", "Segments", 20, 1, 1000) + , _segments("segments", "Segments", 20, 1, 50) , _planet(nullptr) { using constants::scenegraphnode::keyName; diff --git a/src/scenegraph/scenegraph.cpp b/src/scenegraph/scenegraph.cpp index 2924a4f3b9..1641adfa92 100644 --- a/src/scenegraph/scenegraph.cpp +++ b/src/scenegraph/scenegraph.cpp @@ -32,6 +32,7 @@ #include #include #include +#include // ghoul includes #include "ghoul/logging/logmanager.h" @@ -459,6 +460,14 @@ bool SceneGraph::loadSceneInternal(const std::string& sceneDescriptionFilePath) glm::mat4 la = glm::lookAt(c->position().vec3(), fn->worldPosition().vec3(), c->lookUpVector()); c->setRotation(la); + + for (auto node : _nodes) { + std::vector&& properties = node->propertiesRecursive(); + for (auto p : properties) { + OsEng.gui()->registerProperty(p); + } + } + return true; } From 7fc33948ca7ce91f9d78ffd43a6bfda005ebcf74 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:51:25 +0100 Subject: [PATCH 09/14] Remove error logging from PowerScaledSphere --- src/engine/openspaceengine.cpp | 2 +- src/util/powerscaledsphere.cpp | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 8db152ce25..76fdee40c4 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -561,7 +561,7 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint) { void OpenSpaceEngine::mouseButtonCallback(int key, int action) { bool isConsumed = _gui->mouseButtonCallback(key, action); - if (isConsumed) + if (isConsumed && action != SGCT_RELEASE) return; _interactionHandler.mouseButtonCallback(key, action); diff --git a/src/util/powerscaledsphere.cpp b/src/util/powerscaledsphere.cpp index bbcca78e4f..3ab86165b2 100644 --- a/src/util/powerscaledsphere.cpp +++ b/src/util/powerscaledsphere.cpp @@ -184,12 +184,6 @@ bool PowerScaledSphere::initialize() glBufferData(GL_ELEMENT_ARRAY_BUFFER, _isize * sizeof(int), _iarray, GL_STATIC_DRAW); glBindVertexArray(0); - - errorID = glGetError(); - if (errorID != GL_NO_ERROR) { - LERROR("OpenGL error: " << glewGetErrorString(errorID)); - return false; - } return true; } From 40415a2eee1b1893a578877e289f02165e8f7d7b Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 17:51:39 +0100 Subject: [PATCH 10/14] Updated GUI names --- src/engine/gui.cpp | 53 +++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 53de479cc5..d1e2f73e92 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -305,70 +305,65 @@ void GUI::registerProperty(properties::Property* prop) { } -void renderBoolProperty(properties::Property* prop) { +void renderBoolProperty(properties::Property* prop, const std::string& ownerName) { properties::BoolProperty* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); - //std::string name = p->guiName(); + std::string name = p->guiName(); properties::BoolProperty::ValueType value = *p; - ImGui::Checkbox(name.c_str(), &value); + ImGui::Checkbox((ownerName + "." + name).c_str(), &value); p->set(value); } -void renderOptionProperty(properties::Property* prop) { +void renderOptionProperty(properties::Property* prop, const std::string& ownerName) { properties::OptionProperty* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); + std::string name = p->guiName(); int value = *p; std::vector options = p->options(); for (auto o : options) { - ImGui::RadioButton(name.c_str(), &value, o.value); + ImGui::RadioButton((ownerName + "." + name).c_str(), &value, o.value); ImGui::SameLine(); ImGui::Text(o.description.c_str()); } p->set(value); } -void renderIntProperty(properties::Property* prop) { +void renderIntProperty(properties::Property* prop, const std::string& ownerName) { properties::IntProperty* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); - //std::string name = p->guiName(); + std::string name = p->guiName(); properties::IntProperty::ValueType value = *p; - ImGui::SliderInt(name.c_str(), &value, p->minValue(), p->maxValue()); + ImGui::SliderInt((ownerName + "." + name).c_str(), &value, p->minValue(), p->maxValue()); p->set(value); } -void renderFloatProperty(properties::Property* prop) { +void renderFloatProperty(properties::Property* prop, const std::string& ownerName) { properties::FloatProperty* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); - //std::string name = p->guiName(); + std::string name = p->guiName(); properties::FloatProperty::ValueType value = *p; - ImGui::SliderFloat(name.c_str(), &value, p->minValue(), p->maxValue()); + ImGui::SliderFloat((ownerName + "." + name).c_str(), &value, p->minValue(), p->maxValue()); p->set(value); } -void renderVec2Property(properties::Property* prop) { +void renderVec2Property(properties::Property* prop, const std::string& ownerName) { properties::Vec2Property* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); - //std::string name = p->guiName(); + std::string name = p->guiName(); properties::Vec2Property::ValueType value = *p; - ImGui::SliderFloat2(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); + ImGui::SliderFloat2((ownerName + "." + name).c_str(), &value.x, p->minValue().x, p->maxValue().x); p->set(value); } -void renderVec3Property(properties::Property* prop) { +void renderVec3Property(properties::Property* prop, const std::string& ownerName) { properties::Vec3Property* p = static_cast(prop); - std::string name = p->fullyQualifiedIdentifier(); - //std::string name = p->guiName(); + std::string name = p->guiName(); properties::Vec3Property::ValueType value = *p; - ImGui::SliderFloat3(name.c_str(), &value.x, p->minValue().x, p->maxValue().x); + ImGui::SliderFloat3((ownerName + "." + name).c_str(), &value.x, p->minValue().x, p->maxValue().x); p->set(value); } @@ -382,32 +377,32 @@ void GUI::renderGuiElements() { if (ImGui::CollapsingHeader(p.first.c_str())) { for (auto prop : p.second) { if (_boolProperties.find(prop) != _boolProperties.end()) { - renderBoolProperty(prop); + renderBoolProperty(prop, p.first); continue; } if (_intProperties.find(prop) != _intProperties.end()) { - renderIntProperty(prop); + renderIntProperty(prop, p.first); continue; } if (_floatProperties.find(prop) != _floatProperties.end()) { - renderFloatProperty(prop); + renderFloatProperty(prop, p.first); continue; } if (_vec2Properties.find(prop) != _vec2Properties.end()) { - renderVec2Property(prop); + renderVec2Property(prop, p.first); continue; } if (_vec3Properties.find(prop) != _vec3Properties.end()) { - renderVec3Property(prop); + renderVec3Property(prop, p.first); continue; } if (_optionProperty.find(prop) != _optionProperty.end()) { - renderOptionProperty(prop); + renderOptionProperty(prop, p.first); continue; } From 2c85d531640a8f25b5a449e2affea58ecd7db673 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 6 Dec 2014 18:33:11 +0100 Subject: [PATCH 11/14] Made GUI optional --- include/openspace/util/constants.h | 1 + openspace.cfg | 33 +++++++------- src/engine/gui.cpp | 24 +++++++++- src/engine/openspaceengine.cpp | 72 +++++++++++++++++------------- 4 files changed, 83 insertions(+), 47 deletions(-) diff --git a/include/openspace/util/constants.h b/include/openspace/util/constants.h index 4bd73d7f2b..9b102f8957 100644 --- a/include/openspace/util/constants.h +++ b/include/openspace/util/constants.h @@ -45,6 +45,7 @@ namespace configurationmanager { const std::string keyLuaDocumentationType = "LuaDocumentationFile.Type"; const std::string keyLuaDocumentationFile = "LuaDocumentationFile.File"; const std::string keyConfigScene = "Scene"; + const std::string keyEnableGui = "EnableGUI"; const std::string keyStartupScript = "StartupScripts"; const std::string keySpiceTimeKernel = "SpiceKernel.Time"; const std::string keySpiceLeapsecondKernel = "SpiceKernel.LeapSecond"; diff --git a/openspace.cfg b/openspace.cfg index 2ad55cefef..0df8a1f236 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -19,22 +19,23 @@ return { Mono = "${FONTS}/Droid_Sans_Mono/DroidSansMono.ttf", Light = "${FONTS}/Roboto/Roboto-Regular.ttf" }, - SGCTConfig = "${SGCT}/single.xml", - --SGCTConfig = "${SGCT}/two_nodes.xml", - --SGCTConfig = "${SGCT}/single_sbs_stereo.xml", - Scene = "${OPENSPACE_DATA}/scene/default.scene", - StartupScripts = { - "${SCRIPTS}/default_startup.lua" - }, - Logging = { + StartupScripts = { + "${SCRIPTS}/default_startup.lua" + }, + Logging = { LogLevel = "Debug", ImmediateFlush = true, - Logs = { - { Type = "HTML", FileName = "${BASE_PATH}/log.html", Append = false } - } - }, - LuaDocumentationFile = { - Type = "text", - File = "${BASE_PATH}/LuaScripting.txt" - } + Logs = { + { Type = "HTML", FileName = "${BASE_PATH}/log.html", Append = false } + } + }, + LuaDocumentationFile = { + Type = "text", + File = "${BASE_PATH}/LuaScripting.txt" + }, + EnableGUI = true, + SGCTConfig = "${SGCT}/single.xml", + --SGCTConfig = "${SGCT}/two_nodes.xml", + --SGCTConfig = "${SGCT}/single_sbs_stereo.xml", + Scene = "${OPENSPACE_DATA}/scene/default.scene", } \ No newline at end of file diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index d1e2f73e92..04eb990885 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -37,6 +37,9 @@ #include #include +#include +#include + #include #include #define STB_IMAGE_IMPLEMENTATION @@ -44,6 +47,7 @@ namespace { const std::string _loggerCat = "GUI"; + const std::string configurationFile = "imgui.ini"; GLuint fontTex = 0; GLint positionLocation = 0; @@ -132,7 +136,11 @@ static void ImImpl_RenderDrawLists(ImDrawList** const commandLists, int nCommand namespace openspace { GUI::GUI() { + std::string cachedFile; + FileSys.cacheManager()->getCachedFile(configurationFile, "", cachedFile, true); + ImGuiIO& io = ImGui::GetIO(); + io.IniFilename = cachedFile.c_str(); io.DeltaTime = 1.f / 60.f; io.PixelCenterOffset = 0.5f; io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. @@ -371,7 +379,21 @@ void renderVec3Property(properties::Property* prop, const std::string& ownerName void GUI::renderGuiElements() { using namespace properties; - ImGui::Begin("Properties"); + const ImVec2 size = ImVec2(350, 500); + + ImGui::Begin("Properties", nullptr, size, 0.5f); + + ImGuiIO& io = ImGui::GetIO(); + ImVec2 displaySize = io.DisplaySize; + + ImVec2 position; + position.x = displaySize.x - (size.x + 50); + position.y = 50; + ImGui::SetWindowPos(position); + + + //ImGui::ShowUserGuide(); + ImGui::Spacing(); for (auto p : _propertiesByOwner) { if (ImGui::CollapsingHeader(p.first.c_str())) { diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 76fdee40c4..aeb456efd1 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -113,7 +113,6 @@ void OpenSpaceEngine::clearAllWindows() { GLFWwindow* win = sgct::Engine::instance()->getWindowPtr(i)->getWindowHandle(); glfwSwapBuffers(win); } - } bool OpenSpaceEngine::gatherCommandlineArguments() { @@ -437,10 +436,6 @@ bool OpenSpaceEngine::initialize() { if (success) sceneGraph->scheduleLoadSceneFile(sceneDescriptionPath); - // Initialize OpenSpace input devices - //DeviceIdentifier::init(); - //DeviceIdentifier::ref().scanDevices(); - _interactionHandler.setKeyboardController(new interaction::KeyboardControllerFixed); //_interactionHandler.setKeyboardController(new interaction::KeyboardControllerLua); _interactionHandler.setMouseController(new interaction::TrackballMouseController); @@ -451,7 +446,12 @@ bool OpenSpaceEngine::initialize() { // Load a light and a monospaced font loadFonts(); - _gui = new GUI; + using constants::configurationmanager::keyEnableGui; + bool enableGUI = false; + configurationManager().getValue(keyEnableGui, enableGUI); + if (enableGUI) { + _gui = new GUI; + } return true; } @@ -478,7 +478,8 @@ LuaConsole& OpenSpaceEngine::console() { bool OpenSpaceEngine::initializeGL() { bool success = _renderEngine.initializeGL(); - _gui->initializeGL(); + if (_gui) + _gui->initializeGL(); return success; } @@ -498,19 +499,20 @@ void OpenSpaceEngine::preSynchronization() { void OpenSpaceEngine::postSynchronizationPreDraw() { _renderEngine.postSynchronizationPreDraw(); - double posX, posY; - sgct::Engine::instance()->getMousePos(0, &posX, &posY); + if (_gui) { + double posX, posY; + sgct::Engine::instance()->getMousePos(0, &posX, &posY); - int x,y; - sgct::Engine::instance()->getWindowPtr(0)->getFinalFBODimensions(x, y); + int x,y; + sgct::Engine::instance()->getWindowPtr(0)->getFinalFBODimensions(x, y); + int button0 = sgct::Engine::instance()->getMouseButton(0, 0); + int button1 = sgct::Engine::instance()->getMouseButton(0, 1); + bool buttons[2] = { button0 != 0, button1 != 0 }; - int button0 = sgct::Engine::instance()->getMouseButton(0, 0); - int button1 = sgct::Engine::instance()->getMouseButton(0, 1); - bool buttons[2] = { button0 != 0, button1 != 0 }; - - double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); - _gui->startFrame(dt, glm::vec2(glm::ivec2(x,y)), glm::vec2(posX, posY), buttons); + double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); + _gui->startFrame(dt, glm::vec2(glm::ivec2(x,y)), glm::vec2(posX, posY), buttons); + } } void OpenSpaceEngine::render() { @@ -521,7 +523,9 @@ void OpenSpaceEngine::render() { if (sgct::Engine::instance()->isMaster() && !w->isUsingFisheyeRendering() && _console.isVisible()) { _console.render(); } - _gui->endFrame(); + + if (_gui) + _gui->endFrame(); } void OpenSpaceEngine::postDraw() { @@ -533,9 +537,11 @@ void OpenSpaceEngine::postDraw() { void OpenSpaceEngine::keyboardCallback(int key, int action) { if (sgct::Engine::instance()->isMaster()) { - bool isConsumed = _gui->keyCallback(key, action); - if (isConsumed) - return; + if (_gui) { + bool isConsumed = _gui->keyCallback(key, action); + if (isConsumed) + return; + } if (key == _console.commandInputButton() && (action == SGCT_PRESS || action == SGCT_REPEAT)) _console.toggleVisibility(); @@ -550,9 +556,11 @@ void OpenSpaceEngine::keyboardCallback(int key, int action) { } void OpenSpaceEngine::charCallback(unsigned int codepoint) { - bool isConsumed = _gui->charCallback(codepoint); - if (isConsumed) - return; + if (_gui) { + bool isConsumed = _gui->charCallback(codepoint); + if (isConsumed) + return; + } if (_console.isVisible()) { _console.charCallback(codepoint); @@ -560,9 +568,11 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint) { } void OpenSpaceEngine::mouseButtonCallback(int key, int action) { - bool isConsumed = _gui->mouseButtonCallback(key, action); - if (isConsumed && action != SGCT_RELEASE) - return; + if (_gui) { + bool isConsumed = _gui->mouseButtonCallback(key, action); + if (isConsumed && action != SGCT_RELEASE) + return; + } _interactionHandler.mouseButtonCallback(key, action); } @@ -572,9 +582,11 @@ void OpenSpaceEngine::mousePositionCallback(int x, int y) { } void OpenSpaceEngine::mouseScrollWheelCallback(int pos) { - bool isConsumed = _gui->mouseWheelCallback(pos); - if (isConsumed) - return; + if (_gui) { + bool isConsumed = _gui->mouseWheelCallback(pos); + if (isConsumed) + return; + } _interactionHandler.mouseScrollWheelCallback(pos); } From 9cd435f3e3ddf2af052e31fcf38a04d2f5337522 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sun, 7 Dec 2014 00:39:16 +0100 Subject: [PATCH 12/14] Fix imgui configuration definition --- include/openspace/engine/gui.h | 2 +- src/engine/gui.cpp | 23 ++++++++--------------- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h index 673cc9b519..aeaacfe8fd 100644 --- a/include/openspace/engine/gui.h +++ b/include/openspace/engine/gui.h @@ -57,7 +57,7 @@ public: void endFrame(); private: - void renderGuiElements(); + void renderPropertyWindow(); std::set _boolProperties; std::set _intProperties; diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 04eb990885..8e524f2925 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -58,7 +58,7 @@ namespace { GLuint vbo = 0; ghoul::opengl::ProgramObject* _program; - + const ImVec2 size = ImVec2(350, 500); static void ImImpl_RenderDrawLists(ImDrawList** const commandLists, int nCommandLists) { if (nCommandLists == 0) @@ -139,8 +139,12 @@ GUI::GUI() { std::string cachedFile; FileSys.cacheManager()->getCachedFile(configurationFile, "", cachedFile, true); + char* buffer = new char[cachedFile.size() + 1]; + strcpy(buffer, cachedFile.c_str()); + ImGuiIO& io = ImGui::GetIO(); - io.IniFilename = cachedFile.c_str(); + io.IniFilename = buffer; + //io.IniSavingRate = 5.f; io.DeltaTime = 1.f / 60.f; io.PixelCenterOffset = 0.5f; io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. @@ -235,7 +239,7 @@ void GUI::endFrame() { static bool show = true; //ImGui::ShowTestWindow(&show); - renderGuiElements(); + renderPropertyWindow(); ImGui::Render(); } @@ -376,22 +380,11 @@ void renderVec3Property(properties::Property* prop, const std::string& ownerName } -void GUI::renderGuiElements() { +void GUI::renderPropertyWindow() { using namespace properties; - const ImVec2 size = ImVec2(350, 500); - ImGui::Begin("Properties", nullptr, size, 0.5f); - ImGuiIO& io = ImGui::GetIO(); - ImVec2 displaySize = io.DisplaySize; - - ImVec2 position; - position.x = displaySize.x - (size.x + 50); - position.y = 50; - ImGui::SetWindowPos(position); - - //ImGui::ShowUserGuide(); ImGui::Spacing(); From 56e1187ee74e50a316ce2e1d771d54c9bd0f9955 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 8 Dec 2014 12:41:31 +0100 Subject: [PATCH 13/14] Always create the GUI element but make it switchable via scripting --- include/openspace/engine/gui.h | 12 ++ include/openspace/engine/openspaceengine.h | 6 +- openspace.cfg | 1 - src/engine/gui.cpp | 134 +++++++++++++++++---- src/engine/openspaceengine.cpp | 90 +++++++------- src/scenegraph/scenegraph.cpp | 2 +- 6 files changed, 175 insertions(+), 70 deletions(-) diff --git a/include/openspace/engine/gui.h b/include/openspace/engine/gui.h index aeaacfe8fd..1df5293589 100644 --- a/include/openspace/engine/gui.h +++ b/include/openspace/engine/gui.h @@ -25,6 +25,8 @@ #ifndef __GUI_H__ #define __GUI_H__ +#include + #include #include @@ -43,6 +45,11 @@ public: GUI(); ~GUI(); + bool isEnabled() const; + void setEnabled(bool enabled); + + void initialize(); + void initializeGL(); void deinitializeGL(); @@ -56,9 +63,14 @@ public: void startFrame(float deltaTime, const glm::vec2& windowSize, const glm::vec2& mousePos, bool mouseButtonsPressed[2]); void endFrame(); + + static scripting::ScriptEngine::LuaLibrary luaLibrary(); + private: void renderPropertyWindow(); + bool _isEnabled; + std::set _boolProperties; std::set _intProperties; std::set _floatProperties; diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 6699477ff1..a0b38eb422 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -29,7 +29,7 @@ #include #include #include - +#include #include namespace openspace { @@ -59,7 +59,7 @@ public: scripting::ScriptEngine& scriptEngine(); LuaConsole& console(); - GUI* gui() { return _gui; } + GUI& gui(); // SGCT callbacks bool initializeGL(); @@ -97,7 +97,7 @@ private: scripting::ScriptEngine _scriptEngine; ghoul::cmdparser::CommandlineParser _commandlineParser; LuaConsole _console; - GUI* _gui; + GUI _gui; SyncBuffer* _syncBuffer; diff --git a/openspace.cfg b/openspace.cfg index 0df8a1f236..3d29b863fc 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -33,7 +33,6 @@ return { Type = "text", File = "${BASE_PATH}/LuaScripting.txt" }, - EnableGUI = true, SGCTConfig = "${SGCT}/single.xml", --SGCTConfig = "${SGCT}/two_nodes.xml", --SGCTConfig = "${SGCT}/single_sbs_stereo.xml", diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index 8e524f2925..d1a640f59e 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -24,6 +24,7 @@ #include +#include #include #include @@ -135,7 +136,24 @@ static void ImImpl_RenderDrawLists(ImDrawList** const commandLists, int nCommand namespace openspace { -GUI::GUI() { +GUI::GUI() + : _isEnabled(false) +{ +} + +GUI::~GUI() { + ImGui::Shutdown(); +} + +bool GUI::isEnabled() const { + return _isEnabled; +} + +void GUI::setEnabled(bool enabled) { + _isEnabled = enabled; +} + +void GUI::initialize() { std::string cachedFile; FileSys.cacheManager()->getCachedFile(configurationFile, "", cachedFile, true); @@ -147,31 +165,27 @@ GUI::GUI() { //io.IniSavingRate = 5.f; io.DeltaTime = 1.f / 60.f; io.PixelCenterOffset = 0.5f; - io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. - io.KeyMap[ImGuiKey_LeftArrow] = SGCT_KEY_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = SGCT_KEY_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = SGCT_KEY_UP; - io.KeyMap[ImGuiKey_DownArrow] = SGCT_KEY_DOWN; - io.KeyMap[ImGuiKey_Home] = SGCT_KEY_HOME; - io.KeyMap[ImGuiKey_End] = SGCT_KEY_END; - io.KeyMap[ImGuiKey_Delete] = SGCT_KEY_DELETE; - io.KeyMap[ImGuiKey_Backspace] = SGCT_KEY_BACKSPACE; - io.KeyMap[ImGuiKey_Enter] = SGCT_KEY_ENTER; - io.KeyMap[ImGuiKey_Escape] = SGCT_KEY_ESCAPE; - io.KeyMap[ImGuiKey_A] = SGCT_KEY_A; - io.KeyMap[ImGuiKey_C] = SGCT_KEY_C; - io.KeyMap[ImGuiKey_V] = SGCT_KEY_V; - io.KeyMap[ImGuiKey_X] = SGCT_KEY_X; - io.KeyMap[ImGuiKey_Y] = SGCT_KEY_Y; - io.KeyMap[ImGuiKey_Z] = SGCT_KEY_Z; + io.KeyMap[ImGuiKey_Tab] = SGCT_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. + io.KeyMap[ImGuiKey_LeftArrow] = SGCT_KEY_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = SGCT_KEY_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = SGCT_KEY_UP; + io.KeyMap[ImGuiKey_DownArrow] = SGCT_KEY_DOWN; + io.KeyMap[ImGuiKey_Home] = SGCT_KEY_HOME; + io.KeyMap[ImGuiKey_End] = SGCT_KEY_END; + io.KeyMap[ImGuiKey_Delete] = SGCT_KEY_DELETE; + io.KeyMap[ImGuiKey_Backspace] = SGCT_KEY_BACKSPACE; + io.KeyMap[ImGuiKey_Enter] = SGCT_KEY_ENTER; + io.KeyMap[ImGuiKey_Escape] = SGCT_KEY_ESCAPE; + io.KeyMap[ImGuiKey_A] = SGCT_KEY_A; + io.KeyMap[ImGuiKey_C] = SGCT_KEY_C; + io.KeyMap[ImGuiKey_V] = SGCT_KEY_V; + io.KeyMap[ImGuiKey_X] = SGCT_KEY_X; + io.KeyMap[ImGuiKey_Y] = SGCT_KEY_Y; + io.KeyMap[ImGuiKey_Z] = SGCT_KEY_Z; io.RenderDrawListsFn = ImImpl_RenderDrawLists; - //io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; // @TODO implement? ---abock - //io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // @TODO implement? ---abock -} - -GUI::~GUI() { - ImGui::Shutdown(); + //io.SetClipboardTextFn = ImImpl_SetClipboardTextFn; // @TODO implement? ---abock + //io.GetClipboardTextFn = ImImpl_GetClipboardTextFn; // @TODO implement? ---abock } void GUI::initializeGL() { @@ -467,4 +481,76 @@ void GUI::renderPropertyWindow() { } +namespace { + +/** + * \ingroup LuaScripts + * show(): + * Shows the GUI + */ +int show(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(true); + return 0; +} + +/** + * \ingroup LuaScripts + * hide(): + * Hides the console + */ +int hide(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(false); + return 0; +} + +/** + * \ingroup LuaScripts + * toggle(): + * Toggles the console + */ +int toggle(lua_State* L) { + int nArguments = lua_gettop(L); + if (nArguments != 0) + return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); + + OsEng.gui().setEnabled(!OsEng.gui().isEnabled()); + return 0; +} + +} + +scripting::ScriptEngine::LuaLibrary GUI::luaLibrary() { + return { + "gui", + { + { + "show", + &show, + "", + "Shows the console" + }, + { + "hide", + &hide, + "", + "Hides the console" + }, + { + "toggle", + &toggle, + "", + "Toggles the console" + } + } + }; +} + } // namespace openspace diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index aeb456efd1..4c2b20e998 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include @@ -83,7 +82,6 @@ OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr; OpenSpaceEngine::OpenSpaceEngine(std::string programName) : _commandlineParser(programName, true) - , _gui(nullptr) , _syncBuffer(nullptr) { // initialize OpenSpace helpers @@ -402,6 +400,7 @@ bool OpenSpaceEngine::initialize() { _scriptEngine.addLibrary(Time::luaLibrary()); _scriptEngine.addLibrary(interaction::InteractionHandler::luaLibrary()); _scriptEngine.addLibrary(LuaConsole::luaLibrary()); + _scriptEngine.addLibrary(GUI::luaLibrary()); // TODO: Maybe move all scenegraph and renderengine stuff to initializeGL scriptEngine().initialize(); @@ -446,12 +445,7 @@ bool OpenSpaceEngine::initialize() { // Load a light and a monospaced font loadFonts(); - using constants::configurationmanager::keyEnableGui; - bool enableGUI = false; - configurationManager().getValue(keyEnableGui, enableGUI); - if (enableGUI) { - _gui = new GUI; - } + _gui.initialize(); return true; } @@ -476,10 +470,14 @@ LuaConsole& OpenSpaceEngine::console() { return _console; } +GUI& OpenSpaceEngine::gui() { + return _gui; +} + bool OpenSpaceEngine::initializeGL() { bool success = _renderEngine.initializeGL(); - if (_gui) - _gui->initializeGL(); + if (_gui.isEnabled()) + _gui.initializeGL(); return success; } @@ -499,7 +497,7 @@ void OpenSpaceEngine::preSynchronization() { void OpenSpaceEngine::postSynchronizationPreDraw() { _renderEngine.postSynchronizationPreDraw(); - if (_gui) { + if (sgct::Engine::instance()->isMaster() && _gui.isEnabled()) { double posX, posY; sgct::Engine::instance()->getMousePos(0, &posX, &posY); @@ -511,21 +509,23 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { bool buttons[2] = { button0 != 0, button1 != 0 }; double dt = std::max(sgct::Engine::instance()->getDt(), 1.0/60.0); - _gui->startFrame(dt, glm::vec2(glm::ivec2(x,y)), glm::vec2(posX, posY), buttons); + _gui.startFrame(dt, glm::vec2(glm::ivec2(x,y)), glm::vec2(posX, posY), buttons); } } void OpenSpaceEngine::render() { _renderEngine.render(); - // If currently writing a command, render it to screen - sgct::SGCTWindow* w = sgct::Engine::instance()->getActiveWindowPtr(); - if (sgct::Engine::instance()->isMaster() && !w->isUsingFisheyeRendering() && _console.isVisible()) { - _console.render(); - } + if (sgct::Engine::instance()->isMaster()) { + // If currently writing a command, render it to screen + sgct::SGCTWindow* w = sgct::Engine::instance()->getActiveWindowPtr(); + if (sgct::Engine::instance()->isMaster() && !w->isUsingFisheyeRendering() && _console.isVisible()) { + _console.render(); + } - if (_gui) - _gui->endFrame(); + if (_gui.isEnabled()) + _gui.endFrame(); + } } void OpenSpaceEngine::postDraw() { @@ -537,8 +537,8 @@ void OpenSpaceEngine::postDraw() { void OpenSpaceEngine::keyboardCallback(int key, int action) { if (sgct::Engine::instance()->isMaster()) { - if (_gui) { - bool isConsumed = _gui->keyCallback(key, action); + if (_gui.isEnabled()) { + bool isConsumed = _gui.keyCallback(key, action); if (isConsumed) return; } @@ -556,39 +556,47 @@ void OpenSpaceEngine::keyboardCallback(int key, int action) { } void OpenSpaceEngine::charCallback(unsigned int codepoint) { - if (_gui) { - bool isConsumed = _gui->charCallback(codepoint); - if (isConsumed) - return; - } + if (sgct::Engine::instance()->isMaster()) { + if (_gui.isEnabled()) { + bool isConsumed = _gui.charCallback(codepoint); + if (isConsumed) + return; + } - if (_console.isVisible()) { - _console.charCallback(codepoint); + if (_console.isVisible()) { + _console.charCallback(codepoint); + } } } void OpenSpaceEngine::mouseButtonCallback(int key, int action) { - if (_gui) { - bool isConsumed = _gui->mouseButtonCallback(key, action); - if (isConsumed && action != SGCT_RELEASE) - return; + if (sgct::Engine::instance()->isMaster()) { + if (_gui.isEnabled()) { + bool isConsumed = _gui.mouseButtonCallback(key, action); + if (isConsumed && action != SGCT_RELEASE) + return; + } + + _interactionHandler.mouseButtonCallback(key, action); } - - _interactionHandler.mouseButtonCallback(key, action); } void OpenSpaceEngine::mousePositionCallback(int x, int y) { - _interactionHandler.mousePositionCallback(x, y); + if (sgct::Engine::instance()->isMaster()) { + _interactionHandler.mousePositionCallback(x, y); + } } void OpenSpaceEngine::mouseScrollWheelCallback(int pos) { - if (_gui) { - bool isConsumed = _gui->mouseWheelCallback(pos); - if (isConsumed) - return; - } + if (sgct::Engine::instance()->isMaster()) { + if (_gui.isEnabled()) { + bool isConsumed = _gui.mouseWheelCallback(pos); + if (isConsumed) + return; + } - _interactionHandler.mouseScrollWheelCallback(pos); + _interactionHandler.mouseScrollWheelCallback(pos); + } } void OpenSpaceEngine::encode() { diff --git a/src/scenegraph/scenegraph.cpp b/src/scenegraph/scenegraph.cpp index 1641adfa92..97cca49847 100644 --- a/src/scenegraph/scenegraph.cpp +++ b/src/scenegraph/scenegraph.cpp @@ -464,7 +464,7 @@ bool SceneGraph::loadSceneInternal(const std::string& sceneDescriptionFilePath) for (auto node : _nodes) { std::vector&& properties = node->propertiesRecursive(); for (auto p : properties) { - OsEng.gui()->registerProperty(p); + OsEng.gui().registerProperty(p); } } From 7f8fa6add3fa87d11633d06cf05931db5ca85914 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 8 Dec 2014 12:44:29 +0100 Subject: [PATCH 14/14] Remove warning in Windows --- src/engine/gui.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/engine/gui.cpp b/src/engine/gui.cpp index d1a640f59e..60d47ec66a 100644 --- a/src/engine/gui.cpp +++ b/src/engine/gui.cpp @@ -158,7 +158,12 @@ void GUI::initialize() { FileSys.cacheManager()->getCachedFile(configurationFile, "", cachedFile, true); char* buffer = new char[cachedFile.size() + 1]; + +#ifdef WIN32 + strcpy_s(buffer, cachedFile.size() + 1, cachedFile.c_str()); +#else strcpy(buffer, cachedFile.c_str()); +#endif ImGuiIO& io = ImGui::GetIO(); io.IniFilename = buffer;