Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_wgpu.cpp

raw
1 // dear imgui: Renderer for WebGPU
2 // This needs to be used along with a Platform Binding (e.g. GLFW)
3 // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
4
5 // Implemented features:
6 // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef!
7 // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
8 // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
9 // [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures).
10 // Missing features or Issues:
11 // [ ] Renderer: Multi-viewport support (multiple windows), useful for desktop.
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 // CHANGELOG
22 // (minor and older changes stripped away, please see git history for details)
23 // 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465)
24 // 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes.
25 // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
26 // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
27 // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
28 // 2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
29 // 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
30 // 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
31 // 2024-01-22: Fixed pipeline layout leak. (#7245)
32 // 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
33 // 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
34 // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
35 // 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
36 // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
37 // 2022-11-24: Fixed validation error with default depth buffer settings.
38 // 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init().
39 // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
40 // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
41 // 2021-08-24: Fixed for latest specs.
42 // 2021-05-24: Add support for draw_data->FramebufferScale.
43 // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
44 // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
45 // 2021-02-18: Change blending equation to preserve alpha in output buffer.
46 // 2021-01-28: Initial version.
47
48 #include "imgui.h"
49
50 // When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN
51 // or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
52 #ifndef __EMSCRIPTEN__
53 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
54 #error exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined!
55 #endif
56 #else
57 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
58 #error neither IMGUI_IMPL_WEBGPU_BACKEND_DAWN nor IMGUI_IMPL_WEBGPU_BACKEND_WGPU may be defined if targeting emscripten!
59 #endif
60 #endif
61
62 #ifndef IMGUI_DISABLE
63 #include "imgui_impl_wgpu.h"
64 #include <limits.h>
65 #include <webgpu/webgpu.h>
66
67 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
68 // Dawn renamed WGPUProgrammableStageDescriptor to WGPUComputeState (see: https://github.com/webgpu-native/webgpu-headers/pull/413)
69 // Using type alias until WGPU adopts the same naming convention (#8369)
70 using WGPUProgrammableStageDescriptor = WGPUComputeState;
71 #endif
72
73 // Dear ImGui prototypes from imgui_internal.h
74 extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed);
75 #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro).
76
77 // WebGPU data
78 struct ImGui_ImplWGPU_Texture
79 {
80 WGPUTexture Texture = nullptr;
81 WGPUTextureView TextureView = nullptr;
82 };
83
84 struct RenderResources
85 {
86 WGPUSampler Sampler = nullptr; // Sampler for textures
87 WGPUBuffer Uniforms = nullptr; // Shader uniforms
88 WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline
89 ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
90 WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
91 };
92
93 struct FrameResources
94 {
95 WGPUBuffer IndexBuffer;
96 WGPUBuffer VertexBuffer;
97 ImDrawIdx* IndexBufferHost;
98 ImDrawVert* VertexBufferHost;
99 int IndexBufferSize;
100 int VertexBufferSize;
101 };
102
103 struct Uniforms
104 {
105 float MVP[4][4];
106 float Gamma;
107 };
108
109 struct ImGui_ImplWGPU_Data
110 {
111 ImGui_ImplWGPU_InitInfo initInfo;
112 WGPUDevice wgpuDevice = nullptr;
113 WGPUQueue defaultQueue = nullptr;
114 WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
115 WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
116 WGPURenderPipeline pipelineState = nullptr;
117
118 RenderResources renderResources;
119 FrameResources* pFrameResources = nullptr;
120 unsigned int numFramesInFlight = 0;
121 unsigned int frameIndex = UINT_MAX;
122 };
123
124 // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
125 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
126 static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData()
127 {
128 return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
129 }
130
131 //-----------------------------------------------------------------------------
132 // SHADERS
133 //-----------------------------------------------------------------------------
134
135 static const char __shader_vert_wgsl[] = R"(
136 struct VertexInput {
137 @location(0) position: vec2<f32>,
138 @location(1) uv: vec2<f32>,
139 @location(2) color: vec4<f32>,
140 };
141
142 struct VertexOutput {
143 @builtin(position) position: vec4<f32>,
144 @location(0) color: vec4<f32>,
145 @location(1) uv: vec2<f32>,
146 };
147
148 struct Uniforms {
149 mvp: mat4x4<f32>,
150 gamma: f32,
151 };
152
153 @group(0) @binding(0) var<uniform> uniforms: Uniforms;
154
155 @vertex
156 fn main(in: VertexInput) -> VertexOutput {
157 var out: VertexOutput;
158 out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0);
159 out.color = in.color;
160 out.uv = in.uv;
161 return out;
162 }
163 )";
164
165 static const char __shader_frag_wgsl[] = R"(
166 struct VertexOutput {
167 @builtin(position) position: vec4<f32>,
168 @location(0) color: vec4<f32>,
169 @location(1) uv: vec2<f32>,
170 };
171
172 struct Uniforms {
173 mvp: mat4x4<f32>,
174 gamma: f32,
175 };
176
177 @group(0) @binding(0) var<uniform> uniforms: Uniforms;
178 @group(0) @binding(1) var s: sampler;
179 @group(1) @binding(0) var t: texture_2d<f32>;
180
181 @fragment
182 fn main(in: VertexOutput) -> @location(0) vec4<f32> {
183 let color = in.color * textureSample(t, s, in.uv);
184 let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma));
185 return vec4<f32>(corrected_color, color.a);
186 }
187 )";
188
189 static void SafeRelease(ImDrawIdx*& res)
190 {
191 if (res)
192 delete[] res;
193 res = nullptr;
194 }
195 static void SafeRelease(ImDrawVert*& res)
196 {
197 if (res)
198 delete[] res;
199 res = nullptr;
200 }
201 static void SafeRelease(WGPUBindGroupLayout& res)
202 {
203 if (res)
204 wgpuBindGroupLayoutRelease(res);
205 res = nullptr;
206 }
207 static void SafeRelease(WGPUBindGroup& res)
208 {
209 if (res)
210 wgpuBindGroupRelease(res);
211 res = nullptr;
212 }
213 static void SafeRelease(WGPUBuffer& res)
214 {
215 if (res)
216 wgpuBufferRelease(res);
217 res = nullptr;
218 }
219 static void SafeRelease(WGPUPipelineLayout& res)
220 {
221 if (res)
222 wgpuPipelineLayoutRelease(res);
223 res = nullptr;
224 }
225 static void SafeRelease(WGPURenderPipeline& res)
226 {
227 if (res)
228 wgpuRenderPipelineRelease(res);
229 res = nullptr;
230 }
231 static void SafeRelease(WGPUSampler& res)
232 {
233 if (res)
234 wgpuSamplerRelease(res);
235 res = nullptr;
236 }
237 static void SafeRelease(WGPUShaderModule& res)
238 {
239 if (res)
240 wgpuShaderModuleRelease(res);
241 res = nullptr;
242 }
243 static void SafeRelease(RenderResources& res)
244 {
245 SafeRelease(res.Sampler);
246 SafeRelease(res.Uniforms);
247 SafeRelease(res.CommonBindGroup);
248 SafeRelease(res.ImageBindGroupLayout);
249 };
250
251 static void SafeRelease(FrameResources& res)
252 {
253 SafeRelease(res.IndexBuffer);
254 SafeRelease(res.VertexBuffer);
255 SafeRelease(res.IndexBufferHost);
256 SafeRelease(res.VertexBufferHost);
257 }
258
259 static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source)
260 {
261 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
262
263 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
264 WGPUShaderSourceWGSL wgsl_desc = {};
265 wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
266 wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
267 #else
268 WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
269 wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
270 wgsl_desc.code = wgsl_source;
271 #endif
272
273 WGPUShaderModuleDescriptor desc = {};
274 desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc);
275
276 WGPUProgrammableStageDescriptor stage_desc = {};
277 stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
278
279 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
280 stage_desc.entryPoint = { "main", WGPU_STRLEN };
281 #else
282 stage_desc.entryPoint = "main";
283 #endif
284 return stage_desc;
285 }
286
287 static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
288 {
289 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
290 WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
291
292 WGPUBindGroupDescriptor image_bg_descriptor = {};
293 image_bg_descriptor.layout = layout;
294 image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
295 image_bg_descriptor.entries = image_bg_entries;
296 return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor);
297 }
298
299 static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
300 {
301 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
302
303 // Setup orthographic projection matrix into our constant buffer
304 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
305 {
306 float L = draw_data->DisplayPos.x;
307 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
308 float T = draw_data->DisplayPos.y;
309 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
310 float mvp[4][4] =
311 {
312 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
313 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
314 { 0.0f, 0.0f, 0.5f, 0.0f },
315 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
316 };
317 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP));
318 float gamma;
319 switch (bd->renderTargetFormat)
320 {
321 case WGPUTextureFormat_ASTC10x10UnormSrgb:
322 case WGPUTextureFormat_ASTC10x5UnormSrgb:
323 case WGPUTextureFormat_ASTC10x6UnormSrgb:
324 case WGPUTextureFormat_ASTC10x8UnormSrgb:
325 case WGPUTextureFormat_ASTC12x10UnormSrgb:
326 case WGPUTextureFormat_ASTC12x12UnormSrgb:
327 case WGPUTextureFormat_ASTC4x4UnormSrgb:
328 case WGPUTextureFormat_ASTC5x5UnormSrgb:
329 case WGPUTextureFormat_ASTC6x5UnormSrgb:
330 case WGPUTextureFormat_ASTC6x6UnormSrgb:
331 case WGPUTextureFormat_ASTC8x5UnormSrgb:
332 case WGPUTextureFormat_ASTC8x6UnormSrgb:
333 case WGPUTextureFormat_ASTC8x8UnormSrgb:
334 case WGPUTextureFormat_BC1RGBAUnormSrgb:
335 case WGPUTextureFormat_BC2RGBAUnormSrgb:
336 case WGPUTextureFormat_BC3RGBAUnormSrgb:
337 case WGPUTextureFormat_BC7RGBAUnormSrgb:
338 case WGPUTextureFormat_BGRA8UnormSrgb:
339 case WGPUTextureFormat_ETC2RGB8A1UnormSrgb:
340 case WGPUTextureFormat_ETC2RGB8UnormSrgb:
341 case WGPUTextureFormat_ETC2RGBA8UnormSrgb:
342 case WGPUTextureFormat_RGBA8UnormSrgb:
343 gamma = 2.2f;
344 break;
345 default:
346 gamma = 1.0f;
347 }
348 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma));
349 }
350
351 // Setup viewport
352 wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
353
354 // Bind shader and vertex buffers
355 wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
356 wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
357 wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState);
358 wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr);
359
360 // Setup blend factor
361 WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
362 wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
363 }
364
365 // Render function
366 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
367 void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
368 {
369 // Avoid rendering when minimized
370 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
371 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
372 if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0)
373 return;
374
375 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
376 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
377 if (draw_data->Textures != nullptr)
378 for (ImTextureData* tex : *draw_data->Textures)
379 if (tex->Status != ImTextureStatus_OK)
380 ImGui_ImplWGPU_UpdateTexture(tex);
381
382 // FIXME: Assuming that this only gets called once per frame!
383 // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
384 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
385 bd->frameIndex = bd->frameIndex + 1;
386 FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
387
388 // Create and grow vertex/index buffers if needed
389 if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
390 {
391 if (fr->VertexBuffer)
392 {
393 wgpuBufferDestroy(fr->VertexBuffer);
394 wgpuBufferRelease(fr->VertexBuffer);
395 }
396 SafeRelease(fr->VertexBufferHost);
397 fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
398
399 WGPUBufferDescriptor vb_desc =
400 {
401 nullptr,
402 "Dear ImGui Vertex buffer",
403 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
404 WGPU_STRLEN,
405 #endif
406 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
407 MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
408 false
409 };
410 fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc);
411 if (!fr->VertexBuffer)
412 return;
413
414 fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
415 }
416 if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
417 {
418 if (fr->IndexBuffer)
419 {
420 wgpuBufferDestroy(fr->IndexBuffer);
421 wgpuBufferRelease(fr->IndexBuffer);
422 }
423 SafeRelease(fr->IndexBufferHost);
424 fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
425
426 WGPUBufferDescriptor ib_desc =
427 {
428 nullptr,
429 "Dear ImGui Index buffer",
430 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
431 WGPU_STRLEN,
432 #endif
433 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
434 MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
435 false
436 };
437 fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc);
438 if (!fr->IndexBuffer)
439 return;
440
441 fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
442 }
443
444 // Upload vertex/index data into a single contiguous GPU buffer
445 ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
446 ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
447 for (const ImDrawList* draw_list : draw_data->CmdLists)
448 {
449 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
450 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
451 vtx_dst += draw_list->VtxBuffer.Size;
452 idx_dst += draw_list->IdxBuffer.Size;
453 }
454 int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
455 int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
456 wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
457 wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
458
459 // Setup desired render state
460 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
461
462 // Setup render state structure (for callbacks and custom texture bindings)
463 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
464 ImGui_ImplWGPU_RenderState render_state;
465 render_state.Device = bd->wgpuDevice;
466 render_state.RenderPassEncoder = pass_encoder;
467 platform_io.Renderer_RenderState = &render_state;
468
469 // Render command lists
470 // (Because we merged all buffers into a single one, we maintain our own offset into them)
471 int global_vtx_offset = 0;
472 int global_idx_offset = 0;
473 ImVec2 clip_scale = draw_data->FramebufferScale;
474 ImVec2 clip_off = draw_data->DisplayPos;
475 for (const ImDrawList* draw_list : draw_data->CmdLists)
476 {
477 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
478 {
479 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
480 if (pcmd->UserCallback != nullptr)
481 {
482 // User callback, registered via ImDrawList::AddCallback()
483 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
484 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
485 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
486 else
487 pcmd->UserCallback(draw_list, pcmd);
488 }
489 else
490 {
491 // Bind custom texture
492 ImTextureID tex_id = pcmd->GetTexID();
493 ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id), 0);
494 WGPUBindGroup bind_group = (WGPUBindGroup)bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash);
495 if (!bind_group)
496 {
497 bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
498 bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, bind_group);
499 }
500 wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr);
501
502 // Project scissor/clipping rectangles into framebuffer space
503 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
504 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
505
506 // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
507 if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
508 if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
509 if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
510 if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
511 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
512 continue;
513
514 // Apply scissor/clipping rectangle, Draw
515 wgpuRenderPassEncoderSetScissorRect(pass_encoder, (uint32_t)clip_min.x, (uint32_t)clip_min.y, (uint32_t)(clip_max.x - clip_min.x), (uint32_t)(clip_max.y - clip_min.y));
516 wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
517 }
518 }
519 global_idx_offset += draw_list->IdxBuffer.Size;
520 global_vtx_offset += draw_list->VtxBuffer.Size;
521 }
522
523 // Remove all ImageBindGroups
524 ImGuiStorage& image_bind_groups = bd->renderResources.ImageBindGroups;
525 for (int i = 0; i < image_bind_groups.Data.Size; i++)
526 {
527 WGPUBindGroup bind_group = (WGPUBindGroup)image_bind_groups.Data[i].val_p;
528 SafeRelease(bind_group);
529 }
530 image_bind_groups.Data.resize(0);
531
532 platform_io.Renderer_RenderState = nullptr;
533 }
534
535 static void ImGui_ImplWGPU_DestroyTexture(ImTextureData* tex)
536 {
537 ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData;
538 if (backend_tex == nullptr)
539 return;
540
541 IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID);
542 wgpuTextureViewRelease(backend_tex->TextureView);
543 wgpuTextureRelease(backend_tex->Texture);
544 IM_DELETE(backend_tex);
545
546 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
547 tex->SetTexID(ImTextureID_Invalid);
548 tex->SetStatus(ImTextureStatus_Destroyed);
549 tex->BackendUserData = nullptr;
550 }
551
552 void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex)
553 {
554 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
555 if (tex->Status == ImTextureStatus_WantCreate)
556 {
557 // Create and upload new texture to graphics system
558 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
559 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
560 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
561 ImGui_ImplWGPU_Texture* backend_tex = IM_NEW(ImGui_ImplWGPU_Texture)();
562
563 // Create texture
564 WGPUTextureDescriptor tex_desc = {};
565 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
566 tex_desc.label = { "Dear ImGui Texture", WGPU_STRLEN };
567 #else
568 tex_desc.label = "Dear ImGui Texture";
569 #endif
570 tex_desc.dimension = WGPUTextureDimension_2D;
571 tex_desc.size.width = tex->Width;
572 tex_desc.size.height = tex->Height;
573 tex_desc.size.depthOrArrayLayers = 1;
574 tex_desc.sampleCount = 1;
575 tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
576 tex_desc.mipLevelCount = 1;
577 tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
578 backend_tex->Texture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc);
579
580 // Create texture view
581 WGPUTextureViewDescriptor tex_view_desc = {};
582 tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
583 tex_view_desc.dimension = WGPUTextureViewDimension_2D;
584 tex_view_desc.baseMipLevel = 0;
585 tex_view_desc.mipLevelCount = 1;
586 tex_view_desc.baseArrayLayer = 0;
587 tex_view_desc.arrayLayerCount = 1;
588 tex_view_desc.aspect = WGPUTextureAspect_All;
589 backend_tex->TextureView = wgpuTextureCreateView(backend_tex->Texture, &tex_view_desc);
590
591 // Store identifiers
592 tex->SetTexID((ImTextureID)(intptr_t)backend_tex->TextureView);
593 tex->BackendUserData = backend_tex;
594 // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
595 }
596
597 if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
598 {
599 ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData;
600 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
601
602 // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
603 const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
604 const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
605 const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
606 const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
607
608 // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
609 // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
610 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
611 WGPUTexelCopyTextureInfo dst_view = {};
612 #else
613 WGPUImageCopyTexture dst_view = {};
614 #endif
615 dst_view.texture = backend_tex->Texture;
616 dst_view.mipLevel = 0;
617 dst_view.origin = { (uint32_t)upload_x, (uint32_t)upload_y, 0 };
618 dst_view.aspect = WGPUTextureAspect_All;
619 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
620 WGPUTexelCopyBufferLayout layout = {};
621 #else
622 WGPUTextureDataLayout layout = {};
623 #endif
624 layout.offset = 0;
625 layout.bytesPerRow = tex->Width * tex->BytesPerPixel;
626 layout.rowsPerImage = upload_h;
627 WGPUExtent3D write_size = { (uint32_t)upload_w, (uint32_t)upload_h, 1 };
628 wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, tex->GetPixelsAt(upload_x, upload_y), (uint32_t)(tex->Width * upload_h * tex->BytesPerPixel), &layout, &write_size);
629 tex->SetStatus(ImTextureStatus_OK);
630 }
631 if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
632 ImGui_ImplWGPU_DestroyTexture(tex);
633 }
634
635 static void ImGui_ImplWGPU_CreateUniformBuffer()
636 {
637 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
638 WGPUBufferDescriptor ub_desc =
639 {
640 nullptr,
641 "Dear ImGui Uniform buffer",
642 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
643 WGPU_STRLEN,
644 #endif
645 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
646 MEMALIGN(sizeof(Uniforms), 16),
647 false
648 };
649 bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc);
650 }
651
652 bool ImGui_ImplWGPU_CreateDeviceObjects()
653 {
654 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
655 if (!bd->wgpuDevice)
656 return false;
657 if (bd->pipelineState)
658 ImGui_ImplWGPU_InvalidateDeviceObjects();
659
660 // Create render pipeline
661 WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
662 graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
663 graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
664 graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
665 graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
666 graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
667
668 // Bind group layouts
669 WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
670 common_bg_layout_entries[0].binding = 0;
671 common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
672 common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform;
673 common_bg_layout_entries[1].binding = 1;
674 common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment;
675 common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
676
677 WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {};
678 image_bg_layout_entries[0].binding = 0;
679 image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment;
680 image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float;
681 image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
682
683 WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {};
684 common_bg_layout_desc.entryCount = 2;
685 common_bg_layout_desc.entries = common_bg_layout_entries;
686
687 WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {};
688 image_bg_layout_desc.entryCount = 1;
689 image_bg_layout_desc.entries = image_bg_layout_entries;
690
691 WGPUBindGroupLayout bg_layouts[2];
692 bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc);
693 bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc);
694
695 WGPUPipelineLayoutDescriptor layout_desc = {};
696 layout_desc.bindGroupLayoutCount = 2;
697 layout_desc.bindGroupLayouts = bg_layouts;
698 graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc);
699
700 // Create the vertex shader
701 WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl);
702 graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
703 graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
704
705 // Vertex input configuration
706 WGPUVertexAttribute attribute_desc[] =
707 {
708 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
709 { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
710 { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
711 { nullptr, WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
712 #else
713 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
714 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
715 { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
716 #endif
717 };
718
719 WGPUVertexBufferLayout buffer_layouts[1];
720 buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
721 buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
722 buffer_layouts[0].attributeCount = 3;
723 buffer_layouts[0].attributes = attribute_desc;
724
725 graphics_pipeline_desc.vertex.bufferCount = 1;
726 graphics_pipeline_desc.vertex.buffers = buffer_layouts;
727
728 // Create the pixel shader
729 WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl);
730
731 // Create the blending setup
732 WGPUBlendState blend_state = {};
733 blend_state.alpha.operation = WGPUBlendOperation_Add;
734 blend_state.alpha.srcFactor = WGPUBlendFactor_One;
735 blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
736 blend_state.color.operation = WGPUBlendOperation_Add;
737 blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
738 blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
739
740 WGPUColorTargetState color_state = {};
741 color_state.format = bd->renderTargetFormat;
742 color_state.blend = &blend_state;
743 color_state.writeMask = WGPUColorWriteMask_All;
744
745 WGPUFragmentState fragment_state = {};
746 fragment_state.module = pixel_shader_desc.module;
747 fragment_state.entryPoint = pixel_shader_desc.entryPoint;
748 fragment_state.targetCount = 1;
749 fragment_state.targets = &color_state;
750
751 graphics_pipeline_desc.fragment = &fragment_state;
752
753 // Create depth-stencil State
754 WGPUDepthStencilState depth_stencil_state = {};
755 depth_stencil_state.format = bd->depthStencilFormat;
756 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
757 depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
758 #else
759 depth_stencil_state.depthWriteEnabled = false;
760 #endif
761 depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
762 depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
763 depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
764 depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
765 depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
766 depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
767 depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
768 depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
769 depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
770
771 // Configure disabled depth-stencil state
772 graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
773
774 bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc);
775
776 ImGui_ImplWGPU_CreateUniformBuffer();
777
778 // Create sampler
779 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
780 WGPUSamplerDescriptor sampler_desc = {};
781 sampler_desc.minFilter = WGPUFilterMode_Linear;
782 sampler_desc.magFilter = WGPUFilterMode_Linear;
783 sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
784 sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
785 sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
786 sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
787 sampler_desc.maxAnisotropy = 1;
788 bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
789
790 // Create resource bind group
791 WGPUBindGroupEntry common_bg_entries[] =
792 {
793 { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 },
794 { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 },
795 };
796 WGPUBindGroupDescriptor common_bg_descriptor = {};
797 common_bg_descriptor.layout = bg_layouts[0];
798 common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
799 common_bg_descriptor.entries = common_bg_entries;
800 bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
801 bd->renderResources.ImageBindGroupLayout = bg_layouts[1];
802
803 SafeRelease(vertex_shader_desc.module);
804 SafeRelease(pixel_shader_desc.module);
805 SafeRelease(graphics_pipeline_desc.layout);
806 SafeRelease(bg_layouts[0]);
807
808 return true;
809 }
810
811 void ImGui_ImplWGPU_InvalidateDeviceObjects()
812 {
813 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
814 if (!bd->wgpuDevice)
815 return;
816
817 SafeRelease(bd->pipelineState);
818 SafeRelease(bd->renderResources);
819
820 // Destroy all textures
821 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
822 if (tex->RefCount == 1)
823 ImGui_ImplWGPU_DestroyTexture(tex);
824
825 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
826 SafeRelease(bd->pFrameResources[i]);
827 }
828
829 bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
830 {
831 ImGuiIO& io = ImGui::GetIO();
832 IMGUI_CHECKVERSION();
833 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
834
835 // Setup backend capabilities flags
836 ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
837 io.BackendRendererUserData = (void*)bd;
838 #if defined(__EMSCRIPTEN__)
839 io.BackendRendererName = "imgui_impl_webgpu_emscripten";
840 #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
841 io.BackendRendererName = "imgui_impl_webgpu_dawn";
842 #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
843 io.BackendRendererName = "imgui_impl_webgpu_wgpu";
844 #else
845 io.BackendRendererName = "imgui_impl_webgpu";
846 #endif
847 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
848 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
849
850 bd->initInfo = *init_info;
851 bd->wgpuDevice = init_info->Device;
852 bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
853 bd->renderTargetFormat = init_info->RenderTargetFormat;
854 bd->depthStencilFormat = init_info->DepthStencilFormat;
855 bd->numFramesInFlight = init_info->NumFramesInFlight;
856 bd->frameIndex = UINT_MAX;
857
858 bd->renderResources.Sampler = nullptr;
859 bd->renderResources.Uniforms = nullptr;
860 bd->renderResources.CommonBindGroup = nullptr;
861 bd->renderResources.ImageBindGroups.Data.reserve(100);
862 bd->renderResources.ImageBindGroupLayout = nullptr;
863
864 // Create buffers with a default size (they will later be grown as needed)
865 bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
866 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
867 {
868 FrameResources* fr = &bd->pFrameResources[i];
869 fr->IndexBuffer = nullptr;
870 fr->VertexBuffer = nullptr;
871 fr->IndexBufferHost = nullptr;
872 fr->VertexBufferHost = nullptr;
873 fr->IndexBufferSize = 10000;
874 fr->VertexBufferSize = 5000;
875 }
876
877 return true;
878 }
879
880 void ImGui_ImplWGPU_Shutdown()
881 {
882 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
883 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
884 ImGuiIO& io = ImGui::GetIO();
885
886 ImGui_ImplWGPU_InvalidateDeviceObjects();
887 delete[] bd->pFrameResources;
888 bd->pFrameResources = nullptr;
889 wgpuQueueRelease(bd->defaultQueue);
890 bd->wgpuDevice = nullptr;
891 bd->numFramesInFlight = 0;
892 bd->frameIndex = UINT_MAX;
893
894 io.BackendRendererName = nullptr;
895 io.BackendRendererUserData = nullptr;
896 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
897 IM_DELETE(bd);
898 }
899
900 void ImGui_ImplWGPU_NewFrame()
901 {
902 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
903 if (!bd->pipelineState)
904 if (!ImGui_ImplWGPU_CreateDeviceObjects())
905 IM_ASSERT(0 && "ImGui_ImplWGPU_CreateDeviceObjects() failed!");
906 }
907
908 //-----------------------------------------------------------------------------
909
910 #endif // #ifndef IMGUI_DISABLE