• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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!
7 //  [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
8 
9 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
12 // Read online: https://github.com/ocornut/imgui/tree/master/docs
13 
14 // CHANGELOG
15 // (minor and older changes stripped away, please see git history for details)
16 //  2021-08-24: Fix for latest specs.
17 //  2021-05-24: Add support for draw_data->FramebufferScale.
18 //  2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
19 //  2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
20 //  2021-02-18: Change blending equation to preserve alpha in output buffer.
21 //  2021-01-28: Initial version.
22 
23 #include "imgui.h"
24 #include "imgui_impl_wgpu.h"
25 #include <limits.h>
26 #include <webgpu/webgpu.h>
27 
28 #define HAS_EMSCRIPTEN_VERSION(major, minor, tiny) (__EMSCRIPTEN_major__ > (major) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ > (minor)) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ == (minor) && __EMSCRIPTEN_tiny__ >= (tiny)))
29 
30 #if defined(__EMSCRIPTEN__) && !HAS_EMSCRIPTEN_VERSION(2, 0, 20)
31 #error "Requires at least emscripten 2.0.20"
32 #endif
33 
34 // Dear ImGui prototypes from imgui_internal.h
35 extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0);
36 
37 // WebGPU data
38 static WGPUDevice               g_wgpuDevice = NULL;
39 static WGPUQueue                g_defaultQueue = NULL;
40 static WGPUTextureFormat        g_renderTargetFormat = WGPUTextureFormat_Undefined;
41 static WGPURenderPipeline       g_pipelineState = NULL;
42 
43 struct RenderResources
44 {
45     WGPUTexture         FontTexture;            // Font texture
46     WGPUTextureView     FontTextureView;        // Texture view for font texture
47     WGPUSampler         Sampler;                // Sampler for the font texture
48     WGPUBuffer          Uniforms;               // Shader uniforms
49     WGPUBindGroup       CommonBindGroup;        // Resources bind-group to bind the common resources to pipeline
50     ImGuiStorage        ImageBindGroups;        // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
51     WGPUBindGroup       ImageBindGroup;         // Default font-resource of Dear ImGui
52     WGPUBindGroupLayout ImageBindGroupLayout;   // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
53 };
54 static RenderResources  g_resources;
55 
56 struct FrameResources
57 {
58     WGPUBuffer  IndexBuffer;
59     WGPUBuffer  VertexBuffer;
60     ImDrawIdx*  IndexBufferHost;
61     ImDrawVert* VertexBufferHost;
62     int         IndexBufferSize;
63     int         VertexBufferSize;
64 };
65 static FrameResources*  g_pFrameResources = NULL;
66 static unsigned int     g_numFramesInFlight = 0;
67 static unsigned int     g_frameIndex = UINT_MAX;
68 
69 struct Uniforms
70 {
71     float MVP[4][4];
72 };
73 
74 //-----------------------------------------------------------------------------
75 // SHADERS
76 //-----------------------------------------------------------------------------
77 
78 // glsl_shader.vert, compiled with:
79 // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
80 /*
81 #version 450 core
82 layout(location = 0) in vec2 aPos;
83 layout(location = 1) in vec2 aUV;
84 layout(location = 2) in vec4 aColor;
85 layout(set=0, binding = 0) uniform transform { mat4 mvp; };
86 
87 out gl_PerVertex { vec4 gl_Position; };
88 layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
89 
90 void main()
91 {
92     Out.Color = aColor;
93     Out.UV = aUV;
94     gl_Position = mvp * vec4(aPos, 0, 1);
95 }
96 */
97 static uint32_t __glsl_shader_vert_spv[] =
98 {
99     0x07230203,0x00010000,0x00080007,0x0000002c,0x00000000,0x00020011,0x00000001,0x0006000b,
100     0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
101     0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
102     0x0000001b,0x00000023,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
103     0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
104     0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
105     0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
106     0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
107     0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00050005,0x0000001d,
108     0x6e617274,0x726f6673,0x0000006d,0x00040006,0x0000001d,0x00000000,0x0070766d,0x00030005,
109     0x0000001f,0x00000000,0x00040005,0x00000023,0x736f5061,0x00000000,0x00040047,0x0000000b,
110     0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
111     0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
112     0x00000019,0x00000002,0x00040048,0x0000001d,0x00000000,0x00000005,0x00050048,0x0000001d,
113     0x00000000,0x00000023,0x00000000,0x00050048,0x0000001d,0x00000000,0x00000007,0x00000010,
114     0x00030047,0x0000001d,0x00000002,0x00040047,0x0000001f,0x00000022,0x00000000,0x00040047,
115     0x0000001f,0x00000021,0x00000000,0x00040047,0x00000023,0x0000001e,0x00000000,0x00020013,
116     0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,
117     0x00000007,0x00000006,0x00000004,0x00040017,0x00000008,0x00000006,0x00000002,0x0004001e,
118     0x00000009,0x00000007,0x00000008,0x00040020,0x0000000a,0x00000003,0x00000009,0x0004003b,
119     0x0000000a,0x0000000b,0x00000003,0x00040015,0x0000000c,0x00000020,0x00000001,0x0004002b,
120     0x0000000c,0x0000000d,0x00000000,0x00040020,0x0000000e,0x00000001,0x00000007,0x0004003b,
121     0x0000000e,0x0000000f,0x00000001,0x00040020,0x00000011,0x00000003,0x00000007,0x0004002b,
122     0x0000000c,0x00000013,0x00000001,0x00040020,0x00000014,0x00000001,0x00000008,0x0004003b,
123     0x00000014,0x00000015,0x00000001,0x00040020,0x00000017,0x00000003,0x00000008,0x0003001e,
124     0x00000019,0x00000007,0x00040020,0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,
125     0x0000001b,0x00000003,0x00040018,0x0000001c,0x00000007,0x00000004,0x0003001e,0x0000001d,
126     0x0000001c,0x00040020,0x0000001e,0x00000002,0x0000001d,0x0004003b,0x0000001e,0x0000001f,
127     0x00000002,0x00040020,0x00000020,0x00000002,0x0000001c,0x0004003b,0x00000014,0x00000023,
128     0x00000001,0x0004002b,0x00000006,0x00000025,0x00000000,0x0004002b,0x00000006,0x00000026,
129     0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
130     0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,0x0000000b,
131     0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,0x00000015,
132     0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,0x00000016,
133     0x00050041,0x00000020,0x00000021,0x0000001f,0x0000000d,0x0004003d,0x0000001c,0x00000022,
134     0x00000021,0x0004003d,0x00000008,0x00000024,0x00000023,0x00050051,0x00000006,0x00000027,
135     0x00000024,0x00000000,0x00050051,0x00000006,0x00000028,0x00000024,0x00000001,0x00070050,
136     0x00000007,0x00000029,0x00000027,0x00000028,0x00000025,0x00000026,0x00050091,0x00000007,
137     0x0000002a,0x00000022,0x00000029,0x00050041,0x00000011,0x0000002b,0x0000001b,0x0000000d,
138     0x0003003e,0x0000002b,0x0000002a,0x000100fd,0x00010038
139 };
140 
141 // glsl_shader.frag, compiled with:
142 // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
143 /*
144 #version 450 core
145 layout(location = 0) out vec4 fColor;
146 layout(set=0, binding=1) uniform sampler s;
147 layout(set=1, binding=0) uniform texture2D t;
148 layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
149 void main()
150 {
151     fColor = In.Color * texture(sampler2D(t, s), In.UV.st);
152 }
153 */
154 static uint32_t __glsl_shader_frag_spv[] =
155 {
156     0x07230203,0x00010000,0x00080007,0x00000023,0x00000000,0x00020011,0x00000001,0x0006000b,
157     0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
158     0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
159     0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
160     0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
161     0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
162     0x00005655,0x00030005,0x0000000d,0x00006e49,0x00030005,0x00000015,0x00000074,0x00030005,
163     0x00000019,0x00000073,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,
164     0x0000001e,0x00000000,0x00040047,0x00000015,0x00000022,0x00000001,0x00040047,0x00000015,
165     0x00000021,0x00000000,0x00040047,0x00000019,0x00000022,0x00000000,0x00040047,0x00000019,
166     0x00000021,0x00000001,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,
167     0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,
168     0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,
169     0x00000006,0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,
170     0x00000001,0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,
171     0x00000020,0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,
172     0x00000001,0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,
173     0x00000000,0x00000001,0x00000000,0x00040020,0x00000014,0x00000000,0x00000013,0x0004003b,
174     0x00000014,0x00000015,0x00000000,0x0002001a,0x00000017,0x00040020,0x00000018,0x00000000,
175     0x00000017,0x0004003b,0x00000018,0x00000019,0x00000000,0x0003001b,0x0000001b,0x00000013,
176     0x0004002b,0x0000000e,0x0000001d,0x00000001,0x00040020,0x0000001e,0x00000001,0x0000000a,
177     0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,
178     0x00000010,0x00000011,0x0000000d,0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,
179     0x0004003d,0x00000013,0x00000016,0x00000015,0x0004003d,0x00000017,0x0000001a,0x00000019,
180     0x00050056,0x0000001b,0x0000001c,0x00000016,0x0000001a,0x00050041,0x0000001e,0x0000001f,
181     0x0000000d,0x0000001d,0x0004003d,0x0000000a,0x00000020,0x0000001f,0x00050057,0x00000007,
182     0x00000021,0x0000001c,0x00000020,0x00050085,0x00000007,0x00000022,0x00000012,0x00000021,
183     0x0003003e,0x00000009,0x00000022,0x000100fd,0x00010038
184 };
185 
SafeRelease(ImDrawIdx * & res)186 static void SafeRelease(ImDrawIdx*& res)
187 {
188     if (res)
189         delete[] res;
190     res = NULL;
191 }
SafeRelease(ImDrawVert * & res)192 static void SafeRelease(ImDrawVert*& res)
193 {
194     if (res)
195         delete[] res;
196     res = NULL;
197 }
SafeRelease(WGPUBindGroupLayout & res)198 static void SafeRelease(WGPUBindGroupLayout& res)
199 {
200     if (res)
201         wgpuBindGroupLayoutRelease(res);
202     res = NULL;
203 }
SafeRelease(WGPUBindGroup & res)204 static void SafeRelease(WGPUBindGroup& res)
205 {
206     if (res)
207         wgpuBindGroupRelease(res);
208     res = NULL;
209 }
SafeRelease(WGPUBuffer & res)210 static void SafeRelease(WGPUBuffer& res)
211 {
212     if (res)
213         wgpuBufferRelease(res);
214     res = NULL;
215 }
SafeRelease(WGPURenderPipeline & res)216 static void SafeRelease(WGPURenderPipeline& res)
217 {
218     if (res)
219         wgpuRenderPipelineRelease(res);
220     res = NULL;
221 }
SafeRelease(WGPUSampler & res)222 static void SafeRelease(WGPUSampler& res)
223 {
224     if (res)
225         wgpuSamplerRelease(res);
226     res = NULL;
227 }
SafeRelease(WGPUShaderModule & res)228 static void SafeRelease(WGPUShaderModule& res)
229 {
230     if (res)
231         wgpuShaderModuleRelease(res);
232     res = NULL;
233 }
SafeRelease(WGPUTextureView & res)234 static void SafeRelease(WGPUTextureView& res)
235 {
236     if (res)
237         wgpuTextureViewRelease(res);
238     res = NULL;
239 }
SafeRelease(WGPUTexture & res)240 static void SafeRelease(WGPUTexture& res)
241 {
242     if (res)
243         wgpuTextureRelease(res);
244     res = NULL;
245 }
246 
SafeRelease(RenderResources & res)247 static void SafeRelease(RenderResources& res)
248 {
249     SafeRelease(res.FontTexture);
250     SafeRelease(res.FontTextureView);
251     SafeRelease(res.Sampler);
252     SafeRelease(res.Uniforms);
253     SafeRelease(res.CommonBindGroup);
254     SafeRelease(res.ImageBindGroup);
255     SafeRelease(res.ImageBindGroupLayout);
256 };
257 
SafeRelease(FrameResources & res)258 static void SafeRelease(FrameResources& res)
259 {
260     SafeRelease(res.IndexBuffer);
261     SafeRelease(res.VertexBuffer);
262     SafeRelease(res.IndexBufferHost);
263     SafeRelease(res.VertexBufferHost);
264 }
265 
ImGui_ImplWGPU_CreateShaderModule(uint32_t * binary_data,uint32_t binary_data_size)266 static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(uint32_t* binary_data, uint32_t binary_data_size)
267 {
268     WGPUShaderModuleSPIRVDescriptor spirv_desc = {};
269     spirv_desc.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor;
270     spirv_desc.codeSize = binary_data_size;
271     spirv_desc.code = binary_data;
272 
273     WGPUShaderModuleDescriptor desc = {};
274     desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&spirv_desc);
275 
276     WGPUProgrammableStageDescriptor stage_desc = {};
277     stage_desc.module = wgpuDeviceCreateShaderModule(g_wgpuDevice, &desc);
278     stage_desc.entryPoint = "main";
279     return stage_desc;
280 }
281 
ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout,WGPUTextureView texture)282 static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
283 {
284     WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
285 
286     WGPUBindGroupDescriptor image_bg_descriptor = {};
287     image_bg_descriptor.layout = layout;
288     image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
289     image_bg_descriptor.entries = image_bg_entries;
290     return wgpuDeviceCreateBindGroup(g_wgpuDevice, &image_bg_descriptor);
291 }
292 
ImGui_ImplWGPU_SetupRenderState(ImDrawData * draw_data,WGPURenderPassEncoder ctx,FrameResources * fr)293 static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
294 {
295     // Setup orthographic projection matrix into our constant buffer
296     // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
297     {
298         float L = draw_data->DisplayPos.x;
299         float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
300         float T = draw_data->DisplayPos.y;
301         float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
302         float mvp[4][4] =
303         {
304             { 2.0f/(R-L),   0.0f,           0.0f,       0.0f },
305             { 0.0f,         2.0f/(T-B),     0.0f,       0.0f },
306             { 0.0f,         0.0f,           0.5f,       0.0f },
307             { (R+L)/(L-R),  (T+B)/(B-T),    0.5f,       1.0f },
308         };
309         wgpuQueueWriteBuffer(g_defaultQueue, g_resources.Uniforms, 0, mvp, sizeof(mvp));
310     }
311 
312     // Setup viewport
313     wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
314 
315     // Bind shader and vertex buffers
316     wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, 0);
317     wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, 0);
318     wgpuRenderPassEncoderSetPipeline(ctx, g_pipelineState);
319     wgpuRenderPassEncoderSetBindGroup(ctx, 0, g_resources.CommonBindGroup, 0, NULL);
320 
321     // Setup blend factor
322     WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
323     wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
324 }
325 
326 // Render function
327 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
ImGui_ImplWGPU_RenderDrawData(ImDrawData * draw_data,WGPURenderPassEncoder pass_encoder)328 void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
329 {
330     // Avoid rendering when minimized
331     if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
332         return;
333 
334     // FIXME: Assuming that this only gets called once per frame!
335     // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
336     g_frameIndex = g_frameIndex + 1;
337     FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
338 
339     // Create and grow vertex/index buffers if needed
340     if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
341     {
342         if (fr->VertexBuffer)
343         {
344             wgpuBufferDestroy(fr->VertexBuffer);
345             wgpuBufferRelease(fr->VertexBuffer);
346         }
347         SafeRelease(fr->VertexBufferHost);
348         fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
349 
350         WGPUBufferDescriptor vb_desc =
351         {
352             NULL,
353             "Dear ImGui Vertex buffer",
354             WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
355             fr->VertexBufferSize * sizeof(ImDrawVert),
356             false
357         };
358         fr->VertexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &vb_desc);
359         if (!fr->VertexBuffer)
360             return;
361 
362         fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
363     }
364     if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
365     {
366         if (fr->IndexBuffer)
367         {
368             wgpuBufferDestroy(fr->IndexBuffer);
369             wgpuBufferRelease(fr->IndexBuffer);
370         }
371         SafeRelease(fr->IndexBufferHost);
372         fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
373 
374         WGPUBufferDescriptor ib_desc =
375         {
376             NULL,
377             "Dear ImGui Index buffer",
378             WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
379             fr->IndexBufferSize * sizeof(ImDrawIdx),
380             false
381         };
382         fr->IndexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &ib_desc);
383         if (!fr->IndexBuffer)
384             return;
385 
386         fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
387     }
388 
389     // Upload vertex/index data into a single contiguous GPU buffer
390     ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
391     ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
392     for (int n = 0; n < draw_data->CmdListsCount; n++)
393     {
394         const ImDrawList* cmd_list = draw_data->CmdLists[n];
395         memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
396         memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
397         vtx_dst += cmd_list->VtxBuffer.Size;
398         idx_dst += cmd_list->IdxBuffer.Size;
399     }
400     int64_t vb_write_size = ((char*)vtx_dst - (char*)fr->VertexBufferHost + 3) & ~3;
401     int64_t ib_write_size = ((char*)idx_dst - (char*)fr->IndexBufferHost  + 3) & ~3;
402     wgpuQueueWriteBuffer(g_defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
403     wgpuQueueWriteBuffer(g_defaultQueue, fr->IndexBuffer,  0, fr->IndexBufferHost,  ib_write_size);
404 
405     // Setup desired render state
406     ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
407 
408     // Render command lists
409     // (Because we merged all buffers into a single one, we maintain our own offset into them)
410     int global_vtx_offset = 0;
411     int global_idx_offset = 0;
412     ImVec2 clip_scale = draw_data->FramebufferScale;
413     ImVec2 clip_off = draw_data->DisplayPos;
414     for (int n = 0; n < draw_data->CmdListsCount; n++)
415     {
416         const ImDrawList* cmd_list = draw_data->CmdLists[n];
417         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
418         {
419             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
420             if (pcmd->UserCallback != NULL)
421             {
422                 // User callback, registered via ImDrawList::AddCallback()
423                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
424                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
425                     ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
426                 else
427                     pcmd->UserCallback(cmd_list, pcmd);
428             }
429             else
430             {
431                 // Bind custom texture
432                 ImTextureID tex_id = pcmd->GetTexID();
433                 ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
434                 auto bind_group = g_resources.ImageBindGroups.GetVoidPtr(tex_id_hash);
435                 if (bind_group)
436                 {
437                     wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, NULL);
438                 }
439                 else
440                 {
441                     WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(g_resources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
442                     g_resources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
443                     wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, NULL);
444                 }
445 
446                 // Project scissor/clipping rectangles into framebuffer space
447                 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
448                 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
449                 if (clip_max.x < clip_min.x || clip_max.y < clip_min.y)
450                     continue;
451 
452                 // Apply scissor/clipping rectangle, Draw
453                 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));
454                 wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
455             }
456         }
457         global_idx_offset += cmd_list->IdxBuffer.Size;
458         global_vtx_offset += cmd_list->VtxBuffer.Size;
459     }
460 }
461 
ImGui_ImplWGPU_CreateFontsTexture()462 static void ImGui_ImplWGPU_CreateFontsTexture()
463 {
464     // Build texture atlas
465     ImGuiIO& io = ImGui::GetIO();
466     unsigned char* pixels;
467     int width, height, size_pp;
468     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
469 
470     // Upload texture to graphics system
471     {
472         WGPUTextureDescriptor tex_desc = {};
473         tex_desc.label = "Dear ImGui Font Texture";
474         tex_desc.dimension = WGPUTextureDimension_2D;
475         tex_desc.size.width = width;
476         tex_desc.size.height = height;
477         tex_desc.size.depthOrArrayLayers = 1;
478         tex_desc.sampleCount = 1;
479         tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
480         tex_desc.mipLevelCount = 1;
481         tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
482         g_resources.FontTexture = wgpuDeviceCreateTexture(g_wgpuDevice, &tex_desc);
483 
484         WGPUTextureViewDescriptor tex_view_desc = {};
485         tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
486         tex_view_desc.dimension = WGPUTextureViewDimension_2D;
487         tex_view_desc.baseMipLevel = 0;
488         tex_view_desc.mipLevelCount = 1;
489         tex_view_desc.baseArrayLayer = 0;
490         tex_view_desc.arrayLayerCount = 1;
491         tex_view_desc.aspect = WGPUTextureAspect_All;
492         g_resources.FontTextureView = wgpuTextureCreateView(g_resources.FontTexture, &tex_view_desc);
493     }
494 
495     // Upload texture data
496     {
497         WGPUImageCopyTexture dst_view = {};
498         dst_view.texture = g_resources.FontTexture;
499         dst_view.mipLevel = 0;
500         dst_view.origin = { 0, 0, 0 };
501         dst_view.aspect = WGPUTextureAspect_All;
502         WGPUTextureDataLayout layout = {};
503         layout.offset = 0;
504         layout.bytesPerRow = width * size_pp;
505         layout.rowsPerImage = height;
506         WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 };
507         wgpuQueueWriteTexture(g_defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
508     }
509 
510     // Create the associated sampler
511     {
512         WGPUSamplerDescriptor sampler_desc = {};
513         sampler_desc.minFilter = WGPUFilterMode_Linear;
514         sampler_desc.magFilter = WGPUFilterMode_Linear;
515         sampler_desc.mipmapFilter = WGPUFilterMode_Linear;
516         sampler_desc.addressModeU = WGPUAddressMode_Repeat;
517         sampler_desc.addressModeV = WGPUAddressMode_Repeat;
518         sampler_desc.addressModeW = WGPUAddressMode_Repeat;
519         sampler_desc.maxAnisotropy = 1;
520         g_resources.Sampler = wgpuDeviceCreateSampler(g_wgpuDevice, &sampler_desc);
521     }
522 
523     // Store our identifier
524     static_assert(sizeof(ImTextureID) >= sizeof(g_resources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
525     io.Fonts->SetTexID((ImTextureID)g_resources.FontTextureView);
526 }
527 
ImGui_ImplWGPU_CreateUniformBuffer()528 static void ImGui_ImplWGPU_CreateUniformBuffer()
529 {
530     WGPUBufferDescriptor ub_desc =
531     {
532         NULL,
533         "Dear ImGui Uniform buffer",
534         WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
535         sizeof(Uniforms),
536         false
537     };
538     g_resources.Uniforms = wgpuDeviceCreateBuffer(g_wgpuDevice, &ub_desc);
539 }
540 
ImGui_ImplWGPU_CreateDeviceObjects()541 bool ImGui_ImplWGPU_CreateDeviceObjects()
542 {
543     if (!g_wgpuDevice)
544         return false;
545     if (g_pipelineState)
546         ImGui_ImplWGPU_InvalidateDeviceObjects();
547 
548     // Create render pipeline
549     WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
550     graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
551     graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
552     graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
553     graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
554     graphics_pipeline_desc.multisample.count = 1;
555     graphics_pipeline_desc.multisample.mask = UINT_MAX;
556     graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false;
557     graphics_pipeline_desc.layout = nullptr; // Use automatic layout generation
558 
559     // Create the vertex shader
560     WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_vert_spv, sizeof(__glsl_shader_vert_spv) / sizeof(uint32_t));
561     graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
562     graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
563 
564     // Vertex input configuration
565     WGPUVertexAttribute attribute_desc[] =
566     {
567         { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 },
568         { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv),  1 },
569         { WGPUVertexFormat_Unorm8x4,  (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 },
570     };
571 
572     WGPUVertexBufferLayout buffer_layouts[1];
573     buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
574     buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
575     buffer_layouts[0].attributeCount = 3;
576     buffer_layouts[0].attributes = attribute_desc;
577 
578     graphics_pipeline_desc.vertex.bufferCount = 1;
579     graphics_pipeline_desc.vertex.buffers = buffer_layouts;
580 
581     // Create the pixel shader
582     WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_frag_spv, sizeof(__glsl_shader_frag_spv) / sizeof(uint32_t));
583 
584     // Create the blending setup
585     WGPUBlendState blend_state = {};
586     blend_state.alpha.operation = WGPUBlendOperation_Add;
587     blend_state.alpha.srcFactor = WGPUBlendFactor_One;
588     blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
589     blend_state.color.operation = WGPUBlendOperation_Add;
590     blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
591     blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
592 
593     WGPUColorTargetState color_state = {};
594     color_state.format = g_renderTargetFormat;
595     color_state.blend = &blend_state;
596     color_state.writeMask = WGPUColorWriteMask_All;
597 
598     WGPUFragmentState fragment_state = {};
599     fragment_state.module = pixel_shader_desc.module;
600     fragment_state.entryPoint = pixel_shader_desc.entryPoint;
601     fragment_state.targetCount = 1;
602     fragment_state.targets = &color_state;
603 
604     graphics_pipeline_desc.fragment = &fragment_state;
605 
606     // Create depth-stencil State
607     WGPUDepthStencilState depth_stencil_state = {};
608     depth_stencil_state.depthBias = 0;
609     depth_stencil_state.depthBiasClamp = 0;
610     depth_stencil_state.depthBiasSlopeScale = 0;
611 
612     // Configure disabled depth-stencil state
613     graphics_pipeline_desc.depthStencil = nullptr;
614 
615     g_pipelineState = wgpuDeviceCreateRenderPipeline(g_wgpuDevice, &graphics_pipeline_desc);
616 
617     ImGui_ImplWGPU_CreateFontsTexture();
618     ImGui_ImplWGPU_CreateUniformBuffer();
619 
620     // Create resource bind group
621     WGPUBindGroupLayout bg_layouts[2];
622     bg_layouts[0] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 0);
623     bg_layouts[1] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 1);
624 
625     WGPUBindGroupEntry common_bg_entries[] =
626     {
627         { nullptr, 0, g_resources.Uniforms, 0, sizeof(Uniforms), 0, 0 },
628         { nullptr, 1, 0, 0, 0, g_resources.Sampler, 0 },
629     };
630 
631     WGPUBindGroupDescriptor common_bg_descriptor = {};
632     common_bg_descriptor.layout = bg_layouts[0];
633     common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
634     common_bg_descriptor.entries = common_bg_entries;
635     g_resources.CommonBindGroup = wgpuDeviceCreateBindGroup(g_wgpuDevice, &common_bg_descriptor);
636 
637     WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], g_resources.FontTextureView);
638     g_resources.ImageBindGroup = image_bind_group;
639     g_resources.ImageBindGroupLayout = bg_layouts[1];
640     g_resources.ImageBindGroups.SetVoidPtr(ImHashData(&g_resources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
641 
642     SafeRelease(vertex_shader_desc.module);
643     SafeRelease(pixel_shader_desc.module);
644     SafeRelease(bg_layouts[0]);
645 
646     return true;
647 }
648 
ImGui_ImplWGPU_InvalidateDeviceObjects()649 void ImGui_ImplWGPU_InvalidateDeviceObjects()
650 {
651     if (!g_wgpuDevice)
652         return;
653 
654     SafeRelease(g_pipelineState);
655     SafeRelease(g_resources);
656 
657     ImGuiIO& io = ImGui::GetIO();
658     io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
659 
660     for (unsigned int i = 0; i < g_numFramesInFlight; i++)
661         SafeRelease(g_pFrameResources[i]);
662 }
663 
ImGui_ImplWGPU_Init(WGPUDevice device,int num_frames_in_flight,WGPUTextureFormat rt_format)664 bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format)
665 {
666     // Setup backend capabilities flags
667     ImGuiIO& io = ImGui::GetIO();
668     io.BackendRendererName = "imgui_impl_webgpu";
669     io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
670 
671     g_wgpuDevice = device;
672     g_defaultQueue = wgpuDeviceGetQueue(g_wgpuDevice);
673     g_renderTargetFormat = rt_format;
674     g_pFrameResources = new FrameResources[num_frames_in_flight];
675     g_numFramesInFlight = num_frames_in_flight;
676     g_frameIndex = UINT_MAX;
677 
678     g_resources.FontTexture = NULL;
679     g_resources.FontTextureView = NULL;
680     g_resources.Sampler = NULL;
681     g_resources.Uniforms = NULL;
682     g_resources.CommonBindGroup = NULL;
683     g_resources.ImageBindGroups.Data.reserve(100);
684     g_resources.ImageBindGroup = NULL;
685     g_resources.ImageBindGroupLayout = NULL;
686 
687     // Create buffers with a default size (they will later be grown as needed)
688     for (int i = 0; i < num_frames_in_flight; i++)
689     {
690         FrameResources* fr = &g_pFrameResources[i];
691         fr->IndexBuffer = NULL;
692         fr->VertexBuffer = NULL;
693         fr->IndexBufferHost = NULL;
694         fr->VertexBufferHost = NULL;
695         fr->IndexBufferSize = 10000;
696         fr->VertexBufferSize = 5000;
697     }
698 
699     return true;
700 }
701 
ImGui_ImplWGPU_Shutdown()702 void ImGui_ImplWGPU_Shutdown()
703 {
704     ImGui_ImplWGPU_InvalidateDeviceObjects();
705     delete[] g_pFrameResources;
706     g_pFrameResources = NULL;
707     wgpuQueueRelease(g_defaultQueue);
708     g_wgpuDevice = NULL;
709     g_numFramesInFlight = 0;
710     g_frameIndex = UINT_MAX;
711 }
712 
ImGui_ImplWGPU_NewFrame()713 void ImGui_ImplWGPU_NewFrame()
714 {
715     if (!g_pipelineState)
716         ImGui_ImplWGPU_CreateDeviceObjects();
717 }
718