imgui_impl_sdl.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // ImGui SDL2 binding with OpenGL
  2. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  3. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  4. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  5. // https://github.com/ocornut/imgui
  6. #include <SDL.h>
  7. #include <SDL_syswm.h>
  8. #include <SDL_opengl.h>
  9. #include <imgui.h>
  10. #include "imgui_impl_sdl.h"
  11. // Data
  12. static double g_Time = 0.0f;
  13. static bool g_MousePressed[3] = { false, false, false };
  14. static float g_MouseWheel = 0.0f;
  15. static GLuint g_FontTexture = 0;
  16. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  17. // If text or lines are blurry when integrating ImGui in your engine:
  18. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  19. void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
  20. {
  21. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  22. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  23. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  24. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  25. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  26. glEnable(GL_BLEND);
  27. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  28. glDisable(GL_CULL_FACE);
  29. glDisable(GL_DEPTH_TEST);
  30. glEnable(GL_SCISSOR_TEST);
  31. glEnableClientState(GL_VERTEX_ARRAY);
  32. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  33. glEnableClientState(GL_COLOR_ARRAY);
  34. glEnable(GL_TEXTURE_2D);
  35. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
  36. // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
  37. ImGuiIO& io = ImGui::GetIO();
  38. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  39. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  40. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  41. // Setup viewport, orthographic projection matrix
  42. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  43. glMatrixMode(GL_PROJECTION);
  44. glPushMatrix();
  45. glLoadIdentity();
  46. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  47. glMatrixMode(GL_MODELVIEW);
  48. glPushMatrix();
  49. glLoadIdentity();
  50. // Render command lists
  51. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  52. for (int n = 0; n < draw_data->CmdListsCount; n++)
  53. {
  54. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  55. const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
  56. const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
  57. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
  58. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
  59. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));
  60. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  61. {
  62. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  63. if (pcmd->UserCallback)
  64. {
  65. pcmd->UserCallback(cmd_list, pcmd);
  66. }
  67. else
  68. {
  69. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  70. 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));
  71. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  72. }
  73. idx_buffer += pcmd->ElemCount;
  74. }
  75. }
  76. #undef OFFSETOF
  77. // Restore modified state
  78. glDisableClientState(GL_COLOR_ARRAY);
  79. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  80. glDisableClientState(GL_VERTEX_ARRAY);
  81. glBindTexture(GL_TEXTURE_2D, last_texture);
  82. glMatrixMode(GL_MODELVIEW);
  83. glPopMatrix();
  84. glMatrixMode(GL_PROJECTION);
  85. glPopMatrix();
  86. glPopAttrib();
  87. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  88. }
  89. static const char* ImGui_ImplSdl_GetClipboardText()
  90. {
  91. return SDL_GetClipboardText();
  92. }
  93. static void ImGui_ImplSdl_SetClipboardText(const char* text)
  94. {
  95. SDL_SetClipboardText(text);
  96. }
  97. bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event)
  98. {
  99. ImGuiIO& io = ImGui::GetIO();
  100. switch (event->type)
  101. {
  102. case SDL_MOUSEWHEEL:
  103. {
  104. if (event->wheel.y > 0)
  105. g_MouseWheel = 1;
  106. if (event->wheel.y < 0)
  107. g_MouseWheel = -1;
  108. return true;
  109. }
  110. case SDL_MOUSEBUTTONDOWN:
  111. {
  112. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  113. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  114. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  115. return true;
  116. }
  117. case SDL_TEXTINPUT:
  118. {
  119. ImGuiIO& io = ImGui::GetIO();
  120. io.AddInputCharactersUTF8(event->text.text);
  121. return true;
  122. }
  123. case SDL_KEYDOWN:
  124. case SDL_KEYUP:
  125. {
  126. int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK;
  127. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  128. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  129. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  130. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  131. return true;
  132. }
  133. }
  134. return false;
  135. }
  136. bool ImGui_ImplSdl_CreateDeviceObjects()
  137. {
  138. // Build texture atlas
  139. ImGuiIO& io = ImGui::GetIO();
  140. unsigned char* pixels;
  141. int width, height;
  142. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
  143. // Upload texture to graphics system
  144. GLint last_texture;
  145. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  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_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
  151. // Store our identifier
  152. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  153. // Restore state
  154. glBindTexture(GL_TEXTURE_2D, last_texture);
  155. return true;
  156. }
  157. void ImGui_ImplSdl_InvalidateDeviceObjects()
  158. {
  159. if (g_FontTexture)
  160. {
  161. glDeleteTextures(1, &g_FontTexture);
  162. ImGui::GetIO().Fonts->TexID = 0;
  163. g_FontTexture = 0;
  164. }
  165. }
  166. bool ImGui_ImplSdl_Init(SDL_Window *window)
  167. {
  168. ImGuiIO& io = ImGui::GetIO();
  169. io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  170. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  171. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  172. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  173. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  174. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  175. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  176. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  177. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  178. io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
  179. io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
  180. io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
  181. io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
  182. io.KeyMap[ImGuiKey_A] = SDLK_a;
  183. io.KeyMap[ImGuiKey_C] = SDLK_c;
  184. io.KeyMap[ImGuiKey_V] = SDLK_v;
  185. io.KeyMap[ImGuiKey_X] = SDLK_x;
  186. io.KeyMap[ImGuiKey_Y] = SDLK_y;
  187. io.KeyMap[ImGuiKey_Z] = SDLK_z;
  188. io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  189. io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText;
  190. io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText;
  191. #ifdef _WIN32
  192. SDL_SysWMinfo wmInfo;
  193. SDL_VERSION(&wmInfo.version);
  194. SDL_GetWindowWMInfo(window, &wmInfo);
  195. io.ImeWindowHandle = wmInfo.info.win.window;
  196. #endif
  197. return true;
  198. }
  199. void ImGui_ImplSdl_Shutdown()
  200. {
  201. ImGui_ImplSdl_InvalidateDeviceObjects();
  202. ImGui::Shutdown();
  203. }
  204. void ImGui_ImplSdl_NewFrame(SDL_Window *window)
  205. {
  206. if (!g_FontTexture)
  207. ImGui_ImplSdl_CreateDeviceObjects();
  208. ImGuiIO& io = ImGui::GetIO();
  209. // Setup display size (every frame to accommodate for window resizing)
  210. int w, h;
  211. SDL_GetWindowSize(window, &w, &h);
  212. io.DisplaySize = ImVec2((float)w, (float)h);
  213. // Setup time step
  214. Uint32 time = SDL_GetTicks();
  215. double current_time = time / 1000.0;
  216. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  217. g_Time = current_time;
  218. // Setup inputs
  219. // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
  220. int mx, my;
  221. Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
  222. if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
  223. io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  224. else
  225. io.MousePos = ImVec2(-1,-1);
  226. io.MouseDown[0] = g_MousePressed[0] || (mouseMask & 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.
  227. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  228. io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  229. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  230. io.MouseWheel = g_MouseWheel;
  231. g_MouseWheel = 0.0f;
  232. // Hide OS mouse cursor if ImGui is drawing it
  233. SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
  234. // Start the frame
  235. ImGui::NewFrame();
  236. }