imgui_impl_sdlgpu3.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. // dear imgui: Renderer Backend for SDL_GPU
  2. // This needs to be used along with the SDL3 Platform Backend
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID.
  5. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
  6. // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification.
  7. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  8. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  9. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  10. // Learn about Dear ImGui:
  11. // - FAQ https://dearimgui.com/faq
  12. // - Getting Started https://dearimgui.com/getting-started
  13. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  14. // - Introduction, links and more at the top of imgui.cpp
  15. // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app.
  16. // - Unlike other backends, the user must call the function Imgui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData.
  17. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info.
  18. // CHANGELOG
  19. // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device.
  20. // 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend.
  21. #include "imgui.h"
  22. #ifndef IMGUI_DISABLE
  23. #include "imgui_impl_sdlgpu3.h"
  24. #include "imgui_impl_sdlgpu3_shaders.h"
  25. // SDL_GPU Data
  26. // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData()
  27. struct ImGui_ImplSDLGPU3_FrameData
  28. {
  29. SDL_GPUBuffer* VertexBuffer = nullptr;
  30. SDL_GPUBuffer* IndexBuffer = nullptr;
  31. uint32_t VertexBufferSize = 0;
  32. uint32_t IndexBufferSize = 0;
  33. };
  34. struct ImGui_ImplSDLGPU3_Data
  35. {
  36. ImGui_ImplSDLGPU3_InitInfo InitInfo;
  37. // Graphics pipeline & shaders
  38. SDL_GPUShader* VertexShader = nullptr;
  39. SDL_GPUShader* FragmentShader = nullptr;
  40. SDL_GPUGraphicsPipeline* Pipeline = nullptr;
  41. // Font data
  42. SDL_GPUSampler* FontSampler = nullptr;
  43. SDL_GPUTexture* FontTexture = nullptr;
  44. SDL_GPUTextureSamplerBinding FontBinding = { nullptr, nullptr };
  45. // Frame data for main window
  46. ImGui_ImplSDLGPU3_FrameData MainWindowFrameData;
  47. };
  48. // Forward Declarations
  49. static void ImGui_ImplSDLGPU3_DestroyFrameData();
  50. //-----------------------------------------------------------------------------
  51. // FUNCTIONS
  52. //-----------------------------------------------------------------------------
  53. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  54. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  55. // FIXME: multi-context support has never been tested.
  56. static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData()
  57. {
  58. return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  59. }
  60. static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height)
  61. {
  62. //ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  63. // Bind graphics pipeline
  64. SDL_BindGPUGraphicsPipeline(render_pass,pipeline);
  65. // Bind Vertex And Index Buffers
  66. if (draw_data->TotalVtxCount > 0)
  67. {
  68. SDL_GPUBufferBinding vertex_buffer_binding = {};
  69. vertex_buffer_binding.buffer = fd->VertexBuffer;
  70. vertex_buffer_binding.offset = 0;
  71. SDL_GPUBufferBinding index_buffer_binding = {};
  72. index_buffer_binding.buffer = fd->IndexBuffer;
  73. index_buffer_binding.offset = 0;
  74. SDL_BindGPUVertexBuffers(render_pass,0, &vertex_buffer_binding, 1);
  75. SDL_BindGPUIndexBuffer(render_pass, &index_buffer_binding, sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT);
  76. }
  77. // Setup viewport
  78. SDL_GPUViewport viewport = {};
  79. viewport.x = 0;
  80. viewport.y = 0;
  81. viewport.w = (float)fb_width;
  82. viewport.h = (float)fb_height;
  83. viewport.min_depth = 0.0f;
  84. viewport.max_depth = 1.0f;
  85. SDL_SetGPUViewport(render_pass, &viewport);
  86. // Setup scale and translation
  87. // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
  88. struct UBO { float scale[2]; float translation[2]; } ubo;
  89. ubo.scale[0] = 2.0f / draw_data->DisplaySize.x;
  90. ubo.scale[1] = 2.0f / draw_data->DisplaySize.y;
  91. ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0];
  92. ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1];
  93. SDL_PushGPUVertexUniformData(command_buffer, 0, &ubo, sizeof(UBO));
  94. }
  95. static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage)
  96. {
  97. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  98. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  99. // Even though this is fairly rarely called.
  100. SDL_WaitForGPUIdle(v->Device);
  101. SDL_ReleaseGPUBuffer(v->Device, *buffer);
  102. SDL_GPUBufferCreateInfo buffer_info = {};
  103. buffer_info.usage = usage;
  104. buffer_info.size = new_size;
  105. buffer_info.props = 0;
  106. *buffer = SDL_CreateGPUBuffer(v->Device, &buffer_info);
  107. *old_size = new_size;
  108. IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information");
  109. }
  110. // SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound!
  111. // The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example),
  112. // is to split the upload part of ImGui_ImplSDLGPU3_RenderDrawData() to another function that needs to be called by the user before rendering.
  113. void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer)
  114. {
  115. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  116. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  117. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  118. if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0)
  119. return;
  120. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  121. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  122. ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
  123. uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
  124. uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
  125. if (fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size)
  126. CreateOrResizeBuffer(&fd->VertexBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX);
  127. if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size)
  128. CreateOrResizeBuffer(&fd->IndexBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX);
  129. // FIXME: It feels like more code could be shared there.
  130. SDL_GPUTransferBufferCreateInfo vertex_transferbuffer_info = {};
  131. vertex_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
  132. vertex_transferbuffer_info.size = vertex_size;
  133. SDL_GPUTransferBufferCreateInfo index_transferbuffer_info = {};
  134. index_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
  135. index_transferbuffer_info.size = index_size;
  136. SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &vertex_transferbuffer_info);
  137. IM_ASSERT(vertex_transferbuffer != nullptr && "Failed to create the vertex transfer buffer, call SDL_GetError() for more information");
  138. SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &index_transferbuffer_info);
  139. IM_ASSERT(index_transferbuffer != nullptr && "Failed to create the index transfer buffer, call SDL_GetError() for more information");
  140. ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, vertex_transferbuffer, true);
  141. ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, index_transferbuffer, true);
  142. for (int n = 0; n < draw_data->CmdListsCount; n++)
  143. {
  144. const ImDrawList* draw_list = draw_data->CmdLists[n];
  145. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  146. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  147. vtx_dst += draw_list->VtxBuffer.Size;
  148. idx_dst += draw_list->IdxBuffer.Size;
  149. }
  150. SDL_UnmapGPUTransferBuffer(v->Device, vertex_transferbuffer);
  151. SDL_UnmapGPUTransferBuffer(v->Device, index_transferbuffer);
  152. SDL_GPUTransferBufferLocation vertex_buffer_location = {};
  153. vertex_buffer_location.offset = 0;
  154. vertex_buffer_location.transfer_buffer = vertex_transferbuffer;
  155. SDL_GPUTransferBufferLocation index_buffer_location = {};
  156. index_buffer_location.offset = 0;
  157. index_buffer_location.transfer_buffer = index_transferbuffer;
  158. SDL_GPUBufferRegion vertex_buffer_region = {};
  159. vertex_buffer_region.buffer = fd->VertexBuffer;
  160. vertex_buffer_region.offset = 0;
  161. vertex_buffer_region.size = vertex_size;
  162. SDL_GPUBufferRegion index_buffer_region = {};
  163. index_buffer_region.buffer = fd->IndexBuffer;
  164. index_buffer_region.offset = 0;
  165. index_buffer_region.size = index_size;
  166. SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer);
  167. SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region, true);
  168. SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region, true);
  169. SDL_EndGPUCopyPass(copy_pass);
  170. SDL_ReleaseGPUTransferBuffer(v->Device, index_transferbuffer);
  171. SDL_ReleaseGPUTransferBuffer(v->Device, vertex_transferbuffer);
  172. }
  173. void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline)
  174. {
  175. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  176. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  177. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  178. if (fb_width <= 0 || fb_height <= 0)
  179. return;
  180. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  181. ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
  182. if (pipeline == nullptr)
  183. pipeline = bd->Pipeline;
  184. ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height);
  185. // Will project scissor/clipping rectangles into framebuffer space
  186. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  187. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  188. // Render command lists
  189. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  190. int global_vtx_offset = 0;
  191. int global_idx_offset = 0;
  192. for (int n = 0; n < draw_data->CmdListsCount; n++)
  193. {
  194. const ImDrawList* draw_list = draw_data->CmdLists[n];
  195. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  196. {
  197. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  198. if (pcmd->UserCallback != nullptr)
  199. {
  200. pcmd->UserCallback(draw_list, pcmd);
  201. }
  202. else
  203. {
  204. // Project scissor/clipping rectangles into framebuffer space
  205. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  206. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  207. // Clamp to viewport as SDL_SetGPUScissor() won't accept values that are off bounds
  208. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  209. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  210. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  211. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  212. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  213. continue;
  214. // Apply scissor/clipping rectangle
  215. SDL_Rect scissor_rect = {};
  216. scissor_rect.x = (int)clip_min.x;
  217. scissor_rect.y = (int)clip_min.y;
  218. scissor_rect.w = (int)(clip_max.x - clip_min.x);
  219. scissor_rect.h = (int)(clip_max.y - clip_min.y);
  220. SDL_SetGPUScissor(render_pass,&scissor_rect);
  221. // Bind DescriptorSet with font or user texture
  222. SDL_BindGPUFragmentSamplers(render_pass, 0, (SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(), 1);
  223. // Draw
  224. SDL_DrawGPUIndexedPrimitives(render_pass, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  225. }
  226. }
  227. global_idx_offset += draw_list->IdxBuffer.Size;
  228. global_vtx_offset += draw_list->VtxBuffer.Size;
  229. }
  230. // Note: at this point both SDL_SetGPUViewport() and SDL_SetGPUScissor() have been called.
  231. // Our last values will leak into user/application rendering if you forgot to call SDL_SetGPUViewport() and SDL_SetGPUScissor() yourself to explicitly set that state
  232. // In theory we should aim to backup/restore those values but I am not sure this is possible.
  233. // We perform a call to SDL_SetGPUScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644)
  234. SDL_Rect scissor_rect { 0, 0, fb_width, fb_height };
  235. SDL_SetGPUScissor(render_pass, &scissor_rect);
  236. }
  237. void ImGui_ImplSDLGPU3_CreateFontsTexture()
  238. {
  239. ImGuiIO& io = ImGui::GetIO();
  240. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  241. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  242. // Destroy existing texture (if any)
  243. if (bd->FontTexture)
  244. {
  245. SDL_WaitForGPUIdle(v->Device);
  246. ImGui_ImplSDLGPU3_DestroyFontsTexture();
  247. }
  248. unsigned char* pixels;
  249. int width, height;
  250. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  251. uint32_t upload_size = width * height * 4 * sizeof(char);
  252. // Create the Image:
  253. {
  254. SDL_GPUTextureCreateInfo texture_info = {};
  255. texture_info.type = SDL_GPU_TEXTURETYPE_2D;
  256. texture_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
  257. texture_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;
  258. texture_info.width = width;
  259. texture_info.height = height;
  260. texture_info.layer_count_or_depth = 1;
  261. texture_info.num_levels = 1;
  262. texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  263. bd->FontTexture = SDL_CreateGPUTexture(v->Device, &texture_info);
  264. IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info");
  265. }
  266. // Assign the texture to the TextureSamplerBinding
  267. bd->FontBinding.texture = bd->FontTexture;
  268. // Create all the upload structures and upload:
  269. {
  270. SDL_GPUTransferBufferCreateInfo transferbuffer_info = {};
  271. transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
  272. transferbuffer_info.size = upload_size;
  273. SDL_GPUTransferBuffer* transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info);
  274. IM_ASSERT(transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information");
  275. void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, transferbuffer, false);
  276. memcpy(texture_ptr, pixels, upload_size);
  277. SDL_UnmapGPUTransferBuffer(v->Device, transferbuffer);
  278. SDL_GPUTextureTransferInfo transfer_info = {};
  279. transfer_info.offset = 0;
  280. transfer_info.transfer_buffer = transferbuffer;
  281. SDL_GPUTextureRegion texture_region = {};
  282. texture_region.texture = bd->FontTexture;
  283. texture_region.w = width;
  284. texture_region.h = height;
  285. texture_region.d = 1;
  286. SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device);
  287. SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd);
  288. SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false);
  289. SDL_EndGPUCopyPass(copy_pass);
  290. SDL_SubmitGPUCommandBuffer(cmd);
  291. SDL_ReleaseGPUTransferBuffer(v->Device, transferbuffer);
  292. }
  293. // Store our identifier
  294. io.Fonts->SetTexID((ImTextureID)&bd->FontBinding);
  295. }
  296. // You probably never need to call this, as it is called by ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_Shutdown().
  297. void ImGui_ImplSDLGPU3_DestroyFontsTexture()
  298. {
  299. ImGuiIO& io = ImGui::GetIO();
  300. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  301. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  302. if (bd->FontTexture)
  303. {
  304. SDL_ReleaseGPUTexture(v->Device, bd->FontTexture);
  305. bd->FontBinding.texture = nullptr;
  306. bd->FontTexture = nullptr;
  307. }
  308. io.Fonts->SetTexID(0);
  309. }
  310. static void Imgui_ImplSDLGPU3_CreateShaders()
  311. {
  312. // Create the shader modules
  313. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  314. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  315. const char* driver = SDL_GetGPUDeviceDriver(v->Device);
  316. SDL_GPUShaderCreateInfo vertex_shader_info = {};
  317. vertex_shader_info.entrypoint = "main";
  318. vertex_shader_info.stage = SDL_GPU_SHADERSTAGE_VERTEX;
  319. vertex_shader_info.num_uniform_buffers = 1;
  320. vertex_shader_info.num_storage_buffers = 0;
  321. vertex_shader_info.num_storage_textures = 0;
  322. vertex_shader_info.num_samplers = 0;
  323. SDL_GPUShaderCreateInfo fragment_shader_info = {};
  324. fragment_shader_info.entrypoint = "main";
  325. fragment_shader_info.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
  326. fragment_shader_info.num_samplers = 1;
  327. fragment_shader_info.num_storage_buffers = 0;
  328. fragment_shader_info.num_storage_textures = 0;
  329. fragment_shader_info.num_uniform_buffers = 0;
  330. if (strcmp(driver, "vulkan") == 0)
  331. {
  332. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
  333. vertex_shader_info.code = spirv_vertex;
  334. vertex_shader_info.code_size = sizeof(spirv_vertex);
  335. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
  336. fragment_shader_info.code = spirv_fragment;
  337. fragment_shader_info.code_size = sizeof(spirv_fragment);
  338. }
  339. else if (strcmp(driver, "direct3d12") == 0)
  340. {
  341. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
  342. vertex_shader_info.code = dxbc_vertex;
  343. vertex_shader_info.code_size = sizeof(dxbc_vertex);
  344. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
  345. fragment_shader_info.code = dxbc_fragment;
  346. fragment_shader_info.code_size = sizeof(dxbc_fragment);
  347. }
  348. #ifdef __APPLE__
  349. else
  350. {
  351. vertex_shader_info.entrypoint = "main0";
  352. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
  353. vertex_shader_info.code = metallib_vertex;
  354. vertex_shader_info.code_size = sizeof(metallib_vertex);
  355. fragment_shader_info.entrypoint = "main0";
  356. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
  357. fragment_shader_info.code = metallib_fragment;
  358. fragment_shader_info.code_size = sizeof(metallib_fragment);
  359. }
  360. #endif
  361. bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info);
  362. bd->FragmentShader = SDL_CreateGPUShader(v->Device, &fragment_shader_info);
  363. IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information");
  364. IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information");
  365. }
  366. static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline()
  367. {
  368. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  369. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  370. Imgui_ImplSDLGPU3_CreateShaders();
  371. SDL_GPUVertexBufferDescription vertex_buffer_desc[1];
  372. vertex_buffer_desc[0].slot = 0;
  373. vertex_buffer_desc[0].input_rate = SDL_GPU_VERTEXINPUTRATE_VERTEX;
  374. vertex_buffer_desc[0].instance_step_rate = 0;
  375. vertex_buffer_desc[0].pitch = sizeof(ImDrawVert);
  376. SDL_GPUVertexAttribute vertex_attributes[3];
  377. vertex_attributes[0].buffer_slot = 0;
  378. vertex_attributes[0].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
  379. vertex_attributes[0].location = 0;
  380. vertex_attributes[0].offset = offsetof(ImDrawVert,pos);
  381. vertex_attributes[1].buffer_slot = 0;
  382. vertex_attributes[1].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
  383. vertex_attributes[1].location = 1;
  384. vertex_attributes[1].offset = offsetof(ImDrawVert, uv);
  385. vertex_attributes[2].buffer_slot = 0;
  386. vertex_attributes[2].format = SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM;
  387. vertex_attributes[2].location = 2;
  388. vertex_attributes[2].offset = offsetof(ImDrawVert, col);
  389. SDL_GPUVertexInputState vertex_input_state = {};
  390. vertex_input_state.num_vertex_attributes = 3;
  391. vertex_input_state.vertex_attributes = vertex_attributes;
  392. vertex_input_state.num_vertex_buffers = 1;
  393. vertex_input_state.vertex_buffer_descriptions = vertex_buffer_desc;
  394. SDL_GPURasterizerState rasterizer_state = {};
  395. rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
  396. rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
  397. rasterizer_state.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
  398. rasterizer_state.enable_depth_bias = false;
  399. rasterizer_state.enable_depth_clip = false;
  400. SDL_GPUMultisampleState multisample_state = {};
  401. multisample_state.sample_count = v->MSAASamples;
  402. multisample_state.enable_mask = false;
  403. SDL_GPUDepthStencilState depth_stencil_state = {};
  404. depth_stencil_state.enable_depth_test = false;
  405. depth_stencil_state.enable_depth_write = false;
  406. depth_stencil_state.enable_stencil_test = false;
  407. SDL_GPUColorTargetBlendState blend_state = {};
  408. blend_state.enable_blend = true;
  409. blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_SRC_ALPHA;
  410. blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
  411. blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD;
  412. blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;
  413. blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
  414. blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD;
  415. blend_state.color_write_mask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A;
  416. SDL_GPUColorTargetDescription color_target_desc[1];
  417. color_target_desc[0].format = v->ColorTargetFormat;
  418. color_target_desc[0].blend_state = blend_state;
  419. SDL_GPUGraphicsPipelineTargetInfo target_info = {};
  420. target_info.num_color_targets = 1;
  421. target_info.color_target_descriptions = color_target_desc;
  422. target_info.has_depth_stencil_target = false;
  423. SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {};
  424. pipeline_info.vertex_shader = bd->VertexShader;
  425. pipeline_info.fragment_shader = bd->FragmentShader;
  426. pipeline_info.vertex_input_state = vertex_input_state;
  427. pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
  428. pipeline_info.rasterizer_state = rasterizer_state;
  429. pipeline_info.multisample_state = multisample_state;
  430. pipeline_info.depth_stencil_state = depth_stencil_state;
  431. pipeline_info.target_info = target_info;
  432. bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->Device, &pipeline_info);
  433. IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information");
  434. }
  435. void ImGui_ImplSDLGPU3_CreateDeviceObjects()
  436. {
  437. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  438. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  439. if (!bd->FontSampler)
  440. {
  441. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  442. SDL_GPUSamplerCreateInfo sampler_info = {};
  443. sampler_info.min_filter = SDL_GPU_FILTER_LINEAR;
  444. sampler_info.mag_filter = SDL_GPU_FILTER_LINEAR;
  445. sampler_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
  446. sampler_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  447. sampler_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  448. sampler_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  449. sampler_info.mip_lod_bias = 0.0f;
  450. sampler_info.min_lod = -1000.0f;
  451. sampler_info.max_lod = 1000.0f;
  452. sampler_info.enable_anisotropy = false;
  453. sampler_info.max_anisotropy = 1.0f;
  454. sampler_info.enable_compare = false;
  455. bd->FontSampler = SDL_CreateGPUSampler(v->Device, &sampler_info);
  456. bd->FontBinding.sampler = bd->FontSampler;
  457. IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information");
  458. }
  459. ImGui_ImplSDLGPU3_CreateGraphicsPipeline();
  460. ImGui_ImplSDLGPU3_CreateFontsTexture();
  461. }
  462. void ImGui_ImplSDLGPU3_DestroyFrameData()
  463. {
  464. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  465. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  466. SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.VertexBuffer);
  467. SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.IndexBuffer);
  468. bd->MainWindowFrameData.VertexBuffer = nullptr;
  469. bd->MainWindowFrameData.IndexBuffer = nullptr;
  470. bd->MainWindowFrameData.VertexBufferSize = 0;
  471. bd->MainWindowFrameData.IndexBufferSize = 0;
  472. }
  473. void ImGui_ImplSDLGPU3_DestroyDeviceObjects()
  474. {
  475. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  476. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  477. ImGui_ImplSDLGPU3_DestroyFrameData();
  478. ImGui_ImplSDLGPU3_DestroyFontsTexture();
  479. if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr;}
  480. if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr;}
  481. if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->Device, bd->FontSampler); bd->FontSampler = nullptr;}
  482. if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr;}
  483. }
  484. bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info)
  485. {
  486. ImGuiIO& io = ImGui::GetIO();
  487. IMGUI_CHECKVERSION();
  488. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  489. // Setup backend capabilities flags
  490. ImGui_ImplSDLGPU3_Data* bd = IM_NEW(ImGui_ImplSDLGPU3_Data)();
  491. io.BackendRendererUserData = (void*)bd;
  492. io.BackendRendererName = "imgui_impl_sdlgpu3";
  493. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  494. IM_ASSERT(info->Device != nullptr);
  495. IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID);
  496. bd->InitInfo = *info;
  497. ImGui_ImplSDLGPU3_CreateDeviceObjects();
  498. return true;
  499. }
  500. void ImGui_ImplSDLGPU3_Shutdown()
  501. {
  502. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  503. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  504. ImGuiIO& io = ImGui::GetIO();
  505. ImGui_ImplSDLGPU3_DestroyDeviceObjects();
  506. io.BackendRendererName = nullptr;
  507. io.BackendRendererUserData = nullptr;
  508. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  509. IM_DELETE(bd);
  510. }
  511. void ImGui_ImplSDLGPU3_NewFrame()
  512. {
  513. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  514. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?");
  515. if (!bd->FontTexture)
  516. ImGui_ImplSDLGPU3_CreateFontsTexture();
  517. }
  518. #endif // #ifndef IMGUI_DISABLE