imgui_impl_wgpu.cpp 31 KB

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