imgui_impl_wgpu.cpp 34 KB

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