imgui_impl_sdl.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // ImGui SDL2 binding with OpenGL
  2. // You can copy and use unmodified imgui_impl_* files in your project.
  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. // See main.cpp for an example of using this.
  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. // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
  23. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  24. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  25. glEnable(GL_BLEND);
  26. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  27. glDisable(GL_CULL_FACE);
  28. glDisable(GL_DEPTH_TEST);
  29. glEnable(GL_SCISSOR_TEST);
  30. glEnableClientState(GL_VERTEX_ARRAY);
  31. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  32. glEnableClientState(GL_COLOR_ARRAY);
  33. glEnable(GL_TEXTURE_2D);
  34. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
  35. // Setup orthographic projection matrix
  36. const float width = ImGui::GetIO().DisplaySize.x;
  37. const float height = ImGui::GetIO().DisplaySize.y;
  38. glMatrixMode(GL_PROJECTION);
  39. glPushMatrix();
  40. glLoadIdentity();
  41. glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
  42. glMatrixMode(GL_MODELVIEW);
  43. glPushMatrix();
  44. glLoadIdentity();
  45. // Render command lists
  46. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  47. for (int n = 0; n < draw_data->CmdListsCount; n++)
  48. {
  49. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  50. const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
  51. const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
  52. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
  53. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
  54. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));
  55. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  56. {
  57. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  58. if (pcmd->UserCallback)
  59. {
  60. pcmd->UserCallback(cmd_list, pcmd);
  61. }
  62. else
  63. {
  64. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  65. glScissor((int)pcmd->ClipRect.x, (int)(height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  66. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
  67. }
  68. idx_buffer += pcmd->ElemCount;
  69. }
  70. }
  71. #undef OFFSETOF
  72. // Restore modified state
  73. glDisableClientState(GL_COLOR_ARRAY);
  74. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  75. glDisableClientState(GL_VERTEX_ARRAY);
  76. glBindTexture(GL_TEXTURE_2D, 0);
  77. glMatrixMode(GL_MODELVIEW);
  78. glPopMatrix();
  79. glMatrixMode(GL_PROJECTION);
  80. glPopMatrix();
  81. glPopAttrib();
  82. }
  83. static const char* ImGui_ImplSdl_GetClipboardText()
  84. {
  85. return SDL_GetClipboardText();
  86. }
  87. static void ImGui_ImplSdl_SetClipboardText(const char* text)
  88. {
  89. SDL_SetClipboardText(text);
  90. }
  91. bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event)
  92. {
  93. ImGuiIO& io = ImGui::GetIO();
  94. switch (event->type)
  95. {
  96. case SDL_MOUSEWHEEL:
  97. {
  98. if (event->wheel.y > 0)
  99. g_MouseWheel = 1;
  100. if (event->wheel.y < 0)
  101. g_MouseWheel = -1;
  102. return true;
  103. }
  104. case SDL_MOUSEBUTTONDOWN:
  105. {
  106. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  107. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  108. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  109. return true;
  110. }
  111. case SDL_TEXTINPUT:
  112. {
  113. ImGuiIO& io = ImGui::GetIO();
  114. io.AddInputCharactersUTF8(event->text.text);
  115. return true;
  116. }
  117. case SDL_KEYDOWN:
  118. case SDL_KEYUP:
  119. {
  120. int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK;
  121. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  122. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  123. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  124. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. bool ImGui_ImplSdl_CreateDeviceObjects()
  131. {
  132. ImGuiIO& io = ImGui::GetIO();
  133. // Build texture
  134. unsigned char* pixels;
  135. int width, height;
  136. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
  137. // Create texture
  138. glGenTextures(1, &g_FontTexture);
  139. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  140. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  141. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  142. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
  143. // Store our identifier
  144. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  145. // Cleanup (don't clear the input data if you want to append new fonts later)
  146. io.Fonts->ClearInputData();
  147. io.Fonts->ClearTexData();
  148. return true;
  149. }
  150. void ImGui_ImplSdl_InvalidateDeviceObjects()
  151. {
  152. if (g_FontTexture)
  153. {
  154. glDeleteTextures(1, &g_FontTexture);
  155. ImGui::GetIO().Fonts->TexID = 0;
  156. g_FontTexture = 0;
  157. }
  158. }
  159. bool ImGui_ImplSdl_Init(SDL_Window *window)
  160. {
  161. ImGuiIO& io = ImGui::GetIO();
  162. io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  163. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  164. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  165. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  166. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  167. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  168. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  169. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  170. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  171. io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
  172. io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
  173. io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
  174. io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
  175. io.KeyMap[ImGuiKey_A] = SDLK_a;
  176. io.KeyMap[ImGuiKey_C] = SDLK_c;
  177. io.KeyMap[ImGuiKey_V] = SDLK_v;
  178. io.KeyMap[ImGuiKey_X] = SDLK_x;
  179. io.KeyMap[ImGuiKey_Y] = SDLK_y;
  180. io.KeyMap[ImGuiKey_Z] = SDLK_z;
  181. 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.
  182. io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText;
  183. io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText;
  184. #ifdef _WIN32
  185. SDL_SysWMinfo wmInfo;
  186. SDL_VERSION(&wmInfo.version);
  187. SDL_GetWindowWMInfo(window, &wmInfo);
  188. io.ImeWindowHandle = wmInfo.info.win.window;
  189. #endif
  190. return true;
  191. }
  192. void ImGui_ImplSdl_Shutdown()
  193. {
  194. ImGui_ImplSdl_InvalidateDeviceObjects();
  195. ImGui::Shutdown();
  196. }
  197. void ImGui_ImplSdl_NewFrame(SDL_Window *window)
  198. {
  199. if (!g_FontTexture)
  200. ImGui_ImplSdl_CreateDeviceObjects();
  201. ImGuiIO& io = ImGui::GetIO();
  202. // Setup display size (every frame to accommodate for window resizing)
  203. int w, h;
  204. SDL_GetWindowSize(window, &w, &h);
  205. io.DisplaySize = ImVec2((float)w, (float)h);
  206. // Setup time step
  207. Uint32 time = SDL_GetTicks();
  208. double current_time = time / 1000.0;
  209. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  210. g_Time = current_time;
  211. // Setup inputs
  212. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  213. int mx, my;
  214. Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
  215. if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
  216. io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  217. else
  218. io.MousePos = ImVec2(-1,-1);
  219. 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.
  220. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  221. io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  222. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  223. io.MouseWheel = g_MouseWheel;
  224. g_MouseWheel = 0.0f;
  225. // Hide OS mouse cursor if ImGui is drawing it
  226. SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
  227. // Start the frame
  228. ImGui::NewFrame();
  229. }