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