imgui_impl_glfw_gl3.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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* window, 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. (void)mods; // Modifiers are not reliable across systems
  130. io.KeyCtrl = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS;
  131. io.KeyShift = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS;
  132. io.KeyAlt = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS;
  133. }
  134. void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c)
  135. {
  136. ImGuiIO& io = ImGui::GetIO();
  137. if (c > 0 && c < 0x10000)
  138. io.AddInputCharacter((unsigned short)c);
  139. }
  140. void ImGui_ImplGlfwGL3_CreateFontsTexture()
  141. {
  142. ImGuiIO& io = ImGui::GetIO();
  143. unsigned char* pixels;
  144. int width, height;
  145. 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.
  146. glGenTextures(1, &g_FontTexture);
  147. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  148. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  149. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  150. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  151. // Store our identifier
  152. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  153. }
  154. bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
  155. {
  156. const GLchar *vertex_shader =
  157. "#version 330\n"
  158. "uniform mat4 ProjMtx;\n"
  159. "in vec2 Position;\n"
  160. "in vec2 UV;\n"
  161. "in vec4 Color;\n"
  162. "out vec2 Frag_UV;\n"
  163. "out vec4 Frag_Color;\n"
  164. "void main()\n"
  165. "{\n"
  166. " Frag_UV = UV;\n"
  167. " Frag_Color = Color;\n"
  168. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  169. "}\n";
  170. const GLchar* fragment_shader =
  171. "#version 330\n"
  172. "uniform sampler2D Texture;\n"
  173. "in vec2 Frag_UV;\n"
  174. "in vec4 Frag_Color;\n"
  175. "out vec4 Out_Color;\n"
  176. "void main()\n"
  177. "{\n"
  178. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  179. "}\n";
  180. g_ShaderHandle = glCreateProgram();
  181. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  182. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  183. glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
  184. glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
  185. glCompileShader(g_VertHandle);
  186. glCompileShader(g_FragHandle);
  187. glAttachShader(g_ShaderHandle, g_VertHandle);
  188. glAttachShader(g_ShaderHandle, g_FragHandle);
  189. glLinkProgram(g_ShaderHandle);
  190. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  191. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  192. g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
  193. g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
  194. g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
  195. glGenBuffers(1, &g_VboHandle);
  196. glGenVertexArrays(1, &g_VaoHandle);
  197. glBindVertexArray(g_VaoHandle);
  198. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  199. glEnableVertexAttribArray(g_AttribLocationPosition);
  200. glEnableVertexAttribArray(g_AttribLocationUV);
  201. glEnableVertexAttribArray(g_AttribLocationColor);
  202. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  203. glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  204. glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  205. glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  206. #undef OFFSETOF
  207. glBindVertexArray(0);
  208. glBindBuffer(GL_ARRAY_BUFFER, 0);
  209. ImGui_ImplGlfwGL3_CreateFontsTexture();
  210. return true;
  211. }
  212. bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
  213. {
  214. g_Window = window;
  215. ImGuiIO& io = ImGui::GetIO();
  216. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  217. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  218. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  219. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  220. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  221. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  222. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  223. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  224. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  225. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  226. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  227. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  228. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  229. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  230. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  231. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  232. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  233. io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists;
  234. io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText;
  235. io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText;
  236. #ifdef _MSC_VER
  237. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  238. #endif
  239. if (install_callbacks)
  240. {
  241. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback);
  242. glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback);
  243. glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback);
  244. glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback);
  245. }
  246. return true;
  247. }
  248. void ImGui_ImplGlfwGL3_Shutdown()
  249. {
  250. if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
  251. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  252. g_VaoHandle = 0;
  253. g_VboHandle = 0;
  254. glDetachShader(g_ShaderHandle, g_VertHandle);
  255. glDeleteShader(g_VertHandle);
  256. g_VertHandle = 0;
  257. glDetachShader(g_ShaderHandle, g_FragHandle);
  258. glDeleteShader(g_FragHandle);
  259. g_FragHandle = 0;
  260. glDeleteProgram(g_ShaderHandle);
  261. g_ShaderHandle = 0;
  262. if (g_FontTexture)
  263. {
  264. glDeleteTextures(1, &g_FontTexture);
  265. ImGui::GetIO().Fonts->TexID = 0;
  266. g_FontTexture = 0;
  267. }
  268. ImGui::Shutdown();
  269. }
  270. void ImGui_ImplGlfwGL3_NewFrame()
  271. {
  272. if (!g_FontTexture)
  273. ImGui_ImplGlfwGL3_CreateDeviceObjects();
  274. ImGuiIO& io = ImGui::GetIO();
  275. // Setup display size (every frame to accommodate for window resizing)
  276. int w, h;
  277. int display_w, display_h;
  278. glfwGetWindowSize(g_Window, &w, &h);
  279. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  280. io.DisplaySize = ImVec2((float)display_w, (float)display_h);
  281. // Setup time step
  282. double current_time = glfwGetTime();
  283. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  284. g_Time = current_time;
  285. // Setup inputs
  286. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  287. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  288. {
  289. double mouse_x, mouse_y;
  290. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  291. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  292. mouse_y *= (float)display_h / h;
  293. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  294. }
  295. else
  296. {
  297. io.MousePos = ImVec2(-1,-1);
  298. }
  299. for (int i = 0; i < 3; i++)
  300. {
  301. 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.
  302. g_MousePressed[i] = false;
  303. }
  304. io.MouseWheel = g_MouseWheel;
  305. g_MouseWheel = 0.0f;
  306. // Hide/show hardware mouse cursor
  307. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  308. // Start the frame
  309. ImGui::NewFrame();
  310. }