2
0

imgui_impl_sdlrenderer.cpp 9.9 KB

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