imgui_impl_glfw.cpp 13 KB

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