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