imgui_impl_wgpu.cpp 34 KB

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