imgui_impl_wgpu.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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 copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  8. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  9. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  10. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  13. // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
  14. // 2021-02-18: Change blending equation to preserve alpha in output buffer.
  15. // 2021-01-28: Initial version.
  16. #include "imgui.h"
  17. #include "imgui_impl_wgpu.h"
  18. #include <limits.h>
  19. #include <webgpu/webgpu.h>
  20. #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)))
  21. #if defined(__EMSCRIPTEN__) && !HAS_EMSCRIPTEN_VERSION(2, 0, 20)
  22. #error "Requires at least emscripten 2.0.20"
  23. #endif
  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[] = { { 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->DisplaySize.x, draw_data->DisplaySize.y, 0, 1);
  285. // Bind shader and vertex buffers
  286. wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, 0);
  287. wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, 0);
  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_off = draw_data->DisplayPos;
  372. for (int n = 0; n < draw_data->CmdListsCount; n++)
  373. {
  374. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  375. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  376. {
  377. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  378. if (pcmd->UserCallback != NULL)
  379. {
  380. // User callback, registered via ImDrawList::AddCallback()
  381. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  382. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  383. ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
  384. else
  385. pcmd->UserCallback(cmd_list, pcmd);
  386. }
  387. else
  388. {
  389. // Bind custom texture
  390. ImTextureID tex_id = pcmd->GetTexID();
  391. ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
  392. auto bind_group = g_resources.ImageBindGroups.GetVoidPtr(tex_id_hash);
  393. if (bind_group)
  394. {
  395. wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, NULL);
  396. }
  397. else
  398. {
  399. WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(g_resources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
  400. g_resources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
  401. wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, NULL);
  402. }
  403. // Apply Scissor, Bind texture, Draw
  404. uint32_t clip_rect[4];
  405. clip_rect[0] = static_cast<uint32_t>(pcmd->ClipRect.x - clip_off.x);
  406. clip_rect[1] = static_cast<uint32_t>(pcmd->ClipRect.y - clip_off.y);
  407. clip_rect[2] = static_cast<uint32_t>(pcmd->ClipRect.z - clip_off.x);
  408. clip_rect[3] = static_cast<uint32_t>(pcmd->ClipRect.w - clip_off.y);
  409. wgpuRenderPassEncoderSetScissorRect(pass_encoder, clip_rect[0], clip_rect[1], clip_rect[2] - clip_rect[0], clip_rect[3] - clip_rect[1]);
  410. wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  411. }
  412. }
  413. global_idx_offset += cmd_list->IdxBuffer.Size;
  414. global_vtx_offset += cmd_list->VtxBuffer.Size;
  415. }
  416. }
  417. static void ImGui_ImplWGPU_CreateFontsTexture()
  418. {
  419. // Build texture atlas
  420. ImGuiIO& io = ImGui::GetIO();
  421. unsigned char* pixels;
  422. int width, height, size_pp;
  423. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
  424. // Upload texture to graphics system
  425. {
  426. WGPUTextureDescriptor tex_desc = {};
  427. tex_desc.label = "Dear ImGui Font Texture";
  428. tex_desc.dimension = WGPUTextureDimension_2D;
  429. tex_desc.size.width = width;
  430. tex_desc.size.height = height;
  431. tex_desc.size.depthOrArrayLayers = 1;
  432. tex_desc.sampleCount = 1;
  433. tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
  434. tex_desc.mipLevelCount = 1;
  435. tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_Sampled;
  436. g_resources.FontTexture = wgpuDeviceCreateTexture(g_wgpuDevice, &tex_desc);
  437. WGPUTextureViewDescriptor tex_view_desc = {};
  438. tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
  439. tex_view_desc.dimension = WGPUTextureViewDimension_2D;
  440. tex_view_desc.baseMipLevel = 0;
  441. tex_view_desc.mipLevelCount = 1;
  442. tex_view_desc.baseArrayLayer = 0;
  443. tex_view_desc.arrayLayerCount = 1;
  444. tex_view_desc.aspect = WGPUTextureAspect_All;
  445. g_resources.FontTextureView = wgpuTextureCreateView(g_resources.FontTexture, &tex_view_desc);
  446. }
  447. // Upload texture data
  448. {
  449. WGPUImageCopyTexture dst_view = {};
  450. dst_view.texture = g_resources.FontTexture;
  451. dst_view.mipLevel = 0;
  452. dst_view.origin = { 0, 0, 0 };
  453. dst_view.aspect = WGPUTextureAspect_All;
  454. WGPUTextureDataLayout layout = {};
  455. layout.offset = 0;
  456. layout.bytesPerRow = width * size_pp;
  457. layout.rowsPerImage = height;
  458. WGPUExtent3D size = { static_cast<uint32_t>(width), static_cast<uint32_t>(height), 1 };
  459. wgpuQueueWriteTexture(g_defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
  460. }
  461. // Create the associated sampler
  462. {
  463. WGPUSamplerDescriptor sampler_desc = {};
  464. sampler_desc.minFilter = WGPUFilterMode_Linear;
  465. sampler_desc.magFilter = WGPUFilterMode_Linear;
  466. sampler_desc.mipmapFilter = WGPUFilterMode_Linear;
  467. sampler_desc.addressModeU = WGPUAddressMode_Repeat;
  468. sampler_desc.addressModeV = WGPUAddressMode_Repeat;
  469. sampler_desc.addressModeW = WGPUAddressMode_Repeat;
  470. sampler_desc.maxAnisotropy = 1;
  471. g_resources.Sampler = wgpuDeviceCreateSampler(g_wgpuDevice, &sampler_desc);
  472. }
  473. // Store our identifier
  474. static_assert(sizeof(ImTextureID) >= sizeof(g_resources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
  475. io.Fonts->SetTexID((ImTextureID)g_resources.FontTextureView);
  476. }
  477. static void ImGui_ImplWGPU_CreateUniformBuffer()
  478. {
  479. WGPUBufferDescriptor ub_desc =
  480. {
  481. NULL,
  482. "Dear ImGui Uniform buffer",
  483. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
  484. sizeof(Uniforms),
  485. false
  486. };
  487. g_resources.Uniforms = wgpuDeviceCreateBuffer(g_wgpuDevice, &ub_desc);
  488. }
  489. bool ImGui_ImplWGPU_CreateDeviceObjects()
  490. {
  491. if (!g_wgpuDevice)
  492. return false;
  493. if (g_pipelineState)
  494. ImGui_ImplWGPU_InvalidateDeviceObjects();
  495. // Create render pipeline
  496. WGPURenderPipelineDescriptor2 graphics_pipeline_desc = {};
  497. graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
  498. graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
  499. graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
  500. graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
  501. graphics_pipeline_desc.multisample.count = 1;
  502. graphics_pipeline_desc.multisample.mask = UINT_MAX;
  503. graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false;
  504. graphics_pipeline_desc.layout = nullptr; // Use automatic layout generation
  505. // Create the vertex shader
  506. WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_vert_spv, sizeof(__glsl_shader_vert_spv) / sizeof(uint32_t));
  507. graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
  508. graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
  509. // Vertex input configuration
  510. WGPUVertexAttribute attribute_desc[] =
  511. {
  512. { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 },
  513. { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv), 1 },
  514. { WGPUVertexFormat_Unorm8x4, (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 },
  515. };
  516. WGPUVertexBufferLayout buffer_layouts[1];
  517. buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
  518. buffer_layouts[0].stepMode = WGPUInputStepMode_Vertex;
  519. buffer_layouts[0].attributeCount = 3;
  520. buffer_layouts[0].attributes = attribute_desc;
  521. graphics_pipeline_desc.vertex.bufferCount = 1;
  522. graphics_pipeline_desc.vertex.buffers = buffer_layouts;
  523. // Create the pixel shader
  524. WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_frag_spv, sizeof(__glsl_shader_frag_spv) / sizeof(uint32_t));
  525. // Create the blending setup
  526. WGPUBlendState blend_state = {};
  527. blend_state.alpha.operation = WGPUBlendOperation_Add;
  528. blend_state.alpha.srcFactor = WGPUBlendFactor_One;
  529. blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  530. blend_state.color.operation = WGPUBlendOperation_Add;
  531. blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
  532. blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  533. WGPUColorTargetState color_state = {};
  534. color_state.format = g_renderTargetFormat;
  535. color_state.blend = &blend_state;
  536. color_state.writeMask = WGPUColorWriteMask_All;
  537. WGPUFragmentState fragment_state = {};
  538. fragment_state.module = pixel_shader_desc.module;
  539. fragment_state.entryPoint = pixel_shader_desc.entryPoint;
  540. fragment_state.targetCount = 1;
  541. fragment_state.targets = &color_state;
  542. graphics_pipeline_desc.fragment = &fragment_state;
  543. // Create depth-stencil State
  544. WGPUDepthStencilState depth_stencil_state = {};
  545. depth_stencil_state.depthBias = 0;
  546. depth_stencil_state.depthBiasClamp = 0;
  547. depth_stencil_state.depthBiasSlopeScale = 0;
  548. // Configure disabled depth-stencil state
  549. graphics_pipeline_desc.depthStencil = nullptr;
  550. g_pipelineState = wgpuDeviceCreateRenderPipeline2(g_wgpuDevice, &graphics_pipeline_desc);
  551. ImGui_ImplWGPU_CreateFontsTexture();
  552. ImGui_ImplWGPU_CreateUniformBuffer();
  553. // Create resource bind group
  554. WGPUBindGroupLayout bg_layouts[2];
  555. bg_layouts[0] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 0);
  556. bg_layouts[1] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 1);
  557. WGPUBindGroupEntry common_bg_entries[] =
  558. {
  559. { 0, g_resources.Uniforms, 0, sizeof(Uniforms), 0, 0 },
  560. { 1, 0, 0, 0, g_resources.Sampler, 0 },
  561. };
  562. WGPUBindGroupDescriptor common_bg_descriptor = {};
  563. common_bg_descriptor.layout = bg_layouts[0];
  564. common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
  565. common_bg_descriptor.entries = common_bg_entries;
  566. g_resources.CommonBindGroup = wgpuDeviceCreateBindGroup(g_wgpuDevice, &common_bg_descriptor);
  567. WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], g_resources.FontTextureView);
  568. g_resources.ImageBindGroup = image_bind_group;
  569. g_resources.ImageBindGroupLayout = bg_layouts[1];
  570. g_resources.ImageBindGroups.SetVoidPtr(ImHashData(&g_resources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
  571. SafeRelease(vertex_shader_desc.module);
  572. SafeRelease(pixel_shader_desc.module);
  573. SafeRelease(bg_layouts[0]);
  574. return true;
  575. }
  576. void ImGui_ImplWGPU_InvalidateDeviceObjects()
  577. {
  578. if (!g_wgpuDevice)
  579. return;
  580. SafeRelease(g_pipelineState);
  581. SafeRelease(g_resources);
  582. ImGuiIO& io = ImGui::GetIO();
  583. io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
  584. for (unsigned int i = 0; i < g_numFramesInFlight; i++)
  585. SafeRelease(g_pFrameResources[i]);
  586. }
  587. bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format)
  588. {
  589. // Setup backend capabilities flags
  590. ImGuiIO& io = ImGui::GetIO();
  591. io.BackendRendererName = "imgui_impl_webgpu";
  592. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  593. g_wgpuDevice = device;
  594. g_defaultQueue = wgpuDeviceGetQueue(g_wgpuDevice);
  595. g_renderTargetFormat = rt_format;
  596. g_pFrameResources = new FrameResources[num_frames_in_flight];
  597. g_numFramesInFlight = num_frames_in_flight;
  598. g_frameIndex = UINT_MAX;
  599. g_resources.FontTexture = NULL;
  600. g_resources.FontTextureView = NULL;
  601. g_resources.Sampler = NULL;
  602. g_resources.Uniforms = NULL;
  603. g_resources.CommonBindGroup = NULL;
  604. g_resources.ImageBindGroups.Data.reserve(100);
  605. g_resources.ImageBindGroup = NULL;
  606. g_resources.ImageBindGroupLayout = NULL;
  607. // Create buffers with a default size (they will later be grown as needed)
  608. for (int i = 0; i < num_frames_in_flight; i++)
  609. {
  610. FrameResources* fr = &g_pFrameResources[i];
  611. fr->IndexBuffer = NULL;
  612. fr->VertexBuffer = NULL;
  613. fr->IndexBufferHost = NULL;
  614. fr->VertexBufferHost = NULL;
  615. fr->IndexBufferSize = 10000;
  616. fr->VertexBufferSize = 5000;
  617. }
  618. return true;
  619. }
  620. void ImGui_ImplWGPU_Shutdown()
  621. {
  622. ImGui_ImplWGPU_InvalidateDeviceObjects();
  623. delete[] g_pFrameResources;
  624. g_pFrameResources = NULL;
  625. wgpuQueueRelease(g_defaultQueue);
  626. g_wgpuDevice = NULL;
  627. g_numFramesInFlight = 0;
  628. g_frameIndex = UINT_MAX;
  629. }
  630. void ImGui_ImplWGPU_NewFrame()
  631. {
  632. if (!g_pipelineState)
  633. ImGui_ImplWGPU_CreateDeviceObjects();
  634. }