imgui_impl_wgpu.cpp 35 KB

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