├── .gitmodules ├── CMakeLists.txt ├── README.md ├── cubemaps ├── bridge3 │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ ├── posz.jpg │ └── readme.txt ├── coittower2 │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ ├── posz.jpg │ └── readme.txt ├── colors │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ └── posz.jpg ├── powerlines │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ ├── posz.jpg │ └── readme.txt ├── room │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ ├── posz.jpg │ └── readme.txt └── tantolunden2 │ ├── negx.jpg │ ├── negy.jpg │ ├── negz.jpg │ ├── posx.jpg │ ├── posy.jpg │ ├── posz.jpg │ └── readme.txt ├── dog.obj ├── imgui.cpp ├── imgui.h ├── imgui_draw.cpp ├── imgui_impl_glfw_gl3.cpp ├── imgui_impl_glfw_gl3.h ├── imgui_internal.h ├── m_math.h ├── main.cpp ├── result_images ├── dog.jpg └── sphere.jpg ├── s_shader.h ├── sphere.obj ├── stb_image.h ├── stb_rect_pack.h ├── stb_textedit.h ├── stb_truetype.h └── yocto_obj.h /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "glfw"] 2 | path = glfw 3 | url = https://github.com/glfw/glfw.git 4 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | 3 | project(playground) 4 | set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "Build the GLFW example programs") 5 | set(GLFW_BUILD_TESTS OFF CACHE BOOL "Build the GLFW test programs") 6 | set(GLFW_BUILD_DOCS OFF CACHE BOOL "Build the GLFW documentation") 7 | set(GLFW_INSTALL OFF CACHE BOOL "Generate installation target") 8 | add_subdirectory(glfw) 9 | include_directories(${PROJECT_SOURCE_DIR}) 10 | include_directories("glfw/deps") # for glad 11 | include_directories("glfw/include") 12 | add_executable(${PROJECT_NAME} main.cpp glfw/deps/glad.c) 13 | if (MSVC) 14 | add_definitions( "-D _CRT_SECURE_NO_WARNINGS" ) 15 | endif() 16 | #if (UNIX) 17 | # add_definitions( "-std=c99" ) 18 | #endif() 19 | target_link_libraries(${PROJECT_NAME} glfw ${GLFW_LIBRARIES}) 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spherical Harmonics Playground 2 | 3 | This is a simple application that loads an OBJ file and an environment map and calculates & displays the corresponding 3rd order spherical harmonics coefficients for it. 4 | The coefficients can also be modified at runtime to see the effect of each coefficient. 5 | 6 | 7 | Here is a dog statue (that I attempted to scan a few years ago) in a room environment: 8 | ![dog statue in room environment](https://github.com/ands/spherical_harmonics_playground/raw/master/result_images/dog.jpg) 9 | 10 | 11 | And here is a simple sphere in an outdoor environment: 12 | ![sphere in outdoor environment](https://github.com/ands/spherical_harmonics_playground/raw/master/result_images/sphere.jpg) 13 | 14 | 15 | Linux dependencies for glfw: xorg-dev libgl1-mesa-dev 16 | ``` 17 | git clone --recursive https://github.com/ands/spherical_harmonics_playground.git 18 | cd spherical_harmonics_playground 19 | cmake . 20 | make 21 | ./playground 22 | ``` 23 | 24 | dickyjim has collected various resources regarding spherical harmonics on his [blog](https://dickyjim.wordpress.com/2013/09/04/spherical-harmonics-for-beginners/). -------------------------------------------------------------------------------- /cubemaps/bridge3/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/negx.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/negy.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/negz.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/posx.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/posy.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/bridge3/posz.jpg -------------------------------------------------------------------------------- /cubemaps/bridge3/readme.txt: -------------------------------------------------------------------------------- 1 | Author 2 | ====== 3 | 4 | This is the work of Emil Persson, aka Humus. 5 | http://www.humus.name 6 | 7 | 8 | 9 | License 10 | ======= 11 | 12 | This work is licensed under a Creative Commons Attribution 3.0 Unported License. 13 | http://creativecommons.org/licenses/by/3.0/ 14 | -------------------------------------------------------------------------------- /cubemaps/coittower2/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/negx.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/negy.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/negz.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/posx.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/posy.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/coittower2/posz.jpg -------------------------------------------------------------------------------- /cubemaps/coittower2/readme.txt: -------------------------------------------------------------------------------- 1 | Author 2 | ====== 3 | 4 | This is the work of Emil Persson, aka Humus. 5 | http://www.humus.name 6 | 7 | 8 | 9 | License 10 | ======= 11 | 12 | This work is licensed under a Creative Commons Attribution 3.0 Unported License. 13 | http://creativecommons.org/licenses/by/3.0/ 14 | -------------------------------------------------------------------------------- /cubemaps/colors/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/negx.jpg -------------------------------------------------------------------------------- /cubemaps/colors/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/negy.jpg -------------------------------------------------------------------------------- /cubemaps/colors/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/negz.jpg -------------------------------------------------------------------------------- /cubemaps/colors/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/posx.jpg -------------------------------------------------------------------------------- /cubemaps/colors/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/posy.jpg -------------------------------------------------------------------------------- /cubemaps/colors/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/colors/posz.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/negx.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/negy.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/negz.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/posx.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/posy.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/powerlines/posz.jpg -------------------------------------------------------------------------------- /cubemaps/powerlines/readme.txt: -------------------------------------------------------------------------------- 1 | Author 2 | ====== 3 | 4 | This is the work of Emil Persson, aka Humus. 5 | http://www.humus.name 6 | 7 | 8 | 9 | License 10 | ======= 11 | 12 | This work is licensed under a Creative Commons Attribution 3.0 Unported License. 13 | http://creativecommons.org/licenses/by/3.0/ 14 | -------------------------------------------------------------------------------- /cubemaps/room/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/negx.jpg -------------------------------------------------------------------------------- /cubemaps/room/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/negy.jpg -------------------------------------------------------------------------------- /cubemaps/room/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/negz.jpg -------------------------------------------------------------------------------- /cubemaps/room/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/posx.jpg -------------------------------------------------------------------------------- /cubemaps/room/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/posy.jpg -------------------------------------------------------------------------------- /cubemaps/room/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/room/posz.jpg -------------------------------------------------------------------------------- /cubemaps/room/readme.txt: -------------------------------------------------------------------------------- 1 | Author 2 | ====== 3 | 4 | This is the work of Emil Persson, aka Humus. 5 | http://www.humus.name 6 | 7 | 8 | 9 | License 10 | ======= 11 | 12 | This work is licensed under a Creative Commons Attribution 3.0 Unported License. 13 | http://creativecommons.org/licenses/by/3.0/ 14 | -------------------------------------------------------------------------------- /cubemaps/tantolunden2/negx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/negx.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/negy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/negy.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/negz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/negz.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/posx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/posx.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/posy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/posy.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/posz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/cubemaps/tantolunden2/posz.jpg -------------------------------------------------------------------------------- /cubemaps/tantolunden2/readme.txt: -------------------------------------------------------------------------------- 1 | Author 2 | ====== 3 | 4 | This is the work of Emil Persson, aka Humus. 5 | http://www.humus.name 6 | 7 | 8 | 9 | License 10 | ======= 11 | 12 | This work is licensed under a Creative Commons Attribution 3.0 Unported License. 13 | http://creativecommons.org/licenses/by/3.0/ 14 | -------------------------------------------------------------------------------- /imgui_impl_glfw_gl3.cpp: -------------------------------------------------------------------------------- 1 | // ImGui GLFW binding with OpenGL3 + shaders 2 | // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. 3 | 4 | // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. 5 | // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). 6 | // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. 7 | // https://github.com/ocornut/imgui 8 | 9 | //#include 10 | //#include "imgui_impl_glfw_gl3.h" 11 | 12 | // GL3W/GLFW 13 | //#include 14 | #include 15 | #ifdef _WIN32 16 | #undef APIENTRY 17 | #define GLFW_EXPOSE_NATIVE_WIN32 18 | #define GLFW_EXPOSE_NATIVE_WGL 19 | #include 20 | #endif 21 | 22 | // Data 23 | static GLFWwindow* g_Window = NULL; 24 | static double g_Time = 0.0f; 25 | static bool g_MousePressed[3] = { false, false, false }; 26 | static float g_MouseWheel = 0.0f; 27 | static GLuint g_FontTexture = 0; 28 | static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; 29 | static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; 30 | static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; 31 | static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; 32 | 33 | // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) 34 | // If text or lines are blurry when integrating ImGui in your engine: 35 | // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) 36 | void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) 37 | { 38 | // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) 39 | ImGuiIO& io = ImGui::GetIO(); 40 | int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); 41 | int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); 42 | if (fb_width == 0 || fb_height == 0) 43 | return; 44 | draw_data->ScaleClipRects(io.DisplayFramebufferScale); 45 | 46 | // Backup GL state 47 | GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); 48 | GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 49 | GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); 50 | GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); 51 | GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); 52 | GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); 53 | GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); 54 | GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); 55 | GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); 56 | GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); 57 | GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); 58 | GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 59 | GLboolean last_enable_blend = glIsEnabled(GL_BLEND); 60 | GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); 61 | GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); 62 | GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); 63 | 64 | // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled 65 | glEnable(GL_BLEND); 66 | glBlendEquation(GL_FUNC_ADD); 67 | glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 68 | glDisable(GL_CULL_FACE); 69 | glDisable(GL_DEPTH_TEST); 70 | glEnable(GL_SCISSOR_TEST); 71 | glActiveTexture(GL_TEXTURE0); 72 | 73 | // Setup viewport, orthographic projection matrix 74 | glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); 75 | const float ortho_projection[4][4] = 76 | { 77 | { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, 78 | { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, 79 | { 0.0f, 0.0f, -1.0f, 0.0f }, 80 | {-1.0f, 1.0f, 0.0f, 1.0f }, 81 | }; 82 | glUseProgram(g_ShaderHandle); 83 | glUniform1i(g_AttribLocationTex, 0); 84 | glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); 85 | glBindVertexArray(g_VaoHandle); 86 | 87 | for (int n = 0; n < draw_data->CmdListsCount; n++) 88 | { 89 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 90 | const ImDrawIdx* idx_buffer_offset = 0; 91 | 92 | glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); 93 | glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); 94 | 95 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); 96 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); 97 | 98 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 99 | { 100 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 101 | if (pcmd->UserCallback) 102 | { 103 | pcmd->UserCallback(cmd_list, pcmd); 104 | } 105 | else 106 | { 107 | glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); 108 | glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); 109 | glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); 110 | } 111 | idx_buffer_offset += pcmd->ElemCount; 112 | } 113 | } 114 | 115 | // Restore modified GL state 116 | glUseProgram(last_program); 117 | glActiveTexture(last_active_texture); 118 | glBindTexture(GL_TEXTURE_2D, last_texture); 119 | glBindVertexArray(last_vertex_array); 120 | glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 121 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); 122 | glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); 123 | glBlendFunc(last_blend_src, last_blend_dst); 124 | if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); 125 | if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); 126 | if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); 127 | if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); 128 | glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); 129 | glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); 130 | } 131 | 132 | static const char* ImGui_ImplGlfwGL3_GetClipboardText() 133 | { 134 | return glfwGetClipboardString(g_Window); 135 | } 136 | 137 | static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text) 138 | { 139 | glfwSetClipboardString(g_Window, text); 140 | } 141 | 142 | void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/) 143 | { 144 | if (action == GLFW_PRESS && button >= 0 && button < 3) 145 | g_MousePressed[button] = true; 146 | } 147 | 148 | void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset) 149 | { 150 | g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines. 151 | } 152 | 153 | void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods) 154 | { 155 | ImGuiIO& io = ImGui::GetIO(); 156 | if (action == GLFW_PRESS) 157 | io.KeysDown[key] = true; 158 | if (action == GLFW_RELEASE) 159 | io.KeysDown[key] = false; 160 | 161 | (void)mods; // Modifiers are not reliable across systems 162 | io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; 163 | io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; 164 | io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; 165 | io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; 166 | } 167 | 168 | void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c) 169 | { 170 | ImGuiIO& io = ImGui::GetIO(); 171 | if (c > 0 && c < 0x10000) 172 | io.AddInputCharacter((unsigned short)c); 173 | } 174 | 175 | bool ImGui_ImplGlfwGL3_CreateFontsTexture() 176 | { 177 | // Build texture atlas 178 | ImGuiIO& io = ImGui::GetIO(); 179 | unsigned char* pixels; 180 | int width, height; 181 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. 182 | 183 | // Upload texture to graphics system 184 | GLint last_texture; 185 | glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 186 | glGenTextures(1, &g_FontTexture); 187 | glBindTexture(GL_TEXTURE_2D, g_FontTexture); 188 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 189 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 190 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 191 | 192 | // Store our identifier 193 | io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; 194 | 195 | // Restore state 196 | glBindTexture(GL_TEXTURE_2D, last_texture); 197 | 198 | return true; 199 | } 200 | 201 | bool ImGui_ImplGlfwGL3_CreateDeviceObjects() 202 | { 203 | // Backup GL state 204 | GLint last_texture, last_array_buffer, last_vertex_array; 205 | glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 206 | glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); 207 | glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); 208 | 209 | const GLchar *vertex_shader = 210 | "#version 330\n" 211 | "uniform mat4 ProjMtx;\n" 212 | "in vec2 Position;\n" 213 | "in vec2 UV;\n" 214 | "in vec4 Color;\n" 215 | "out vec2 Frag_UV;\n" 216 | "out vec4 Frag_Color;\n" 217 | "void main()\n" 218 | "{\n" 219 | " Frag_UV = UV;\n" 220 | " Frag_Color = Color;\n" 221 | " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 222 | "}\n"; 223 | 224 | const GLchar* fragment_shader = 225 | "#version 330\n" 226 | "uniform sampler2D Texture;\n" 227 | "in vec2 Frag_UV;\n" 228 | "in vec4 Frag_Color;\n" 229 | "out vec4 Out_Color;\n" 230 | "void main()\n" 231 | "{\n" 232 | " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" 233 | "}\n"; 234 | 235 | g_ShaderHandle = glCreateProgram(); 236 | g_VertHandle = glCreateShader(GL_VERTEX_SHADER); 237 | g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); 238 | glShaderSource(g_VertHandle, 1, &vertex_shader, 0); 239 | glShaderSource(g_FragHandle, 1, &fragment_shader, 0); 240 | glCompileShader(g_VertHandle); 241 | glCompileShader(g_FragHandle); 242 | glAttachShader(g_ShaderHandle, g_VertHandle); 243 | glAttachShader(g_ShaderHandle, g_FragHandle); 244 | glLinkProgram(g_ShaderHandle); 245 | 246 | g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); 247 | g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); 248 | g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); 249 | g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); 250 | g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); 251 | 252 | glGenBuffers(1, &g_VboHandle); 253 | glGenBuffers(1, &g_ElementsHandle); 254 | 255 | glGenVertexArrays(1, &g_VaoHandle); 256 | glBindVertexArray(g_VaoHandle); 257 | glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); 258 | glEnableVertexAttribArray(g_AttribLocationPosition); 259 | glEnableVertexAttribArray(g_AttribLocationUV); 260 | glEnableVertexAttribArray(g_AttribLocationColor); 261 | 262 | #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) 263 | glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); 264 | glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); 265 | glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); 266 | #undef OFFSETOF 267 | 268 | ImGui_ImplGlfwGL3_CreateFontsTexture(); 269 | 270 | // Restore modified GL state 271 | glBindTexture(GL_TEXTURE_2D, last_texture); 272 | glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 273 | glBindVertexArray(last_vertex_array); 274 | 275 | return true; 276 | } 277 | 278 | void ImGui_ImplGlfwGL3_InvalidateDeviceObjects() 279 | { 280 | if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); 281 | if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); 282 | if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); 283 | g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; 284 | 285 | glDetachShader(g_ShaderHandle, g_VertHandle); 286 | glDeleteShader(g_VertHandle); 287 | g_VertHandle = 0; 288 | 289 | glDetachShader(g_ShaderHandle, g_FragHandle); 290 | glDeleteShader(g_FragHandle); 291 | g_FragHandle = 0; 292 | 293 | glDeleteProgram(g_ShaderHandle); 294 | g_ShaderHandle = 0; 295 | 296 | if (g_FontTexture) 297 | { 298 | glDeleteTextures(1, &g_FontTexture); 299 | ImGui::GetIO().Fonts->TexID = 0; 300 | g_FontTexture = 0; 301 | } 302 | } 303 | 304 | bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks) 305 | { 306 | g_Window = window; 307 | 308 | ImGuiIO& io = ImGui::GetIO(); 309 | io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. 310 | io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; 311 | io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; 312 | io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; 313 | io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; 314 | io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; 315 | io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; 316 | io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; 317 | io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; 318 | io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; 319 | io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; 320 | io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; 321 | io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; 322 | io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; 323 | io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; 324 | io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; 325 | io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; 326 | io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; 327 | io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; 328 | 329 | io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. 330 | io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; 331 | io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; 332 | #ifdef _WIN32 333 | io.ImeWindowHandle = glfwGetWin32Window(g_Window); 334 | #endif 335 | 336 | if (install_callbacks) 337 | { 338 | glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback); 339 | glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback); 340 | glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback); 341 | glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback); 342 | } 343 | 344 | return true; 345 | } 346 | 347 | void ImGui_ImplGlfwGL3_Shutdown() 348 | { 349 | ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); 350 | ImGui::Shutdown(); 351 | } 352 | 353 | void ImGui_ImplGlfwGL3_NewFrame() 354 | { 355 | if (!g_FontTexture) 356 | ImGui_ImplGlfwGL3_CreateDeviceObjects(); 357 | 358 | ImGuiIO& io = ImGui::GetIO(); 359 | 360 | // Setup display size (every frame to accommodate for window resizing) 361 | int w, h; 362 | int display_w, display_h; 363 | glfwGetWindowSize(g_Window, &w, &h); 364 | glfwGetFramebufferSize(g_Window, &display_w, &display_h); 365 | io.DisplaySize = ImVec2((float)w, (float)h); 366 | io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); 367 | 368 | // Setup time step 369 | double current_time = glfwGetTime(); 370 | io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); 371 | g_Time = current_time; 372 | 373 | // Setup inputs 374 | // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) 375 | if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED)) 376 | { 377 | double mouse_x, mouse_y; 378 | glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); 379 | io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.) 380 | } 381 | else 382 | { 383 | io.MousePos = ImVec2(-1,-1); 384 | } 385 | 386 | for (int i = 0; i < 3; i++) 387 | { 388 | io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. 389 | g_MousePressed[i] = false; 390 | } 391 | 392 | io.MouseWheel = g_MouseWheel; 393 | g_MouseWheel = 0.0f; 394 | 395 | // Hide OS mouse cursor if ImGui is drawing it 396 | glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL); 397 | 398 | // Start the frame 399 | ImGui::NewFrame(); 400 | } 401 | -------------------------------------------------------------------------------- /imgui_impl_glfw_gl3.h: -------------------------------------------------------------------------------- 1 | // ImGui GLFW binding with OpenGL3 + shaders 2 | // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. 3 | 4 | // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. 5 | // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). 6 | // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. 7 | // https://github.com/ocornut/imgui 8 | 9 | struct GLFWwindow; 10 | 11 | IMGUI_API bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks); 12 | IMGUI_API void ImGui_ImplGlfwGL3_Shutdown(); 13 | IMGUI_API void ImGui_ImplGlfwGL3_NewFrame(); 14 | 15 | // Use if you want to reset your rendering device without losing ImGui state. 16 | IMGUI_API void ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); 17 | IMGUI_API bool ImGui_ImplGlfwGL3_CreateDeviceObjects(); 18 | 19 | // GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization) 20 | // Provided here if you want to chain callbacks. 21 | // You can also handle inputs yourself and use those as a reference. 22 | IMGUI_API void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); 23 | IMGUI_API void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); 24 | IMGUI_API void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); 25 | IMGUI_API void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow* window, unsigned int c); 26 | -------------------------------------------------------------------------------- /imgui_internal.h: -------------------------------------------------------------------------------- 1 | // dear imgui, v1.50 WIP 2 | // (internals) 3 | 4 | // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! 5 | // Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) 6 | // #define IMGUI_DEFINE_MATH_OPERATORS 7 | 8 | #pragma once 9 | 10 | #ifndef IMGUI_VERSION 11 | #error Must include imgui.h before imgui_internal.h 12 | #endif 13 | 14 | #include // FILE* 15 | #include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf 16 | 17 | #ifdef _MSC_VER 18 | #pragma warning (push) 19 | #pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) 20 | #endif 21 | 22 | #ifdef __clang__ 23 | #pragma clang diagnostic push 24 | #pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h 25 | #pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h 26 | #pragma clang diagnostic ignored "-Wold-style-cast" 27 | #endif 28 | 29 | //----------------------------------------------------------------------------- 30 | // Forward Declarations 31 | //----------------------------------------------------------------------------- 32 | 33 | struct ImRect; 34 | struct ImGuiColMod; 35 | struct ImGuiStyleMod; 36 | struct ImGuiGroupData; 37 | struct ImGuiSimpleColumns; 38 | struct ImGuiDrawContext; 39 | struct ImGuiTextEditState; 40 | struct ImGuiIniData; 41 | struct ImGuiMouseCursorData; 42 | struct ImGuiPopupRef; 43 | struct ImGuiWindow; 44 | 45 | typedef int ImGuiLayoutType; // enum ImGuiLayoutType_ 46 | typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ 47 | typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ 48 | typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_ 49 | 50 | //------------------------------------------------------------------------- 51 | // STB libraries 52 | //------------------------------------------------------------------------- 53 | 54 | namespace ImGuiStb 55 | { 56 | 57 | #undef STB_TEXTEDIT_STRING 58 | #undef STB_TEXTEDIT_CHARTYPE 59 | #define STB_TEXTEDIT_STRING ImGuiTextEditState 60 | #define STB_TEXTEDIT_CHARTYPE ImWchar 61 | #define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f 62 | #include "stb_textedit.h" 63 | 64 | } // namespace ImGuiStb 65 | 66 | //----------------------------------------------------------------------------- 67 | // Context 68 | //----------------------------------------------------------------------------- 69 | 70 | extern IMGUI_API ImGuiContext* GImGui; // current implicit ImGui context pointer 71 | 72 | //----------------------------------------------------------------------------- 73 | // Helpers 74 | //----------------------------------------------------------------------------- 75 | 76 | #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) 77 | #define IM_PI 3.14159265358979323846f 78 | #define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM)) 79 | 80 | // Helpers: UTF-8 <> wchar 81 | IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count 82 | IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count 83 | IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count 84 | IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) 85 | IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points 86 | 87 | // Helpers: Misc 88 | IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings 89 | IMGUI_API void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); 90 | IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c); 91 | static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } 92 | static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } 93 | 94 | // Helpers: String 95 | IMGUI_API int ImStricmp(const char* str1, const char* str2); 96 | IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count); 97 | IMGUI_API char* ImStrdup(const char* str); 98 | IMGUI_API int ImStrlenW(const ImWchar* str); 99 | IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line 100 | IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); 101 | IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3); 102 | IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args); 103 | 104 | // Helpers: Math 105 | // We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined) 106 | #ifdef IMGUI_DEFINE_MATH_OPERATORS 107 | static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } 108 | static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } 109 | static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } 110 | static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } 111 | static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } 112 | static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } 113 | static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } 114 | static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } 115 | static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } 116 | static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } 117 | static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } 118 | #endif 119 | 120 | static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } 121 | static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } 122 | static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } 123 | static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } 124 | static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } 125 | static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } 126 | static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } 127 | static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } 128 | 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)); } 129 | static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } 130 | static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } 131 | 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); } 132 | static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } 133 | static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } 134 | static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; } 135 | static inline float ImFloor(float f) { return (float)(int)f; } 136 | static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } 137 | 138 | // We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. 139 | // Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. 140 | #ifdef IMGUI_DEFINE_PLACEMENT_NEW 141 | struct ImPlacementNewDummy {}; 142 | inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; } 143 | inline void operator delete(void*, ImPlacementNewDummy, void*) {} 144 | #define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR) 145 | #endif 146 | 147 | //----------------------------------------------------------------------------- 148 | // Types 149 | //----------------------------------------------------------------------------- 150 | 151 | enum ImGuiButtonFlags_ 152 | { 153 | ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat 154 | ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set) 155 | ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release) 156 | ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release) 157 | ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release) 158 | ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping 159 | ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press 160 | ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction 161 | ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only 162 | ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held 163 | ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable 164 | }; 165 | 166 | enum ImGuiSliderFlags_ 167 | { 168 | ImGuiSliderFlags_Vertical = 1 << 0 169 | }; 170 | 171 | enum ImGuiSelectableFlagsPrivate_ 172 | { 173 | // NB: need to be in sync with last value of ImGuiSelectableFlags_ 174 | ImGuiSelectableFlags_Menu = 1 << 3, 175 | ImGuiSelectableFlags_MenuItem = 1 << 4, 176 | ImGuiSelectableFlags_Disabled = 1 << 5, 177 | ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 178 | }; 179 | 180 | // FIXME: this is in development, not exposed/functional as a generic feature yet. 181 | enum ImGuiLayoutType_ 182 | { 183 | ImGuiLayoutType_Vertical, 184 | ImGuiLayoutType_Horizontal 185 | }; 186 | 187 | enum ImGuiPlotType 188 | { 189 | ImGuiPlotType_Lines, 190 | ImGuiPlotType_Histogram 191 | }; 192 | 193 | enum ImGuiDataType 194 | { 195 | ImGuiDataType_Int, 196 | ImGuiDataType_Float, 197 | ImGuiDataType_Float2, 198 | }; 199 | 200 | // 2D axis aligned bounding-box 201 | // NB: we can't rely on ImVec2 math operators being available here 202 | struct IMGUI_API ImRect 203 | { 204 | ImVec2 Min; // Upper-left 205 | ImVec2 Max; // Lower-right 206 | 207 | ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} 208 | ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} 209 | ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} 210 | ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} 211 | 212 | ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } 213 | ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } 214 | float GetWidth() const { return Max.x-Min.x; } 215 | float GetHeight() const { return Max.y-Min.y; } 216 | ImVec2 GetTL() const { return Min; } // Top-left 217 | ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right 218 | ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left 219 | ImVec2 GetBR() const { return Max; } // Bottom-right 220 | bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } 221 | bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } 222 | bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } 223 | void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } 224 | void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } 225 | void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } 226 | void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } 227 | void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } 228 | void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } 229 | void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } 230 | ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const 231 | { 232 | if (!on_edge && Contains(p)) 233 | return p; 234 | if (p.x > Max.x) p.x = Max.x; 235 | else if (p.x < Min.x) p.x = Min.x; 236 | if (p.y > Max.y) p.y = Max.y; 237 | else if (p.y < Min.y) p.y = Min.y; 238 | return p; 239 | } 240 | }; 241 | 242 | // Stacked color modifier, backup of modified data so we can restore it 243 | struct ImGuiColMod 244 | { 245 | ImGuiCol Col; 246 | ImVec4 BackupValue; 247 | }; 248 | 249 | // Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. 250 | struct ImGuiStyleMod 251 | { 252 | ImGuiStyleVar VarIdx; 253 | union { int BackupInt[2]; float BackupFloat[2]; }; 254 | ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } 255 | ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } 256 | ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } 257 | }; 258 | 259 | // Stacked data for BeginGroup()/EndGroup() 260 | struct ImGuiGroupData 261 | { 262 | ImVec2 BackupCursorPos; 263 | ImVec2 BackupCursorMaxPos; 264 | float BackupIndentX; 265 | float BackupGroupOffsetX; 266 | float BackupCurrentLineHeight; 267 | float BackupCurrentLineTextBaseOffset; 268 | float BackupLogLinePosY; 269 | bool BackupActiveIdIsAlive; 270 | bool AdvanceCursor; 271 | }; 272 | 273 | // Per column data for Columns() 274 | struct ImGuiColumnData 275 | { 276 | float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) 277 | //float IndentX; 278 | }; 279 | 280 | // Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. 281 | struct IMGUI_API ImGuiSimpleColumns 282 | { 283 | int Count; 284 | float Spacing; 285 | float Width, NextWidth; 286 | float Pos[8], NextWidths[8]; 287 | 288 | ImGuiSimpleColumns(); 289 | void Update(int count, float spacing, bool clear); 290 | float DeclColumns(float w0, float w1, float w2); 291 | float CalcExtraSpace(float avail_w); 292 | }; 293 | 294 | // Internal state of the currently focused/edited text input box 295 | struct IMGUI_API ImGuiTextEditState 296 | { 297 | ImGuiID Id; // widget id owning the text state 298 | ImVector Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. 299 | ImVector InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) 300 | ImVector TempTextBuffer; 301 | int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. 302 | int BufSizeA; // end-user buffer size 303 | float ScrollX; 304 | ImGuiStb::STB_TexteditState StbState; 305 | float CursorAnim; 306 | bool CursorFollow; 307 | bool SelectedAllMouseLock; 308 | 309 | ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } 310 | void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking 311 | void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } 312 | bool HasSelection() const { return StbState.select_start != StbState.select_end; } 313 | void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } 314 | void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } 315 | void OnKeyPressed(int key); 316 | }; 317 | 318 | // Data saved in imgui.ini file 319 | struct ImGuiIniData 320 | { 321 | char* Name; 322 | ImGuiID Id; 323 | ImVec2 Pos; 324 | ImVec2 Size; 325 | bool Collapsed; 326 | }; 327 | 328 | // Mouse cursor data (used when io.MouseDrawCursor is set) 329 | struct ImGuiMouseCursorData 330 | { 331 | ImGuiMouseCursor Type; 332 | ImVec2 HotOffset; 333 | ImVec2 Size; 334 | ImVec2 TexUvMin[2]; 335 | ImVec2 TexUvMax[2]; 336 | }; 337 | 338 | // Storage for current popup stack 339 | struct ImGuiPopupRef 340 | { 341 | ImGuiID PopupId; // Set on OpenPopup() 342 | ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() 343 | ImGuiWindow* ParentWindow; // Set on OpenPopup() 344 | ImGuiID ParentMenuSet; // Set on OpenPopup() 345 | ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup 346 | 347 | ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } 348 | }; 349 | 350 | // Main state for ImGui 351 | struct ImGuiContext 352 | { 353 | bool Initialized; 354 | ImGuiIO IO; 355 | ImGuiStyle Style; 356 | ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() 357 | float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() 358 | float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. 359 | ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel 360 | 361 | float Time; 362 | int FrameCount; 363 | int FrameCountEnded; 364 | int FrameCountRendered; 365 | ImVector Windows; 366 | ImVector WindowsSortBuffer; 367 | ImGuiWindow* CurrentWindow; // Being drawn into 368 | ImVector CurrentWindowStack; 369 | ImGuiWindow* FocusedWindow; // Will catch keyboard inputs 370 | ImGuiWindow* HoveredWindow; // Will catch mouse inputs 371 | ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) 372 | ImGuiID HoveredId; // Hovered widget 373 | bool HoveredIdAllowOverlap; 374 | ImGuiID HoveredIdPreviousFrame; 375 | ImGuiID ActiveId; // Active widget 376 | ImGuiID ActiveIdPreviousFrame; 377 | bool ActiveIdIsAlive; 378 | bool ActiveIdIsJustActivated; // Set at the time of activation for one frame 379 | bool ActiveIdAllowOverlap; // Set only by active widget 380 | ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) 381 | ImGuiWindow* ActiveIdWindow; 382 | ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. 383 | ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId 384 | ImVector Settings; // .ini Settings 385 | float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero 386 | ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() 387 | ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() 388 | ImVector FontStack; // Stack for PushFont()/PopFont() 389 | ImVector OpenPopupStack; // Which popups are open (persistent) 390 | ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) 391 | 392 | // Storage for SetNexWindow** and SetNextTreeNode*** functions 393 | ImVec2 SetNextWindowPosVal; 394 | ImVec2 SetNextWindowSizeVal; 395 | ImVec2 SetNextWindowContentSizeVal; 396 | bool SetNextWindowCollapsedVal; 397 | ImGuiSetCond SetNextWindowPosCond; 398 | ImGuiSetCond SetNextWindowSizeCond; 399 | ImGuiSetCond SetNextWindowContentSizeCond; 400 | ImGuiSetCond SetNextWindowCollapsedCond; 401 | ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true 402 | ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback; 403 | void* SetNextWindowSizeConstraintCallbackUserData; 404 | bool SetNextWindowSizeConstraint; 405 | bool SetNextWindowFocus; 406 | bool SetNextTreeNodeOpenVal; 407 | ImGuiSetCond SetNextTreeNodeOpenCond; 408 | 409 | // Render 410 | ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user 411 | ImVector RenderDrawLists[3]; 412 | float ModalWindowDarkeningRatio; 413 | ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays 414 | ImGuiMouseCursor MouseCursor; 415 | ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; 416 | 417 | // Widget state 418 | ImGuiTextEditState InputTextState; 419 | ImFont InputTextPasswordFont; 420 | ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. 421 | ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode 422 | float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings 423 | ImVec2 DragLastMouseDelta; 424 | float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio 425 | float DragSpeedScaleSlow; 426 | float DragSpeedScaleFast; 427 | ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? 428 | char Tooltip[1024]; 429 | char* PrivateClipboard; // If no custom clipboard handler is defined 430 | ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor 431 | 432 | // Logging 433 | bool LogEnabled; 434 | FILE* LogFile; // If != NULL log to stdout/ file 435 | ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. 436 | int LogStartDepth; 437 | int LogAutoExpandMaxDepth; 438 | 439 | // Misc 440 | float FramerateSecPerFrame[120]; // calculate estimate of framerate for user 441 | int FramerateSecPerFrameIdx; 442 | float FramerateSecPerFrameAccum; 443 | int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags 444 | int CaptureKeyboardNextFrame; 445 | char TempBuffer[1024*3+1]; // temporary text buffer 446 | 447 | ImGuiContext() 448 | { 449 | Initialized = false; 450 | Font = NULL; 451 | FontSize = FontBaseSize = 0.0f; 452 | FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); 453 | 454 | Time = 0.0f; 455 | FrameCount = 0; 456 | FrameCountEnded = FrameCountRendered = -1; 457 | CurrentWindow = NULL; 458 | FocusedWindow = NULL; 459 | HoveredWindow = NULL; 460 | HoveredRootWindow = NULL; 461 | HoveredId = 0; 462 | HoveredIdAllowOverlap = false; 463 | HoveredIdPreviousFrame = 0; 464 | ActiveId = 0; 465 | ActiveIdPreviousFrame = 0; 466 | ActiveIdIsAlive = false; 467 | ActiveIdIsJustActivated = false; 468 | ActiveIdAllowOverlap = false; 469 | ActiveIdClickOffset = ImVec2(-1,-1); 470 | ActiveIdWindow = NULL; 471 | MovedWindow = NULL; 472 | MovedWindowMoveId = 0; 473 | SettingsDirtyTimer = 0.0f; 474 | 475 | SetNextWindowPosVal = ImVec2(0.0f, 0.0f); 476 | SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); 477 | SetNextWindowCollapsedVal = false; 478 | SetNextWindowPosCond = 0; 479 | SetNextWindowSizeCond = 0; 480 | SetNextWindowContentSizeCond = 0; 481 | SetNextWindowCollapsedCond = 0; 482 | SetNextWindowFocus = false; 483 | SetNextWindowSizeConstraintCallback = NULL; 484 | SetNextWindowSizeConstraintCallbackUserData = NULL; 485 | SetNextTreeNodeOpenVal = false; 486 | SetNextTreeNodeOpenCond = 0; 487 | 488 | ScalarAsInputTextId = 0; 489 | DragCurrentValue = 0.0f; 490 | DragLastMouseDelta = ImVec2(0.0f, 0.0f); 491 | DragSpeedDefaultRatio = 1.0f / 100.0f; 492 | DragSpeedScaleSlow = 0.01f; 493 | DragSpeedScaleFast = 10.0f; 494 | ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); 495 | memset(Tooltip, 0, sizeof(Tooltip)); 496 | PrivateClipboard = NULL; 497 | OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); 498 | 499 | ModalWindowDarkeningRatio = 0.0f; 500 | OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging 501 | MouseCursor = ImGuiMouseCursor_Arrow; 502 | memset(MouseCursorData, 0, sizeof(MouseCursorData)); 503 | 504 | LogEnabled = false; 505 | LogFile = NULL; 506 | LogClipboard = NULL; 507 | LogStartDepth = 0; 508 | LogAutoExpandMaxDepth = 2; 509 | 510 | memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); 511 | FramerateSecPerFrameIdx = 0; 512 | FramerateSecPerFrameAccum = 0.0f; 513 | CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1; 514 | memset(TempBuffer, 0, sizeof(TempBuffer)); 515 | } 516 | }; 517 | 518 | // Transient per-window data, reset at the beginning of the frame 519 | // FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered. 520 | struct IMGUI_API ImGuiDrawContext 521 | { 522 | ImVec2 CursorPos; 523 | ImVec2 CursorPosPrevLine; 524 | ImVec2 CursorStartPos; 525 | ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame 526 | float CurrentLineHeight; 527 | float CurrentLineTextBaseOffset; 528 | float PrevLineHeight; 529 | float PrevLineTextBaseOffset; 530 | float LogLinePosY; 531 | int TreeDepth; 532 | ImGuiID LastItemId; 533 | ImRect LastItemRect; 534 | bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window) 535 | bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window) 536 | bool MenuBarAppending; 537 | float MenuBarOffsetX; 538 | ImVector ChildWindows; 539 | ImGuiStorage* StateStorage; 540 | ImGuiLayoutType LayoutType; 541 | 542 | // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. 543 | float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window 544 | float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] 545 | bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true] 546 | bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false] 547 | ImVector ItemWidthStack; 548 | ImVector TextWrapPosStack; 549 | ImVector AllowKeyboardFocusStack; 550 | ImVector ButtonRepeatStack; 551 | ImVectorGroupStack; 552 | ImGuiColorEditMode ColorEditMode; 553 | int StackSizesBackup[6]; // Store size of various stacks for asserting 554 | 555 | float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) 556 | float GroupOffsetX; 557 | 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. 558 | int ColumnsCurrent; 559 | int ColumnsCount; 560 | float ColumnsMinX; 561 | float ColumnsMaxX; 562 | float ColumnsStartPosY; 563 | float ColumnsCellMinY; 564 | float ColumnsCellMaxY; 565 | bool ColumnsShowBorders; 566 | ImGuiID ColumnsSetId; 567 | ImVector ColumnsData; 568 | 569 | ImGuiDrawContext() 570 | { 571 | CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); 572 | CurrentLineHeight = PrevLineHeight = 0.0f; 573 | CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; 574 | LogLinePosY = -1.0f; 575 | TreeDepth = 0; 576 | LastItemId = 0; 577 | LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); 578 | LastItemHoveredAndUsable = LastItemHoveredRect = false; 579 | MenuBarAppending = false; 580 | MenuBarOffsetX = 0.0f; 581 | StateStorage = NULL; 582 | LayoutType = ImGuiLayoutType_Vertical; 583 | ItemWidth = 0.0f; 584 | ButtonRepeat = false; 585 | AllowKeyboardFocus = true; 586 | TextWrapPos = -1.0f; 587 | ColorEditMode = ImGuiColorEditMode_RGB; 588 | memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); 589 | 590 | IndentX = 0.0f; 591 | ColumnsOffsetX = 0.0f; 592 | ColumnsCurrent = 0; 593 | ColumnsCount = 1; 594 | ColumnsMinX = ColumnsMaxX = 0.0f; 595 | ColumnsStartPosY = 0.0f; 596 | ColumnsCellMinY = ColumnsCellMaxY = 0.0f; 597 | ColumnsShowBorders = true; 598 | ColumnsSetId = 0; 599 | } 600 | }; 601 | 602 | // Windows data 603 | struct IMGUI_API ImGuiWindow 604 | { 605 | char* Name; 606 | ImGuiID ID; // == ImHash(Name) 607 | ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ 608 | int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. 609 | ImVec2 PosFloat; 610 | ImVec2 Pos; // Position rounded-up to nearest pixel 611 | ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) 612 | ImVec2 SizeFull; // Size when non collapsed 613 | ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame 614 | ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() 615 | ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis 616 | ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect 617 | ImGuiID MoveId; // == window->GetID("#MOVE") 618 | ImVec2 Scroll; 619 | ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) 620 | ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered 621 | bool ScrollbarX, ScrollbarY; 622 | ImVec2 ScrollbarSizes; 623 | float BorderSize; 624 | bool Active; // Set to true on Begin() 625 | bool WasActive; 626 | bool Accessed; // Set to true when any widget access the current window 627 | bool Collapsed; // Set when collapsing window to become only title-bar 628 | bool SkipItems; // == Visible && !Collapsed 629 | int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) 630 | ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) 631 | int AutoFitFramesX, AutoFitFramesY; 632 | bool AutoFitOnlyGrows; 633 | int AutoPosLastDirection; 634 | int HiddenFrames; 635 | int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. 636 | int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. 637 | int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. 638 | bool SetWindowPosCenterWanted; 639 | 640 | ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame 641 | ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack 642 | ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. 643 | ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. 644 | int LastFrameActive; 645 | float ItemWidthDefault; 646 | ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items 647 | ImGuiStorage StateStorage; 648 | float FontWindowScale; // Scale multiplier per-window 649 | ImDrawList* DrawList; 650 | ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself. 651 | ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself. 652 | ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL. 653 | 654 | // Navigation / Focus 655 | int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() 656 | int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) 657 | int FocusIdxAllRequestCurrent; // Item being requested for focus 658 | int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus 659 | 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) 660 | int FocusIdxTabRequestNext; // " 661 | 662 | public: 663 | ImGuiWindow(const char* name); 664 | ~ImGuiWindow(); 665 | 666 | ImGuiID GetID(const char* str, const char* str_end = NULL); 667 | ImGuiID GetID(const void* ptr); 668 | ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); 669 | 670 | ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } 671 | float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } 672 | float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } 673 | ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } 674 | float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } 675 | ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } 676 | }; 677 | 678 | //----------------------------------------------------------------------------- 679 | // Internal API 680 | // No guarantee of forward compatibility here. 681 | //----------------------------------------------------------------------------- 682 | 683 | namespace ImGui 684 | { 685 | // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) 686 | // If this ever crash because g.CurrentWindow is NULL it means that either 687 | // - ImGui::NewFrame() has never been called, which is illegal. 688 | // - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. 689 | inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } 690 | inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } 691 | IMGUI_API ImGuiWindow* GetParentWindow(); 692 | IMGUI_API ImGuiWindow* FindWindowByName(const char* name); 693 | IMGUI_API void FocusWindow(ImGuiWindow* window); 694 | 695 | IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead! 696 | 697 | IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); 698 | IMGUI_API void SetHoveredID(ImGuiID id); 699 | IMGUI_API void KeepAliveID(ImGuiID id); 700 | 701 | IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); 702 | IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); 703 | IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id); 704 | IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); 705 | IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false); 706 | IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested 707 | IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); 708 | IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); 709 | IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); 710 | 711 | IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing); 712 | 713 | // NB: All position are in absolute pixels coordinates (not window coordinates) 714 | // FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. 715 | // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers. 716 | IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); 717 | IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); 718 | IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); 719 | IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); 720 | IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f, bool shadow = false); 721 | IMGUI_API void RenderBullet(ImVec2 pos); 722 | IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col); 723 | IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. 724 | 725 | IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); 726 | IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); 727 | IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); 728 | 729 | IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0); 730 | IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power); 731 | IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format); 732 | 733 | IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power); 734 | IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power); 735 | IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format); 736 | 737 | IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); 738 | IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags); 739 | IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags); 740 | IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags); 741 | IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision); 742 | 743 | IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); 744 | IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging 745 | IMGUI_API void TreePushRawID(ImGuiID id); 746 | 747 | IMGUI_API void PlotEx(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); 748 | 749 | IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value); 750 | IMGUI_API float RoundScalar(float value, int decimal_precision); 751 | 752 | } // namespace ImGui 753 | 754 | #ifdef __clang__ 755 | #pragma clang diagnostic pop 756 | #endif 757 | 758 | #ifdef _MSC_VER 759 | #pragma warning (pop) 760 | #endif 761 | -------------------------------------------------------------------------------- /m_math.h: -------------------------------------------------------------------------------- 1 | /*********************************************************** 2 | * A single-header inlined math library, extended on demand * 3 | * no warranty implied | use at your own risk * 4 | * author: Andreas Mantler (ands) | last change: 13.04.2018 * 5 | * * 6 | * License: * 7 | * This software is in the public domain. * 8 | * Where that dedication is not recognized, * 9 | * you are granted a perpetual, irrevocable license to copy * 10 | * and modify this file however you want. * 11 | ***********************************************************/ 12 | 13 | #if defined(_MSC_VER) && !defined(__cplusplus) // TODO: specific versions only? 14 | #define inline __inline 15 | #endif 16 | 17 | typedef int m_bool; 18 | #define M_FALSE 0 19 | #define M_TRUE 1 20 | 21 | #if defined(_MSC_VER) && (_MSC_VER <= 1700) 22 | static inline m_bool m_finite(float a) { return _finite(a); } 23 | #else 24 | static inline m_bool m_finite(float a) { return isfinite(a); } 25 | #endif 26 | 27 | static inline int m_mini (int a, int b) { return a < b ? a : b; } 28 | static inline int m_maxi (int a, int b) { return a > b ? a : b; } 29 | static inline int m_absi (int a ) { return a < 0 ? -a : a; } 30 | static inline float m_minf (float a, float b) { return a < b ? a : b; } 31 | static inline float m_maxf (float a, float b) { return a > b ? a : b; } 32 | static inline float m_absf (float a ) { return a < 0.0f ? -a : a; } 33 | static inline float m_pmodf (float a, float b) { return (a < 0.0f ? 1.0f : 0.0f) + (float)fmod(a, b); } // positive mod 34 | 35 | typedef struct m_ivec2 { int x, y; } m_ivec2; 36 | static inline m_ivec2 m_i2 (int x, int y) { m_ivec2 v = { x, y }; return v; } 37 | 38 | typedef struct m_vec2 { float x, y; } m_vec2; 39 | static inline m_vec2 m_v2i (int x, int y) { m_vec2 v = { (float)x, (float)y }; return v; } 40 | static inline m_vec2 m_v2 (float x, float y) { m_vec2 v = { x, y }; return v; } 41 | static inline m_vec2 m_negate2 (m_vec2 a ) { return m_v2(-a.x, -a.y); } 42 | static inline m_vec2 m_add2 (m_vec2 a, m_vec2 b) { return m_v2(a.x + b.x, a.y + b.y); } 43 | static inline m_vec2 m_sub2 (m_vec2 a, m_vec2 b) { return m_v2(a.x - b.x, a.y - b.y); } 44 | static inline m_vec2 m_mul2 (m_vec2 a, m_vec2 b) { return m_v2(a.x * b.x, a.y * b.y); } 45 | static inline m_vec2 m_scale2 (m_vec2 a, float b) { return m_v2(a.x * b, a.y * b); } 46 | static inline m_vec2 m_div2 (m_vec2 a, float b) { return m_scale2(a, 1.0f / b); } 47 | static inline m_vec2 m_pmod2 (m_vec2 a, float b) { return m_v2(m_pmodf(a.x, b), m_pmodf(a.y, b)); } 48 | static inline m_vec2 m_min2 (m_vec2 a, m_vec2 b) { return m_v2(m_minf(a.x, b.x), m_minf(a.y, b.y)); } 49 | static inline m_vec2 m_max2 (m_vec2 a, m_vec2 b) { return m_v2(m_maxf(a.x, b.x), m_maxf(a.y, b.y)); } 50 | static inline m_vec2 m_abs2 (m_vec2 a ) { return m_v2(m_absf(a.x), m_absf(a.y)); } 51 | static inline m_vec2 m_floor2 (m_vec2 a ) { return m_v2(floorf(a.x), floorf(a.y)); } 52 | static inline m_vec2 m_ceil2 (m_vec2 a ) { return m_v2(ceilf (a.x), ceilf (a.y)); } 53 | static inline float m_dot2 (m_vec2 a, m_vec2 b) { return a.x * b.x + a.y * b.y; } 54 | static inline float m_cross2 (m_vec2 a, m_vec2 b) { return a.x * b.y - a.y * b.x; } // pseudo cross product 55 | static inline float m_length2sq (m_vec2 a ) { return a.x * a.x + a.y * a.y; } 56 | static inline float m_length2 (m_vec2 a ) { return sqrtf(m_length2sq(a)); } 57 | static inline m_vec2 m_normalize2(m_vec2 a ) { return m_div2(a, m_length2(a)); } 58 | static inline m_bool m_finite2 (m_vec2 a ) { return m_finite(a.x) && m_finite(a.y); } 59 | 60 | typedef struct m_vec3 { float x, y, z; } m_vec3; 61 | static inline m_vec3 m_v3 (float x, float y, float z) { m_vec3 v = { x, y, z }; return v; } 62 | static inline m_vec3 m_negate3 (m_vec3 a ) { return m_v3(-a.x, -a.y, -a.z); } 63 | static inline m_vec3 m_add3 (m_vec3 a, m_vec3 b) { return m_v3(a.x + b.x, a.y + b.y, a.z + b.z); } 64 | static inline m_vec3 m_sub3 (m_vec3 a, m_vec3 b) { return m_v3(a.x - b.x, a.y - b.y, a.z - b.z); } 65 | static inline m_vec3 m_mul3 (m_vec3 a, m_vec3 b) { return m_v3(a.x * b.x, a.y * b.y, a.z * b.z); } 66 | static inline m_vec3 m_scale3 (m_vec3 a, float b) { return m_v3(a.x * b, a.y * b, a.z * b); } 67 | static inline m_vec3 m_div3 (m_vec3 a, float b) { return m_scale3(a, 1.0f / b); } 68 | static inline m_vec3 m_pmod3 (m_vec3 a, float b) { return m_v3(m_pmodf(a.x, b), m_pmodf(a.y, b), m_pmodf(a.z, b)); } 69 | static inline m_vec3 m_min3 (m_vec3 a, m_vec3 b) { return m_v3(m_minf(a.x, b.x), m_minf(a.y, b.y), m_minf(a.z, b.z)); } 70 | static inline m_vec3 m_max3 (m_vec3 a, m_vec3 b) { return m_v3(m_maxf(a.x, b.x), m_maxf(a.y, b.y), m_maxf(a.z, b.z)); } 71 | static inline m_vec3 m_abs3 (m_vec3 a ) { return m_v3(m_absf(a.x), m_absf(a.y), m_absf(a.z)); } 72 | static inline m_vec3 m_floor3 (m_vec3 a ) { return m_v3(floorf(a.x), floorf(a.y), floorf(a.z)); } 73 | static inline m_vec3 m_ceil3 (m_vec3 a ) { return m_v3(ceilf (a.x), ceilf (a.y), ceilf (a.z)); } 74 | static inline float m_dot3 (m_vec3 a, m_vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } 75 | static inline m_vec3 m_cross3 (m_vec3 a, m_vec3 b) { return m_v3(a.y * b.z - b.y * a.z, a.z * b.x - b.z * a.x, a.x * b.y - b.x * a.y); } 76 | static inline float m_length3sq (m_vec3 a ) { return a.x * a.x + a.y * a.y + a.z * a.z; } 77 | static inline float m_length3 (m_vec3 a ) { return sqrtf(m_length3sq(a)); } 78 | static inline m_vec3 m_normalize3(m_vec3 a ) { return m_div3(a, m_length3(a)); } 79 | static inline m_bool m_finite3 (m_vec3 a ) { return m_finite(a.x) && m_finite(a.y) && m_finite(a.z); } 80 | 81 | #define M_M_PI 3.14159265358979323846f 82 | 83 | static void m_mul44(float *out, float *a, float *b) 84 | { 85 | for (int y = 0; y < 4; y++) 86 | for (int x = 0; x < 4; x++) 87 | out[y * 4 + x] = a[x] * b[y * 4] + a[4 + x] * b[y * 4 + 1] + a[8 + x] * b[y * 4 + 2] + a[12 + x] * b[y * 4 + 3]; 88 | } 89 | static void m_translation44(float *out, float x, float y, float z) 90 | { 91 | out[ 0] = 1.0f; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f; 92 | out[ 4] = 0.0f; out[ 5] = 1.0f; out[ 6] = 0.0f; out[ 7] = 0.0f; 93 | out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = 1.0f; out[11] = 0.0f; 94 | out[12] = x; out[13] = y; out[14] = z; out[15] = 1.0f; 95 | } 96 | static void m_rotation44(float *out, float angle, float x, float y, float z) 97 | { 98 | angle *= M_M_PI / 180.0f; 99 | float c = cosf(angle), s = sinf(angle), c2 = 1.0f - c; 100 | out[ 0] = x*x*c2 + c; out[ 1] = y*x*c2 + z*s; out[ 2] = x*z*c2 - y*s; out[ 3] = 0.0f; 101 | out[ 4] = x*y*c2 - z*s; out[ 5] = y*y*c2 + c; out[ 6] = y*z*c2 + x*s; out[ 7] = 0.0f; 102 | out[ 8] = x*z*c2 + y*s; out[ 9] = y*z*c2 - x*s; out[10] = z*z*c2 + c; out[11] = 0.0f; 103 | out[12] = 0.0f; out[13] = 0.0f; out[14] = 0.0f; out[15] = 1.0f; 104 | } 105 | static void m_transform44(float *out, float *m, float *p) 106 | { 107 | float d = 1.0f / (m[3] * p[0] + m[7] * p[1] + m[11] * p[2] + m[15]); 108 | out[2] = d * (m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]); 109 | out[1] = d * (m[1] * p[0] + m[5] * p[1] + m[ 9] * p[2] + m[13]); 110 | out[0] = d * (m[0] * p[0] + m[4] * p[1] + m[ 8] * p[2] + m[12]); 111 | } 112 | static void m_transpose44(float *out, float *m) 113 | { 114 | out[ 0] = m[0]; out[ 1] = m[4]; out[ 2] = m[ 8]; out[ 3] = m[12]; 115 | out[ 4] = m[1]; out[ 5] = m[5]; out[ 6] = m[ 9]; out[ 7] = m[13]; 116 | out[ 8] = m[2]; out[ 9] = m[6]; out[10] = m[10]; out[11] = m[14]; 117 | out[12] = m[3]; out[13] = m[7]; out[14] = m[11]; out[15] = m[15]; 118 | } 119 | static void m_perspective44(float *out, float fovy, float aspect, float zNear, float zFar) 120 | { 121 | float f = 1.0f / tanf(fovy * M_M_PI / 360.0f); 122 | float izFN = 1.0f / (zNear - zFar); 123 | out[ 0] = f / aspect; out[ 1] = 0.0f; out[ 2] = 0.0f; out[ 3] = 0.0f; 124 | out[ 4] = 0.0f; out[ 5] = f; out[ 6] = 0.0f; out[ 7] = 0.0f; 125 | out[ 8] = 0.0f; out[ 9] = 0.0f; out[10] = (zFar + zNear) * izFN; out[11] = -1.0f; 126 | out[12] = 0.0f; out[13] = 0.0f; out[14] = 2.0f * zFar * zNear * izFN; out[15] = 0.0f; 127 | } -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | /*********************************************************** 2 | * A spherical harmonics computation example and playground * 3 | * no warranty implied | use at your own risk * 4 | * author: Andreas Mantler (ands) | last change: 13.04.2018 * 5 | * * 6 | * License: * 7 | * This software is in the public domain. * 8 | * Where that dedication is not recognized, * 9 | * you are granted a perpetual, irrevocable license to copy * 10 | * and modify this file however you want. * 11 | ***********************************************************/ 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include "glad/glad.h" 18 | #include "GLFW/glfw3.h" 19 | 20 | extern "C" 21 | { 22 | #define YO_IMPLEMENTATION 23 | #define YO_NOIMG 24 | #include "yocto_obj.h" 25 | } 26 | 27 | #define STB_IMAGE_IMPLEMENTATION 28 | #include "stb_image.h" 29 | 30 | #include "imgui.cpp" 31 | #include "imgui_draw.cpp" 32 | #include "imgui_impl_glfw_gl3.cpp" 33 | 34 | #include "m_math.h" 35 | #include "s_shader.h" 36 | 37 | typedef struct 38 | { 39 | struct 40 | { 41 | GLuint program; 42 | GLint u_view; 43 | GLint u_projection; 44 | GLint u_cubemap; 45 | 46 | GLuint vao, vbo, ibo; 47 | int indices; 48 | 49 | GLuint texture; 50 | } sky; 51 | 52 | struct 53 | { 54 | GLuint program; 55 | GLint u_view; 56 | GLint u_projection; 57 | GLint u_coefficients; 58 | 59 | GLuint vao, vbo; 60 | int vertices; 61 | 62 | m_vec3 coefficients[9]; 63 | } mesh; 64 | } scene_t; 65 | 66 | static int initScene(scene_t *scene) 67 | { 68 | // sky 69 | int vertexSize = 3 * sizeof(float); 70 | m_vec3 vertices[] = 71 | { 72 | { 1, -1, 1 }, 73 | { 1, 1, 1 }, 74 | { 1, 1, -1 }, 75 | { -1, 1, -1 }, 76 | { 1, -1, -1 }, 77 | { -1, -1, -1 }, 78 | { -1, -1, 1 }, 79 | { -1, 1, 1 } 80 | }; 81 | 82 | scene->sky.indices = 14; 83 | uint16_t indices[] = { 0, 1, 2, 3, 4, 5, 6, 3, 7, 1, 6, 0, 4, 2 }; 84 | 85 | glGenVertexArrays(1, &scene->sky.vao); 86 | glBindVertexArray(scene->sky.vao); 87 | 88 | glGenBuffers(1, &scene->sky.vbo); 89 | glBindBuffer(GL_ARRAY_BUFFER, scene->sky.vbo); 90 | glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); 91 | glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, vertexSize, (void *)0); 92 | glEnableVertexAttribArray(0); 93 | 94 | glGenBuffers(1, &scene->sky.ibo); 95 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scene->sky.ibo); 96 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint16_t) * scene->sky.indices, indices, GL_STATIC_DRAW); 97 | 98 | const char *skyAttribs[] = 99 | { 100 | "a_position" 101 | }; 102 | 103 | const char *skyVP = 104 | "#version 150 core\n" 105 | "in vec3 a_position;\n" 106 | "uniform mat4 u_view;\n" 107 | "uniform mat4 u_projection;\n" 108 | "out vec3 v_direction;\n" 109 | 110 | "void main()\n" 111 | "{\n" 112 | " vec4 position = u_projection * (u_view * vec4(a_position, 0.0));\n" 113 | " gl_Position = position.xyww;\n" 114 | " v_direction = a_position;\n" 115 | "}\n"; 116 | 117 | const char *skyFP = 118 | "#version 150 core\n" 119 | "in vec3 v_direction;\n" 120 | "uniform samplerCube u_cubemap;\n" 121 | "out vec4 o_color;\n" 122 | 123 | "void main()\n" 124 | "{\n" 125 | " o_color = vec4(texture(u_cubemap, v_direction).rgb, 1.0);\n" 126 | "}\n"; 127 | 128 | scene->sky.program = s_loadProgram(skyVP, skyFP, skyAttribs, 1); 129 | if (!scene->sky.program) 130 | { 131 | fprintf(stderr, "Error loading mesh shader\n"); 132 | return 0; 133 | } 134 | scene->sky.u_view = glGetUniformLocation(scene->sky.program, "u_view"); 135 | scene->sky.u_projection = glGetUniformLocation(scene->sky.program, "u_projection"); 136 | scene->sky.u_cubemap = glGetUniformLocation(scene->sky.program, "u_cubemap"); 137 | 138 | //#define SKY_DIR "cubemaps/colors/" 139 | //#define SKY_DIR "cubemaps/tantolunden2/" 140 | #define SKY_DIR "cubemaps/room/" 141 | //#define SKY_DIR "cubemaps/powerlines/" 142 | //#define SKY_DIR "cubemaps/bridge3/" 143 | //#define SKY_DIR "cubemaps/coittower2/" 144 | 145 | const char *skyTextureFiles[] = { 146 | SKY_DIR "posx.jpg", SKY_DIR "negx.jpg", 147 | SKY_DIR "posy.jpg", SKY_DIR "negy.jpg", 148 | SKY_DIR "posz.jpg", SKY_DIR "negz.jpg" 149 | }; 150 | const m_vec3 skyDir[] = { 151 | m_v3(1.0f, 0.0f, 0.0f), m_v3(-1.0f, 0.0f, 0.0f), 152 | m_v3(0.0f, 1.0f, 0.0f), m_v3(0.0f, -1.0f, 0.0f), 153 | m_v3(0.0f, 0.0f, 1.0f), m_v3(0.0f, 0.0f, -1.0f) 154 | }; 155 | const m_vec3 skyX[] = { 156 | m_v3(0.0f, 0.0f, -1.0f), m_v3(0.0f, 0.0f, 1.0f), 157 | m_v3(-1.0f, 0.0f, 0.0f), m_v3(1.0f, 0.0f, 0.0f), 158 | m_v3(1.0f, 0.0f, 0.0f), m_v3(-1.0f, 0.0f, 0.0f) 159 | }; 160 | const m_vec3 skyY[] = { 161 | m_v3(0.0f, 1.0f, 0.0f), m_v3(0.0f, 1.0f, 0.0f), 162 | m_v3(0.0f, 0.0f, -1.0f), m_v3(0.0f, 0.0f, 1.0f), 163 | m_v3(0.0f, 1.0f, 0.0f), m_v3(0.0f, 1.0f, 0.0f) 164 | }; 165 | glGenTextures(1, &scene->sky.texture); 166 | glBindTexture(GL_TEXTURE_CUBE_MAP, scene->sky.texture); 167 | 168 | float weightSum = 0.0f; 169 | for (int i = 0; i < 6; i++) 170 | { 171 | int w, h, c; 172 | unsigned char *stbidata = stbi_load(skyTextureFiles[i], &w, &h, &c, 3); 173 | if (!stbidata) 174 | { 175 | fprintf(stderr, "Error loading sky texture\n"); 176 | return 0; 177 | } 178 | glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, stbidata); 179 | 180 | // also calculate SH coefficients: 181 | int step = 16; 182 | for (int y = 0; y < h; y += step) 183 | { 184 | unsigned char *p = stbidata + y * w * 3; 185 | for (int x = 0; x < w; x += step) 186 | { 187 | m_vec3 n = m_add3( 188 | m_add3( 189 | m_scale3(skyX[i], 2.0f * (x / (w - 1.0f)) - 1.0f), 190 | m_scale3(skyY[i], -2.0f * (y / (h - 1.0f)) + 1.0f)), 191 | skyDir[i]); // texelDirection; 192 | float l = m_length3(n); 193 | float weight = 1.0f / (l * l * l); // fast approximation of texelSolidAngle 194 | m_vec3 c_light = m_scale3(m_v3(p[0], p[1], p[2]), weight / 255.0f); 195 | n = m_normalize3(n); 196 | scene->mesh.coefficients[0] = m_add3(scene->mesh.coefficients[0], m_scale3(c_light, 0.282095f)); 197 | scene->mesh.coefficients[1] = m_add3(scene->mesh.coefficients[1], m_scale3(c_light, -0.488603f * n.y * 2.0f / 3.0f)); 198 | scene->mesh.coefficients[2] = m_add3(scene->mesh.coefficients[2], m_scale3(c_light, 0.488603f * n.z * 2.0f / 3.0f)); 199 | scene->mesh.coefficients[3] = m_add3(scene->mesh.coefficients[3], m_scale3(c_light, -0.488603f * n.x * 2.0f / 3.0f)); 200 | scene->mesh.coefficients[4] = m_add3(scene->mesh.coefficients[4], m_scale3(c_light, 1.092548f * n.x * n.y / 4.0f)); 201 | scene->mesh.coefficients[5] = m_add3(scene->mesh.coefficients[5], m_scale3(c_light, -1.092548f * n.y * n.z / 4.0f)); 202 | scene->mesh.coefficients[6] = m_add3(scene->mesh.coefficients[6], m_scale3(c_light, 0.315392f * (3.0f * n.z * n.z - 1.0f) / 4.0f)); 203 | scene->mesh.coefficients[7] = m_add3(scene->mesh.coefficients[7], m_scale3(c_light, -1.092548f * n.x * n.z / 4.0f)); 204 | scene->mesh.coefficients[8] = m_add3(scene->mesh.coefficients[8], m_scale3(c_light, 0.546274f * (n.x * n.x - n.y * n.y) / 4.0f)); 205 | p += 3 * step; 206 | weightSum += weight; 207 | } 208 | } 209 | 210 | free(stbidata); 211 | } 212 | for (int s = 0; s < 9; s++) 213 | scene->mesh.coefficients[s] = m_scale3(scene->mesh.coefficients[s], 4.0f * M_M_PI / weightSum); 214 | 215 | glGenerateMipmap(GL_TEXTURE_CUBE_MAP); 216 | glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 217 | glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); 218 | glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 219 | glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 220 | glBindTexture(GL_TEXTURE_CUBE_MAP, 0); 221 | 222 | // mesh 223 | //yo_scene *yo = yo_load_obj("sphere.obj", true, false); 224 | yo_scene *yo = yo_load_obj("dog.obj", true, false); 225 | if (!yo || !yo->nshapes) 226 | { 227 | fprintf(stderr, "Error loading obj file\n"); 228 | return 0; 229 | } 230 | 231 | scene->mesh.vertices = 0; 232 | for (int i = 0; i < yo->nshapes; i++) 233 | scene->mesh.vertices += yo->shapes[i].nelems * 3; 234 | 235 | m_vec3 *positions = (m_vec3*)calloc(scene->mesh.vertices, sizeof(m_vec3)); 236 | m_vec3 *normals = (m_vec3*)calloc(scene->mesh.vertices, sizeof(m_vec3)); 237 | size_t positionsSize = scene->mesh.vertices * sizeof(m_vec3); 238 | size_t normalsSize = scene->mesh.vertices * sizeof(m_vec3); 239 | 240 | int n = 0; 241 | for (int i = 0; i < yo->nshapes; i++) 242 | { 243 | yo_shape *shape = yo->shapes + i; 244 | for (int j = 0; j < shape->nelems * 3; j++) 245 | { 246 | positions[n + j] = *(m_vec3*)&shape->pos[shape->elem[j] * 3]; 247 | normals[n + j] = *(m_vec3*)&shape->norm[shape->elem[j] * 3]; 248 | } 249 | n += shape->nelems * 3; 250 | } 251 | yo_free_scene(yo); 252 | 253 | // upload geometry to opengl 254 | glGenVertexArrays(1, &scene->mesh.vao); 255 | glBindVertexArray(scene->mesh.vao); 256 | 257 | glGenBuffers(1, &scene->mesh.vbo); 258 | glBindBuffer(GL_ARRAY_BUFFER, scene->mesh.vbo); 259 | glBufferData(GL_ARRAY_BUFFER, positionsSize + normalsSize, NULL, GL_STATIC_DRAW); 260 | unsigned char *buffer = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); 261 | assert(buffer); 262 | memcpy(buffer, positions, positionsSize); 263 | memcpy(buffer + positionsSize, normals, normalsSize); 264 | glUnmapBuffer(GL_ARRAY_BUFFER); 265 | 266 | glEnableVertexAttribArray(0); 267 | glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); 268 | glEnableVertexAttribArray(1); 269 | glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)positionsSize); 270 | 271 | free(positions); 272 | free(normals); 273 | 274 | const char *attribs[] = 275 | { 276 | "a_position", 277 | "a_normal" 278 | }; 279 | 280 | const char *vp = 281 | "#version 150 core\n" 282 | "in vec3 a_position;\n" 283 | "in vec3 a_normal;\n" 284 | "uniform mat4 u_view;\n" 285 | "uniform mat4 u_projection;\n" 286 | "out vec3 v_normal;\n" 287 | 288 | "void main()\n" 289 | "{\n" 290 | " gl_Position = u_projection * (u_view * vec4(a_position, 1.0));\n" 291 | " v_normal = a_normal;\n" 292 | "}\n"; 293 | 294 | const char *fp = 295 | "#version 150 core\n" 296 | "in vec3 v_normal;\n" 297 | "uniform vec3 u_coefficients[9];\n" 298 | "out vec4 o_color;\n" 299 | 300 | "void main()\n" 301 | "{\n" 302 | " vec3 n = normalize(v_normal);\n" 303 | " vec3 SHLightResult[9];\n" 304 | " SHLightResult[0] = 0.282095f * u_coefficients[0];\n" 305 | " SHLightResult[1] = -0.488603f * n.y * u_coefficients[1];\n" 306 | " SHLightResult[2] = 0.488603f * n.z * u_coefficients[2];\n" 307 | " SHLightResult[3] = -0.488603f * n.x * u_coefficients[3];\n" 308 | " SHLightResult[4] = 1.092548f * n.x * n.y * u_coefficients[4];\n" 309 | " SHLightResult[5] = -1.092548f * n.y * n.z * u_coefficients[5];\n" 310 | " SHLightResult[6] = 0.315392f * (3.0f * n.z * n.z - 1.0f) * u_coefficients[6];\n" 311 | " SHLightResult[7] = -1.092548f * n.x * n.z * u_coefficients[7];\n" 312 | " SHLightResult[8] = 0.546274f * (n.x * n.x - n.y * n.y) * u_coefficients[8];\n" 313 | " vec3 result = vec3(0.0);\n" 314 | " for (int i = 0; i < 9; ++i)\n" 315 | " result += SHLightResult[i];\n" 316 | " o_color = vec4(result, 1.0);\n" 317 | "}\n"; 318 | 319 | scene->mesh.program = s_loadProgram(vp, fp, attribs, 2); 320 | if (!scene->mesh.program) 321 | { 322 | fprintf(stderr, "Error loading mesh shader\n"); 323 | return 0; 324 | } 325 | scene->mesh.u_view = glGetUniformLocation(scene->mesh.program, "u_view"); 326 | scene->mesh.u_projection = glGetUniformLocation(scene->mesh.program, "u_projection"); 327 | scene->mesh.u_coefficients = glGetUniformLocation(scene->mesh.program, "u_coefficients"); 328 | 329 | return 1; 330 | } 331 | 332 | static void drawScene(scene_t *scene, float *view, float *projection) 333 | { 334 | glClear(GL_DEPTH_BUFFER_BIT); 335 | glEnable(GL_DEPTH_TEST); 336 | glDepthFunc(GL_LEQUAL); 337 | //glDisable(GL_CULL_FACE); 338 | 339 | // mesh 340 | glUseProgram(scene->mesh.program); 341 | glUniformMatrix4fv(scene->mesh.u_projection, 1, GL_FALSE, projection); 342 | glUniformMatrix4fv(scene->mesh.u_view, 1, GL_FALSE, view); 343 | glUniform3fv(scene->mesh.u_coefficients, 9, &scene->mesh.coefficients[0].x); 344 | glBindVertexArray(scene->mesh.vao); 345 | glDrawArrays(GL_TRIANGLES, 0, scene->mesh.vertices); 346 | 347 | // sky 348 | glDepthMask(GL_FALSE); 349 | glUseProgram(scene->sky.program); 350 | glUniformMatrix4fv(scene->sky.u_projection, 1, GL_FALSE, projection); 351 | glUniformMatrix4fv(scene->sky.u_view, 1, GL_FALSE, view); 352 | glUniform1i(scene->sky.u_cubemap, 0); 353 | glBindTexture(GL_TEXTURE_CUBE_MAP, scene->sky.texture); 354 | glBindVertexArray(scene->sky.vao); 355 | glDrawElements(GL_TRIANGLE_STRIP, scene->sky.indices, GL_UNSIGNED_SHORT, 0); 356 | glDepthMask(GL_TRUE); 357 | } 358 | 359 | static void destroyScene(scene_t *scene) 360 | { 361 | // sky 362 | glDeleteProgram(scene->sky.program); 363 | glDeleteVertexArrays(1, &scene->sky.vao); 364 | glDeleteBuffers(1, &scene->sky.vbo); 365 | glDeleteBuffers(1, &scene->sky.ibo); 366 | glDeleteTextures(1, &scene->sky.texture); 367 | 368 | // mesh 369 | glDeleteProgram(scene->mesh.program); 370 | glDeleteVertexArrays(1, &scene->mesh.vao); 371 | glDeleteBuffers(1, &scene->mesh.vbo); 372 | } 373 | 374 | static void fpsCameraViewMatrix(GLFWwindow *window, float *view, bool ignoreInput) 375 | { 376 | // initial camera config 377 | static float position[] = { 0.0f, 0.0f, 3.0f }; 378 | static float rotation[] = { 0.0f, 0.0f }; 379 | 380 | // mouse look 381 | static double lastMouse[] = { 0.0, 0.0 }; 382 | double mouse[2]; 383 | glfwGetCursorPos(window, &mouse[0], &mouse[1]); 384 | if (!ignoreInput && glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) 385 | { 386 | rotation[0] += (float)(mouse[1] - lastMouse[1]) * -0.2f; 387 | rotation[1] += (float)(mouse[0] - lastMouse[0]) * -0.2f; 388 | } 389 | lastMouse[0] = mouse[0]; 390 | lastMouse[1] = mouse[1]; 391 | 392 | float rotationY[16], rotationX[16], rotationYX[16]; 393 | m_rotation44(rotationX, rotation[0], 1.0f, 0.0f, 0.0f); 394 | m_rotation44(rotationY, rotation[1], 0.0f, 1.0f, 0.0f); 395 | m_mul44(rotationYX, rotationY, rotationX); 396 | 397 | // keyboard movement (WSADEQ) 398 | float speed = (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) ? 0.1f : 0.01f; 399 | float movement[3] = { 0 }; 400 | if (!ignoreInput) 401 | { 402 | if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) movement[2] -= speed; 403 | if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) movement[2] += speed; 404 | if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) movement[0] -= speed; 405 | if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) movement[0] += speed; 406 | if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) movement[1] -= speed; 407 | if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) movement[1] += speed; 408 | } 409 | 410 | float worldMovement[3]; 411 | m_transform44(worldMovement, rotationYX, movement); 412 | position[0] += worldMovement[0]; 413 | position[1] += worldMovement[1]; 414 | position[2] += worldMovement[2]; 415 | 416 | // construct view matrix 417 | float inverseRotation[16], inverseTranslation[16]; 418 | m_transpose44(inverseRotation, rotationYX); 419 | m_translation44(inverseTranslation, -position[0], -position[1], -position[2]); 420 | m_mul44(view, inverseRotation, inverseTranslation); // = inverse(translation(position) * rotationYX); 421 | } 422 | 423 | static void error_callback(int error, const char *description) 424 | { 425 | fprintf(stderr, "Error: %s\n", description); 426 | } 427 | 428 | int main(int argc, char* argv[]) 429 | { 430 | glfwSetErrorCallback(error_callback); 431 | if (!glfwInit()) return 1; 432 | glfwWindowHint(GLFW_RED_BITS, 8); 433 | glfwWindowHint(GLFW_GREEN_BITS, 8); 434 | glfwWindowHint(GLFW_BLUE_BITS, 8); 435 | glfwWindowHint(GLFW_ALPHA_BITS, 8); 436 | glfwWindowHint(GLFW_DEPTH_BITS, 32); 437 | glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE); 438 | glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 439 | glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); 440 | glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 441 | glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 442 | glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); 443 | glfwWindowHint(GLFW_SAMPLES, 4); 444 | GLFWwindow *window = glfwCreateWindow(1280, 800, "Spherical Harmonics Playground", NULL, NULL); 445 | if (!window) return 1; 446 | glfwMakeContextCurrent(window); 447 | gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); 448 | glfwSwapInterval(1); 449 | 450 | ImGui_ImplGlfwGL3_Init(window, true); 451 | 452 | scene_t scene = {0}; 453 | if (!initScene(&scene)) 454 | { 455 | fprintf(stderr, "Could not initialize scene.\n"); 456 | return 1; 457 | } 458 | 459 | while (!glfwWindowShouldClose(window)) 460 | { 461 | glfwPollEvents(); 462 | if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) 463 | { 464 | destroyScene(&scene); 465 | if (!initScene(&scene)) 466 | { 467 | fprintf(stderr, "Could not reinitialize scene.\n"); 468 | break; 469 | } 470 | } 471 | ImGui_ImplGlfwGL3_NewFrame(); 472 | 473 | ImGui::SetNextWindowSize(ImVec2(300, 300), ImGuiSetCond_FirstUseEver); 474 | static bool show_another_window = true; 475 | ImGui::Begin("Coefficients", &show_another_window); 476 | for (int i = 0; i < 9; i++) 477 | { 478 | char name[] = "[?]"; 479 | name[1] = i + '0'; 480 | m_vec3 remapped = m_scale3(m_add3(scene.mesh.coefficients[i], m_v3(1.0f, 1.0f, 1.0f)), 0.5f); 481 | ImGui::ColorEdit3(name, &remapped.x); 482 | scene.mesh.coefficients[i] = m_sub3(m_scale3(remapped, 2.0f), m_v3(1.0f, 1.0f, 1.0f)); 483 | } 484 | ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); 485 | ImGui::End(); 486 | 487 | int w, h; 488 | glfwGetFramebufferSize(window, &w, &h); 489 | glViewport(0, 0, w, h); 490 | float view[16], projection[16]; 491 | fpsCameraViewMatrix(window, view, ImGui::IsAnyItemActive()); 492 | m_perspective44(projection, 45.0f, (float)w / (float)h, 0.01f, 100.0f); 493 | drawScene(&scene, view, projection); 494 | 495 | ImGui::Render(); 496 | glfwSwapBuffers(window); 497 | } 498 | 499 | destroyScene(&scene); 500 | ImGui_ImplGlfwGL3_Shutdown(); 501 | glfwDestroyWindow(window); 502 | glfwTerminate(); 503 | return 0; 504 | } -------------------------------------------------------------------------------- /result_images/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/result_images/dog.jpg -------------------------------------------------------------------------------- /result_images/sphere.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ands/spherical_harmonics_playground/347ddb722efde4df6a29b4fee5c76f712d014d96/result_images/sphere.jpg -------------------------------------------------------------------------------- /s_shader.h: -------------------------------------------------------------------------------- 1 | /*********************************************************** 2 | * OpenGL shader load helper * 3 | * no warranty implied | use at your own risk * 4 | * author: Andreas Mantler (ands) | last change: 13.04.2018 * 5 | * * 6 | * License: * 7 | * This software is in the public domain. * 8 | * Where that dedication is not recognized, * 9 | * you are granted a perpetual, irrevocable license to copy * 10 | * and modify this file however you want. * 11 | ***********************************************************/ 12 | 13 | static GLuint s_loadShader(GLenum type, const char *source) 14 | { 15 | GLuint shader = glCreateShader(type); 16 | if (shader == 0) 17 | { 18 | fprintf(stderr, "Could not create shader!\n"); 19 | return 0; 20 | } 21 | glShaderSource(shader, 1, &source, NULL); 22 | glCompileShader(shader); 23 | GLint compiled; 24 | glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); 25 | if (!compiled) 26 | { 27 | fprintf(stderr, "Could not compile shader!\n"); 28 | GLint infoLen = 0; 29 | glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); 30 | if (infoLen) 31 | { 32 | char* infoLog = (char*)malloc(infoLen); 33 | glGetShaderInfoLog(shader, infoLen, NULL, infoLog); 34 | fprintf(stderr, "%s\n", infoLog); 35 | free(infoLog); 36 | } 37 | glDeleteShader(shader); 38 | return 0; 39 | } 40 | return shader; 41 | } 42 | 43 | static GLuint s_loadProgram(const char *vp, const char *fp, const char **attributes, int attributeCount) 44 | { 45 | GLuint vertexShader = s_loadShader(GL_VERTEX_SHADER, vp); 46 | if (!vertexShader) 47 | return 0; 48 | GLuint fragmentShader = s_loadShader(GL_FRAGMENT_SHADER, fp); 49 | if (!fragmentShader) 50 | { 51 | glDeleteShader(vertexShader); 52 | return 0; 53 | } 54 | 55 | GLuint program = glCreateProgram(); 56 | if (program == 0) 57 | { 58 | fprintf(stderr, "Could not create program!\n"); 59 | return 0; 60 | } 61 | glAttachShader(program, vertexShader); 62 | glAttachShader(program, fragmentShader); 63 | 64 | for (int i = 0; i < attributeCount; i++) 65 | glBindAttribLocation(program, i, attributes[i]); 66 | 67 | glLinkProgram(program); 68 | glDeleteShader(vertexShader); 69 | glDeleteShader(fragmentShader); 70 | GLint linked; 71 | glGetProgramiv(program, GL_LINK_STATUS, &linked); 72 | if (!linked) 73 | { 74 | fprintf(stderr, "Could not link program!\n"); 75 | GLint infoLen = 0; 76 | glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen); 77 | if (infoLen) 78 | { 79 | char* infoLog = (char*)malloc(sizeof(char) * infoLen); 80 | glGetProgramInfoLog(program, infoLen, NULL, infoLog); 81 | fprintf(stderr, "%s\n", infoLog); 82 | free(infoLog); 83 | } 84 | glDeleteProgram(program); 85 | return 0; 86 | } 87 | return program; 88 | } -------------------------------------------------------------------------------- /stb_rect_pack.h: -------------------------------------------------------------------------------- 1 | // stb_rect_pack.h - v0.08 - public domain - rectangle packing 2 | // Sean Barrett 2014 3 | // 4 | // Useful for e.g. packing rectangular textures into an atlas. 5 | // Does not do rotation. 6 | // 7 | // Not necessarily the awesomest packing method, but better than 8 | // the totally naive one in stb_truetype (which is primarily what 9 | // this is meant to replace). 10 | // 11 | // Has only had a few tests run, may have issues. 12 | // 13 | // More docs to come. 14 | // 15 | // No memory allocations; uses qsort() and assert() from stdlib. 16 | // Can override those by defining STBRP_SORT and STBRP_ASSERT. 17 | // 18 | // This library currently uses the Skyline Bottom-Left algorithm. 19 | // 20 | // Please note: better rectangle packers are welcome! Please 21 | // implement them to the same API, but with a different init 22 | // function. 23 | // 24 | // Credits 25 | // 26 | // Library 27 | // Sean Barrett 28 | // Minor features 29 | // Martins Mozeiko 30 | // Bugfixes / warning fixes 31 | // Jeremy Jaussaud 32 | // 33 | // Version history: 34 | // 35 | // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) 36 | // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) 37 | // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort 38 | // 0.05: added STBRP_ASSERT to allow replacing assert 39 | // 0.04: fixed minor bug in STBRP_LARGE_RECTS support 40 | // 0.01: initial release 41 | // 42 | // LICENSE 43 | // 44 | // This software is in the public domain. Where that dedication is not 45 | // recognized, you are granted a perpetual, irrevocable license to copy, 46 | // distribute, and modify this file as you see fit. 47 | 48 | ////////////////////////////////////////////////////////////////////////////// 49 | // 50 | // INCLUDE SECTION 51 | // 52 | 53 | #ifndef STB_INCLUDE_STB_RECT_PACK_H 54 | #define STB_INCLUDE_STB_RECT_PACK_H 55 | 56 | #define STB_RECT_PACK_VERSION 1 57 | 58 | #ifdef STBRP_STATIC 59 | #define STBRP_DEF static 60 | #else 61 | #define STBRP_DEF extern 62 | #endif 63 | 64 | #ifdef __cplusplus 65 | extern "C" { 66 | #endif 67 | 68 | typedef struct stbrp_context stbrp_context; 69 | typedef struct stbrp_node stbrp_node; 70 | typedef struct stbrp_rect stbrp_rect; 71 | 72 | #ifdef STBRP_LARGE_RECTS 73 | typedef int stbrp_coord; 74 | #else 75 | typedef unsigned short stbrp_coord; 76 | #endif 77 | 78 | STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); 79 | // Assign packed locations to rectangles. The rectangles are of type 80 | // 'stbrp_rect' defined below, stored in the array 'rects', and there 81 | // are 'num_rects' many of them. 82 | // 83 | // Rectangles which are successfully packed have the 'was_packed' flag 84 | // set to a non-zero value and 'x' and 'y' store the minimum location 85 | // on each axis (i.e. bottom-left in cartesian coordinates, top-left 86 | // if you imagine y increasing downwards). Rectangles which do not fit 87 | // have the 'was_packed' flag set to 0. 88 | // 89 | // You should not try to access the 'rects' array from another thread 90 | // while this function is running, as the function temporarily reorders 91 | // the array while it executes. 92 | // 93 | // To pack into another rectangle, you need to call stbrp_init_target 94 | // again. To continue packing into the same rectangle, you can call 95 | // this function again. Calling this multiple times with multiple rect 96 | // arrays will probably produce worse packing results than calling it 97 | // a single time with the full rectangle array, but the option is 98 | // available. 99 | 100 | struct stbrp_rect 101 | { 102 | // reserved for your use: 103 | int id; 104 | 105 | // input: 106 | stbrp_coord w, h; 107 | 108 | // output: 109 | stbrp_coord x, y; 110 | int was_packed; // non-zero if valid packing 111 | 112 | }; // 16 bytes, nominally 113 | 114 | 115 | STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); 116 | // Initialize a rectangle packer to: 117 | // pack a rectangle that is 'width' by 'height' in dimensions 118 | // using temporary storage provided by the array 'nodes', which is 'num_nodes' long 119 | // 120 | // You must call this function every time you start packing into a new target. 121 | // 122 | // There is no "shutdown" function. The 'nodes' memory must stay valid for 123 | // the following stbrp_pack_rects() call (or calls), but can be freed after 124 | // the call (or calls) finish. 125 | // 126 | // Note: to guarantee best results, either: 127 | // 1. make sure 'num_nodes' >= 'width' 128 | // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' 129 | // 130 | // If you don't do either of the above things, widths will be quantized to multiples 131 | // of small integers to guarantee the algorithm doesn't run out of temporary storage. 132 | // 133 | // If you do #2, then the non-quantized algorithm will be used, but the algorithm 134 | // may run out of temporary storage and be unable to pack some rectangles. 135 | 136 | STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); 137 | // Optionally call this function after init but before doing any packing to 138 | // change the handling of the out-of-temp-memory scenario, described above. 139 | // If you call init again, this will be reset to the default (false). 140 | 141 | 142 | STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); 143 | // Optionally select which packing heuristic the library should use. Different 144 | // heuristics will produce better/worse results for different data sets. 145 | // If you call init again, this will be reset to the default. 146 | 147 | enum 148 | { 149 | STBRP_HEURISTIC_Skyline_default=0, 150 | STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, 151 | STBRP_HEURISTIC_Skyline_BF_sortHeight 152 | }; 153 | 154 | 155 | ////////////////////////////////////////////////////////////////////////////// 156 | // 157 | // the details of the following structures don't matter to you, but they must 158 | // be visible so you can handle the memory allocations for them 159 | 160 | struct stbrp_node 161 | { 162 | stbrp_coord x,y; 163 | stbrp_node *next; 164 | }; 165 | 166 | struct stbrp_context 167 | { 168 | int width; 169 | int height; 170 | int align; 171 | int init_mode; 172 | int heuristic; 173 | int num_nodes; 174 | stbrp_node *active_head; 175 | stbrp_node *free_head; 176 | stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' 177 | }; 178 | 179 | #ifdef __cplusplus 180 | } 181 | #endif 182 | 183 | #endif 184 | 185 | ////////////////////////////////////////////////////////////////////////////// 186 | // 187 | // IMPLEMENTATION SECTION 188 | // 189 | 190 | #ifdef STB_RECT_PACK_IMPLEMENTATION 191 | #ifndef STBRP_SORT 192 | #include 193 | #define STBRP_SORT qsort 194 | #endif 195 | 196 | #ifndef STBRP_ASSERT 197 | #include 198 | #define STBRP_ASSERT assert 199 | #endif 200 | 201 | enum 202 | { 203 | STBRP__INIT_skyline = 1 204 | }; 205 | 206 | STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) 207 | { 208 | switch (context->init_mode) { 209 | case STBRP__INIT_skyline: 210 | STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); 211 | context->heuristic = heuristic; 212 | break; 213 | default: 214 | STBRP_ASSERT(0); 215 | } 216 | } 217 | 218 | STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) 219 | { 220 | if (allow_out_of_mem) 221 | // if it's ok to run out of memory, then don't bother aligning them; 222 | // this gives better packing, but may fail due to OOM (even though 223 | // the rectangles easily fit). @TODO a smarter approach would be to only 224 | // quantize once we've hit OOM, then we could get rid of this parameter. 225 | context->align = 1; 226 | else { 227 | // if it's not ok to run out of memory, then quantize the widths 228 | // so that num_nodes is always enough nodes. 229 | // 230 | // I.e. num_nodes * align >= width 231 | // align >= width / num_nodes 232 | // align = ceil(width/num_nodes) 233 | 234 | context->align = (context->width + context->num_nodes-1) / context->num_nodes; 235 | } 236 | } 237 | 238 | STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) 239 | { 240 | int i; 241 | #ifndef STBRP_LARGE_RECTS 242 | STBRP_ASSERT(width <= 0xffff && height <= 0xffff); 243 | #endif 244 | 245 | for (i=0; i < num_nodes-1; ++i) 246 | nodes[i].next = &nodes[i+1]; 247 | nodes[i].next = NULL; 248 | context->init_mode = STBRP__INIT_skyline; 249 | context->heuristic = STBRP_HEURISTIC_Skyline_default; 250 | context->free_head = &nodes[0]; 251 | context->active_head = &context->extra[0]; 252 | context->width = width; 253 | context->height = height; 254 | context->num_nodes = num_nodes; 255 | stbrp_setup_allow_out_of_mem(context, 0); 256 | 257 | // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) 258 | context->extra[0].x = 0; 259 | context->extra[0].y = 0; 260 | context->extra[0].next = &context->extra[1]; 261 | context->extra[1].x = (stbrp_coord) width; 262 | #ifdef STBRP_LARGE_RECTS 263 | context->extra[1].y = (1<<30); 264 | #else 265 | context->extra[1].y = 65535; 266 | #endif 267 | context->extra[1].next = NULL; 268 | } 269 | 270 | // find minimum y position if it starts at x1 271 | static int stbrp__skyline_find_min_y(stbrp_context *, stbrp_node *first, int x0, int width, int *pwaste) 272 | { 273 | //(void)c; 274 | stbrp_node *node = first; 275 | int x1 = x0 + width; 276 | int min_y, visited_width, waste_area; 277 | STBRP_ASSERT(first->x <= x0); 278 | 279 | #if 0 280 | // skip in case we're past the node 281 | while (node->next->x <= x0) 282 | ++node; 283 | #else 284 | STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency 285 | #endif 286 | 287 | STBRP_ASSERT(node->x <= x0); 288 | 289 | min_y = 0; 290 | waste_area = 0; 291 | visited_width = 0; 292 | while (node->x < x1) { 293 | if (node->y > min_y) { 294 | // raise min_y higher. 295 | // we've accounted for all waste up to min_y, 296 | // but we'll now add more waste for everything we've visted 297 | waste_area += visited_width * (node->y - min_y); 298 | min_y = node->y; 299 | // the first time through, visited_width might be reduced 300 | if (node->x < x0) 301 | visited_width += node->next->x - x0; 302 | else 303 | visited_width += node->next->x - node->x; 304 | } else { 305 | // add waste area 306 | int under_width = node->next->x - node->x; 307 | if (under_width + visited_width > width) 308 | under_width = width - visited_width; 309 | waste_area += under_width * (min_y - node->y); 310 | visited_width += under_width; 311 | } 312 | node = node->next; 313 | } 314 | 315 | *pwaste = waste_area; 316 | return min_y; 317 | } 318 | 319 | typedef struct 320 | { 321 | int x,y; 322 | stbrp_node **prev_link; 323 | } stbrp__findresult; 324 | 325 | static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) 326 | { 327 | int best_waste = (1<<30), best_x, best_y = (1 << 30); 328 | stbrp__findresult fr; 329 | stbrp_node **prev, *node, *tail, **best = NULL; 330 | 331 | // align to multiple of c->align 332 | width = (width + c->align - 1); 333 | width -= width % c->align; 334 | STBRP_ASSERT(width % c->align == 0); 335 | 336 | node = c->active_head; 337 | prev = &c->active_head; 338 | while (node->x + width <= c->width) { 339 | int y,waste; 340 | y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); 341 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL 342 | // bottom left 343 | if (y < best_y) { 344 | best_y = y; 345 | best = prev; 346 | } 347 | } else { 348 | // best-fit 349 | if (y + height <= c->height) { 350 | // can only use it if it first vertically 351 | if (y < best_y || (y == best_y && waste < best_waste)) { 352 | best_y = y; 353 | best_waste = waste; 354 | best = prev; 355 | } 356 | } 357 | } 358 | prev = &node->next; 359 | node = node->next; 360 | } 361 | 362 | best_x = (best == NULL) ? 0 : (*best)->x; 363 | 364 | // if doing best-fit (BF), we also have to try aligning right edge to each node position 365 | // 366 | // e.g, if fitting 367 | // 368 | // ____________________ 369 | // |____________________| 370 | // 371 | // into 372 | // 373 | // | | 374 | // | ____________| 375 | // |____________| 376 | // 377 | // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned 378 | // 379 | // This makes BF take about 2x the time 380 | 381 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { 382 | tail = c->active_head; 383 | node = c->active_head; 384 | prev = &c->active_head; 385 | // find first node that's admissible 386 | while (tail->x < width) 387 | tail = tail->next; 388 | while (tail) { 389 | int xpos = tail->x - width; 390 | int y,waste; 391 | STBRP_ASSERT(xpos >= 0); 392 | // find the left position that matches this 393 | while (node->next->x <= xpos) { 394 | prev = &node->next; 395 | node = node->next; 396 | } 397 | STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); 398 | y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); 399 | if (y + height < c->height) { 400 | if (y <= best_y) { 401 | if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { 402 | best_x = xpos; 403 | STBRP_ASSERT(y <= best_y); 404 | best_y = y; 405 | best_waste = waste; 406 | best = prev; 407 | } 408 | } 409 | } 410 | tail = tail->next; 411 | } 412 | } 413 | 414 | fr.prev_link = best; 415 | fr.x = best_x; 416 | fr.y = best_y; 417 | return fr; 418 | } 419 | 420 | static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) 421 | { 422 | // find best position according to heuristic 423 | stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); 424 | stbrp_node *node, *cur; 425 | 426 | // bail if: 427 | // 1. it failed 428 | // 2. the best node doesn't fit (we don't always check this) 429 | // 3. we're out of memory 430 | if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { 431 | res.prev_link = NULL; 432 | return res; 433 | } 434 | 435 | // on success, create new node 436 | node = context->free_head; 437 | node->x = (stbrp_coord) res.x; 438 | node->y = (stbrp_coord) (res.y + height); 439 | 440 | context->free_head = node->next; 441 | 442 | // insert the new node into the right starting point, and 443 | // let 'cur' point to the remaining nodes needing to be 444 | // stiched back in 445 | 446 | cur = *res.prev_link; 447 | if (cur->x < res.x) { 448 | // preserve the existing one, so start testing with the next one 449 | stbrp_node *next = cur->next; 450 | cur->next = node; 451 | cur = next; 452 | } else { 453 | *res.prev_link = node; 454 | } 455 | 456 | // from here, traverse cur and free the nodes, until we get to one 457 | // that shouldn't be freed 458 | while (cur->next && cur->next->x <= res.x + width) { 459 | stbrp_node *next = cur->next; 460 | // move the current node to the free list 461 | cur->next = context->free_head; 462 | context->free_head = cur; 463 | cur = next; 464 | } 465 | 466 | // stitch the list back in 467 | node->next = cur; 468 | 469 | if (cur->x < res.x + width) 470 | cur->x = (stbrp_coord) (res.x + width); 471 | 472 | #ifdef _DEBUG 473 | cur = context->active_head; 474 | while (cur->x < context->width) { 475 | STBRP_ASSERT(cur->x < cur->next->x); 476 | cur = cur->next; 477 | } 478 | STBRP_ASSERT(cur->next == NULL); 479 | 480 | { 481 | stbrp_node *L1 = NULL, *L2 = NULL; 482 | int count=0; 483 | cur = context->active_head; 484 | while (cur) { 485 | L1 = cur; 486 | cur = cur->next; 487 | ++count; 488 | } 489 | cur = context->free_head; 490 | while (cur) { 491 | L2 = cur; 492 | cur = cur->next; 493 | ++count; 494 | } 495 | STBRP_ASSERT(count == context->num_nodes+2); 496 | } 497 | #endif 498 | 499 | return res; 500 | } 501 | 502 | static int rect_height_compare(const void *a, const void *b) 503 | { 504 | stbrp_rect *p = (stbrp_rect *) a; 505 | stbrp_rect *q = (stbrp_rect *) b; 506 | if (p->h > q->h) 507 | return -1; 508 | if (p->h < q->h) 509 | return 1; 510 | return (p->w > q->w) ? -1 : (p->w < q->w); 511 | } 512 | 513 | static int rect_width_compare(const void *a, const void *b) 514 | { 515 | stbrp_rect *p = (stbrp_rect *) a; 516 | stbrp_rect *q = (stbrp_rect *) b; 517 | if (p->w > q->w) 518 | return -1; 519 | if (p->w < q->w) 520 | return 1; 521 | return (p->h > q->h) ? -1 : (p->h < q->h); 522 | } 523 | 524 | static int rect_original_order(const void *a, const void *b) 525 | { 526 | stbrp_rect *p = (stbrp_rect *) a; 527 | stbrp_rect *q = (stbrp_rect *) b; 528 | return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); 529 | } 530 | 531 | #ifdef STBRP_LARGE_RECTS 532 | #define STBRP__MAXVAL 0xffffffff 533 | #else 534 | #define STBRP__MAXVAL 0xffff 535 | #endif 536 | 537 | STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) 538 | { 539 | int i; 540 | 541 | // we use the 'was_packed' field internally to allow sorting/unsorting 542 | for (i=0; i < num_rects; ++i) { 543 | rects[i].was_packed = i; 544 | #ifndef STBRP_LARGE_RECTS 545 | STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff); 546 | #endif 547 | } 548 | 549 | // sort according to heuristic 550 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); 551 | 552 | for (i=0; i < num_rects; ++i) { 553 | if (rects[i].w == 0 || rects[i].h == 0) { 554 | rects[i].x = rects[i].y = 0; // empty rect needs no space 555 | } else { 556 | stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); 557 | if (fr.prev_link) { 558 | rects[i].x = (stbrp_coord) fr.x; 559 | rects[i].y = (stbrp_coord) fr.y; 560 | } else { 561 | rects[i].x = rects[i].y = STBRP__MAXVAL; 562 | } 563 | } 564 | } 565 | 566 | // unsort 567 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); 568 | 569 | // set was_packed flags 570 | for (i=0; i < num_rects; ++i) 571 | rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); 572 | } 573 | #endif 574 | -------------------------------------------------------------------------------- /stb_textedit.h: -------------------------------------------------------------------------------- 1 | // [ImGui] this is a slightly modified version of stb_truetype.h 1.8 2 | // [ImGui] - fixed a state corruption/crash bug in stb_text_redo and stb_textedit_discard_redo (#715) 3 | // [ImGui] - fixed a crash bug in stb_textedit_discard_redo (#681) 4 | // [ImGui] - fixed some minor warnings 5 | // [ImGui] - added STB_TEXTEDIT_MOVEWORDLEFT/STB_TEXTEDIT_MOVEWORDRIGHT custom handler (#473) 6 | 7 | // stb_textedit.h - v1.8 - public domain - Sean Barrett 8 | // Development of this library was sponsored by RAD Game Tools 9 | // 10 | // This C header file implements the guts of a multi-line text-editing 11 | // widget; you implement display, word-wrapping, and low-level string 12 | // insertion/deletion, and stb_textedit will map user inputs into 13 | // insertions & deletions, plus updates to the cursor position, 14 | // selection state, and undo state. 15 | // 16 | // It is intended for use in games and other systems that need to build 17 | // their own custom widgets and which do not have heavy text-editing 18 | // requirements (this library is not recommended for use for editing large 19 | // texts, as its performance does not scale and it has limited undo). 20 | // 21 | // Non-trivial behaviors are modelled after Windows text controls. 22 | // 23 | // 24 | // LICENSE 25 | // 26 | // This software is dual-licensed to the public domain and under the following 27 | // license: you are granted a perpetual, irrevocable license to copy, modify, 28 | // publish, and distribute this file as you see fit. 29 | // 30 | // 31 | // DEPENDENCIES 32 | // 33 | // Uses the C runtime function 'memmove', which you can override 34 | // by defining STB_TEXTEDIT_memmove before the implementation. 35 | // Uses no other functions. Performs no runtime allocations. 36 | // 37 | // 38 | // VERSION HISTORY 39 | // 40 | // 1.8 (2016-04-02) better keyboard handling when mouse button is down 41 | // 1.7 (2015-09-13) change y range handling in case baseline is non-0 42 | // 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove 43 | // 1.5 (2014-09-10) add support for secondary keys for OS X 44 | // 1.4 (2014-08-17) fix signed/unsigned warnings 45 | // 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary 46 | // 1.2 (2014-05-27) fix some RAD types that had crept into the new code 47 | // 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) 48 | // 1.0 (2012-07-26) improve documentation, initial public release 49 | // 0.3 (2012-02-24) bugfixes, single-line mode; insert mode 50 | // 0.2 (2011-11-28) fixes to undo/redo 51 | // 0.1 (2010-07-08) initial version 52 | // 53 | // ADDITIONAL CONTRIBUTORS 54 | // 55 | // Ulf Winklemann: move-by-word in 1.1 56 | // Fabian Giesen: secondary key inputs in 1.5 57 | // Martins Mozeiko: STB_TEXTEDIT_memmove 58 | // 59 | // Bugfixes: 60 | // Scott Graham 61 | // Daniel Keller 62 | // Omar Cornut 63 | // 64 | // USAGE 65 | // 66 | // This file behaves differently depending on what symbols you define 67 | // before including it. 68 | // 69 | // 70 | // Header-file mode: 71 | // 72 | // If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, 73 | // it will operate in "header file" mode. In this mode, it declares a 74 | // single public symbol, STB_TexteditState, which encapsulates the current 75 | // state of a text widget (except for the string, which you will store 76 | // separately). 77 | // 78 | // To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a 79 | // primitive type that defines a single character (e.g. char, wchar_t, etc). 80 | // 81 | // To save space or increase undo-ability, you can optionally define the 82 | // following things that are used by the undo system: 83 | // 84 | // STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position 85 | // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow 86 | // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer 87 | // 88 | // If you don't define these, they are set to permissive types and 89 | // moderate sizes. The undo system does no memory allocations, so 90 | // it grows STB_TexteditState by the worst-case storage which is (in bytes): 91 | // 92 | // [4 + sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT 93 | // + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT 94 | // 95 | // 96 | // Implementation mode: 97 | // 98 | // If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it 99 | // will compile the implementation of the text edit widget, depending 100 | // on a large number of symbols which must be defined before the include. 101 | // 102 | // The implementation is defined only as static functions. You will then 103 | // need to provide your own APIs in the same file which will access the 104 | // static functions. 105 | // 106 | // The basic concept is that you provide a "string" object which 107 | // behaves like an array of characters. stb_textedit uses indices to 108 | // refer to positions in the string, implicitly representing positions 109 | // in the displayed textedit. This is true for both plain text and 110 | // rich text; even with rich text stb_truetype interacts with your 111 | // code as if there was an array of all the displayed characters. 112 | // 113 | // Symbols that must be the same in header-file and implementation mode: 114 | // 115 | // STB_TEXTEDIT_CHARTYPE the character type 116 | // STB_TEXTEDIT_POSITIONTYPE small type that a valid cursor position 117 | // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow 118 | // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer 119 | // 120 | // Symbols you must define for implementation mode: 121 | // 122 | // STB_TEXTEDIT_STRING the type of object representing a string being edited, 123 | // typically this is a wrapper object with other data you need 124 | // 125 | // STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) 126 | // STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters 127 | // starting from character #n (see discussion below) 128 | // STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character 129 | // to the xpos of the i+1'th char for a line of characters 130 | // starting at character #n (i.e. accounts for kerning 131 | // with previous char) 132 | // STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character 133 | // (return type is int, -1 means not valid to insert) 134 | // STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based 135 | // STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize 136 | // as manually wordwrapping for end-of-line positioning 137 | // 138 | // STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i 139 | // STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) 140 | // 141 | // STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key 142 | // 143 | // STB_TEXTEDIT_K_LEFT keyboard input to move cursor left 144 | // STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right 145 | // STB_TEXTEDIT_K_UP keyboard input to move cursor up 146 | // STB_TEXTEDIT_K_DOWN keyboard input to move cursor down 147 | // STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME 148 | // STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END 149 | // STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME 150 | // STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END 151 | // STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor 152 | // STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor 153 | // STB_TEXTEDIT_K_UNDO keyboard input to perform undo 154 | // STB_TEXTEDIT_K_REDO keyboard input to perform redo 155 | // 156 | // Optional: 157 | // STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode 158 | // STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), 159 | // required for default WORDLEFT/WORDRIGHT handlers 160 | // STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to 161 | // STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to 162 | // STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT 163 | // STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT 164 | // STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line 165 | // STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line 166 | // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text 167 | // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text 168 | // 169 | // Todo: 170 | // STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page 171 | // STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page 172 | // 173 | // Keyboard input must be encoded as a single integer value; e.g. a character code 174 | // and some bitflags that represent shift states. to simplify the interface, SHIFT must 175 | // be a bitflag, so we can test the shifted state of cursor movements to allow selection, 176 | // i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. 177 | // 178 | // You can encode other things, such as CONTROL or ALT, in additional bits, and 179 | // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, 180 | // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN 181 | // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, 182 | // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the 183 | // API below. The control keys will only match WM_KEYDOWN events because of the 184 | // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN 185 | // bit so it only decodes WM_CHAR events. 186 | // 187 | // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed 188 | // row of characters assuming they start on the i'th character--the width and 189 | // the height and the number of characters consumed. This allows this library 190 | // to traverse the entire layout incrementally. You need to compute word-wrapping 191 | // here. 192 | // 193 | // Each textfield keeps its own insert mode state, which is not how normal 194 | // applications work. To keep an app-wide insert mode, update/copy the 195 | // "insert_mode" field of STB_TexteditState before/after calling API functions. 196 | // 197 | // API 198 | // 199 | // void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) 200 | // 201 | // void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 202 | // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 203 | // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 204 | // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) 205 | // void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) 206 | // 207 | // Each of these functions potentially updates the string and updates the 208 | // state. 209 | // 210 | // initialize_state: 211 | // set the textedit state to a known good default state when initially 212 | // constructing the textedit. 213 | // 214 | // click: 215 | // call this with the mouse x,y on a mouse down; it will update the cursor 216 | // and reset the selection start/end to the cursor point. the x,y must 217 | // be relative to the text widget, with (0,0) being the top left. 218 | // 219 | // drag: 220 | // call this with the mouse x,y on a mouse drag/up; it will update the 221 | // cursor and the selection end point 222 | // 223 | // cut: 224 | // call this to delete the current selection; returns true if there was 225 | // one. you should FIRST copy the current selection to the system paste buffer. 226 | // (To copy, just copy the current selection out of the string yourself.) 227 | // 228 | // paste: 229 | // call this to paste text at the current cursor point or over the current 230 | // selection if there is one. 231 | // 232 | // key: 233 | // call this for keyboard inputs sent to the textfield. you can use it 234 | // for "key down" events or for "translated" key events. if you need to 235 | // do both (as in Win32), or distinguish Unicode characters from control 236 | // inputs, set a high bit to distinguish the two; then you can define the 237 | // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit 238 | // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is 239 | // clear. 240 | // 241 | // When rendering, you can read the cursor position and selection state from 242 | // the STB_TexteditState. 243 | // 244 | // 245 | // Notes: 246 | // 247 | // This is designed to be usable in IMGUI, so it allows for the possibility of 248 | // running in an IMGUI that has NOT cached the multi-line layout. For this 249 | // reason, it provides an interface that is compatible with computing the 250 | // layout incrementally--we try to make sure we make as few passes through 251 | // as possible. (For example, to locate the mouse pointer in the text, we 252 | // could define functions that return the X and Y positions of characters 253 | // and binary search Y and then X, but if we're doing dynamic layout this 254 | // will run the layout algorithm many times, so instead we manually search 255 | // forward in one pass. Similar logic applies to e.g. up-arrow and 256 | // down-arrow movement.) 257 | // 258 | // If it's run in a widget that *has* cached the layout, then this is less 259 | // efficient, but it's not horrible on modern computers. But you wouldn't 260 | // want to edit million-line files with it. 261 | 262 | 263 | //////////////////////////////////////////////////////////////////////////// 264 | //////////////////////////////////////////////////////////////////////////// 265 | //// 266 | //// Header-file mode 267 | //// 268 | //// 269 | 270 | #ifndef INCLUDE_STB_TEXTEDIT_H 271 | #define INCLUDE_STB_TEXTEDIT_H 272 | 273 | //////////////////////////////////////////////////////////////////////// 274 | // 275 | // STB_TexteditState 276 | // 277 | // Definition of STB_TexteditState which you should store 278 | // per-textfield; it includes cursor position, selection state, 279 | // and undo state. 280 | // 281 | 282 | #ifndef STB_TEXTEDIT_UNDOSTATECOUNT 283 | #define STB_TEXTEDIT_UNDOSTATECOUNT 99 284 | #endif 285 | #ifndef STB_TEXTEDIT_UNDOCHARCOUNT 286 | #define STB_TEXTEDIT_UNDOCHARCOUNT 999 287 | #endif 288 | #ifndef STB_TEXTEDIT_CHARTYPE 289 | #define STB_TEXTEDIT_CHARTYPE int 290 | #endif 291 | #ifndef STB_TEXTEDIT_POSITIONTYPE 292 | #define STB_TEXTEDIT_POSITIONTYPE int 293 | #endif 294 | 295 | typedef struct 296 | { 297 | // private data 298 | STB_TEXTEDIT_POSITIONTYPE where; 299 | short insert_length; 300 | short delete_length; 301 | short char_storage; 302 | } StbUndoRecord; 303 | 304 | typedef struct 305 | { 306 | // private data 307 | StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; 308 | STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; 309 | short undo_point, redo_point; 310 | short undo_char_point, redo_char_point; 311 | } StbUndoState; 312 | 313 | typedef struct 314 | { 315 | ///////////////////// 316 | // 317 | // public data 318 | // 319 | 320 | int cursor; 321 | // position of the text cursor within the string 322 | 323 | int select_start; // selection start point 324 | int select_end; 325 | // selection start and end point in characters; if equal, no selection. 326 | // note that start may be less than or greater than end (e.g. when 327 | // dragging the mouse, start is where the initial click was, and you 328 | // can drag in either direction) 329 | 330 | unsigned char insert_mode; 331 | // each textfield keeps its own insert mode state. to keep an app-wide 332 | // insert mode, copy this value in/out of the app state 333 | 334 | ///////////////////// 335 | // 336 | // private data 337 | // 338 | unsigned char cursor_at_end_of_line; // not implemented yet 339 | unsigned char initialized; 340 | unsigned char has_preferred_x; 341 | unsigned char single_line; 342 | unsigned char padding1, padding2, padding3; 343 | float preferred_x; // this determines where the cursor up/down tries to seek to along x 344 | StbUndoState undostate; 345 | } STB_TexteditState; 346 | 347 | 348 | //////////////////////////////////////////////////////////////////////// 349 | // 350 | // StbTexteditRow 351 | // 352 | // Result of layout query, used by stb_textedit to determine where 353 | // the text in each row is. 354 | 355 | // result of layout query 356 | typedef struct 357 | { 358 | float x0,x1; // starting x location, end x location (allows for align=right, etc) 359 | float baseline_y_delta; // position of baseline relative to previous row's baseline 360 | float ymin,ymax; // height of row above and below baseline 361 | int num_chars; 362 | } StbTexteditRow; 363 | #endif //INCLUDE_STB_TEXTEDIT_H 364 | 365 | 366 | //////////////////////////////////////////////////////////////////////////// 367 | //////////////////////////////////////////////////////////////////////////// 368 | //// 369 | //// Implementation mode 370 | //// 371 | //// 372 | 373 | 374 | // implementation isn't include-guarded, since it might have indirectly 375 | // included just the "header" portion 376 | #ifdef STB_TEXTEDIT_IMPLEMENTATION 377 | 378 | #ifndef STB_TEXTEDIT_memmove 379 | #include 380 | #define STB_TEXTEDIT_memmove memmove 381 | #endif 382 | 383 | 384 | ///////////////////////////////////////////////////////////////////////////// 385 | // 386 | // Mouse input handling 387 | // 388 | 389 | // traverse the layout to locate the nearest character to a display position 390 | static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) 391 | { 392 | StbTexteditRow r; 393 | int n = STB_TEXTEDIT_STRINGLEN(str); 394 | float base_y = 0, prev_x; 395 | int i=0, k; 396 | 397 | r.x0 = r.x1 = 0; 398 | r.ymin = r.ymax = 0; 399 | r.num_chars = 0; 400 | 401 | // search rows to find one that straddles 'y' 402 | while (i < n) { 403 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 404 | if (r.num_chars <= 0) 405 | return n; 406 | 407 | if (i==0 && y < base_y + r.ymin) 408 | return 0; 409 | 410 | if (y < base_y + r.ymax) 411 | break; 412 | 413 | i += r.num_chars; 414 | base_y += r.baseline_y_delta; 415 | } 416 | 417 | // below all text, return 'after' last character 418 | if (i >= n) 419 | return n; 420 | 421 | // check if it's before the beginning of the line 422 | if (x < r.x0) 423 | return i; 424 | 425 | // check if it's before the end of the line 426 | if (x < r.x1) { 427 | // search characters in row for one that straddles 'x' 428 | k = i; 429 | prev_x = r.x0; 430 | for (i=0; i < r.num_chars; ++i) { 431 | float w = STB_TEXTEDIT_GETWIDTH(str, k, i); 432 | if (x < prev_x+w) { 433 | if (x < prev_x+w/2) 434 | return k+i; 435 | else 436 | return k+i+1; 437 | } 438 | prev_x += w; 439 | } 440 | // shouldn't happen, but if it does, fall through to end-of-line case 441 | } 442 | 443 | // if the last character is a newline, return that. otherwise return 'after' the last character 444 | if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) 445 | return i+r.num_chars-1; 446 | else 447 | return i+r.num_chars; 448 | } 449 | 450 | // API click: on mouse down, move the cursor to the clicked location, and reset the selection 451 | static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 452 | { 453 | state->cursor = stb_text_locate_coord(str, x, y); 454 | state->select_start = state->cursor; 455 | state->select_end = state->cursor; 456 | state->has_preferred_x = 0; 457 | } 458 | 459 | // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location 460 | static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 461 | { 462 | int p = stb_text_locate_coord(str, x, y); 463 | if (state->select_start == state->select_end) 464 | state->select_start = state->cursor; 465 | state->cursor = state->select_end = p; 466 | } 467 | 468 | ///////////////////////////////////////////////////////////////////////////// 469 | // 470 | // Keyboard input handling 471 | // 472 | 473 | // forward declarations 474 | static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); 475 | static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); 476 | static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); 477 | static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); 478 | static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); 479 | 480 | typedef struct 481 | { 482 | float x,y; // position of n'th character 483 | float height; // height of line 484 | int first_char, length; // first char of row, and length 485 | int prev_first; // first char of previous row 486 | } StbFindState; 487 | 488 | // find the x/y location of a character, and remember info about the previous row in 489 | // case we get a move-up event (for page up, we'll have to rescan) 490 | static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) 491 | { 492 | StbTexteditRow r; 493 | int prev_start = 0; 494 | int z = STB_TEXTEDIT_STRINGLEN(str); 495 | int i=0, first; 496 | 497 | if (n == z) { 498 | // if it's at the end, then find the last line -- simpler than trying to 499 | // explicitly handle this case in the regular code 500 | if (single_line) { 501 | STB_TEXTEDIT_LAYOUTROW(&r, str, 0); 502 | find->y = 0; 503 | find->first_char = 0; 504 | find->length = z; 505 | find->height = r.ymax - r.ymin; 506 | find->x = r.x1; 507 | } else { 508 | find->y = 0; 509 | find->x = 0; 510 | find->height = 1; 511 | while (i < z) { 512 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 513 | prev_start = i; 514 | i += r.num_chars; 515 | } 516 | find->first_char = i; 517 | find->length = 0; 518 | find->prev_first = prev_start; 519 | } 520 | return; 521 | } 522 | 523 | // search rows to find the one that straddles character n 524 | find->y = 0; 525 | 526 | for(;;) { 527 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 528 | if (n < i + r.num_chars) 529 | break; 530 | prev_start = i; 531 | i += r.num_chars; 532 | find->y += r.baseline_y_delta; 533 | } 534 | 535 | find->first_char = first = i; 536 | find->length = r.num_chars; 537 | find->height = r.ymax - r.ymin; 538 | find->prev_first = prev_start; 539 | 540 | // now scan to find xpos 541 | find->x = r.x0; 542 | i = 0; 543 | for (i=0; first+i < n; ++i) 544 | find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); 545 | } 546 | 547 | #define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) 548 | 549 | // make the selection/cursor state valid if client altered the string 550 | static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 551 | { 552 | int n = STB_TEXTEDIT_STRINGLEN(str); 553 | if (STB_TEXT_HAS_SELECTION(state)) { 554 | if (state->select_start > n) state->select_start = n; 555 | if (state->select_end > n) state->select_end = n; 556 | // if clamping forced them to be equal, move the cursor to match 557 | if (state->select_start == state->select_end) 558 | state->cursor = state->select_start; 559 | } 560 | if (state->cursor > n) state->cursor = n; 561 | } 562 | 563 | // delete characters while updating undo 564 | static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) 565 | { 566 | stb_text_makeundo_delete(str, state, where, len); 567 | STB_TEXTEDIT_DELETECHARS(str, where, len); 568 | state->has_preferred_x = 0; 569 | } 570 | 571 | // delete the section 572 | static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 573 | { 574 | stb_textedit_clamp(str, state); 575 | if (STB_TEXT_HAS_SELECTION(state)) { 576 | if (state->select_start < state->select_end) { 577 | stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); 578 | state->select_end = state->cursor = state->select_start; 579 | } else { 580 | stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); 581 | state->select_start = state->cursor = state->select_end; 582 | } 583 | state->has_preferred_x = 0; 584 | } 585 | } 586 | 587 | // canoncialize the selection so start <= end 588 | static void stb_textedit_sortselection(STB_TexteditState *state) 589 | { 590 | if (state->select_end < state->select_start) { 591 | int temp = state->select_end; 592 | state->select_end = state->select_start; 593 | state->select_start = temp; 594 | } 595 | } 596 | 597 | // move cursor to first character of selection 598 | static void stb_textedit_move_to_first(STB_TexteditState *state) 599 | { 600 | if (STB_TEXT_HAS_SELECTION(state)) { 601 | stb_textedit_sortselection(state); 602 | state->cursor = state->select_start; 603 | state->select_end = state->select_start; 604 | state->has_preferred_x = 0; 605 | } 606 | } 607 | 608 | // move cursor to last character of selection 609 | static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 610 | { 611 | if (STB_TEXT_HAS_SELECTION(state)) { 612 | stb_textedit_sortselection(state); 613 | stb_textedit_clamp(str, state); 614 | state->cursor = state->select_end; 615 | state->select_start = state->select_end; 616 | state->has_preferred_x = 0; 617 | } 618 | } 619 | 620 | #ifdef STB_TEXTEDIT_IS_SPACE 621 | static int is_word_boundary( STB_TEXTEDIT_STRING *_str, int _idx ) 622 | { 623 | return _idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str,_idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str, _idx) ) ) : 1; 624 | } 625 | 626 | #ifndef STB_TEXTEDIT_MOVEWORDLEFT 627 | static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, int c ) 628 | { 629 | while( c >= 0 && !is_word_boundary( _str, c ) ) 630 | --c; 631 | 632 | if( c < 0 ) 633 | c = 0; 634 | 635 | return c; 636 | } 637 | #define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous 638 | #endif 639 | 640 | #ifndef STB_TEXTEDIT_MOVEWORDRIGHT 641 | static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, int c ) 642 | { 643 | const int len = STB_TEXTEDIT_STRINGLEN(_str); 644 | while( c < len && !is_word_boundary( _str, c ) ) 645 | ++c; 646 | 647 | if( c > len ) 648 | c = len; 649 | 650 | return c; 651 | } 652 | #define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next 653 | #endif 654 | 655 | #endif 656 | 657 | // update selection and cursor to match each other 658 | static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) 659 | { 660 | if (!STB_TEXT_HAS_SELECTION(state)) 661 | state->select_start = state->select_end = state->cursor; 662 | else 663 | state->cursor = state->select_end; 664 | } 665 | 666 | // API cut: delete selection 667 | static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 668 | { 669 | if (STB_TEXT_HAS_SELECTION(state)) { 670 | stb_textedit_delete_selection(str,state); // implicity clamps 671 | state->has_preferred_x = 0; 672 | return 1; 673 | } 674 | return 0; 675 | } 676 | 677 | // API paste: replace existing selection with passed-in text 678 | static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) 679 | { 680 | STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext; 681 | // if there's a selection, the paste should delete it 682 | stb_textedit_clamp(str, state); 683 | stb_textedit_delete_selection(str,state); 684 | // try to insert the characters 685 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { 686 | stb_text_makeundo_insert(state, state->cursor, len); 687 | state->cursor += len; 688 | state->has_preferred_x = 0; 689 | return 1; 690 | } 691 | // remove the undo since we didn't actually insert the characters 692 | if (state->undostate.undo_point) 693 | --state->undostate.undo_point; 694 | return 0; 695 | } 696 | 697 | // API key: process a keyboard input 698 | static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) 699 | { 700 | retry: 701 | switch (key) { 702 | default: { 703 | int c = STB_TEXTEDIT_KEYTOTEXT(key); 704 | if (c > 0) { 705 | STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; 706 | 707 | // can't add newline in single-line mode 708 | if (c == '\n' && state->single_line) 709 | break; 710 | 711 | if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { 712 | stb_text_makeundo_replace(str, state, state->cursor, 1, 1); 713 | STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); 714 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { 715 | ++state->cursor; 716 | state->has_preferred_x = 0; 717 | } 718 | } else { 719 | stb_textedit_delete_selection(str,state); // implicity clamps 720 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { 721 | stb_text_makeundo_insert(state, state->cursor, 1); 722 | ++state->cursor; 723 | state->has_preferred_x = 0; 724 | } 725 | } 726 | } 727 | break; 728 | } 729 | 730 | #ifdef STB_TEXTEDIT_K_INSERT 731 | case STB_TEXTEDIT_K_INSERT: 732 | state->insert_mode = !state->insert_mode; 733 | break; 734 | #endif 735 | 736 | case STB_TEXTEDIT_K_UNDO: 737 | stb_text_undo(str, state); 738 | state->has_preferred_x = 0; 739 | break; 740 | 741 | case STB_TEXTEDIT_K_REDO: 742 | stb_text_redo(str, state); 743 | state->has_preferred_x = 0; 744 | break; 745 | 746 | case STB_TEXTEDIT_K_LEFT: 747 | // if currently there's a selection, move cursor to start of selection 748 | if (STB_TEXT_HAS_SELECTION(state)) 749 | stb_textedit_move_to_first(state); 750 | else 751 | if (state->cursor > 0) 752 | --state->cursor; 753 | state->has_preferred_x = 0; 754 | break; 755 | 756 | case STB_TEXTEDIT_K_RIGHT: 757 | // if currently there's a selection, move cursor to end of selection 758 | if (STB_TEXT_HAS_SELECTION(state)) 759 | stb_textedit_move_to_last(str, state); 760 | else 761 | ++state->cursor; 762 | stb_textedit_clamp(str, state); 763 | state->has_preferred_x = 0; 764 | break; 765 | 766 | case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: 767 | stb_textedit_clamp(str, state); 768 | stb_textedit_prep_selection_at_cursor(state); 769 | // move selection left 770 | if (state->select_end > 0) 771 | --state->select_end; 772 | state->cursor = state->select_end; 773 | state->has_preferred_x = 0; 774 | break; 775 | 776 | #ifdef STB_TEXTEDIT_MOVEWORDLEFT 777 | case STB_TEXTEDIT_K_WORDLEFT: 778 | if (STB_TEXT_HAS_SELECTION(state)) 779 | stb_textedit_move_to_first(state); 780 | else { 781 | state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); 782 | stb_textedit_clamp( str, state ); 783 | } 784 | break; 785 | 786 | case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: 787 | if( !STB_TEXT_HAS_SELECTION( state ) ) 788 | stb_textedit_prep_selection_at_cursor(state); 789 | 790 | state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); 791 | state->select_end = state->cursor; 792 | 793 | stb_textedit_clamp( str, state ); 794 | break; 795 | #endif 796 | 797 | #ifdef STB_TEXTEDIT_MOVEWORDRIGHT 798 | case STB_TEXTEDIT_K_WORDRIGHT: 799 | if (STB_TEXT_HAS_SELECTION(state)) 800 | stb_textedit_move_to_last(str, state); 801 | else { 802 | state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); 803 | stb_textedit_clamp( str, state ); 804 | } 805 | break; 806 | 807 | case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: 808 | if( !STB_TEXT_HAS_SELECTION( state ) ) 809 | stb_textedit_prep_selection_at_cursor(state); 810 | 811 | state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); 812 | state->select_end = state->cursor; 813 | 814 | stb_textedit_clamp( str, state ); 815 | break; 816 | #endif 817 | 818 | case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: 819 | stb_textedit_prep_selection_at_cursor(state); 820 | // move selection right 821 | ++state->select_end; 822 | stb_textedit_clamp(str, state); 823 | state->cursor = state->select_end; 824 | state->has_preferred_x = 0; 825 | break; 826 | 827 | case STB_TEXTEDIT_K_DOWN: 828 | case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { 829 | StbFindState find; 830 | StbTexteditRow row; 831 | int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; 832 | 833 | if (state->single_line) { 834 | // on windows, up&down in single-line behave like left&right 835 | key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); 836 | goto retry; 837 | } 838 | 839 | if (sel) 840 | stb_textedit_prep_selection_at_cursor(state); 841 | else if (STB_TEXT_HAS_SELECTION(state)) 842 | stb_textedit_move_to_last(str,state); 843 | 844 | // compute current position of cursor point 845 | stb_textedit_clamp(str, state); 846 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 847 | 848 | // now find character position down a row 849 | if (find.length) { 850 | float goal_x = state->has_preferred_x ? state->preferred_x : find.x; 851 | float x; 852 | int start = find.first_char + find.length; 853 | state->cursor = start; 854 | STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); 855 | x = row.x0; 856 | for (i=0; i < row.num_chars; ++i) { 857 | float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); 858 | #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE 859 | if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) 860 | break; 861 | #endif 862 | x += dx; 863 | if (x > goal_x) 864 | break; 865 | ++state->cursor; 866 | } 867 | stb_textedit_clamp(str, state); 868 | 869 | state->has_preferred_x = 1; 870 | state->preferred_x = goal_x; 871 | 872 | if (sel) 873 | state->select_end = state->cursor; 874 | } 875 | break; 876 | } 877 | 878 | case STB_TEXTEDIT_K_UP: 879 | case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { 880 | StbFindState find; 881 | StbTexteditRow row; 882 | int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; 883 | 884 | if (state->single_line) { 885 | // on windows, up&down become left&right 886 | key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); 887 | goto retry; 888 | } 889 | 890 | if (sel) 891 | stb_textedit_prep_selection_at_cursor(state); 892 | else if (STB_TEXT_HAS_SELECTION(state)) 893 | stb_textedit_move_to_first(state); 894 | 895 | // compute current position of cursor point 896 | stb_textedit_clamp(str, state); 897 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 898 | 899 | // can only go up if there's a previous row 900 | if (find.prev_first != find.first_char) { 901 | // now find character position up a row 902 | float goal_x = state->has_preferred_x ? state->preferred_x : find.x; 903 | float x; 904 | state->cursor = find.prev_first; 905 | STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); 906 | x = row.x0; 907 | for (i=0; i < row.num_chars; ++i) { 908 | float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); 909 | #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE 910 | if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) 911 | break; 912 | #endif 913 | x += dx; 914 | if (x > goal_x) 915 | break; 916 | ++state->cursor; 917 | } 918 | stb_textedit_clamp(str, state); 919 | 920 | state->has_preferred_x = 1; 921 | state->preferred_x = goal_x; 922 | 923 | if (sel) 924 | state->select_end = state->cursor; 925 | } 926 | break; 927 | } 928 | 929 | case STB_TEXTEDIT_K_DELETE: 930 | case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: 931 | if (STB_TEXT_HAS_SELECTION(state)) 932 | stb_textedit_delete_selection(str, state); 933 | else { 934 | int n = STB_TEXTEDIT_STRINGLEN(str); 935 | if (state->cursor < n) 936 | stb_textedit_delete(str, state, state->cursor, 1); 937 | } 938 | state->has_preferred_x = 0; 939 | break; 940 | 941 | case STB_TEXTEDIT_K_BACKSPACE: 942 | case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: 943 | if (STB_TEXT_HAS_SELECTION(state)) 944 | stb_textedit_delete_selection(str, state); 945 | else { 946 | stb_textedit_clamp(str, state); 947 | if (state->cursor > 0) { 948 | stb_textedit_delete(str, state, state->cursor-1, 1); 949 | --state->cursor; 950 | } 951 | } 952 | state->has_preferred_x = 0; 953 | break; 954 | 955 | #ifdef STB_TEXTEDIT_K_TEXTSTART2 956 | case STB_TEXTEDIT_K_TEXTSTART2: 957 | #endif 958 | case STB_TEXTEDIT_K_TEXTSTART: 959 | state->cursor = state->select_start = state->select_end = 0; 960 | state->has_preferred_x = 0; 961 | break; 962 | 963 | #ifdef STB_TEXTEDIT_K_TEXTEND2 964 | case STB_TEXTEDIT_K_TEXTEND2: 965 | #endif 966 | case STB_TEXTEDIT_K_TEXTEND: 967 | state->cursor = STB_TEXTEDIT_STRINGLEN(str); 968 | state->select_start = state->select_end = 0; 969 | state->has_preferred_x = 0; 970 | break; 971 | 972 | #ifdef STB_TEXTEDIT_K_TEXTSTART2 973 | case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: 974 | #endif 975 | case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: 976 | stb_textedit_prep_selection_at_cursor(state); 977 | state->cursor = state->select_end = 0; 978 | state->has_preferred_x = 0; 979 | break; 980 | 981 | #ifdef STB_TEXTEDIT_K_TEXTEND2 982 | case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: 983 | #endif 984 | case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: 985 | stb_textedit_prep_selection_at_cursor(state); 986 | state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); 987 | state->has_preferred_x = 0; 988 | break; 989 | 990 | 991 | #ifdef STB_TEXTEDIT_K_LINESTART2 992 | case STB_TEXTEDIT_K_LINESTART2: 993 | #endif 994 | case STB_TEXTEDIT_K_LINESTART: { 995 | StbFindState find; 996 | stb_textedit_clamp(str, state); 997 | stb_textedit_move_to_first(state); 998 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 999 | state->cursor = find.first_char; 1000 | state->has_preferred_x = 0; 1001 | break; 1002 | } 1003 | 1004 | #ifdef STB_TEXTEDIT_K_LINEEND2 1005 | case STB_TEXTEDIT_K_LINEEND2: 1006 | #endif 1007 | case STB_TEXTEDIT_K_LINEEND: { 1008 | StbFindState find; 1009 | stb_textedit_clamp(str, state); 1010 | stb_textedit_move_to_first(state); 1011 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 1012 | 1013 | state->has_preferred_x = 0; 1014 | state->cursor = find.first_char + find.length; 1015 | if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) 1016 | --state->cursor; 1017 | break; 1018 | } 1019 | 1020 | #ifdef STB_TEXTEDIT_K_LINESTART2 1021 | case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: 1022 | #endif 1023 | case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: { 1024 | StbFindState find; 1025 | stb_textedit_clamp(str, state); 1026 | stb_textedit_prep_selection_at_cursor(state); 1027 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 1028 | state->cursor = state->select_end = find.first_char; 1029 | state->has_preferred_x = 0; 1030 | break; 1031 | } 1032 | 1033 | #ifdef STB_TEXTEDIT_K_LINEEND2 1034 | case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: 1035 | #endif 1036 | case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { 1037 | StbFindState find; 1038 | stb_textedit_clamp(str, state); 1039 | stb_textedit_prep_selection_at_cursor(state); 1040 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 1041 | state->has_preferred_x = 0; 1042 | state->cursor = find.first_char + find.length; 1043 | if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) 1044 | --state->cursor; 1045 | state->select_end = state->cursor; 1046 | break; 1047 | } 1048 | 1049 | // @TODO: 1050 | // STB_TEXTEDIT_K_PGUP - move cursor up a page 1051 | // STB_TEXTEDIT_K_PGDOWN - move cursor down a page 1052 | } 1053 | } 1054 | 1055 | ///////////////////////////////////////////////////////////////////////////// 1056 | // 1057 | // Undo processing 1058 | // 1059 | // @OPTIMIZE: the undo/redo buffer should be circular 1060 | 1061 | static void stb_textedit_flush_redo(StbUndoState *state) 1062 | { 1063 | state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; 1064 | state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; 1065 | } 1066 | 1067 | // discard the oldest entry in the undo list 1068 | static void stb_textedit_discard_undo(StbUndoState *state) 1069 | { 1070 | if (state->undo_point > 0) { 1071 | // if the 0th undo state has characters, clean those up 1072 | if (state->undo_rec[0].char_storage >= 0) { 1073 | int n = state->undo_rec[0].insert_length, i; 1074 | // delete n characters from all other records 1075 | state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 1076 | STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); 1077 | for (i=0; i < state->undo_point; ++i) 1078 | if (state->undo_rec[i].char_storage >= 0) 1079 | state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it 1080 | } 1081 | --state->undo_point; 1082 | STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); 1083 | } 1084 | } 1085 | 1086 | // discard the oldest entry in the redo list--it's bad if this 1087 | // ever happens, but because undo & redo have to store the actual 1088 | // characters in different cases, the redo character buffer can 1089 | // fill up even though the undo buffer didn't 1090 | static void stb_textedit_discard_redo(StbUndoState *state) 1091 | { 1092 | int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; 1093 | 1094 | if (state->redo_point <= k) { 1095 | // if the k'th undo state has characters, clean those up 1096 | if (state->undo_rec[k].char_storage >= 0) { 1097 | int n = state->undo_rec[k].insert_length, i; 1098 | // delete n characters from all other records 1099 | state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 1100 | STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); 1101 | for (i=state->redo_point; i < k; ++i) 1102 | if (state->undo_rec[i].char_storage >= 0) 1103 | state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 1104 | } 1105 | STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point, state->undo_rec + state->redo_point-1, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); 1106 | ++state->redo_point; 1107 | } 1108 | } 1109 | 1110 | static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) 1111 | { 1112 | // any time we create a new undo record, we discard redo 1113 | stb_textedit_flush_redo(state); 1114 | 1115 | // if we have no free records, we have to make room, by sliding the 1116 | // existing records down 1117 | if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1118 | stb_textedit_discard_undo(state); 1119 | 1120 | // if the characters to store won't possibly fit in the buffer, we can't undo 1121 | if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { 1122 | state->undo_point = 0; 1123 | state->undo_char_point = 0; 1124 | return NULL; 1125 | } 1126 | 1127 | // if we don't have enough free characters in the buffer, we have to make room 1128 | while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) 1129 | stb_textedit_discard_undo(state); 1130 | 1131 | return &state->undo_rec[state->undo_point++]; 1132 | } 1133 | 1134 | static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) 1135 | { 1136 | StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); 1137 | if (r == NULL) 1138 | return NULL; 1139 | 1140 | r->where = pos; 1141 | r->insert_length = (short) insert_len; 1142 | r->delete_length = (short) delete_len; 1143 | 1144 | if (insert_len == 0) { 1145 | r->char_storage = -1; 1146 | return NULL; 1147 | } else { 1148 | r->char_storage = state->undo_char_point; 1149 | state->undo_char_point = state->undo_char_point + (short) insert_len; 1150 | return &state->undo_char[r->char_storage]; 1151 | } 1152 | } 1153 | 1154 | static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 1155 | { 1156 | StbUndoState *s = &state->undostate; 1157 | StbUndoRecord u, *r; 1158 | if (s->undo_point == 0) 1159 | return; 1160 | 1161 | // we need to do two things: apply the undo record, and create a redo record 1162 | u = s->undo_rec[s->undo_point-1]; 1163 | r = &s->undo_rec[s->redo_point-1]; 1164 | r->char_storage = -1; 1165 | 1166 | r->insert_length = u.delete_length; 1167 | r->delete_length = u.insert_length; 1168 | r->where = u.where; 1169 | 1170 | if (u.delete_length) { 1171 | // if the undo record says to delete characters, then the redo record will 1172 | // need to re-insert the characters that get deleted, so we need to store 1173 | // them. 1174 | 1175 | // there are three cases: 1176 | // there's enough room to store the characters 1177 | // characters stored for *redoing* don't leave room for redo 1178 | // characters stored for *undoing* don't leave room for redo 1179 | // if the last is true, we have to bail 1180 | 1181 | if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { 1182 | // the undo records take up too much character space; there's no space to store the redo characters 1183 | r->insert_length = 0; 1184 | } else { 1185 | int i; 1186 | 1187 | // there's definitely room to store the characters eventually 1188 | while (s->undo_char_point + u.delete_length > s->redo_char_point) { 1189 | // there's currently not enough room, so discard a redo record 1190 | stb_textedit_discard_redo(s); 1191 | // should never happen: 1192 | if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1193 | return; 1194 | } 1195 | r = &s->undo_rec[s->redo_point-1]; 1196 | 1197 | r->char_storage = s->redo_char_point - u.delete_length; 1198 | s->redo_char_point = s->redo_char_point - (short) u.delete_length; 1199 | 1200 | // now save the characters 1201 | for (i=0; i < u.delete_length; ++i) 1202 | s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); 1203 | } 1204 | 1205 | // now we can carry out the deletion 1206 | STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); 1207 | } 1208 | 1209 | // check type of recorded action: 1210 | if (u.insert_length) { 1211 | // easy case: was a deletion, so we need to insert n characters 1212 | STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); 1213 | s->undo_char_point -= u.insert_length; 1214 | } 1215 | 1216 | state->cursor = u.where + u.insert_length; 1217 | 1218 | s->undo_point--; 1219 | s->redo_point--; 1220 | } 1221 | 1222 | static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 1223 | { 1224 | StbUndoState *s = &state->undostate; 1225 | StbUndoRecord *u, r; 1226 | if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1227 | return; 1228 | 1229 | // we need to do two things: apply the redo record, and create an undo record 1230 | u = &s->undo_rec[s->undo_point]; 1231 | r = s->undo_rec[s->redo_point]; 1232 | 1233 | // we KNOW there must be room for the undo record, because the redo record 1234 | // was derived from an undo record 1235 | 1236 | u->delete_length = r.insert_length; 1237 | u->insert_length = r.delete_length; 1238 | u->where = r.where; 1239 | u->char_storage = -1; 1240 | 1241 | if (r.delete_length) { 1242 | // the redo record requires us to delete characters, so the undo record 1243 | // needs to store the characters 1244 | 1245 | if (s->undo_char_point + u->insert_length > s->redo_char_point) { 1246 | u->insert_length = 0; 1247 | u->delete_length = 0; 1248 | } else { 1249 | int i; 1250 | u->char_storage = s->undo_char_point; 1251 | s->undo_char_point = s->undo_char_point + u->insert_length; 1252 | 1253 | // now save the characters 1254 | for (i=0; i < u->insert_length; ++i) 1255 | s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); 1256 | } 1257 | 1258 | STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); 1259 | } 1260 | 1261 | if (r.insert_length) { 1262 | // easy case: need to insert n characters 1263 | STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); 1264 | s->redo_char_point += r.insert_length; 1265 | } 1266 | 1267 | state->cursor = r.where + r.insert_length; 1268 | 1269 | s->undo_point++; 1270 | s->redo_point++; 1271 | } 1272 | 1273 | static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) 1274 | { 1275 | stb_text_createundo(&state->undostate, where, 0, length); 1276 | } 1277 | 1278 | static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) 1279 | { 1280 | int i; 1281 | STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); 1282 | if (p) { 1283 | for (i=0; i < length; ++i) 1284 | p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); 1285 | } 1286 | } 1287 | 1288 | static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) 1289 | { 1290 | int i; 1291 | STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); 1292 | if (p) { 1293 | for (i=0; i < old_length; ++i) 1294 | p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); 1295 | } 1296 | } 1297 | 1298 | // reset the state to default 1299 | static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) 1300 | { 1301 | state->undostate.undo_point = 0; 1302 | state->undostate.undo_char_point = 0; 1303 | state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; 1304 | state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; 1305 | state->select_end = state->select_start = 0; 1306 | state->cursor = 0; 1307 | state->has_preferred_x = 0; 1308 | state->preferred_x = 0; 1309 | state->cursor_at_end_of_line = 0; 1310 | state->initialized = 1; 1311 | state->single_line = (unsigned char) is_single_line; 1312 | state->insert_mode = 0; 1313 | } 1314 | 1315 | // API initialize 1316 | static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) 1317 | { 1318 | stb_textedit_clear_state(state, is_single_line); 1319 | } 1320 | #endif//STB_TEXTEDIT_IMPLEMENTATION 1321 | --------------------------------------------------------------------------------