imgui_impl_sdl.cpp 12 KB

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