imgui_impl_wgpu.cpp 31 KB

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