imgui_impl_glfw_gl3.cpp 13 KB

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