imgui_impl_glfw_gl3.cpp 13 KB

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