imgui_impl_wgpu.cpp 35 KB

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