imgui_impl_glfw.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // ImGui GLFW binding with OpenGL
  2. // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // If your context is GL3/GL3 then prefer using the code in opengl3_example.
  4. // You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render().
  5. // We cannot do that from GL2 code because the function doesn't exist.
  6. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  7. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  8. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  9. // https://github.com/ocornut/imgui
  10. #include <imgui.h>
  11. #include "imgui_impl_glfw.h"
  12. // GLFW
  13. #include <GLFW/glfw3.h>
  14. #ifdef _WIN32
  15. #undef APIENTRY
  16. #define GLFW_EXPOSE_NATIVE_WIN32
  17. #define GLFW_EXPOSE_NATIVE_WGL
  18. #include <GLFW/glfw3native.h>
  19. #endif
  20. // Data
  21. static GLFWwindow* g_Window = NULL;
  22. static double g_Time = 0.0f;
  23. static bool g_MousePressed[3] = { false, false, false };
  24. static float g_MouseWheel = 0.0f;
  25. static GLuint g_FontTexture = 0;
  26. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  27. // If text or lines are blurry when integrating ImGui in your engine:
  28. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  29. void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
  30. {
  31. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  32. ImGuiIO& io = ImGui::GetIO();
  33. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  34. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  35. if (fb_width == 0 || fb_height == 0)
  36. return;
  37. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  38. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  39. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  40. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  41. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  42. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  43. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  44. glEnable(GL_BLEND);
  45. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  46. glDisable(GL_CULL_FACE);
  47. glDisable(GL_DEPTH_TEST);
  48. glEnable(GL_SCISSOR_TEST);
  49. glEnableClientState(GL_VERTEX_ARRAY);
  50. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  51. glEnableClientState(GL_COLOR_ARRAY);
  52. glEnable(GL_TEXTURE_2D);
  53. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
  54. // Setup viewport, orthographic projection matrix
  55. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  56. glMatrixMode(GL_PROJECTION);
  57. glPushMatrix();
  58. glLoadIdentity();
  59. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  60. glMatrixMode(GL_MODELVIEW);
  61. glPushMatrix();
  62. glLoadIdentity();
  63. // Render command lists
  64. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  65. for (int n = 0; n < draw_data->CmdListsCount; n++)
  66. {
  67. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  68. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  69. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  70. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
  71. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
  72. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
  73. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  74. {
  75. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  76. if (pcmd->UserCallback)
  77. {
  78. pcmd->UserCallback(cmd_list, pcmd);
  79. }
  80. else
  81. {
  82. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  83. 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));
  84. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  85. }
  86. idx_buffer += pcmd->ElemCount;
  87. }
  88. }
  89. #undef OFFSETOF
  90. // Restore modified state
  91. glDisableClientState(GL_COLOR_ARRAY);
  92. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  93. glDisableClientState(GL_VERTEX_ARRAY);
  94. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  95. glMatrixMode(GL_MODELVIEW);
  96. glPopMatrix();
  97. glMatrixMode(GL_PROJECTION);
  98. glPopMatrix();
  99. glPopAttrib();
  100. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  101. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  102. }
  103. static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
  104. {
  105. return glfwGetClipboardString((GLFWwindow*)user_data);
  106. }
  107. static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
  108. {
  109. glfwSetClipboardString((GLFWwindow*)user_data, text);
  110. }
  111. void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  112. {
  113. if (action == GLFW_PRESS && button >= 0 && button < 3)
  114. g_MousePressed[button] = true;
  115. }
  116. void ImGui_ImplGlfw_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
  117. {
  118. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  119. }
  120. void ImGui_ImplGlFw_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
  121. {
  122. ImGuiIO& io = ImGui::GetIO();
  123. if (action == GLFW_PRESS)
  124. io.KeysDown[key] = true;
  125. if (action == GLFW_RELEASE)
  126. io.KeysDown[key] = false;
  127. (void)mods; // Modifiers are not reliable across systems
  128. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  129. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  130. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  131. io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
  132. }
  133. void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c)
  134. {
  135. ImGuiIO& io = ImGui::GetIO();
  136. if (c > 0 && c < 0x10000)
  137. io.AddInputCharacter((unsigned short)c);
  138. }
  139. bool ImGui_ImplGlfw_CreateDeviceObjects()
  140. {
  141. // Build texture atlas
  142. ImGuiIO& io = ImGui::GetIO();
  143. unsigned char* pixels;
  144. int width, height;
  145. 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.
  146. // Upload texture to graphics system
  147. GLint last_texture;
  148. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  149. glGenTextures(1, &g_FontTexture);
  150. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  151. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  152. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  153. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  154. // Store our identifier
  155. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  156. // Restore state
  157. glBindTexture(GL_TEXTURE_2D, last_texture);
  158. return true;
  159. }
  160. void ImGui_ImplGlfw_InvalidateDeviceObjects()
  161. {
  162. if (g_FontTexture)
  163. {
  164. glDeleteTextures(1, &g_FontTexture);
  165. ImGui::GetIO().Fonts->TexID = 0;
  166. g_FontTexture = 0;
  167. }
  168. }
  169. bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks)
  170. {
  171. g_Window = window;
  172. ImGuiIO& io = ImGui::GetIO();
  173. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  174. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  175. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  176. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  177. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  178. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  179. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  180. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  181. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  182. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  183. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  184. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  185. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  186. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  187. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  188. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  189. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  190. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  191. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  192. io.RenderDrawListsFn = ImGui_ImplGlfw_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  193. io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
  194. io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
  195. io.ClipboardUserData = g_Window;
  196. #ifdef _WIN32
  197. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  198. #endif
  199. if (install_callbacks)
  200. {
  201. glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
  202. glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
  203. glfwSetKeyCallback(window, ImGui_ImplGlFw_KeyCallback);
  204. glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
  205. }
  206. return true;
  207. }
  208. void ImGui_ImplGlfw_Shutdown()
  209. {
  210. ImGui_ImplGlfw_InvalidateDeviceObjects();
  211. ImGui::Shutdown();
  212. }
  213. void ImGui_ImplGlfw_NewFrame()
  214. {
  215. if (!g_FontTexture)
  216. ImGui_ImplGlfw_CreateDeviceObjects();
  217. ImGuiIO& io = ImGui::GetIO();
  218. // Setup display size (every frame to accommodate for window resizing)
  219. int w, h;
  220. int display_w, display_h;
  221. glfwGetWindowSize(g_Window, &w, &h);
  222. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  223. io.DisplaySize = ImVec2((float)w, (float)h);
  224. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  225. // Setup time step
  226. double current_time = glfwGetTime();
  227. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  228. g_Time = current_time;
  229. // Setup inputs
  230. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  231. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  232. {
  233. double mouse_x, mouse_y;
  234. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  235. 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.)
  236. }
  237. else
  238. {
  239. io.MousePos = ImVec2(-1,-1);
  240. }
  241. for (int i = 0; i < 3; i++)
  242. {
  243. 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.
  244. g_MousePressed[i] = false;
  245. }
  246. io.MouseWheel = g_MouseWheel;
  247. g_MouseWheel = 0.0f;
  248. // Hide OS mouse cursor if ImGui is drawing it
  249. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  250. // Start the frame
  251. ImGui::NewFrame();
  252. }