Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_sdlgpu3.cpp

raw
1 // dear imgui: Renderer Backend for SDL_GPU
2 // This needs to be used along with the SDL3 Platform Backend
3
4 // Implemented features:
5 // [X] Renderer: User texture binding. Use 'SDL_GPUTexture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! **IMPORTANT** Before 2025/08/08, ImTextureID was a reference to a SDL_GPUTextureSamplerBinding struct.
6 // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7 // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
8 // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
10 // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification.
11 // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
12
13 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
14 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
15 // Learn about Dear ImGui:
16 // - FAQ https://dearimgui.com/faq
17 // - Getting Started https://dearimgui.com/getting-started
18 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
19 // - Introduction, links and more at the top of imgui.cpp
20
21 // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app.
22 // - Unlike other backends, the user must call the function ImGui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData.
23 // 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.
24
25 // CHANGELOG
26 // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
27 // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988)
28 // 2025-08-08: Expose SamplerDefault and SamplerCurrent in ImGui_ImplSDLGPU3_RenderState. Allow callback to change sampler.
29 // 2025-06-25: Mapping transfer buffer for texture update use cycle=true. Fixes artifacts e.g. on Metal backend.
30 // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture().
31 // 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
32 // 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now.
33 // 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData().
34 // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device.
35 // 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend.
36
37 #include "imgui.h"
38 #ifndef IMGUI_DISABLE
39 #include "imgui_impl_sdlgpu3.h"
40 #include "imgui_impl_sdlgpu3_shaders.h"
41
42 // SDL_GPU Data
43
44 // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData()
45 struct ImGui_ImplSDLGPU3_FrameData
46 {
47 SDL_GPUBuffer* VertexBuffer = nullptr;
48 SDL_GPUTransferBuffer* VertexTransferBuffer = nullptr;
49 uint32_t VertexBufferSize = 0;
50 SDL_GPUBuffer* IndexBuffer = nullptr;
51 SDL_GPUTransferBuffer* IndexTransferBuffer = nullptr;
52 uint32_t IndexBufferSize = 0;
53 };
54
55 struct ImGui_ImplSDLGPU3_Data
56 {
57 ImGui_ImplSDLGPU3_InitInfo InitInfo;
58
59 // Graphics pipeline & shaders
60 SDL_GPUShader* VertexShader = nullptr;
61 SDL_GPUShader* FragmentShader = nullptr;
62 SDL_GPUGraphicsPipeline* Pipeline = nullptr;
63 SDL_GPUSampler* TexSampler = nullptr;
64 SDL_GPUTransferBuffer* TexTransferBuffer = nullptr;
65 uint32_t TexTransferBufferSize = 0;
66
67 // Frame data for main window
68 ImGui_ImplSDLGPU3_FrameData MainWindowFrameData;
69 };
70
71 // Forward Declarations
72 static void ImGui_ImplSDLGPU3_DestroyFrameData();
73
74 //-----------------------------------------------------------------------------
75 // FUNCTIONS
76 //-----------------------------------------------------------------------------
77
78 // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
79 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
80 // FIXME: multi-context support has never been tested.
81 static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData()
82 {
83 return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
84 }
85
86 static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, ImGui_ImplSDLGPU3_RenderState* render_state, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height)
87 {
88 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
89 render_state->SamplerCurrent = render_state->SamplerCurrent = bd->TexSampler;
90
91 // Bind graphics pipeline
92 SDL_BindGPUGraphicsPipeline(render_pass, pipeline);
93
94 // Bind Vertex And Index Buffers
95 if (draw_data->TotalVtxCount > 0)
96 {
97 SDL_GPUBufferBinding vertex_buffer_binding = {};
98 vertex_buffer_binding.buffer = fd->VertexBuffer;
99 vertex_buffer_binding.offset = 0;
100 SDL_GPUBufferBinding index_buffer_binding = {};
101 index_buffer_binding.buffer = fd->IndexBuffer;
102 index_buffer_binding.offset = 0;
103 SDL_BindGPUVertexBuffers(render_pass,0, &vertex_buffer_binding, 1);
104 SDL_BindGPUIndexBuffer(render_pass, &index_buffer_binding, sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT);
105 }
106
107 // Setup viewport
108 SDL_GPUViewport viewport = {};
109 viewport.x = 0;
110 viewport.y = 0;
111 viewport.w = (float)fb_width;
112 viewport.h = (float)fb_height;
113 viewport.min_depth = 0.0f;
114 viewport.max_depth = 1.0f;
115 SDL_SetGPUViewport(render_pass, &viewport);
116
117 // Setup scale and translation
118 // 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.
119 struct UBO { float scale[2]; float translation[2]; } ubo;
120 ubo.scale[0] = 2.0f / draw_data->DisplaySize.x;
121 ubo.scale[1] = 2.0f / draw_data->DisplaySize.y;
122 ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0];
123 ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1];
124 SDL_PushGPUVertexUniformData(command_buffer, 0, &ubo, sizeof(UBO));
125 }
126
127 static void CreateOrResizeBuffers(SDL_GPUBuffer** buffer, SDL_GPUTransferBuffer** transferbuffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage)
128 {
129 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
130 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
131
132 // FIXME-OPT: Not optimal, but this is fairly rarely called.
133 SDL_WaitForGPUIdle(v->Device);
134 SDL_ReleaseGPUBuffer(v->Device, *buffer);
135 SDL_ReleaseGPUTransferBuffer(v->Device, *transferbuffer);
136
137 SDL_GPUBufferCreateInfo buffer_info = {};
138 buffer_info.usage = usage;
139 buffer_info.size = new_size;
140 buffer_info.props = 0;
141 *buffer = SDL_CreateGPUBuffer(v->Device, &buffer_info);
142 *old_size = new_size;
143 IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information");
144
145 SDL_GPUTransferBufferCreateInfo transferbuffer_info = {};
146 transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
147 transferbuffer_info.size = new_size;
148 *transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info);
149 IM_ASSERT(*transferbuffer != nullptr && "Failed to create GPU Transfer Buffer, call SDL_GetError() for more information");
150 }
151
152 // SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound!
153 // The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example),
154 // is to split the upload part of ImGui_ImplSDLGPU3_RenderDrawData() to another function that needs to be called by the user before rendering.
155 void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer)
156 {
157 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
158 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
159 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
160 if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0)
161 return;
162
163 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
164 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
165 if (draw_data->Textures != nullptr)
166 for (ImTextureData* tex : *draw_data->Textures)
167 if (tex->Status != ImTextureStatus_OK)
168 ImGui_ImplSDLGPU3_UpdateTexture(tex);
169
170 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
171 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
172 ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
173
174 uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
175 uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
176 if (fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size)
177 CreateOrResizeBuffers(&fd->VertexBuffer, &fd->VertexTransferBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX);
178 if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size)
179 CreateOrResizeBuffers(&fd->IndexBuffer, &fd->IndexTransferBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX);
180
181 ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer, true);
182 ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer, true);
183 for (const ImDrawList* draw_list : draw_data->CmdLists)
184 {
185 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
186 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
187 vtx_dst += draw_list->VtxBuffer.Size;
188 idx_dst += draw_list->IdxBuffer.Size;
189 }
190 SDL_UnmapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer);
191 SDL_UnmapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer);
192
193 SDL_GPUTransferBufferLocation vertex_buffer_location = {};
194 vertex_buffer_location.offset = 0;
195 vertex_buffer_location.transfer_buffer = fd->VertexTransferBuffer;
196 SDL_GPUTransferBufferLocation index_buffer_location = {};
197 index_buffer_location.offset = 0;
198 index_buffer_location.transfer_buffer = fd->IndexTransferBuffer;
199
200 SDL_GPUBufferRegion vertex_buffer_region = {};
201 vertex_buffer_region.buffer = fd->VertexBuffer;
202 vertex_buffer_region.offset = 0;
203 vertex_buffer_region.size = vertex_size;
204
205 SDL_GPUBufferRegion index_buffer_region = {};
206 index_buffer_region.buffer = fd->IndexBuffer;
207 index_buffer_region.offset = 0;
208 index_buffer_region.size = index_size;
209
210 SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer);
211 SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region, true);
212 SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region, true);
213 SDL_EndGPUCopyPass(copy_pass);
214 }
215
216 void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline)
217 {
218 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
219 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
220 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
221 if (fb_width <= 0 || fb_height <= 0)
222 return;
223
224 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
225 ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
226
227 if (pipeline == nullptr)
228 pipeline = bd->Pipeline;
229
230 // Will project scissor/clipping rectangles into framebuffer space
231 ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
232 ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
233
234 // Setup render state structure (for callbacks and custom texture bindings)
235 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
236 ImGui_ImplSDLGPU3_RenderState render_state;
237 render_state.Device = bd->InitInfo.Device;
238 render_state.SamplerDefault = render_state.SamplerCurrent = bd->TexSampler;
239 platform_io.Renderer_RenderState = &render_state;
240
241 ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height);
242
243 // Render command lists
244 // (Because we merged all buffers into a single one, we maintain our own offset into them)
245 int global_vtx_offset = 0;
246 int global_idx_offset = 0;
247 for (const ImDrawList* draw_list : draw_data->CmdLists)
248 {
249 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
250 {
251 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
252 if (pcmd->UserCallback != nullptr)
253 {
254 // User callback, registered via ImDrawList::AddCallback()
255 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
256 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
257 ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height);
258 else
259 pcmd->UserCallback(draw_list, pcmd);
260 }
261 else
262 {
263 // Project scissor/clipping rectangles into framebuffer space
264 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
265 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
266
267 // Clamp to viewport as SDL_SetGPUScissor() won't accept values that are off bounds
268 if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
269 if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
270 if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
271 if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
272 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
273 continue;
274
275 // Apply scissor/clipping rectangle
276 SDL_Rect scissor_rect = {};
277 scissor_rect.x = (int)clip_min.x;
278 scissor_rect.y = (int)clip_min.y;
279 scissor_rect.w = (int)(clip_max.x - clip_min.x);
280 scissor_rect.h = (int)(clip_max.y - clip_min.y);
281 SDL_SetGPUScissor(render_pass,&scissor_rect);
282
283 // Bind DescriptorSet with font or user texture
284 SDL_GPUTextureSamplerBinding texture_sampler_binding;
285 texture_sampler_binding.texture = (SDL_GPUTexture*)(intptr_t)pcmd->GetTexID();
286 texture_sampler_binding.sampler = render_state.SamplerCurrent;
287 SDL_BindGPUFragmentSamplers(render_pass, 0, &texture_sampler_binding, 1);
288
289 // Draw
290 // **IF YOU GET A CRASH HERE** In 1.92.2 on 2025/08/08 we have changed ImTextureID to store 'SDL_GPUTexture*' instead of storing 'SDL_GPUTextureSamplerBinding'.
291 // Any code loading custom texture using this backend needs to be updated.
292 SDL_DrawGPUIndexedPrimitives(render_pass, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
293 }
294 }
295 global_idx_offset += draw_list->IdxBuffer.Size;
296 global_vtx_offset += draw_list->VtxBuffer.Size;
297 }
298
299 // Note: at this point both SDL_SetGPUViewport() and SDL_SetGPUScissor() have been called.
300 // 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
301 // In theory we should aim to backup/restore those values but I am not sure this is possible.
302 // 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)
303 SDL_Rect scissor_rect { 0, 0, fb_width, fb_height };
304 SDL_SetGPUScissor(render_pass, &scissor_rect);
305 }
306
307 static void ImGui_ImplSDLGPU3_DestroyTexture(ImTextureData* tex)
308 {
309 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
310 SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID();
311 if (raw_tex != nullptr)
312 SDL_ReleaseGPUTexture(bd->InitInfo.Device, raw_tex);
313
314 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
315 tex->SetTexID(ImTextureID_Invalid);
316 tex->SetStatus(ImTextureStatus_Destroyed);
317 }
318
319 void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex)
320 {
321 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
322 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
323
324 if (tex->Status == ImTextureStatus_WantCreate)
325 {
326 // Create and upload new texture to graphics system
327 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
328 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
329 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
330
331 // Create texture
332 SDL_GPUTextureCreateInfo texture_info = {};
333 texture_info.type = SDL_GPU_TEXTURETYPE_2D;
334 texture_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
335 texture_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;
336 texture_info.width = tex->Width;
337 texture_info.height = tex->Height;
338 texture_info.layer_count_or_depth = 1;
339 texture_info.num_levels = 1;
340 texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1;
341
342 SDL_GPUTexture* raw_tex = SDL_CreateGPUTexture(v->Device, &texture_info);
343 IM_ASSERT(raw_tex != nullptr && "Failed to create font texture, call SDL_GetError() for more info");
344
345 // Store identifiers
346 tex->SetTexID((ImTextureID)(intptr_t)raw_tex);
347 }
348
349 if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
350 {
351 SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID();
352 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
353
354 // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
355 // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
356 // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
357 const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
358 const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
359 const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
360 const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
361 uint32_t upload_pitch = upload_w * tex->BytesPerPixel;
362 uint32_t upload_size = upload_w * upload_h * tex->BytesPerPixel;
363
364 // Create transfer buffer
365 if (bd->TexTransferBufferSize < upload_size)
366 {
367 SDL_ReleaseGPUTransferBuffer(v->Device, bd->TexTransferBuffer);
368 SDL_GPUTransferBufferCreateInfo transferbuffer_info = {};
369 transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
370 transferbuffer_info.size = upload_size + 1024;
371 bd->TexTransferBufferSize = upload_size + 1024;
372 bd->TexTransferBuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info);
373 IM_ASSERT(bd->TexTransferBuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information");
374 }
375
376 // Copy to transfer buffer
377 {
378 void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, bd->TexTransferBuffer, true);
379 for (int y = 0; y < upload_h; y++)
380 memcpy((void*)((uintptr_t)texture_ptr + y * upload_pitch), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch);
381 SDL_UnmapGPUTransferBuffer(v->Device, bd->TexTransferBuffer);
382 }
383
384 SDL_GPUTextureTransferInfo transfer_info = {};
385 transfer_info.offset = 0;
386 transfer_info.transfer_buffer = bd->TexTransferBuffer;
387
388 SDL_GPUTextureRegion texture_region = {};
389 texture_region.texture = raw_tex;
390 texture_region.x = (Uint32)upload_x;
391 texture_region.y = (Uint32)upload_y;
392 texture_region.w = (Uint32)upload_w;
393 texture_region.h = (Uint32)upload_h;
394 texture_region.d = 1;
395
396 // Upload
397 {
398 SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device);
399 SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd);
400 SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false);
401 SDL_EndGPUCopyPass(copy_pass);
402 SDL_SubmitGPUCommandBuffer(cmd);
403 }
404
405 tex->SetStatus(ImTextureStatus_OK);
406 }
407 if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
408 ImGui_ImplSDLGPU3_DestroyTexture(tex);
409 }
410
411 static void ImGui_ImplSDLGPU3_CreateShaders()
412 {
413 // Create the shader modules
414 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
415 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
416
417 const char* driver = SDL_GetGPUDeviceDriver(v->Device);
418
419 SDL_GPUShaderCreateInfo vertex_shader_info = {};
420 vertex_shader_info.entrypoint = "main";
421 vertex_shader_info.stage = SDL_GPU_SHADERSTAGE_VERTEX;
422 vertex_shader_info.num_uniform_buffers = 1;
423 vertex_shader_info.num_storage_buffers = 0;
424 vertex_shader_info.num_storage_textures = 0;
425 vertex_shader_info.num_samplers = 0;
426
427 SDL_GPUShaderCreateInfo fragment_shader_info = {};
428 fragment_shader_info.entrypoint = "main";
429 fragment_shader_info.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
430 fragment_shader_info.num_samplers = 1;
431 fragment_shader_info.num_storage_buffers = 0;
432 fragment_shader_info.num_storage_textures = 0;
433 fragment_shader_info.num_uniform_buffers = 0;
434
435 if (strcmp(driver, "vulkan") == 0)
436 {
437 vertex_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
438 vertex_shader_info.code = spirv_vertex;
439 vertex_shader_info.code_size = sizeof(spirv_vertex);
440 fragment_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
441 fragment_shader_info.code = spirv_fragment;
442 fragment_shader_info.code_size = sizeof(spirv_fragment);
443 }
444 else if (strcmp(driver, "direct3d12") == 0)
445 {
446 vertex_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
447 vertex_shader_info.code = dxbc_vertex;
448 vertex_shader_info.code_size = sizeof(dxbc_vertex);
449 fragment_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
450 fragment_shader_info.code = dxbc_fragment;
451 fragment_shader_info.code_size = sizeof(dxbc_fragment);
452 }
453 #ifdef __APPLE__
454 else
455 {
456 vertex_shader_info.entrypoint = "main0";
457 vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
458 vertex_shader_info.code = metallib_vertex;
459 vertex_shader_info.code_size = sizeof(metallib_vertex);
460 fragment_shader_info.entrypoint = "main0";
461 fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
462 fragment_shader_info.code = metallib_fragment;
463 fragment_shader_info.code_size = sizeof(metallib_fragment);
464 }
465 #endif
466 bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info);
467 bd->FragmentShader = SDL_CreateGPUShader(v->Device, &fragment_shader_info);
468 IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information");
469 IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information");
470 }
471
472 static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline()
473 {
474 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
475 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
476 ImGui_ImplSDLGPU3_CreateShaders();
477
478 SDL_GPUVertexBufferDescription vertex_buffer_desc[1];
479 vertex_buffer_desc[0].slot = 0;
480 vertex_buffer_desc[0].input_rate = SDL_GPU_VERTEXINPUTRATE_VERTEX;
481 vertex_buffer_desc[0].instance_step_rate = 0;
482 vertex_buffer_desc[0].pitch = sizeof(ImDrawVert);
483
484 SDL_GPUVertexAttribute vertex_attributes[3];
485 vertex_attributes[0].buffer_slot = 0;
486 vertex_attributes[0].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
487 vertex_attributes[0].location = 0;
488 vertex_attributes[0].offset = offsetof(ImDrawVert,pos);
489
490 vertex_attributes[1].buffer_slot = 0;
491 vertex_attributes[1].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
492 vertex_attributes[1].location = 1;
493 vertex_attributes[1].offset = offsetof(ImDrawVert, uv);
494
495 vertex_attributes[2].buffer_slot = 0;
496 vertex_attributes[2].format = SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM;
497 vertex_attributes[2].location = 2;
498 vertex_attributes[2].offset = offsetof(ImDrawVert, col);
499
500 SDL_GPUVertexInputState vertex_input_state = {};
501 vertex_input_state.num_vertex_attributes = 3;
502 vertex_input_state.vertex_attributes = vertex_attributes;
503 vertex_input_state.num_vertex_buffers = 1;
504 vertex_input_state.vertex_buffer_descriptions = vertex_buffer_desc;
505
506 SDL_GPURasterizerState rasterizer_state = {};
507 rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
508 rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
509 rasterizer_state.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
510 rasterizer_state.enable_depth_bias = false;
511 rasterizer_state.enable_depth_clip = false;
512
513 SDL_GPUMultisampleState multisample_state = {};
514 multisample_state.sample_count = v->MSAASamples;
515 multisample_state.enable_mask = false;
516
517 SDL_GPUDepthStencilState depth_stencil_state = {};
518 depth_stencil_state.enable_depth_test = false;
519 depth_stencil_state.enable_depth_write = false;
520 depth_stencil_state.enable_stencil_test = false;
521
522 SDL_GPUColorTargetBlendState blend_state = {};
523 blend_state.enable_blend = true;
524 blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_SRC_ALPHA;
525 blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
526 blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD;
527 blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;
528 blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
529 blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD;
530 blend_state.color_write_mask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A;
531
532 SDL_GPUColorTargetDescription color_target_desc[1];
533 color_target_desc[0].format = v->ColorTargetFormat;
534 color_target_desc[0].blend_state = blend_state;
535
536 SDL_GPUGraphicsPipelineTargetInfo target_info = {};
537 target_info.num_color_targets = 1;
538 target_info.color_target_descriptions = color_target_desc;
539 target_info.has_depth_stencil_target = false;
540
541 SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {};
542 pipeline_info.vertex_shader = bd->VertexShader;
543 pipeline_info.fragment_shader = bd->FragmentShader;
544 pipeline_info.vertex_input_state = vertex_input_state;
545 pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
546 pipeline_info.rasterizer_state = rasterizer_state;
547 pipeline_info.multisample_state = multisample_state;
548 pipeline_info.depth_stencil_state = depth_stencil_state;
549 pipeline_info.target_info = target_info;
550
551 bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->Device, &pipeline_info);
552 IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information");
553 }
554
555 void ImGui_ImplSDLGPU3_CreateDeviceObjects()
556 {
557 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
558 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
559
560 ImGui_ImplSDLGPU3_DestroyDeviceObjects();
561
562 if (bd->TexSampler == nullptr)
563 {
564 // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
565 SDL_GPUSamplerCreateInfo sampler_info = {};
566 sampler_info.min_filter = SDL_GPU_FILTER_LINEAR;
567 sampler_info.mag_filter = SDL_GPU_FILTER_LINEAR;
568 sampler_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
569 sampler_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
570 sampler_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
571 sampler_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
572 sampler_info.mip_lod_bias = 0.0f;
573 sampler_info.min_lod = -1000.0f;
574 sampler_info.max_lod = 1000.0f;
575 sampler_info.enable_anisotropy = false;
576 sampler_info.max_anisotropy = 1.0f;
577 sampler_info.enable_compare = false;
578
579 bd->TexSampler = SDL_CreateGPUSampler(v->Device, &sampler_info);
580 IM_ASSERT(bd->TexSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information");
581 }
582
583 ImGui_ImplSDLGPU3_CreateGraphicsPipeline();
584 }
585
586 void ImGui_ImplSDLGPU3_DestroyFrameData()
587 {
588 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
589 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
590
591 ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
592 SDL_ReleaseGPUBuffer(v->Device, fd->VertexBuffer);
593 SDL_ReleaseGPUBuffer(v->Device, fd->IndexBuffer);
594 SDL_ReleaseGPUTransferBuffer(v->Device, fd->VertexTransferBuffer);
595 SDL_ReleaseGPUTransferBuffer(v->Device, fd->IndexTransferBuffer);
596 fd->VertexBuffer = fd->IndexBuffer = nullptr;
597 fd->VertexTransferBuffer = fd->IndexTransferBuffer = nullptr;
598 fd->VertexBufferSize = fd->IndexBufferSize = 0;
599 }
600
601 void ImGui_ImplSDLGPU3_DestroyDeviceObjects()
602 {
603 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
604 ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
605
606 ImGui_ImplSDLGPU3_DestroyFrameData();
607
608 // Destroy all textures
609 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
610 if (tex->RefCount == 1)
611 ImGui_ImplSDLGPU3_DestroyTexture(tex);
612 if (bd->TexTransferBuffer) { SDL_ReleaseGPUTransferBuffer(v->Device, bd->TexTransferBuffer); bd->TexTransferBuffer = nullptr; }
613 if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr; }
614 if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr; }
615 if (bd->TexSampler) { SDL_ReleaseGPUSampler(v->Device, bd->TexSampler); bd->TexSampler = nullptr; }
616 if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr; }
617 }
618
619 static void ImGui_ImplSDLGPU3_InitMultiViewportSupport();
620 static void ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport();
621
622 bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info)
623 {
624 ImGuiIO& io = ImGui::GetIO();
625 IMGUI_CHECKVERSION();
626 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
627
628 // Setup backend capabilities flags
629 ImGui_ImplSDLGPU3_Data* bd = IM_NEW(ImGui_ImplSDLGPU3_Data)();
630 io.BackendRendererUserData = (void*)bd;
631 io.BackendRendererName = "imgui_impl_sdlgpu3";
632 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
633 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
634 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
635
636 IM_ASSERT(info->Device != nullptr);
637 IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID);
638
639 bd->InitInfo = *info;
640
641 ImGui_ImplSDLGPU3_InitMultiViewportSupport();
642
643 return true;
644 }
645
646 void ImGui_ImplSDLGPU3_Shutdown()
647 {
648 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
649 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
650 ImGuiIO& io = ImGui::GetIO();
651
652 ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport();
653 ImGui_ImplSDLGPU3_DestroyDeviceObjects();
654 io.BackendRendererName = nullptr;
655 io.BackendRendererUserData = nullptr;
656 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
657 IM_DELETE(bd);
658 }
659
660 void ImGui_ImplSDLGPU3_NewFrame()
661 {
662 ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
663 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?");
664
665 if (!bd->TexSampler)
666 ImGui_ImplSDLGPU3_CreateDeviceObjects();
667 }
668
669 //--------------------------------------------------------------------------------------------------------
670 // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
671 // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
672 // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
673 //--------------------------------------------------------------------------------------------------------
674
675 static void ImGui_ImplSDLGPU3_CreateWindow(ImGuiViewport* viewport)
676 {
677 ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
678 SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
679 SDL_ClaimWindowForGPUDevice(data->InitInfo.Device, window);
680 viewport->RendererUserData = (void*)1;
681 }
682
683 static void ImGui_ImplSDLGPU3_RenderWindow(ImGuiViewport* viewport, void*)
684 {
685 ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
686 SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
687
688 ImDrawData* draw_data = viewport->DrawData;
689
690 SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(data->InitInfo.Device);
691
692 SDL_GPUTexture* swapchain_texture;
693 SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr);
694
695 if (swapchain_texture != nullptr)
696 {
697 ImGui_ImplSDLGPU3_PrepareDrawData(draw_data, command_buffer); // FIXME-OPT: Not optimal, may this be done earlier?
698 SDL_GPUColorTargetInfo target_info = {};
699 target_info.texture = swapchain_texture;
700 target_info.clear_color = SDL_FColor{ 0.0f,0.0f,0.0f,1.0f };
701 target_info.load_op = SDL_GPU_LOADOP_CLEAR;
702 target_info.store_op = SDL_GPU_STOREOP_STORE;
703 target_info.mip_level = 0;
704 target_info.layer_or_depth_plane = 0;
705 target_info.cycle = false;
706 SDL_GPURenderPass* render_pass = SDL_BeginGPURenderPass(command_buffer, &target_info, 1, nullptr);
707 ImGui_ImplSDLGPU3_RenderDrawData(draw_data, command_buffer, render_pass);
708 SDL_EndGPURenderPass(render_pass);
709 }
710
711 SDL_SubmitGPUCommandBuffer(command_buffer);
712 }
713
714 static void ImGui_ImplSDLGPU3_DestroyWindow(ImGuiViewport* viewport)
715 {
716 ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
717 if (viewport->RendererUserData)
718 {
719 SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
720 SDL_ReleaseWindowFromGPUDevice(data->InitInfo.Device, window);
721 }
722 viewport->RendererUserData = nullptr;
723 }
724
725 static void ImGui_ImplSDLGPU3_InitMultiViewportSupport()
726 {
727 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
728 platform_io.Renderer_RenderWindow = ImGui_ImplSDLGPU3_RenderWindow;
729 platform_io.Renderer_CreateWindow = ImGui_ImplSDLGPU3_CreateWindow;
730 platform_io.Renderer_DestroyWindow = ImGui_ImplSDLGPU3_DestroyWindow;
731 }
732
733 static void ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport()
734 {
735 ImGui::DestroyPlatformWindows();
736 }
737
738 //-----------------------------------------------------------------------------
739
740 #endif // #ifndef IMGUI_DISABLE