imgui_impl_wgpu.cpp 33 KB

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