imgui_impl_wgpu.cpp 39 KB

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