57.3 KB、1162行 生 Blame 履歴
1// dear imgui: Renderer for WebGPU
2// This needs to be used along with a Platform Binding (e.g. GLFW, SDL2, SDL3)
3// (Please note that WebGPU is a recent API, may not be supported by all browser, and its ecosystem is generally a mess)
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// Read imgui_impl_wgpu.h about how to use the IMGUI_IMPL_WEBGPU_BACKEND_WGPU or IMGUI_IMPL_WEBGPU_BACKEND_DAWN flags.
14
15// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
16// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
17// Learn about Dear ImGui:
18// - FAQ https://dearimgui.com/faq
19// - Getting Started https://dearimgui.com/getting-started
20// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
21// - Introduction, links and more at the top of imgui.cpp
22
23// CHANGELOG
24// (minor and older changes stripped away, please see git history for details)
25// 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378)
26// 2026-03-25: Added support for WGVK native backend via IMGUI_IMPL_WEBGPU_BACKEND_WGVK define, with SPIRV shaders if WGSL is not available. (#9316, #9246, #9257)
27// 2026-03-09: Removed support for Emscripten < 4.0.10. (#9281)
28// 2025-10-16: Update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898)
29// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
30// 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465)
31// 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes.
32// 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
33// 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
34// 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
35// 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)
36// 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
37// 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
38// 2024-01-22: Fixed pipeline layout leak. (#7245)
39// 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
40// 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
41// 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
42// 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).
43// 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
44// 2022-11-24: Fixed validation error with default depth buffer settings.
45// 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init().
46// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
47// 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
48// 2021-08-24: Fixed for latest specs.
49// 2021-05-24: Add support for draw_data->FramebufferScale.
50// 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
51// 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
52// 2021-02-18: Change blending equation to preserve alpha in output buffer.
53// 2021-01-28: Initial version.
54
55#include "imgui.h"
56
57#ifndef IMGUI_DISABLE
58#include "imgui_impl_wgpu.h"
59#include <limits.h>
60#include <stdio.h>
61
62// One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
63#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
64#error Exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN, IMGUI_IMPL_WEBGPU_BACKEND_WGPU or IMGUI_IMPL_WEBGPU_BACKEND_WGVK must be defined!
65#endif
66#if defined(__EMSCRIPTEN__) && defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
67#error Emscripten <4.0.10 with '-sUSE_WEBGPU=1' is not supported anymore.
68#endif
69
70#if defined IMGUI_IMPL_WEBGPU_BACKEND_DAWN || defined IMGUI_IMPL_WEBGPU_BACKEND_WGVK
71// Dawn renamed WGPUProgrammableStageDescriptor to WGPUComputeState (see: https://github.com/webgpu-native/webgpu-headers/pull/413)
72// Using type alias until WGPU adopts the same naming convention (#8369)
73using WGPUProgrammableStageDescriptor = WGPUComputeState;
74#endif
75
76// Dear ImGui prototypes from imgui_internal.h
77extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed);
78#define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro).
79
80// WebGPU data
81struct ImGui_ImplWGPU_Texture
82{
83 WGPUTexture Texture = nullptr;
84 WGPUTextureView TextureView = nullptr;
85};
86
87struct RenderResources
88{
89 WGPUSampler SamplerLinear = nullptr; // Bilinear sampler
90 WGPUSampler SamplerNearest = nullptr; // Nearest/point sampler
91 WGPUBuffer Uniforms = nullptr; // Shader uniforms
92 WGPUBindGroup CommonBindGroupLinear = nullptr; // Common bind-group bound to group 0 (uniforms + SamplerLinear)
93 WGPUBindGroup CommonBindGroupNearest = nullptr; // Common bind-group bound to group 0 (uniforms + SamplerNearest)
94 ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
95 WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
96};
97
98struct FrameResources
99{
100 WGPUBuffer IndexBuffer;
101 WGPUBuffer VertexBuffer;
102 ImDrawIdx* IndexBufferHost;
103 ImDrawVert* VertexBufferHost;
104 int IndexBufferSize;
105 int VertexBufferSize;
106};
107
108struct Uniforms
109{
110 float MVP[4][4];
111 float Gamma;
112};
113
114struct ImGui_ImplWGPU_Data
115{
116 ImGui_ImplWGPU_InitInfo initInfo;
117 WGPUDevice wgpuDevice = nullptr;
118 WGPUQueue defaultQueue = nullptr;
119 WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
120 WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
121 WGPURenderPipeline pipelineState = nullptr;
122 ImGui_ImplWGPU_RenderState* RenderState = nullptr; // == ImGui::GetPlatformIO().Renderer_RenderState during rendering.
123
124 RenderResources renderResources;
125 FrameResources* pFrameResources = nullptr;
126 unsigned int numFramesInFlight = 0;
127 unsigned int frameIndex = UINT_MAX;
128};
129
130// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
131// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
132static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData()
133{
134 return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
135}
136
137//-----------------------------------------------------------------------------
138// SHADERS
139//-----------------------------------------------------------------------------
140
141static const char __shader_vert_wgsl[] = R"(
142struct VertexInput {
143 @location(0) position: vec2<f32>,
144 @location(1) uv: vec2<f32>,
145 @location(2) color: vec4<f32>,
146};
147
148struct VertexOutput {
149 @builtin(position) position: vec4<f32>,
150 @location(0) color: vec4<f32>,
151 @location(1) uv: vec2<f32>,
152};
153
154struct Uniforms {
155 mvp: mat4x4<f32>,
156 gamma: f32,
157};
158
159@group(0) @binding(0) var<uniform> uniforms: Uniforms;
160
161@vertex
162fn main(in: VertexInput) -> VertexOutput {
163 var out: VertexOutput;
164 out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0);
165 out.color = in.color;
166 out.uv = in.uv;
167 return out;
168}
169)";
170
171static const char __shader_frag_wgsl[] = R"(
172struct VertexOutput {
173 @builtin(position) position: vec4<f32>,
174 @location(0) color: vec4<f32>,
175 @location(1) uv: vec2<f32>,
176};
177
178struct Uniforms {
179 mvp: mat4x4<f32>,
180 gamma: f32,
181};
182
183@group(0) @binding(0) var<uniform> uniforms: Uniforms;
184@group(0) @binding(1) var s: sampler;
185@group(1) @binding(0) var t: texture_2d<f32>;
186
187@fragment
188fn main(in: VertexOutput) -> @location(0) vec4<f32> {
189 let color = in.color * textureSample(t, s, in.uv);
190 let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma));
191 return vec4<f32>(corrected_color, color.a);
192}
193)";
194
195// Same shader as __shader_vert_wgsl[] but compiled as SPIRV.
196// 'wgslc -o vert.spv vert.wgsl' + 'binary_to_compressed_c -u8 -nocompress vert.spv'
197static const unsigned char __shader_vert_spirv[1996] =
198{
199 3,2,35,7,0,3,1,0,1,0,23,0,90,0,0,0,0,0,0,0,17,0,2,0,1,0,0,0,14,0,3,0,0,0,0,0,1,0,0,0,15,0,12,0,0,0,0,0,78,0,0,0,109,97,105,110,0,0,0,0,8,0,0,0,12,0,0,0,13,0,0,0,16,0,0,0,18,0,0,0,19,
200 0,0,0,21,0,0,0,71,0,4,0,4,0,0,0,6,0,0,0,16,0,0,0,72,0,5,0,3,0,0,0,0,0,0,0,35,0,0,0,0,0,0,0,71,0,3,0,3,0,0,0,2,0,0,0,71,0,4,0,1,0,0,0,34,0,0,0,0,0,0,0,71,0,4,0,1,0,0,0,33,0,0,0,0,0,
201 0,0,71,0,3,0,1,0,0,0,24,0,0,0,71,0,4,0,8,0,0,0,30,0,0,0,0,0,0,0,71,0,4,0,12,0,0,0,30,0,0,0,1,0,0,0,71,0,4,0,13,0,0,0,30,0,0,0,2,0,0,0,71,0,4,0,16,0,0,0,11,0,0,0,0,0,0,0,71,0,4,0,18,
202 0,0,0,30,0,0,0,0,0,0,0,71,0,4,0,19,0,0,0,30,0,0,0,1,0,0,0,71,0,4,0,21,0,0,0,11,0,0,0,1,0,0,0,21,0,4,0,6,0,0,0,32,0,0,0,0,0,0,0,23,0,4,0,5,0,0,0,6,0,0,0,4,0,0,0,43,0,4,0,6,0,0,0,7,0,
203 0,0,5,0,0,0,28,0,4,0,4,0,0,0,5,0,0,0,7,0,0,0,30,0,3,0,3,0,0,0,4,0,0,0,32,0,4,0,2,0,0,0,2,0,0,0,3,0,0,0,59,0,4,0,2,0,0,0,1,0,0,0,2,0,0,0,22,0,3,0,11,0,0,0,32,0,0,0,23,0,4,0,10,0,0,0,
204 11,0,0,0,2,0,0,0,32,0,4,0,9,0,0,0,1,0,0,0,10,0,0,0,59,0,4,0,9,0,0,0,8,0,0,0,1,0,0,0,59,0,4,0,9,0,0,0,12,0,0,0,1,0,0,0,23,0,4,0,15,0,0,0,11,0,0,0,4,0,0,0,32,0,4,0,14,0,0,0,1,0,0,0,15,
205 0,0,0,59,0,4,0,14,0,0,0,13,0,0,0,1,0,0,0,32,0,4,0,17,0,0,0,3,0,0,0,15,0,0,0,59,0,4,0,17,0,0,0,16,0,0,0,3,0,0,0,59,0,4,0,17,0,0,0,18,0,0,0,3,0,0,0,32,0,4,0,20,0,0,0,3,0,0,0,10,0,0,0,
206 59,0,4,0,20,0,0,0,19,0,0,0,3,0,0,0,32,0,4,0,22,0,0,0,3,0,0,0,11,0,0,0,59,0,4,0,22,0,0,0,21,0,0,0,3,0,0,0,30,0,5,0,24,0,0,0,15,0,0,0,15,0,0,0,10,0,0,0,30,0,5,0,25,0,0,0,10,0,0,0,10,
207 0,0,0,15,0,0,0,33,0,4,0,27,0,0,0,24,0,0,0,25,0,0,0,32,0,4,0,30,0,0,0,7,0,0,0,24,0,0,0,46,0,3,0,24,0,0,0,31,0,0,0,32,0,4,0,33,0,0,0,7,0,0,0,15,0,0,0,43,0,4,0,6,0,0,0,34,0,0,0,0,0,0,
208 0,24,0,4,0,36,0,0,0,15,0,0,0,4,0,0,0,43,0,4,0,11,0,0,0,40,0,0,0,0,0,0,0,43,0,4,0,11,0,0,0,41,0,0,0,0,0,128,63,43,0,4,0,6,0,0,0,44,0,0,0,1,0,0,0,32,0,4,0,47,0,0,0,7,0,0,0,10,0,0,0,43,
209 0,4,0,6,0,0,0,48,0,0,0,2,0,0,0,33,0,4,0,52,0,0,0,36,0,0,0,6,0,0,0,43,0,4,0,6,0,0,0,55,0,0,0,16,0,0,0,32,0,4,0,57,0,0,0,2,0,0,0,5,0,0,0,43,0,4,0,6,0,0,0,66,0,0,0,32,0,0,0,43,0,4,0,6,
210 0,0,0,72,0,0,0,48,0,0,0,19,0,2,0,79,0,0,0,33,0,3,0,80,0,0,0,79,0,0,0,54,0,5,0,24,0,0,0,23,0,0,0,0,0,0,0,27,0,0,0,55,0,3,0,25,0,0,0,26,0,0,0,248,0,2,0,28,0,0,0,59,0,5,0,30,0,0,0,29,
211 0,0,0,7,0,0,0,31,0,0,0,65,0,5,0,33,0,0,0,32,0,0,0,29,0,0,0,34,0,0,0,57,0,5,0,36,0,0,0,35,0,0,0,37,0,0,0,34,0,0,0,81,0,5,0,10,0,0,0,38,0,0,0,26,0,0,0,0,0,0,0,80,0,6,0,15,0,0,0,39,0,
212 0,0,38,0,0,0,40,0,0,0,41,0,0,0,145,0,5,0,15,0,0,0,42,0,0,0,35,0,0,0,39,0,0,0,62,0,4,0,32,0,0,0,42,0,0,0,0,0,0,0,65,0,5,0,33,0,0,0,43,0,0,0,29,0,0,0,44,0,0,0,81,0,5,0,15,0,0,0,45,0,
213 0,0,26,0,0,0,2,0,0,0,62,0,4,0,43,0,0,0,45,0,0,0,0,0,0,0,65,0,5,0,47,0,0,0,46,0,0,0,29,0,0,0,48,0,0,0,81,0,5,0,10,0,0,0,49,0,0,0,26,0,0,0,1,0,0,0,62,0,4,0,46,0,0,0,49,0,0,0,0,0,0,0,
214 61,0,5,0,24,0,0,0,50,0,0,0,29,0,0,0,0,0,0,0,254,0,2,0,50,0,0,0,56,0,1,0,54,0,5,0,36,0,0,0,37,0,0,0,0,0,0,0,52,0,0,0,55,0,3,0,6,0,0,0,51,0,0,0,248,0,2,0,53,0,0,0,134,0,5,0,6,0,0,0,54,
215 0,0,0,51,0,0,0,55,0,0,0,65,0,6,0,57,0,0,0,56,0,0,0,1,0,0,0,34,0,0,0,54,0,0,0,61,0,5,0,5,0,0,0,58,0,0,0,56,0,0,0,0,0,0,0,124,0,4,0,15,0,0,0,59,0,0,0,58,0,0,0,128,0,5,0,6,0,0,0,60,0,
216 0,0,55,0,0,0,51,0,0,0,134,0,5,0,6,0,0,0,61,0,0,0,60,0,0,0,55,0,0,0,65,0,6,0,57,0,0,0,62,0,0,0,1,0,0,0,34,0,0,0,61,0,0,0,61,0,5,0,5,0,0,0,63,0,0,0,62,0,0,0,0,0,0,0,124,0,4,0,15,0,0,
217 0,64,0,0,0,63,0,0,0,128,0,5,0,6,0,0,0,65,0,0,0,66,0,0,0,51,0,0,0,134,0,5,0,6,0,0,0,67,0,0,0,65,0,0,0,55,0,0,0,65,0,6,0,57,0,0,0,68,0,0,0,1,0,0,0,34,0,0,0,67,0,0,0,61,0,5,0,5,0,0,0,
218 69,0,0,0,68,0,0,0,0,0,0,0,124,0,4,0,15,0,0,0,70,0,0,0,69,0,0,0,128,0,5,0,6,0,0,0,71,0,0,0,72,0,0,0,51,0,0,0,134,0,5,0,6,0,0,0,73,0,0,0,71,0,0,0,55,0,0,0,65,0,6,0,57,0,0,0,74,0,0,0,
219 1,0,0,0,34,0,0,0,73,0,0,0,61,0,5,0,5,0,0,0,75,0,0,0,74,0,0,0,0,0,0,0,124,0,4,0,15,0,0,0,76,0,0,0,75,0,0,0,80,0,7,0,36,0,0,0,77,0,0,0,59,0,0,0,64,0,0,0,70,0,0,0,76,0,0,0,254,0,2,0,77,
220 0,0,0,56,0,1,0,54,0,5,0,79,0,0,0,78,0,0,0,0,0,0,0,80,0,0,0,248,0,2,0,81,0,0,0,61,0,5,0,10,0,0,0,82,0,0,0,8,0,0,0,0,0,0,0,61,0,5,0,10,0,0,0,83,0,0,0,12,0,0,0,0,0,0,0,61,0,5,0,15,0,0,
221 0,84,0,0,0,13,0,0,0,0,0,0,0,80,0,6,0,25,0,0,0,85,0,0,0,82,0,0,0,83,0,0,0,84,0,0,0,57,0,5,0,24,0,0,0,86,0,0,0,23,0,0,0,85,0,0,0,81,0,5,0,15,0,0,0,87,0,0,0,86,0,0,0,0,0,0,0,62,0,4,0,
222 16,0,0,0,87,0,0,0,0,0,0,0,81,0,5,0,15,0,0,0,88,0,0,0,86,0,0,0,1,0,0,0,62,0,4,0,18,0,0,0,88,0,0,0,0,0,0,0,81,0,5,0,10,0,0,0,89,0,0,0,86,0,0,0,2,0,0,0,62,0,4,0,19,0,0,0,89,0,0,0,0,0,
223 0,0,62,0,4,0,21,0,0,0,41,0,0,0,0,0,0,0,253,0,1,0,56,0,1,0,
224};
225
226// Same shader as __shader_frag_wgsl[] but compiled as SPIRV.
227// 'wgslc -o frag.spv frag.wgsl' + 'binary_to_compressed_c -u8 -nocompress frag.spv'
228static const unsigned char __shader_frag_spirv[1392] =
229{
230 3,2,35,7,0,3,1,0,1,0,23,0,60,0,0,0,0,0,0,0,17,0,2,0,1,0,0,0,11,0,6,0,48,0,0,0,71,76,83,76,46,115,116,100,46,52,53,48,0,0,0,0,14,0,3,0,0,0,0,0,1,0,0,0,15,0,9,0,4,0,0,0,51,0,0,0,109,
231 97,105,110,0,0,0,0,15,0,0,0,18,0,0,0,19,0,0,0,22,0,0,0,16,0,3,0,51,0,0,0,7,0,0,0,71,0,4,0,4,0,0,0,6,0,0,0,16,0,0,0,72,0,5,0,3,0,0,0,0,0,0,0,35,0,0,0,0,0,0,0,71,0,3,0,3,0,0,0,2,0,0,
232 0,71,0,4,0,1,0,0,0,34,0,0,0,0,0,0,0,71,0,4,0,1,0,0,0,33,0,0,0,0,0,0,0,71,0,3,0,1,0,0,0,24,0,0,0,71,0,4,0,8,0,0,0,34,0,0,0,0,0,0,0,71,0,4,0,8,0,0,0,33,0,0,0,1,0,0,0,71,0,4,0,11,0,0,
233 0,34,0,0,0,1,0,0,0,71,0,4,0,11,0,0,0,33,0,0,0,0,0,0,0,71,0,4,0,15,0,0,0,11,0,0,0,15,0,0,0,71,0,4,0,18,0,0,0,30,0,0,0,0,0,0,0,71,0,4,0,19,0,0,0,30,0,0,0,1,0,0,0,71,0,4,0,22,0,0,0,30,
234 0,0,0,0,0,0,0,21,0,4,0,6,0,0,0,32,0,0,0,0,0,0,0,23,0,4,0,5,0,0,0,6,0,0,0,4,0,0,0,43,0,4,0,6,0,0,0,7,0,0,0,5,0,0,0,28,0,4,0,4,0,0,0,5,0,0,0,7,0,0,0,30,0,3,0,3,0,0,0,4,0,0,0,32,0,4,0,
235 2,0,0,0,2,0,0,0,3,0,0,0,59,0,4,0,2,0,0,0,1,0,0,0,2,0,0,0,26,0,2,0,10,0,0,0,32,0,4,0,9,0,0,0,0,0,0,0,10,0,0,0,59,0,4,0,9,0,0,0,8,0,0,0,0,0,0,0,22,0,3,0,14,0,0,0,32,0,0,0,25,0,9,0,13,
236 0,0,0,14,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,32,0,4,0,12,0,0,0,0,0,0,0,13,0,0,0,59,0,4,0,12,0,0,0,11,0,0,0,0,0,0,0,23,0,4,0,17,0,0,0,14,0,0,0,4,0,0,0,32,0,4,0,16,
237 0,0,0,1,0,0,0,17,0,0,0,59,0,4,0,16,0,0,0,15,0,0,0,1,0,0,0,59,0,4,0,16,0,0,0,18,0,0,0,1,0,0,0,23,0,4,0,21,0,0,0,14,0,0,0,2,0,0,0,32,0,4,0,20,0,0,0,1,0,0,0,21,0,0,0,59,0,4,0,20,0,0,0,
238 19,0,0,0,1,0,0,0,32,0,4,0,23,0,0,0,3,0,0,0,17,0,0,0,59,0,4,0,23,0,0,0,22,0,0,0,3,0,0,0,30,0,5,0,25,0,0,0,17,0,0,0,17,0,0,0,21,0,0,0,33,0,4,0,27,0,0,0,17,0,0,0,25,0,0,0,27,0,3,0,34,
239 0,0,0,13,0,0,0,23,0,4,0,38,0,0,0,14,0,0,0,3,0,0,0,32,0,4,0,40,0,0,0,2,0,0,0,5,0,0,0,43,0,4,0,6,0,0,0,41,0,0,0,0,0,0,0,43,0,4,0,6,0,0,0,42,0,0,0,4,0,0,0,19,0,2,0,52,0,0,0,33,0,3,0,53,
240 0,0,0,52,0,0,0,54,0,5,0,17,0,0,0,24,0,0,0,0,0,0,0,27,0,0,0,55,0,3,0,25,0,0,0,26,0,0,0,248,0,2,0,28,0,0,0,81,0,5,0,17,0,0,0,29,0,0,0,26,0,0,0,1,0,0,0,61,0,5,0,13,0,0,0,30,0,0,0,11,0,
241 0,0,0,0,0,0,61,0,5,0,10,0,0,0,31,0,0,0,8,0,0,0,0,0,0,0,81,0,5,0,21,0,0,0,32,0,0,0,26,0,0,0,2,0,0,0,86,0,5,0,34,0,0,0,33,0,0,0,30,0,0,0,31,0,0,0,87,0,6,0,17,0,0,0,35,0,0,0,33,0,0,0,
242 32,0,0,0,0,0,0,0,133,0,5,0,17,0,0,0,36,0,0,0,29,0,0,0,35,0,0,0,79,0,8,0,38,0,0,0,37,0,0,0,36,0,0,0,36,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,65,0,6,0,40,0,0,0,39,0,0,0,1,0,0,0,41,0,0,0,42,0,
243 0,0,61,0,5,0,5,0,0,0,43,0,0,0,39,0,0,0,0,0,0,0,81,0,5,0,6,0,0,0,44,0,0,0,43,0,0,0,0,0,0,0,124,0,4,0,14,0,0,0,45,0,0,0,44,0,0,0,80,0,6,0,38,0,0,0,46,0,0,0,45,0,0,0,45,0,0,0,45,0,0,0,
244 12,0,7,0,38,0,0,0,47,0,0,0,48,0,0,0,26,0,0,0,37,0,0,0,46,0,0,0,81,0,5,0,14,0,0,0,49,0,0,0,36,0,0,0,3,0,0,0,80,0,5,0,17,0,0,0,50,0,0,0,47,0,0,0,49,0,0,0,254,0,2,0,50,0,0,0,56,0,1,0,
245 54,0,5,0,52,0,0,0,51,0,0,0,0,0,0,0,53,0,0,0,248,0,2,0,54,0,0,0,61,0,5,0,17,0,0,0,55,0,0,0,15,0,0,0,0,0,0,0,61,0,5,0,17,0,0,0,56,0,0,0,18,0,0,0,0,0,0,0,61,0,5,0,21,0,0,0,57,0,0,0,19,
246 0,0,0,0,0,0,0,80,0,6,0,25,0,0,0,58,0,0,0,55,0,0,0,56,0,0,0,57,0,0,0,57,0,5,0,17,0,0,0,59,0,0,0,24,0,0,0,58,0,0,0,62,0,4,0,22,0,0,0,59,0,0,0,0,0,0,0,253,0,1,0,56,0,1,0,
247};
248
249static void SafeRelease(ImDrawIdx*& res)
250{
251 if (res)
252 delete[] res;
253 res = nullptr;
254}
255static void SafeRelease(ImDrawVert*& res)
256{
257 if (res)
258 delete[] res;
259 res = nullptr;
260}
261static void SafeRelease(WGPUBindGroupLayout& res)
262{
263 if (res)
264 wgpuBindGroupLayoutRelease(res);
265 res = nullptr;
266}
267static void SafeRelease(WGPUBindGroup& res)
268{
269 if (res)
270 wgpuBindGroupRelease(res);
271 res = nullptr;
272}
273static void SafeRelease(WGPUBuffer& res)
274{
275 if (res)
276 wgpuBufferRelease(res);
277 res = nullptr;
278}
279static void SafeRelease(WGPUPipelineLayout& res)
280{
281 if (res)
282 wgpuPipelineLayoutRelease(res);
283 res = nullptr;
284}
285static void SafeRelease(WGPURenderPipeline& res)
286{
287 if (res)
288 wgpuRenderPipelineRelease(res);
289 res = nullptr;
290}
291static void SafeRelease(WGPUSampler& res)
292{
293 if (res)
294 wgpuSamplerRelease(res);
295 res = nullptr;
296}
297static void SafeRelease(WGPUShaderModule& res)
298{
299 if (res)
300 wgpuShaderModuleRelease(res);
301 res = nullptr;
302}
303static void SafeRelease(RenderResources& res)
304{
305 SafeRelease(res.SamplerLinear);
306 SafeRelease(res.SamplerNearest);
307 SafeRelease(res.Uniforms);
308 SafeRelease(res.CommonBindGroupLinear);
309 SafeRelease(res.CommonBindGroupNearest);
310 SafeRelease(res.ImageBindGroupLayout);
311};
312
313static void SafeRelease(FrameResources& res)
314{
315 SafeRelease(res.IndexBuffer);
316 SafeRelease(res.VertexBuffer);
317 SafeRelease(res.IndexBufferHost);
318 SafeRelease(res.VertexBufferHost);
319}
320
321static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModuleWGSL(const char* wgsl_source)
322{
323 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
324 IM_UNUSED(bd);
325
326 WGPUShaderSourceWGSL wgsl_desc = {};
327 wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
328 wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
329
330 WGPUShaderModuleDescriptor desc = {};
331 desc.nextInChain = (WGPUChainedStruct*)&wgsl_desc;
332
333 // Detect shader compilation errors by using an error scope.
334 // Flag to be passed into the validation callback `userdata1` pointer.
335 int validation_error = 0;
336 wgpuDevicePushErrorScope(bd->wgpuDevice, WGPUErrorFilter_Validation);
337 WGPUShaderModule module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
338 WGPUPopErrorScopeCallbackInfo pop_cb = {};
339 pop_cb.mode = WGPUCallbackMode_AllowSpontaneous;
340 pop_cb.callback = [](WGPUPopErrorScopeStatus, WGPUErrorType type, WGPUStringView, void* userdata1, void*)
341 {
342 if (type == WGPUErrorType_Validation)
343 *static_cast<int*>(userdata1) = 1;
344 };
345 pop_cb.userdata1 = &validation_error;
346 wgpuDevicePopErrorScope(bd->wgpuDevice, pop_cb);
347
348 WGPUProgrammableStageDescriptor stage_desc = {};
349 if (module && !validation_error)
350 {
351 stage_desc.module = module;
352 stage_desc.entryPoint = { "main", WGPU_STRLEN };
353 }
354 else if (module)
355 {
356 wgpuShaderModuleRelease(module);
357 }
358 return stage_desc;
359}
360
361static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModuleSPIRV(const void* spirv_binary, size_t spirv_length)
362{
363 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
364
365 WGPUShaderSourceSPIRV spirv_desc = {};
366 spirv_desc.chain.sType = WGPUSType_ShaderSourceSPIRV;
367 spirv_desc.code = (const uint32_t *)spirv_binary;
368 spirv_desc.codeSize = ((uint32_t)(spirv_length / 4));
369
370 WGPUShaderModuleDescriptor desc = {};
371 desc.nextInChain = (WGPUChainedStruct*)&spirv_desc;
372
373 WGPUProgrammableStageDescriptor stage_desc = {};
374 stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
375
376 stage_desc.entryPoint = { "main", WGPU_STRLEN };
377 return stage_desc;
378}
379
380static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
381{
382 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
383 WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
384
385 WGPUBindGroupDescriptor image_bg_descriptor = {};
386 image_bg_descriptor.layout = layout;
387 image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
388 image_bg_descriptor.entries = image_bg_entries;
389 return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor);
390}
391
392static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
393{
394 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
395
396 // Setup orthographic projection matrix into our constant buffer
397 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
398 {
399 float L = draw_data->DisplayPos.x;
400 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
401 float T = draw_data->DisplayPos.y;
402 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
403 float mvp[4][4] =
404 {
405 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
406 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
407 { 0.0f, 0.0f, 0.5f, 0.0f },
408 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
409 };
410 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP));
411 float gamma;
412 switch (bd->renderTargetFormat)
413 {
414 case WGPUTextureFormat_ASTC10x10UnormSrgb:
415 case WGPUTextureFormat_ASTC10x5UnormSrgb:
416 case WGPUTextureFormat_ASTC10x6UnormSrgb:
417 case WGPUTextureFormat_ASTC10x8UnormSrgb:
418 case WGPUTextureFormat_ASTC12x10UnormSrgb:
419 case WGPUTextureFormat_ASTC12x12UnormSrgb:
420 case WGPUTextureFormat_ASTC4x4UnormSrgb:
421 case WGPUTextureFormat_ASTC5x5UnormSrgb:
422 case WGPUTextureFormat_ASTC6x5UnormSrgb:
423 case WGPUTextureFormat_ASTC6x6UnormSrgb:
424 case WGPUTextureFormat_ASTC8x5UnormSrgb:
425 case WGPUTextureFormat_ASTC8x6UnormSrgb:
426 case WGPUTextureFormat_ASTC8x8UnormSrgb:
427 case WGPUTextureFormat_BC1RGBAUnormSrgb:
428 case WGPUTextureFormat_BC2RGBAUnormSrgb:
429 case WGPUTextureFormat_BC3RGBAUnormSrgb:
430 case WGPUTextureFormat_BC7RGBAUnormSrgb:
431 case WGPUTextureFormat_BGRA8UnormSrgb:
432 case WGPUTextureFormat_ETC2RGB8A1UnormSrgb:
433 case WGPUTextureFormat_ETC2RGB8UnormSrgb:
434 case WGPUTextureFormat_ETC2RGBA8UnormSrgb:
435 case WGPUTextureFormat_RGBA8UnormSrgb:
436 gamma = 2.2f;
437 break;
438 default:
439 gamma = 1.0f;
440 }
441 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma));
442 }
443
444 // Setup viewport
445 wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
446
447 // Bind shader and vertex buffers
448 wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
449 wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
450 wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState);
451 wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroupLinear, 0, nullptr);
452
453 // Setup blend factor
454 WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
455 wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
456}
457
458// Draw callbacks
459static void ImGui_ImplWGPU_DrawCallback_ResetRenderState(const ImDrawList*, const ImDrawCmd*) {} // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
460static void ImGui_ImplWGPU_DrawCallback_SetSamplerLinear(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); wgpuRenderPassEncoderSetBindGroup(bd->RenderState->RenderPassEncoder, 0, bd->renderResources.CommonBindGroupLinear, 0, nullptr); }
461static void ImGui_ImplWGPU_DrawCallback_SetSamplerNearest(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); wgpuRenderPassEncoderSetBindGroup(bd->RenderState->RenderPassEncoder, 0, bd->renderResources.CommonBindGroupNearest, 0, nullptr); }
462
463// Render function
464void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
465{
466 // Avoid rendering when minimized
467 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
468 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
469 if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0)
470 return;
471
472 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
473 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
474 if (draw_data->Textures != nullptr)
475 for (ImTextureData* tex : *draw_data->Textures)
476 if (tex->Status != ImTextureStatus_OK)
477 ImGui_ImplWGPU_UpdateTexture(tex);
478
479 // FIXME: Assuming that this only gets called once per frame!
480 // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
481 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
482 bd->frameIndex = bd->frameIndex + 1;
483 FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
484
485 // Create and grow vertex/index buffers if needed
486 if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
487 {
488 if (fr->VertexBuffer)
489 {
490 wgpuBufferDestroy(fr->VertexBuffer);
491 wgpuBufferRelease(fr->VertexBuffer);
492 }
493 SafeRelease(fr->VertexBufferHost);
494 fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
495
496 WGPUBufferDescriptor vb_desc =
497 {
498 nullptr,
499 { "Dear ImGui Vertex buffer", WGPU_STRLEN, },
500 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
501 MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
502 false
503 };
504 fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc);
505 if (!fr->VertexBuffer)
506 return;
507
508 fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
509 }
510 if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
511 {
512 if (fr->IndexBuffer)
513 {
514 wgpuBufferDestroy(fr->IndexBuffer);
515 wgpuBufferRelease(fr->IndexBuffer);
516 }
517 SafeRelease(fr->IndexBufferHost);
518 fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
519
520 WGPUBufferDescriptor ib_desc =
521 {
522 nullptr,
523 { "Dear ImGui Index buffer", WGPU_STRLEN, },
524 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
525 MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
526 false
527 };
528 fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc);
529 if (!fr->IndexBuffer)
530 return;
531
532 fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
533 }
534
535 // Upload vertex/index data into a single contiguous GPU buffer
536 ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
537 ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
538 for (const ImDrawList* draw_list : draw_data->CmdLists)
539 {
540 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
541 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
542 vtx_dst += draw_list->VtxBuffer.Size;
543 idx_dst += draw_list->IdxBuffer.Size;
544 }
545 int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
546 int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
547 wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, (size_t)vb_write_size);
548 wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, (size_t)ib_write_size);
549
550 // Setup desired render state
551 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
552
553 // Setup render state structure (for callbacks and custom texture bindings)
554 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
555 ImGui_ImplWGPU_RenderState render_state;
556 render_state.Device = bd->wgpuDevice;
557 render_state.RenderPassEncoder = pass_encoder;
558 platform_io.Renderer_RenderState = bd->RenderState = &render_state;
559
560 // Render command lists
561 // (Because we merged all buffers into a single one, we maintain our own offset into them)
562 int global_vtx_offset = 0;
563 int global_idx_offset = 0;
564 ImVec2 clip_scale = draw_data->FramebufferScale;
565 ImVec2 clip_off = draw_data->DisplayPos;
566 for (const ImDrawList* draw_list : draw_data->CmdLists)
567 {
568 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
569 {
570 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
571 if (pcmd->UserCallback != nullptr)
572 {
573 // User callback, registered via ImDrawList::AddCallback()
574 if (pcmd->UserCallback == ImGui_ImplWGPU_DrawCallback_ResetRenderState)
575 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
576 else
577 pcmd->UserCallback(draw_list, pcmd);
578 }
579 else
580 {
581 // Bind custom texture
582 ImTextureID tex_id = pcmd->GetTexID();
583 ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id), 0);
584 WGPUBindGroup bind_group = (WGPUBindGroup)bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash);
585 if (!bind_group && tex_id != 0)
586 if ((bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id)) != 0)
587 bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, bind_group);
588 if (bind_group)
589 wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr);
590
591 // Project scissor/clipping rectangles into framebuffer space
592 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
593 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
594
595 // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
596 if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
597 if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
598 if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; }
599 if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; }
600 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
601 continue;
602
603 // Apply scissor/clipping rectangle, Draw
604 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));
605 wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
606 }
607 }
608 global_idx_offset += draw_list->IdxBuffer.Size;
609 global_vtx_offset += draw_list->VtxBuffer.Size;
610 }
611
612 // Remove all ImageBindGroups
613 ImGuiStorage& image_bind_groups = bd->renderResources.ImageBindGroups;
614 for (int i = 0; i < image_bind_groups.Data.Size; i++)
615 {
616 WGPUBindGroup bind_group = (WGPUBindGroup)image_bind_groups.Data[i].val_p;
617 SafeRelease(bind_group);
618 }
619 image_bind_groups.Data.resize(0);
620
621 platform_io.Renderer_RenderState = bd->RenderState = nullptr;
622}
623
624static void ImGui_ImplWGPU_DestroyTexture(ImTextureData* tex)
625{
626 if (ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData)
627 {
628 IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID);
629 wgpuTextureViewRelease(backend_tex->TextureView);
630 wgpuTextureRelease(backend_tex->Texture);
631 IM_DELETE(backend_tex);
632
633 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
634 tex->SetTexID(ImTextureID_Invalid);
635 tex->BackendUserData = nullptr;
636 }
637 tex->SetStatus(ImTextureStatus_Destroyed);
638}
639
640void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex)
641{
642 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
643 if (tex->Status == ImTextureStatus_WantCreate)
644 {
645 // Create and upload new texture to graphics system
646 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
647 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
648 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
649 ImGui_ImplWGPU_Texture* backend_tex = IM_NEW(ImGui_ImplWGPU_Texture)();
650
651 // Create texture
652 WGPUTextureDescriptor tex_desc = {};
653 tex_desc.label = { "Dear ImGui Texture", WGPU_STRLEN };
654 tex_desc.dimension = WGPUTextureDimension_2D;
655 tex_desc.size.width = tex->Width;
656 tex_desc.size.height = tex->Height;
657 tex_desc.size.depthOrArrayLayers = 1;
658 tex_desc.sampleCount = 1;
659 tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
660 tex_desc.mipLevelCount = 1;
661 tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
662 backend_tex->Texture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc);
663
664 // Create texture view
665 WGPUTextureViewDescriptor tex_view_desc = {};
666 tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
667 tex_view_desc.dimension = WGPUTextureViewDimension_2D;
668 tex_view_desc.baseMipLevel = 0;
669 tex_view_desc.mipLevelCount = 1;
670 tex_view_desc.baseArrayLayer = 0;
671 tex_view_desc.arrayLayerCount = 1;
672 tex_view_desc.aspect = WGPUTextureAspect_All;
673 backend_tex->TextureView = wgpuTextureCreateView(backend_tex->Texture, &tex_view_desc);
674
675 // Store identifiers
676 tex->SetTexID((ImTextureID)(intptr_t)backend_tex->TextureView);
677 tex->BackendUserData = backend_tex;
678 // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
679 }
680
681 if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
682 {
683 ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData;
684 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
685
686 // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
687 const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
688 const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
689 const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
690 const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
691
692 // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
693 // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
694 WGPUTexelCopyTextureInfo dst_view = {};
695 dst_view.texture = backend_tex->Texture;
696 dst_view.mipLevel = 0;
697 dst_view.origin = { (uint32_t)upload_x, (uint32_t)upload_y, 0 };
698 dst_view.aspect = WGPUTextureAspect_All;
699 WGPUTexelCopyBufferLayout layout = {};
700 layout.offset = 0;
701 layout.bytesPerRow = tex->Width * tex->BytesPerPixel;
702 layout.rowsPerImage = upload_h;
703 WGPUExtent3D write_size = { (uint32_t)upload_w, (uint32_t)upload_h, 1 };
704 wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, tex->GetPixelsAt(upload_x, upload_y), (uint32_t)(tex->Width * upload_h * tex->BytesPerPixel), &layout, &write_size);
705 tex->SetStatus(ImTextureStatus_OK);
706 }
707 if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
708 ImGui_ImplWGPU_DestroyTexture(tex);
709}
710
711static void ImGui_ImplWGPU_CreateUniformBuffer()
712{
713 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
714 WGPUBufferDescriptor ub_desc =
715 {
716 nullptr,
717 { "Dear ImGui Uniform buffer", WGPU_STRLEN, },
718 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
719 MEMALIGN(sizeof(Uniforms), 16),
720 false
721 };
722 bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc);
723}
724
725bool ImGui_ImplWGPU_CreateDeviceObjects()
726{
727 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
728 if (!bd->wgpuDevice)
729 return false;
730 if (bd->pipelineState)
731 ImGui_ImplWGPU_InvalidateDeviceObjects();
732
733 // Create render pipeline
734 WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
735 graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
736 graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
737 graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
738 graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
739 graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
740
741 // Bind group layouts
742 WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
743 common_bg_layout_entries[0].binding = 0;
744 common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
745 common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform;
746 common_bg_layout_entries[1].binding = 1;
747 common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment;
748 common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
749
750 WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {};
751 image_bg_layout_entries[0].binding = 0;
752 image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment;
753 image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float;
754 image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
755
756 WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {};
757 common_bg_layout_desc.entryCount = 2;
758 common_bg_layout_desc.entries = common_bg_layout_entries;
759
760 WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {};
761 image_bg_layout_desc.entryCount = 1;
762 image_bg_layout_desc.entries = image_bg_layout_entries;
763
764 WGPUBindGroupLayout bg_layouts[2];
765 bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc);
766 bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc);
767
768 WGPUPipelineLayoutDescriptor layout_desc = {};
769 layout_desc.bindGroupLayoutCount = 2;
770 layout_desc.bindGroupLayouts = bg_layouts;
771 graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc);
772
773 // Create the vertex shader
774 WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModuleWGSL(__shader_vert_wgsl);
775 if (!vertex_shader_desc.module) vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModuleSPIRV(__shader_vert_spirv, sizeof(__shader_vert_spirv));
776 graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
777 graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
778
779 // Vertex input configuration
780 WGPUVertexAttribute attribute_desc[] =
781 {
782#if defined IMGUI_IMPL_WEBGPU_BACKEND_DAWN || defined IMGUI_IMPL_WEBGPU_BACKEND_WGVK
783 { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
784 { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
785 { nullptr, WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
786#else
787 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
788 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
789 { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
790#endif
791 };
792
793 WGPUVertexBufferLayout buffer_layouts[1];
794 buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
795 buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
796 buffer_layouts[0].attributeCount = 3;
797 buffer_layouts[0].attributes = attribute_desc;
798
799 graphics_pipeline_desc.vertex.bufferCount = 1;
800 graphics_pipeline_desc.vertex.buffers = buffer_layouts;
801
802 // Create the pixel shader
803 WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModuleWGSL(__shader_frag_wgsl);
804 if (!pixel_shader_desc.module) pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModuleSPIRV(__shader_frag_spirv, sizeof(__shader_frag_spirv));
805
806 // Create the blending setup
807 WGPUBlendState blend_state = {};
808 blend_state.alpha.operation = WGPUBlendOperation_Add;
809 blend_state.alpha.srcFactor = WGPUBlendFactor_One;
810 blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
811 blend_state.color.operation = WGPUBlendOperation_Add;
812 blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
813 blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
814
815 WGPUColorTargetState color_state = {};
816 color_state.format = bd->renderTargetFormat;
817 color_state.blend = &blend_state;
818 color_state.writeMask = WGPUColorWriteMask_All;
819
820 WGPUFragmentState fragment_state = {};
821 fragment_state.module = pixel_shader_desc.module;
822 fragment_state.entryPoint = pixel_shader_desc.entryPoint;
823 fragment_state.targetCount = 1;
824 fragment_state.targets = &color_state;
825
826 graphics_pipeline_desc.fragment = &fragment_state;
827
828 // Create depth-stencil State
829 WGPUDepthStencilState depth_stencil_state = {};
830 depth_stencil_state.format = bd->depthStencilFormat;
831 depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
832 depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
833 depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
834 depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
835 depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
836 depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
837 depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
838 depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
839 depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
840 depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
841
842 // Configure disabled depth-stencil state
843 graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
844
845 bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc);
846
847 ImGui_ImplWGPU_CreateUniformBuffer();
848
849 // Create samplers (Linear/Nearest)
850 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
851 WGPUSamplerDescriptor sampler_desc = {};
852 sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
853 sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
854 sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
855 sampler_desc.maxAnisotropy = 1;
856 sampler_desc.minFilter = WGPUFilterMode_Linear;
857 sampler_desc.magFilter = WGPUFilterMode_Linear;
858 sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
859 bd->renderResources.SamplerLinear = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
860 sampler_desc.minFilter = WGPUFilterMode_Nearest;
861 sampler_desc.magFilter = WGPUFilterMode_Nearest;
862 sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Nearest;
863 bd->renderResources.SamplerNearest = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
864
865 // Create resource bind groups (one per sampler, otherwise identical)
866 WGPUBindGroupEntry common_bg_entries[] =
867 {
868 { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 },
869 { nullptr, 1, 0, 0, 0, bd->renderResources.SamplerLinear, 0 },
870 };
871 WGPUBindGroupDescriptor common_bg_descriptor = {};
872 common_bg_descriptor.layout = bg_layouts[0];
873 common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
874 common_bg_descriptor.entries = common_bg_entries;
875 bd->renderResources.CommonBindGroupLinear = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
876 common_bg_entries[1].sampler = bd->renderResources.SamplerNearest;
877 bd->renderResources.CommonBindGroupNearest = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
878 bd->renderResources.ImageBindGroupLayout = bg_layouts[1];
879
880 SafeRelease(vertex_shader_desc.module);
881 SafeRelease(pixel_shader_desc.module);
882 SafeRelease(graphics_pipeline_desc.layout);
883 SafeRelease(bg_layouts[0]);
884
885 return true;
886}
887
888void ImGui_ImplWGPU_InvalidateDeviceObjects()
889{
890 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
891 if (!bd->wgpuDevice)
892 return;
893
894 SafeRelease(bd->pipelineState);
895 SafeRelease(bd->renderResources);
896
897 // Destroy all textures
898 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
899 if (tex->RefCount == 1)
900 ImGui_ImplWGPU_DestroyTexture(tex);
901
902 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
903 SafeRelease(bd->pFrameResources[i]);
904}
905
906bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
907{
908 ImGuiIO& io = ImGui::GetIO();
909 IMGUI_CHECKVERSION();
910 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
911
912 // Setup backend capabilities flags
913 ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
914 io.BackendRendererUserData = (void*)bd;
915#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
916#if defined(__EMSCRIPTEN__)
917 io.BackendRendererName = "imgui_impl_wgpu (Dawn, Emscripten)"; // compiled & linked using EMSCRIPTEN with "--use-port=emdawnwebgpu" flag
918#else
919 io.BackendRendererName = "imgui_impl_wgpu (Dawn, Native)";
920#endif
921#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
922 io.BackendRendererName = "imgui_impl_wgpu (WGPU, Native)";
923#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
924 io.BackendRendererName = "imgui_impl_wgpu (WGVK, Native)";
925#endif
926 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
927 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
928
929 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
930 platform_io.DrawCallback_ResetRenderState = ImGui_ImplWGPU_DrawCallback_ResetRenderState;
931 platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplWGPU_DrawCallback_SetSamplerLinear;
932 platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplWGPU_DrawCallback_SetSamplerNearest;
933
934 bd->initInfo = *init_info;
935 bd->wgpuDevice = init_info->Device;
936 bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
937 bd->renderTargetFormat = init_info->RenderTargetFormat;
938 bd->depthStencilFormat = init_info->DepthStencilFormat;
939 bd->numFramesInFlight = init_info->NumFramesInFlight;
940 bd->frameIndex = UINT_MAX;
941
942 bd->renderResources.ImageBindGroups.Data.reserve(100);
943
944 // Create buffers with a default size (they will later be grown as needed)
945 bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
946 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
947 {
948 FrameResources* fr = &bd->pFrameResources[i];
949 fr->IndexBuffer = nullptr;
950 fr->VertexBuffer = nullptr;
951 fr->IndexBufferHost = nullptr;
952 fr->VertexBufferHost = nullptr;
953 fr->IndexBufferSize = 10000;
954 fr->VertexBufferSize = 5000;
955 }
956
957 return true;
958}
959
960void ImGui_ImplWGPU_Shutdown()
961{
962 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
963 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
964 ImGuiIO& io = ImGui::GetIO();
965 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
966
967 ImGui_ImplWGPU_InvalidateDeviceObjects();
968 delete[] bd->pFrameResources;
969 bd->pFrameResources = nullptr;
970 wgpuQueueRelease(bd->defaultQueue);
971 bd->wgpuDevice = nullptr;
972 bd->numFramesInFlight = 0;
973 bd->frameIndex = UINT_MAX;
974
975 io.BackendRendererName = nullptr;
976 io.BackendRendererUserData = nullptr;
977 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
978 platform_io.ClearRendererHandlers();
979 IM_DELETE(bd);
980}
981
982void ImGui_ImplWGPU_NewFrame()
983{
984 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
985 if (!bd->pipelineState)
986 if (!ImGui_ImplWGPU_CreateDeviceObjects())
987 IM_ASSERT(0 && "ImGui_ImplWGPU_CreateDeviceObjects() failed!");
988}
989
990//-------------------------------------------------------------------------
991// Internal Helpers
992// Those are currently used by our example applications.
993//-------------------------------------------------------------------------
994
995bool ImGui_ImplWGPU_IsSurfaceStatusError(WGPUSurfaceGetCurrentTextureStatus status)
996{
997#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
998 return (status == WGPUSurfaceGetCurrentTextureStatus_Error);
999#else
1000 return (status == WGPUSurfaceGetCurrentTextureStatus_OutOfMemory || status == WGPUSurfaceGetCurrentTextureStatus_DeviceLost);
1001#endif
1002}
1003
1004bool ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(WGPUSurfaceGetCurrentTextureStatus status)
1005{
1006#if defined(__EMSCRIPTEN__) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
1007 return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost);
1008#else
1009 return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost || status == WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal);
1010#endif
1011}
1012
1013// Helpers to obtain a string
1014#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
1015const char* ImGui_ImplWGPU_GetErrorTypeName(WGPUErrorType type)
1016{
1017 switch (type)
1018 {
1019 case WGPUErrorType_Validation: return "Validation";
1020 case WGPUErrorType_OutOfMemory: return "OutOfMemory";
1021 case WGPUErrorType_Unknown: return "Unknown";
1022 case WGPUErrorType_Internal: return "Internal";
1023 default: return "Unknown";
1024 }
1025}
1026const char* ImGui_ImplWGPU_GetDeviceLostReasonName(WGPUDeviceLostReason type)
1027{
1028 switch (type)
1029 {
1030 case WGPUDeviceLostReason_Unknown: return "Unknown";
1031 case WGPUDeviceLostReason_Destroyed: return "Destroyed";
1032 case WGPUDeviceLostReason_CallbackCancelled: return "CallbackCancelled";
1033 case WGPUDeviceLostReason_FailedCreation: return "FailedCreation";
1034 default: return "Unknown";
1035 }
1036}
1037#elif !defined(__EMSCRIPTEN__)
1038const char* ImGui_ImplWGPU_GetLogLevelName(WGPULogLevel level)
1039{
1040 switch (level)
1041 {
1042 case WGPULogLevel_Error: return "Error";
1043 case WGPULogLevel_Warn: return "Warn";
1044 case WGPULogLevel_Info: return "Info";
1045 case WGPULogLevel_Debug: return "Debug";
1046 case WGPULogLevel_Trace: return "Trace";
1047 default: return "Unknown";
1048 }
1049}
1050#endif
1051
1052const char* ImGui_ImplWGPU_GetBackendTypeName(WGPUBackendType type)
1053{
1054 switch (type)
1055 {
1056 case WGPUBackendType_WebGPU: return "WebGPU";
1057 case WGPUBackendType_D3D11: return "D3D11";
1058 case WGPUBackendType_D3D12: return "D3D12";
1059 case WGPUBackendType_Metal: return "Metal";
1060 case WGPUBackendType_Vulkan: return "Vulkan";
1061 case WGPUBackendType_OpenGL: return "OpenGL";
1062 case WGPUBackendType_OpenGLES: return "OpenGLES";
1063 default: return "Unknown";
1064 }
1065}
1066
1067const char* ImGui_ImplWGPU_GetAdapterTypeName(WGPUAdapterType type)
1068{
1069 switch (type)
1070 {
1071 case WGPUAdapterType_DiscreteGPU: return "DiscreteGPU";
1072 case WGPUAdapterType_IntegratedGPU: return "IntegratedGPU";
1073 case WGPUAdapterType_CPU: return "CPU";
1074 default: return "Unknown";
1075 }
1076}
1077
1078void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter)
1079{
1080 WGPUAdapterInfo info = {};
1081 wgpuAdapterGetInfo(adapter, &info);
1082 printf("description: \"%.*s\"\n", (int)info.description.length, info.description.data);
1083 printf("vendor: \"%.*s\", vendorID: %x\n", (int)info.vendor.length, info.vendor.data, info.vendorID);
1084 printf("architecture: \"%.*s\"\n", (int) info.architecture.length, info.architecture.data);
1085 printf("device: \"%.*s\", deviceID: %x\n", (int)info.device.length, info.device.data, info.deviceID);
1086 printf("backendType: \"%s\"\n", ImGui_ImplWGPU_GetBackendTypeName(info.backendType));
1087 printf("adapterType: \"%s\"\n", ImGui_ImplWGPU_GetAdapterTypeName(info.adapterType));
1088 wgpuAdapterInfoFreeMembers(info);
1089}
1090
1091#ifndef __EMSCRIPTEN__
1092
1093#if defined(__APPLE__)
1094// MacOS specific: is necessary to compile with "-x objective-c++" flags
1095// (e.g. using cmake: set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") )
1096#include <TargetConditionals.h>
1097#if TARGET_OS_OSX
1098#include <Cocoa/Cocoa.h>
1099#include <QuartzCore/CAMetalLayer.h>
1100#endif
1101#endif
1102
1103WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info)
1104{
1105 WGPUSurfaceDescriptor surface_descriptor = {};
1106 WGPUSurface surface = {};
1107#if defined(__APPLE__) && TARGET_OS_OSX
1108 if (strcmp(info->System, "cocoa") == 0)
1109 {
1110 IM_ASSERT(info->RawWindow != nullptr);
1111 NSWindow* ns_window = (NSWindow*)info->RawWindow;
1112 id metal_layer = [CAMetalLayer layer];
1113 [ns_window.contentView setWantsLayer : YES] ;
1114 [ns_window.contentView setLayer : metal_layer] ;
1115 WGPUSurfaceSourceMetalLayer surface_src_metal = {};
1116 surface_src_metal.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
1117 surface_src_metal.layer = metal_layer;
1118 surface_descriptor.nextInChain = &surface_src_metal.chain;
1119 surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
1120 }
1121#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
1122 if (strcmp(info->System, "wayland") == 0)
1123 {
1124 IM_ASSERT(info->RawDisplay != nullptr && info->RawSurface != nullptr);
1125 WGPUSurfaceSourceWaylandSurface surface_src_wayland = {};
1126 surface_src_wayland.chain.sType = WGPUSType_SurfaceSourceWaylandSurface;
1127 surface_src_wayland.display = info->RawDisplay;
1128 surface_src_wayland.surface = info->RawSurface;
1129 surface_descriptor.nextInChain = &surface_src_wayland.chain;
1130 surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
1131 }
1132 else if (strcmp(info->System, "x11") == 0)
1133 {
1134 IM_ASSERT(info->RawDisplay != nullptr && info->RawWindow != nullptr);
1135 WGPUSurfaceSourceXlibWindow surface_src_xlib = {};
1136 surface_src_xlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow;
1137 surface_src_xlib.display = info->RawDisplay;
1138 surface_src_xlib.window = (uint64_t)info->RawWindow;
1139 surface_descriptor.nextInChain = &surface_src_xlib.chain;
1140 surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
1141 }
1142#elif defined(_WIN32)
1143 if (strcmp(info->System, "win32") == 0)
1144 {
1145 IM_ASSERT(info->RawWindow != nullptr && info->RawInstance != nullptr);
1146 WGPUSurfaceSourceWindowsHWND surface_src_hwnd = {};
1147 surface_src_hwnd.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
1148 surface_src_hwnd.hinstance = info->RawInstance;
1149 surface_src_hwnd.hwnd = info->RawWindow;
1150 surface_descriptor.nextInChain = &surface_src_hwnd.chain;
1151 surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
1152 }
1153#else
1154 IM_ASSERT(0 && "Unsupported WebGPU native platform!");
1155#endif
1156 return surface;
1157}
1158#endif // #ifndef __EMSCRIPTEN__
1159
1160//-----------------------------------------------------------------------------
1161
1162#endif // #ifndef IMGUI_DISABLE