imgui_impl_glfw_gl3.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 bool g_FontTextureLoaded = false;
  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 size_t g_VboMaxSize = 20000;
  24. static unsigned int g_VboHandle = 0, g_VaoHandle = 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(ImDrawList** const cmd_lists, int cmd_lists_count)
  29. {
  30. if (cmd_lists_count == 0)
  31. return;
  32. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  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. // Grow our buffer according to what we need
  54. size_t total_vtx_count = 0;
  55. for (int n = 0; n < cmd_lists_count; n++)
  56. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  57. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  58. size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
  59. if (neededBufferSize > g_VboMaxSize)
  60. {
  61. g_VboMaxSize = neededBufferSize + 5000; // Grow buffer
  62. glBufferData(GL_ARRAY_BUFFER, g_VboMaxSize, NULL, GL_STREAM_DRAW);
  63. }
  64. // Copy and convert all vertices into a single contiguous buffer
  65. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  66. if (!buffer_data)
  67. return;
  68. for (int n = 0; n < cmd_lists_count; n++)
  69. {
  70. const ImDrawList* cmd_list = cmd_lists[n];
  71. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  72. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  73. }
  74. glUnmapBuffer(GL_ARRAY_BUFFER);
  75. glBindBuffer(GL_ARRAY_BUFFER, 0);
  76. glBindVertexArray(g_VaoHandle);
  77. int cmd_offset = 0;
  78. for (int n = 0; n < cmd_lists_count; n++)
  79. {
  80. const ImDrawList* cmd_list = cmd_lists[n];
  81. int vtx_offset = cmd_offset;
  82. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  83. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  84. {
  85. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
  86. glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
  87. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  88. vtx_offset += pcmd->vtx_count;
  89. }
  90. cmd_offset = vtx_offset;
  91. }
  92. // Restore modified state
  93. glBindVertexArray(0);
  94. glUseProgram(0);
  95. glDisable(GL_SCISSOR_TEST);
  96. glBindTexture(GL_TEXTURE_2D, 0);
  97. }
  98. static const char* ImGui_ImplGlfwGL3_GetClipboardText()
  99. {
  100. return glfwGetClipboardString(g_Window);
  101. }
  102. static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text)
  103. {
  104. glfwSetClipboardString(g_Window, text);
  105. }
  106. void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
  107. {
  108. if (action == GLFW_PRESS && button >= 0 && button < 3)
  109. g_MousePressed[button] = true;
  110. }
  111. void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
  112. {
  113. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  114. }
  115. void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
  116. {
  117. ImGuiIO& io = ImGui::GetIO();
  118. if (action == GLFW_PRESS)
  119. io.KeysDown[key] = true;
  120. if (action == GLFW_RELEASE)
  121. io.KeysDown[key] = false;
  122. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  123. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  124. }
  125. void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow* window, unsigned int c)
  126. {
  127. ImGuiIO& io = ImGui::GetIO();
  128. if (c > 0 && c < 0x10000)
  129. io.AddInputCharacter((unsigned short)c);
  130. }
  131. void ImGui_ImplGlfwGL3_InitFontsTexture()
  132. {
  133. ImGuiIO& io = ImGui::GetIO();
  134. unsigned char* pixels;
  135. int width, height;
  136. 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.
  137. GLuint tex_id;
  138. glGenTextures(1, &tex_id);
  139. glBindTexture(GL_TEXTURE_2D, tex_id);
  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)tex_id;
  145. g_FontTextureLoaded = true;
  146. }
  147. static void InitGL()
  148. {
  149. const GLchar *vertex_shader =
  150. "#version 330\n"
  151. "uniform mat4 ProjMtx;\n"
  152. "in vec2 Position;\n"
  153. "in vec2 UV;\n"
  154. "in vec4 Color;\n"
  155. "out vec2 Frag_UV;\n"
  156. "out vec4 Frag_Color;\n"
  157. "void main()\n"
  158. "{\n"
  159. " Frag_UV = UV;\n"
  160. " Frag_Color = Color;\n"
  161. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  162. "}\n";
  163. const GLchar* fragment_shader =
  164. "#version 330\n"
  165. "uniform sampler2D Texture;\n"
  166. "in vec2 Frag_UV;\n"
  167. "in vec4 Frag_Color;\n"
  168. "out vec4 Out_Color;\n"
  169. "void main()\n"
  170. "{\n"
  171. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  172. "}\n";
  173. g_ShaderHandle = glCreateProgram();
  174. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  175. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  176. glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
  177. glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
  178. glCompileShader(g_VertHandle);
  179. glCompileShader(g_FragHandle);
  180. glAttachShader(g_ShaderHandle, g_VertHandle);
  181. glAttachShader(g_ShaderHandle, g_FragHandle);
  182. glLinkProgram(g_ShaderHandle);
  183. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  184. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  185. g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
  186. g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
  187. g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
  188. glGenBuffers(1, &g_VboHandle);
  189. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  190. glBufferData(GL_ARRAY_BUFFER, g_VboMaxSize, NULL, GL_DYNAMIC_DRAW);
  191. glGenVertexArrays(1, &g_VaoHandle);
  192. glBindVertexArray(g_VaoHandle);
  193. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  194. glEnableVertexAttribArray(g_AttribLocationPosition);
  195. glEnableVertexAttribArray(g_AttribLocationUV);
  196. glEnableVertexAttribArray(g_AttribLocationColor);
  197. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  198. glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  199. glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  200. glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  201. #undef OFFSETOF
  202. glBindVertexArray(0);
  203. glBindBuffer(GL_ARRAY_BUFFER, 0);
  204. }
  205. bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
  206. {
  207. InitGL();
  208. g_Window = window;
  209. ImGuiIO& io = ImGui::GetIO();
  210. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  211. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  212. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  213. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  214. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  215. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  216. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  217. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  218. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  219. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  220. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  221. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  222. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  223. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  224. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  225. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  226. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  227. io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists;
  228. io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText;
  229. io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText;
  230. #ifdef _MSC_VER
  231. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  232. #endif
  233. if (install_callbacks)
  234. {
  235. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback);
  236. glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback);
  237. glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback);
  238. glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback);
  239. }
  240. return true;
  241. }
  242. void ImGui_ImplGlfwGL3_Shutdown()
  243. {
  244. if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
  245. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  246. g_VaoHandle = 0;
  247. g_VboHandle = 0;
  248. glDetachShader(g_ShaderHandle, g_VertHandle);
  249. glDeleteShader(g_VertHandle);
  250. g_VertHandle = 0;
  251. glDetachShader(g_ShaderHandle, g_FragHandle);
  252. glDeleteShader(g_FragHandle);
  253. g_FragHandle = 0;
  254. glDeleteProgram(g_ShaderHandle);
  255. g_ShaderHandle = 0;
  256. if (GLuint tex_id = (GLuint)ImGui::GetIO().Fonts->TexID)
  257. {
  258. glDeleteTextures(1, &tex_id);
  259. ImGui::GetIO().Fonts->TexID = 0;
  260. }
  261. ImGui::Shutdown();
  262. }
  263. void ImGui_ImplGlfwGL3_NewFrame()
  264. {
  265. if (!g_FontTextureLoaded)
  266. ImGui_ImplGlfwGL3_InitFontsTexture();
  267. ImGuiIO& io = ImGui::GetIO();
  268. // Setup display size (every frame to accommodate for window resizing)
  269. int w, h;
  270. int display_w, display_h;
  271. glfwGetWindowSize(g_Window, &w, &h);
  272. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  273. io.DisplaySize = ImVec2((float)display_w, (float)display_h);
  274. // Setup time step
  275. double current_time = glfwGetTime();
  276. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  277. g_Time = current_time;
  278. // Setup inputs
  279. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  280. double mouse_x, mouse_y;
  281. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  282. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  283. mouse_y *= (float)display_h / h;
  284. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  285. io.MouseDown[0] = g_MousePressed[0] || glfwGetMouseButton(g_Window, GLFW_MOUSE_BUTTON_LEFT) != 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.
  286. io.MouseDown[1] = g_MousePressed[1] || glfwGetMouseButton(g_Window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  287. io.MouseDown[2] = g_MousePressed[2] || glfwGetMouseButton(g_Window, GLFW_MOUSE_BUTTON_MIDDLE) != 0;
  288. g_MousePressed[0] = false;
  289. g_MousePressed[1] = false;
  290. g_MousePressed[2] = false;
  291. io.MouseWheel = g_MouseWheel;
  292. g_MouseWheel = 0.0f;
  293. // Start the frame
  294. ImGui::NewFrame();
  295. }