imgui_impl_sdlrenderer.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // dear imgui: Renderer Backend for SDL_Renderer
  2. // (Requires: SDL 2.0.17+)
  3. // Important to understand: SDL_Renderer is an _optional_ component of SDL. We do not recommend you use SDL_Renderer
  4. // because it provide a rather limited API to the end-user. We provide this backend for the sake of completeness.
  5. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
  6. // Implemented features:
  7. // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
  8. // Missing features:
  9. // [ ] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
  10. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  11. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  12. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  13. // CHANGELOG
  14. // 2021-10-06: Backup and restore modified ClipRect/Viewport.
  15. // 2021-09-21: Initial version.
  16. #include "imgui.h"
  17. #include "imgui_impl_sdlrenderer.h"
  18. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  19. #include <stddef.h> // intptr_t
  20. #else
  21. #include <stdint.h> // intptr_t
  22. #endif
  23. // SDL
  24. #include <SDL.h>
  25. #if !SDL_VERSION_ATLEAST(2,0,17)
  26. #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function
  27. #endif
  28. // SDL_Renderer data
  29. struct ImGui_ImplSDLRenderer_Data
  30. {
  31. SDL_Renderer* SDLRenderer;
  32. SDL_Texture* FontTexture;
  33. ImGui_ImplSDLRenderer_Data() { memset(this, 0, sizeof(*this)); }
  34. };
  35. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  36. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  37. static ImGui_ImplSDLRenderer_Data* ImGui_ImplSDLRenderer_GetBackendData()
  38. {
  39. return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
  40. }
  41. // Functions
  42. bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer)
  43. {
  44. ImGuiIO& io = ImGui::GetIO();
  45. IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
  46. IM_ASSERT(renderer != NULL && "SDL_Renderer not initialized!");
  47. // Setup backend capabilities flags
  48. ImGui_ImplSDLRenderer_Data* bd = IM_NEW(ImGui_ImplSDLRenderer_Data)();
  49. io.BackendRendererUserData = (void*)bd;
  50. io.BackendRendererName = "imgui_impl_sdlrenderer";
  51. bd->SDLRenderer = renderer;
  52. return true;
  53. }
  54. void ImGui_ImplSDLRenderer_Shutdown()
  55. {
  56. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  57. IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?");
  58. ImGuiIO& io = ImGui::GetIO();
  59. ImGui_ImplSDLRenderer_DestroyDeviceObjects();
  60. io.BackendRendererName = NULL;
  61. io.BackendRendererUserData = NULL;
  62. IM_DELETE(bd);
  63. }
  64. static void ImGui_ImplSDLRenderer_SetupRenderState()
  65. {
  66. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  67. // Clear out any viewports and cliprect set by the user
  68. // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
  69. SDL_RenderSetViewport(bd->SDLRenderer, NULL);
  70. SDL_RenderSetClipRect(bd->SDLRenderer, NULL);
  71. }
  72. void ImGui_ImplSDLRenderer_NewFrame()
  73. {
  74. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  75. IM_ASSERT(bd != NULL && "Did you call ImGui_ImplSDLRenderer_Init()?");
  76. if (!bd->FontTexture)
  77. ImGui_ImplSDLRenderer_CreateDeviceObjects();
  78. }
  79. void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data)
  80. {
  81. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  82. // If there's a scale factor set by the user, use that instead
  83. // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
  84. // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
  85. float rsx = 1.0f;
  86. float rsy = 1.0f;
  87. SDL_RenderGetScale(bd->SDLRenderer, &rsx, &rsy);
  88. ImVec2 render_scale;
  89. render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
  90. render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
  91. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  92. int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
  93. int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
  94. if (fb_width == 0 || fb_height == 0)
  95. return;
  96. // Backup SDL_Renderer state that will be modified to restore it afterwards
  97. struct BackupSDLRendererState
  98. {
  99. SDL_Rect Viewport;
  100. bool ClipEnabled;
  101. SDL_Rect ClipRect;
  102. };
  103. BackupSDLRendererState old = {};
  104. old.ClipEnabled = SDL_RenderIsClipEnabled(bd->SDLRenderer);
  105. SDL_RenderGetViewport(bd->SDLRenderer, &old.Viewport);
  106. SDL_RenderGetClipRect(bd->SDLRenderer, &old.ClipRect);
  107. // Will project scissor/clipping rectangles into framebuffer space
  108. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  109. ImVec2 clip_scale = render_scale;
  110. // Render command lists
  111. ImGui_ImplSDLRenderer_SetupRenderState();
  112. for (int n = 0; n < draw_data->CmdListsCount; n++)
  113. {
  114. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  115. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  116. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  117. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  118. {
  119. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  120. if (pcmd->UserCallback)
  121. {
  122. // User callback, registered via ImDrawList::AddCallback()
  123. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  124. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  125. ImGui_ImplSDLRenderer_SetupRenderState();
  126. else
  127. pcmd->UserCallback(cmd_list, pcmd);
  128. }
  129. else
  130. {
  131. // Project scissor/clipping rectangles into framebuffer space
  132. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  133. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  134. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  135. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  136. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  137. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  138. if (clip_max.x < clip_min.x || clip_max.y < clip_min.y)
  139. continue;
  140. SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) };
  141. SDL_RenderSetClipRect(bd->SDLRenderer, &r);
  142. const float* xy = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos));
  143. const float* uv = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv));
  144. const int* color = (const int*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col));
  145. // Bind texture, Draw
  146. SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
  147. SDL_RenderGeometryRaw(bd->SDLRenderer, tex,
  148. xy, (int)sizeof(ImDrawVert),
  149. color, (int)sizeof(ImDrawVert),
  150. uv, (int)sizeof(ImDrawVert),
  151. cmd_list->VtxBuffer.Size,
  152. idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
  153. }
  154. }
  155. }
  156. // Restore modified SDL_Renderer state
  157. SDL_RenderSetViewport(bd->SDLRenderer, &old.Viewport);
  158. SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : NULL);
  159. }
  160. // Called by Init/NewFrame/Shutdown
  161. bool ImGui_ImplSDLRenderer_CreateFontsTexture()
  162. {
  163. ImGuiIO& io = ImGui::GetIO();
  164. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  165. // Build texture atlas
  166. unsigned char* pixels;
  167. int width, height;
  168. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
  169. // Upload texture to graphics system
  170. bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height);
  171. if (bd->FontTexture == NULL)
  172. {
  173. SDL_Log("error creating texture");
  174. return false;
  175. }
  176. SDL_UpdateTexture(bd->FontTexture, NULL, pixels, 4 * width);
  177. SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
  178. // Store our identifier
  179. io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
  180. return true;
  181. }
  182. void ImGui_ImplSDLRenderer_DestroyFontsTexture()
  183. {
  184. ImGuiIO& io = ImGui::GetIO();
  185. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  186. if (bd->FontTexture)
  187. {
  188. io.Fonts->SetTexID(0);
  189. SDL_DestroyTexture(bd->FontTexture);
  190. bd->FontTexture = NULL;
  191. }
  192. }
  193. bool ImGui_ImplSDLRenderer_CreateDeviceObjects()
  194. {
  195. return ImGui_ImplSDLRenderer_CreateFontsTexture();
  196. }
  197. void ImGui_ImplSDLRenderer_DestroyDeviceObjects()
  198. {
  199. ImGui_ImplSDLRenderer_DestroyFontsTexture();
  200. }