imgui_impl_wgpu.cpp 46 KB

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