imgui_impl_sdl_gl2.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // ImGui SDL2 binding with OpenGL (legacy, fixed pipeline)
  2. // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
  4. // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
  5. // **Prefer using the code in the sdl_opengl3_example/ folder**
  6. // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
  7. // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
  8. // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
  9. // confuse your GPU driver.
  10. // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
  11. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  12. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  13. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  14. // https://github.com/ocornut/imgui
  15. #include <SDL.h>
  16. #include <SDL_syswm.h>
  17. #include <SDL_opengl.h>
  18. #include <imgui.h>
  19. #include "imgui_impl_sdl_gl2.h"
  20. // Data
  21. static double g_Time = 0.0f;
  22. static bool g_MousePressed[3] = { false, false, false };
  23. static float g_MouseHorizWheel = 0.0f;
  24. static float g_MouseWheel = 0.0f;
  25. static GLuint g_FontTexture = 0;
  26. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  27. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
  28. // If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  29. void ImGui_ImplSdlGL2_RenderDrawLists(ImDrawData* draw_data)
  30. {
  31. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  32. ImGuiIO& io = ImGui::GetIO();
  33. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  34. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  35. if (fb_width == 0 || fb_height == 0)
  36. return;
  37. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  38. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  39. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
  40. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  41. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  42. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  43. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  44. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  45. glEnable(GL_BLEND);
  46. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  47. glDisable(GL_CULL_FACE);
  48. glDisable(GL_DEPTH_TEST);
  49. glEnable(GL_SCISSOR_TEST);
  50. glEnableClientState(GL_VERTEX_ARRAY);
  51. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  52. glEnableClientState(GL_COLOR_ARRAY);
  53. glEnable(GL_TEXTURE_2D);
  54. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  55. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
  56. // Setup viewport, orthographic projection matrix
  57. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  58. glMatrixMode(GL_PROJECTION);
  59. glPushMatrix();
  60. glLoadIdentity();
  61. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  62. glMatrixMode(GL_MODELVIEW);
  63. glPushMatrix();
  64. glLoadIdentity();
  65. // Render command lists
  66. for (int n = 0; n < draw_data->CmdListsCount; n++)
  67. {
  68. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  69. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  70. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  71. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
  72. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
  73. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
  74. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  75. {
  76. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  77. if (pcmd->UserCallback)
  78. {
  79. pcmd->UserCallback(cmd_list, pcmd);
  80. }
  81. else
  82. {
  83. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  84. glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  85. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  86. }
  87. idx_buffer += pcmd->ElemCount;
  88. }
  89. }
  90. // Restore modified state
  91. glDisableClientState(GL_COLOR_ARRAY);
  92. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  93. glDisableClientState(GL_VERTEX_ARRAY);
  94. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  95. glMatrixMode(GL_MODELVIEW);
  96. glPopMatrix();
  97. glMatrixMode(GL_PROJECTION);
  98. glPopMatrix();
  99. glPopAttrib();
  100. glPolygonMode(GL_FRONT, last_polygon_mode[0]); glPolygonMode(GL_BACK, last_polygon_mode[1]);
  101. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  102. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  103. }
  104. static const char* ImGui_ImplSdlGL2_GetClipboardText(void*)
  105. {
  106. return SDL_GetClipboardText();
  107. }
  108. static void ImGui_ImplSdlGL2_SetClipboardText(void*, const char* text)
  109. {
  110. SDL_SetClipboardText(text);
  111. }
  112. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  113. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  114. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  115. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  116. bool ImGui_ImplSdlGL2_ProcessEvent(SDL_Event* event)
  117. {
  118. ImGuiIO& io = ImGui::GetIO();
  119. switch (event->type)
  120. {
  121. case SDL_MOUSEWHEEL:
  122. {
  123. if (event->wheel.x > 0)
  124. g_MouseHorizWheel = 1;
  125. if (event->wheel.x < 0)
  126. g_MouseHorizWheel = -1;
  127. if (event->wheel.y > 0)
  128. g_MouseWheel = 1;
  129. if (event->wheel.y < 0)
  130. g_MouseWheel = -1;
  131. return true;
  132. }
  133. case SDL_MOUSEBUTTONDOWN:
  134. {
  135. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  136. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  137. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  138. return true;
  139. }
  140. case SDL_TEXTINPUT:
  141. {
  142. io.AddInputCharactersUTF8(event->text.text);
  143. return true;
  144. }
  145. case SDL_KEYDOWN:
  146. case SDL_KEYUP:
  147. {
  148. int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK;
  149. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  150. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  151. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  152. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  153. io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. bool ImGui_ImplSdlGL2_CreateDeviceObjects()
  160. {
  161. // Build texture atlas
  162. ImGuiIO& io = ImGui::GetIO();
  163. unsigned char* pixels;
  164. int width, height;
  165. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
  166. // Upload texture to graphics system
  167. GLint last_texture;
  168. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  169. glGenTextures(1, &g_FontTexture);
  170. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  171. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  172. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  173. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  174. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
  175. // Store our identifier
  176. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  177. // Restore state
  178. glBindTexture(GL_TEXTURE_2D, last_texture);
  179. return true;
  180. }
  181. void ImGui_ImplSdlGL2_InvalidateDeviceObjects()
  182. {
  183. if (g_FontTexture)
  184. {
  185. glDeleteTextures(1, &g_FontTexture);
  186. ImGui::GetIO().Fonts->TexID = 0;
  187. g_FontTexture = 0;
  188. }
  189. }
  190. bool ImGui_ImplSdlGL2_Init(SDL_Window* window)
  191. {
  192. ImGuiIO& io = ImGui::GetIO();
  193. io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  194. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  195. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  196. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  197. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  198. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  199. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  200. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  201. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  202. io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
  203. io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
  204. io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
  205. io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
  206. io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
  207. io.KeyMap[ImGuiKey_A] = SDLK_a;
  208. io.KeyMap[ImGuiKey_C] = SDLK_c;
  209. io.KeyMap[ImGuiKey_V] = SDLK_v;
  210. io.KeyMap[ImGuiKey_X] = SDLK_x;
  211. io.KeyMap[ImGuiKey_Y] = SDLK_y;
  212. io.KeyMap[ImGuiKey_Z] = SDLK_z;
  213. io.RenderDrawListsFn = ImGui_ImplSdlGL2_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  214. io.SetClipboardTextFn = ImGui_ImplSdlGL2_SetClipboardText;
  215. io.GetClipboardTextFn = ImGui_ImplSdlGL2_GetClipboardText;
  216. io.ClipboardUserData = NULL;
  217. #ifdef _WIN32
  218. SDL_SysWMinfo wmInfo;
  219. SDL_VERSION(&wmInfo.version);
  220. SDL_GetWindowWMInfo(window, &wmInfo);
  221. io.ImeWindowHandle = wmInfo.info.win.window;
  222. #else
  223. (void)window;
  224. #endif
  225. return true;
  226. }
  227. void ImGui_ImplSdlGL2_Shutdown()
  228. {
  229. ImGui_ImplSdlGL2_InvalidateDeviceObjects();
  230. ImGui::Shutdown();
  231. }
  232. void ImGui_ImplSdlGL2_NewFrame(SDL_Window *window)
  233. {
  234. if (!g_FontTexture)
  235. ImGui_ImplSdlGL2_CreateDeviceObjects();
  236. ImGuiIO& io = ImGui::GetIO();
  237. // Setup display size (every frame to accommodate for window resizing)
  238. int w, h;
  239. int display_w, display_h;
  240. SDL_GetWindowSize(window, &w, &h);
  241. SDL_GL_GetDrawableSize(window, &display_w, &display_h);
  242. io.DisplaySize = ImVec2((float)w, (float)h);
  243. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  244. // Setup time step
  245. Uint32 time = SDL_GetTicks();
  246. double current_time = time / 1000.0;
  247. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
  248. g_Time = current_time;
  249. // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler)
  250. int mx, my;
  251. Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
  252. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  253. io.MouseWheel = g_MouseWheel;
  254. io.MouseHorizWheel = g_MouseHorizWheel;
  255. io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_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.
  256. io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  257. io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  258. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  259. g_MouseWheel = g_MouseHorizWheel = 0.0f;
  260. // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016)
  261. #if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4)
  262. if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0)
  263. io.MousePos = ImVec2((float)mx, (float)my);
  264. bool any_mouse_button_down = false;
  265. for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
  266. any_mouse_button_down |= io.MouseDown[n];
  267. if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0)
  268. SDL_CaptureMouse(SDL_TRUE);
  269. if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0)
  270. SDL_CaptureMouse(SDL_FALSE);
  271. #else
  272. if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0)
  273. io.MousePos = ImVec2((float)mx, (float)my);
  274. #endif
  275. // Hide OS mouse cursor if ImGui is drawing it
  276. SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
  277. // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
  278. ImGui::NewFrame();
  279. }