imgui_impl_sdl.cpp 11 KB

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