imgui_impl_glfw_gl3.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // ImGui GLFW binding with OpenGL3 + shaders
  2. // https://github.com/ocornut/imgui
  3. #include <imgui.h>
  4. #include "imgui_impl_glfw_gl3.h"
  5. // GL3W/GLFW
  6. #include <GL/gl3w.h>
  7. #include <GLFW/glfw3.h>
  8. #ifdef _WIN32
  9. #undef APIENTRY
  10. #define GLFW_EXPOSE_NATIVE_WIN32
  11. #define GLFW_EXPOSE_NATIVE_WGL
  12. #include <GLFW/glfw3native.h>
  13. #endif
  14. // Data
  15. static GLFWwindow* g_Window = NULL;
  16. static double g_Time = 0.0f;
  17. static bool g_MousePressed[3] = { false, false, false };
  18. static float g_MouseWheel = 0.0f;
  19. static GLuint g_FontTexture = 0;
  20. static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
  21. static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
  22. static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
  23. static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
  24. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  25. // If text or lines are blurry when integrating ImGui in your engine:
  26. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  27. static void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
  28. {
  29. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  30. GLint last_program, last_texture;
  31. glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
  32. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  33. glEnable(GL_BLEND);
  34. glBlendEquation(GL_FUNC_ADD);
  35. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  36. glDisable(GL_CULL_FACE);
  37. glDisable(GL_DEPTH_TEST);
  38. glEnable(GL_SCISSOR_TEST);
  39. glActiveTexture(GL_TEXTURE0);
  40. // Setup orthographic projection matrix
  41. const float width = ImGui::GetIO().DisplaySize.x;
  42. const float height = ImGui::GetIO().DisplaySize.y;
  43. const float ortho_projection[4][4] =
  44. {
  45. { 2.0f/width, 0.0f, 0.0f, 0.0f },
  46. { 0.0f, 2.0f/-height, 0.0f, 0.0f },
  47. { 0.0f, 0.0f, -1.0f, 0.0f },
  48. { -1.0f, 1.0f, 0.0f, 1.0f },
  49. };
  50. glUseProgram(g_ShaderHandle);
  51. glUniform1i(g_AttribLocationTex, 0);
  52. glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
  53. glBindVertexArray(g_VaoHandle);
  54. for (int n = 0; n < draw_data->CmdListsCount; n++)
  55. {
  56. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  57. const ImDrawIdx* idx_buffer_offset = 0;
  58. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  59. glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);
  60. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
  61. glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
  62. for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
  63. {
  64. if (pcmd->UserCallback)
  65. {
  66. pcmd->UserCallback(cmd_list, pcmd);
  67. }
  68. else
  69. {
  70. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  71. glScissor((int)pcmd->ClipRect.x, (int)(height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  72. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset);
  73. }
  74. idx_buffer_offset += pcmd->ElemCount;
  75. }
  76. }
  77. // Restore modified state
  78. glBindVertexArray(0);
  79. glBindBuffer(GL_ARRAY_BUFFER, 0);
  80. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  81. glUseProgram(last_program);
  82. glDisable(GL_SCISSOR_TEST);
  83. glBindTexture(GL_TEXTURE_2D, last_texture);
  84. }
  85. static const char* ImGui_ImplGlfwGL3_GetClipboardText()
  86. {
  87. return glfwGetClipboardString(g_Window);
  88. }
  89. static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text)
  90. {
  91. glfwSetClipboardString(g_Window, text);
  92. }
  93. void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  94. {
  95. if (action == GLFW_PRESS && button >= 0 && button < 3)
  96. g_MousePressed[button] = true;
  97. }
  98. void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
  99. {
  100. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  101. }
  102. void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
  103. {
  104. ImGuiIO& io = ImGui::GetIO();
  105. if (action == GLFW_PRESS)
  106. io.KeysDown[key] = true;
  107. if (action == GLFW_RELEASE)
  108. io.KeysDown[key] = false;
  109. (void)mods; // Modifiers are not reliable across systems
  110. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  111. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  112. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  113. }
  114. void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c)
  115. {
  116. ImGuiIO& io = ImGui::GetIO();
  117. if (c > 0 && c < 0x10000)
  118. io.AddInputCharacter((unsigned short)c);
  119. }
  120. void ImGui_ImplGlfwGL3_CreateFontsTexture()
  121. {
  122. ImGuiIO& io = ImGui::GetIO();
  123. unsigned char* pixels;
  124. int width, height;
  125. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
  126. glGenTextures(1, &g_FontTexture);
  127. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  128. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  129. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  130. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  131. // Store our identifier
  132. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  133. // Cleanup (don't clear the input data if you want to append new fonts later)
  134. io.Fonts->ClearInputData();
  135. io.Fonts->ClearTexData();
  136. }
  137. bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
  138. {
  139. const GLchar *vertex_shader =
  140. "#version 330\n"
  141. "uniform mat4 ProjMtx;\n"
  142. "in vec2 Position;\n"
  143. "in vec2 UV;\n"
  144. "in vec4 Color;\n"
  145. "out vec2 Frag_UV;\n"
  146. "out vec4 Frag_Color;\n"
  147. "void main()\n"
  148. "{\n"
  149. " Frag_UV = UV;\n"
  150. " Frag_Color = Color;\n"
  151. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  152. "}\n";
  153. const GLchar* fragment_shader =
  154. "#version 330\n"
  155. "uniform sampler2D Texture;\n"
  156. "in vec2 Frag_UV;\n"
  157. "in vec4 Frag_Color;\n"
  158. "out vec4 Out_Color;\n"
  159. "void main()\n"
  160. "{\n"
  161. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  162. "}\n";
  163. g_ShaderHandle = glCreateProgram();
  164. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  165. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  166. glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
  167. glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
  168. glCompileShader(g_VertHandle);
  169. glCompileShader(g_FragHandle);
  170. glAttachShader(g_ShaderHandle, g_VertHandle);
  171. glAttachShader(g_ShaderHandle, g_FragHandle);
  172. glLinkProgram(g_ShaderHandle);
  173. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  174. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  175. g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
  176. g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
  177. g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
  178. glGenBuffers(1, &g_VboHandle);
  179. glGenBuffers(1, &g_ElementsHandle);
  180. glGenVertexArrays(1, &g_VaoHandle);
  181. glBindVertexArray(g_VaoHandle);
  182. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  183. glEnableVertexAttribArray(g_AttribLocationPosition);
  184. glEnableVertexAttribArray(g_AttribLocationUV);
  185. glEnableVertexAttribArray(g_AttribLocationColor);
  186. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  187. glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  188. glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  189. glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  190. #undef OFFSETOF
  191. glBindVertexArray(0);
  192. glBindBuffer(GL_ARRAY_BUFFER, 0);
  193. ImGui_ImplGlfwGL3_CreateFontsTexture();
  194. return true;
  195. }
  196. bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
  197. {
  198. g_Window = window;
  199. ImGuiIO& io = ImGui::GetIO();
  200. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  201. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  202. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  203. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  204. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  205. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  206. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  207. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  208. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  209. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  210. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  211. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  212. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  213. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  214. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  215. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  216. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  217. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  218. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  219. io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists;
  220. io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText;
  221. io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText;
  222. #ifdef _WIN32
  223. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  224. #endif
  225. if (install_callbacks)
  226. {
  227. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback);
  228. glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback);
  229. glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback);
  230. glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback);
  231. }
  232. return true;
  233. }
  234. void ImGui_ImplGlfwGL3_Shutdown()
  235. {
  236. if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
  237. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  238. if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
  239. g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
  240. glDetachShader(g_ShaderHandle, g_VertHandle);
  241. glDeleteShader(g_VertHandle);
  242. g_VertHandle = 0;
  243. glDetachShader(g_ShaderHandle, g_FragHandle);
  244. glDeleteShader(g_FragHandle);
  245. g_FragHandle = 0;
  246. glDeleteProgram(g_ShaderHandle);
  247. g_ShaderHandle = 0;
  248. if (g_FontTexture)
  249. {
  250. glDeleteTextures(1, &g_FontTexture);
  251. ImGui::GetIO().Fonts->TexID = 0;
  252. g_FontTexture = 0;
  253. }
  254. ImGui::Shutdown();
  255. }
  256. void ImGui_ImplGlfwGL3_NewFrame()
  257. {
  258. if (!g_FontTexture)
  259. ImGui_ImplGlfwGL3_CreateDeviceObjects();
  260. ImGuiIO& io = ImGui::GetIO();
  261. // Setup display size (every frame to accommodate for window resizing)
  262. int w, h;
  263. int display_w, display_h;
  264. glfwGetWindowSize(g_Window, &w, &h);
  265. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  266. io.DisplaySize = ImVec2((float)display_w, (float)display_h);
  267. // Setup time step
  268. double current_time = glfwGetTime();
  269. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  270. g_Time = current_time;
  271. // Setup inputs
  272. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  273. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  274. {
  275. double mouse_x, mouse_y;
  276. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  277. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  278. mouse_y *= (float)display_h / h;
  279. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  280. }
  281. else
  282. {
  283. io.MousePos = ImVec2(-1,-1);
  284. }
  285. for (int i = 0; i < 3; i++)
  286. {
  287. 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.
  288. g_MousePressed[i] = false;
  289. }
  290. io.MouseWheel = g_MouseWheel;
  291. g_MouseWheel = 0.0f;
  292. // Hide OS mouse cursor if ImGui is drawing it
  293. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  294. // Start the frame
  295. ImGui::NewFrame();
  296. }