imgui_impl_wgpu.cpp 32 KB

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