imgui_impl_glfw_gl2.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // ImGui GLFW binding with OpenGL (legacy, fixed pipeline)
  2. // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
  3. // Implemented features:
  4. // [X] User texture binding. Cast 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  5. // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
  6. // **Prefer using the code in the opengl3_example/ folder**
  7. // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
  8. // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
  9. // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
  10. // confuse your GPU driver.
  11. // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
  12. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  13. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  14. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  15. // https://github.com/ocornut/imgui
  16. // CHANGELOG
  17. // (minor and older changes stripped away, please see git history for details)
  18. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  19. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
  20. // 2018-02-20: Inputs: Renamed GLFW callbacks exposed in .h to not include GL2 in their name.
  21. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplGlfwGL2_RenderDrawData() in the .h file so you can call it yourself.
  22. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  23. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  24. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos flag by repositioning the mouse (ImGuiConfigFlags_NavEnableSetMousePos is set).
  25. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  26. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  27. // 2018-01-09: Misc: Renamed imgui_impl_glfw.* to imgui_impl_glfw_gl2.*.
  28. // 2017-09-01: OpenGL: Save and restore current polygon mode.
  29. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  30. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  31. // 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal).
  32. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
  33. #include "imgui.h"
  34. #include "imgui_impl_glfw_gl2.h"
  35. // GLFW
  36. #include <GLFW/glfw3.h>
  37. #ifdef _WIN32
  38. #undef APIENTRY
  39. #define GLFW_EXPOSE_NATIVE_WIN32
  40. #define GLFW_EXPOSE_NATIVE_WGL
  41. #include <GLFW/glfw3native.h>
  42. #endif
  43. // GLFW data
  44. static GLFWwindow* g_Window = NULL;
  45. static double g_Time = 0.0f;
  46. static bool g_MouseJustPressed[3] = { false, false, false };
  47. static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = { 0 };
  48. // OpenGL data
  49. static GLuint g_FontTexture = 0;
  50. // OpenGL2 Render function.
  51. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  52. // 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.
  53. void ImGui_ImplGlfwGL2_RenderDrawData(ImDrawData* draw_data)
  54. {
  55. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  56. ImGuiIO& io = ImGui::GetIO();
  57. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  58. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  59. if (fb_width == 0 || fb_height == 0)
  60. return;
  61. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  62. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  63. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
  64. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  65. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  66. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  67. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  68. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  69. glEnable(GL_BLEND);
  70. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  71. glDisable(GL_CULL_FACE);
  72. glDisable(GL_DEPTH_TEST);
  73. glEnable(GL_SCISSOR_TEST);
  74. glEnableClientState(GL_VERTEX_ARRAY);
  75. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  76. glEnableClientState(GL_COLOR_ARRAY);
  77. glEnable(GL_TEXTURE_2D);
  78. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  79. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
  80. // Setup viewport, orthographic projection matrix
  81. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  82. glMatrixMode(GL_PROJECTION);
  83. glPushMatrix();
  84. glLoadIdentity();
  85. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  86. glMatrixMode(GL_MODELVIEW);
  87. glPushMatrix();
  88. glLoadIdentity();
  89. // Render command lists
  90. for (int n = 0; n < draw_data->CmdListsCount; n++)
  91. {
  92. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  93. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  94. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  95. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
  96. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
  97. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
  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);
  110. }
  111. idx_buffer += pcmd->ElemCount;
  112. }
  113. }
  114. // Restore modified state
  115. glDisableClientState(GL_COLOR_ARRAY);
  116. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  117. glDisableClientState(GL_VERTEX_ARRAY);
  118. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  119. glMatrixMode(GL_MODELVIEW);
  120. glPopMatrix();
  121. glMatrixMode(GL_PROJECTION);
  122. glPopMatrix();
  123. glPopAttrib();
  124. glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
  125. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  126. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  127. }
  128. static const char* ImGui_ImplGlfwGL2_GetClipboardText(void* user_data)
  129. {
  130. return glfwGetClipboardString((GLFWwindow*)user_data);
  131. }
  132. static void ImGui_ImplGlfwGL2_SetClipboardText(void* user_data, const char* text)
  133. {
  134. glfwSetClipboardString((GLFWwindow*)user_data, text);
  135. }
  136. void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  137. {
  138. if (action == GLFW_PRESS && button >= 0 && button < 3)
  139. g_MouseJustPressed[button] = true;
  140. }
  141. void ImGui_ImplGlfw_ScrollCallback(GLFWwindow*, double xoffset, double yoffset)
  142. {
  143. ImGuiIO& io = ImGui::GetIO();
  144. io.MouseWheelH += (float)xoffset;
  145. io.MouseWheel += (float)yoffset;
  146. }
  147. void ImGui_ImplGlfw_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
  148. {
  149. ImGuiIO& io = ImGui::GetIO();
  150. if (action == GLFW_PRESS)
  151. io.KeysDown[key] = true;
  152. if (action == GLFW_RELEASE)
  153. io.KeysDown[key] = false;
  154. (void)mods; // Modifiers are not reliable across systems
  155. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  156. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  157. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  158. io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
  159. }
  160. void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c)
  161. {
  162. ImGuiIO& io = ImGui::GetIO();
  163. if (c > 0 && c < 0x10000)
  164. io.AddInputCharacter((unsigned short)c);
  165. }
  166. bool ImGui_ImplGlfwGL2_CreateDeviceObjects()
  167. {
  168. // Build texture atlas
  169. ImGuiIO& io = ImGui::GetIO();
  170. unsigned char* pixels;
  171. int width, height;
  172. 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.
  173. // Upload texture to graphics system
  174. GLint last_texture;
  175. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  176. glGenTextures(1, &g_FontTexture);
  177. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  178. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  179. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  180. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  181. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  182. // Store our identifier
  183. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  184. // Restore state
  185. glBindTexture(GL_TEXTURE_2D, last_texture);
  186. return true;
  187. }
  188. void ImGui_ImplGlfwGL2_InvalidateDeviceObjects()
  189. {
  190. if (g_FontTexture)
  191. {
  192. glDeleteTextures(1, &g_FontTexture);
  193. ImGui::GetIO().Fonts->TexID = 0;
  194. g_FontTexture = 0;
  195. }
  196. }
  197. static void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
  198. {
  199. glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
  200. glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
  201. glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
  202. glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
  203. }
  204. bool ImGui_ImplGlfwGL2_Init(GLFWwindow* window, bool install_callbacks)
  205. {
  206. g_Window = window;
  207. // Setup back-end capabilities flags
  208. ImGuiIO& io = ImGui::GetIO();
  209. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  210. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  211. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
  212. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
  213. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  214. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  215. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  216. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  217. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  218. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  219. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  220. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  221. io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
  222. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  223. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  224. io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
  225. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  226. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  227. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  228. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  229. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  230. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  231. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  232. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  233. io.SetClipboardTextFn = ImGui_ImplGlfwGL2_SetClipboardText;
  234. io.GetClipboardTextFn = ImGui_ImplGlfwGL2_GetClipboardText;
  235. io.ClipboardUserData = g_Window;
  236. #ifdef _WIN32
  237. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  238. #endif
  239. // Load cursors
  240. // FIXME: GLFW doesn't expose suitable cursors for ResizeAll, ResizeNESW, ResizeNWSE. We revert to arrow cursor for those.
  241. g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  242. g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
  243. g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  244. g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
  245. g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
  246. g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  247. g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
  248. if (install_callbacks)
  249. ImGui_ImplGlfw_InstallCallbacks(window);
  250. return true;
  251. }
  252. void ImGui_ImplGlfwGL2_Shutdown()
  253. {
  254. // Destroy GLFW mouse cursors
  255. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
  256. glfwDestroyCursor(g_MouseCursors[cursor_n]);
  257. memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
  258. // Destroy OpenGL objects
  259. ImGui_ImplGlfwGL2_InvalidateDeviceObjects();
  260. }
  261. void ImGui_ImplGlfwGL2_NewFrame()
  262. {
  263. if (!g_FontTexture)
  264. ImGui_ImplGlfwGL2_CreateDeviceObjects();
  265. ImGuiIO& io = ImGui::GetIO();
  266. // Setup display size (every frame to accommodate for window resizing)
  267. int w, h;
  268. int display_w, display_h;
  269. glfwGetWindowSize(g_Window, &w, &h);
  270. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  271. io.DisplaySize = ImVec2((float)w, (float)h);
  272. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  273. // Setup time step
  274. double current_time = glfwGetTime();
  275. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  276. g_Time = current_time;
  277. // Setup inputs
  278. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  279. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  280. {
  281. // Set OS mouse position if requested (only used when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  282. if (io.WantSetMousePos)
  283. {
  284. glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y);
  285. }
  286. else
  287. {
  288. double mouse_x, mouse_y;
  289. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  290. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
  291. }
  292. }
  293. else
  294. {
  295. io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
  296. }
  297. for (int i = 0; i < 3; i++)
  298. {
  299. // 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.
  300. io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
  301. g_MouseJustPressed[i] = false;
  302. }
  303. // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
  304. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0 && glfwGetInputMode(g_Window, GLFW_CURSOR) != GLFW_CURSOR_DISABLED)
  305. {
  306. ImGuiMouseCursor cursor = ImGui::GetMouseCursor();
  307. if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None)
  308. {
  309. glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  310. }
  311. else
  312. {
  313. glfwSetCursor(g_Window, g_MouseCursors[cursor] ? g_MouseCursors[cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
  314. glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  315. }
  316. }
  317. // 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.
  318. ImGui::NewFrame();
  319. }