imgui_impl_vulkan.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  1. // dear imgui: Renderer Backend for Vulkan
  2. // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
  3. // Implemented features:
  4. // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
  5. // [x] Platform: Multi-viewport / platform windows. With issues (flickering when creating a new viewport).
  6. // Missing features:
  7. // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914
  8. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  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. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
  12. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  13. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
  14. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
  15. // You will use those if you want to use this rendering backend in your engine/app.
  16. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
  17. // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
  18. // Read comments in imgui_impl_vulkan.h.
  19. // CHANGELOG
  20. // (minor and older changes stripped away, please see git history for details)
  21. // 2020-11-11: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation.
  22. // 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init).
  23. // 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices.
  24. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices.
  25. // 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before.
  26. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  27. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  28. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount().
  29. // 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper.
  30. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like.
  31. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int).
  32. // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display.
  33. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  34. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case.
  35. // 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends.
  36. // 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example.
  37. // 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  38. // 2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use.
  39. // 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology.
  40. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself.
  41. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  42. // 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy.
  43. // 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex.
  44. // 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources.
  45. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
  46. #include "imgui.h"
  47. #include "imgui_impl_vulkan.h"
  48. #include <stdio.h>
  49. // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData()
  50. // [Please zero-clear before use!]
  51. struct ImGui_ImplVulkanH_FrameRenderBuffers
  52. {
  53. VkDeviceMemory VertexBufferMemory;
  54. VkDeviceMemory IndexBufferMemory;
  55. VkDeviceSize VertexBufferSize;
  56. VkDeviceSize IndexBufferSize;
  57. VkBuffer VertexBuffer;
  58. VkBuffer IndexBuffer;
  59. };
  60. // Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers
  61. // [Please zero-clear before use!]
  62. struct ImGui_ImplVulkanH_WindowRenderBuffers
  63. {
  64. uint32_t Index;
  65. uint32_t Count;
  66. ImGui_ImplVulkanH_FrameRenderBuffers* FrameRenderBuffers;
  67. };
  68. // For multi-viewport support:
  69. // Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
  70. struct ImGuiViewportDataVulkan
  71. {
  72. bool WindowOwned;
  73. ImGui_ImplVulkanH_Window Window; // Used by secondary viewports only
  74. ImGui_ImplVulkanH_WindowRenderBuffers RenderBuffers; // Used by all viewports
  75. ImGuiViewportDataVulkan() { WindowOwned = false; memset(&RenderBuffers, 0, sizeof(RenderBuffers)); }
  76. ~ImGuiViewportDataVulkan() { }
  77. };
  78. // Vulkan data
  79. static ImGui_ImplVulkan_InitInfo g_VulkanInitInfo = {};
  80. static VkRenderPass g_RenderPass = VK_NULL_HANDLE;
  81. static VkDeviceSize g_BufferMemoryAlignment = 256;
  82. static VkPipelineCreateFlags g_PipelineCreateFlags = 0x00;
  83. static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE;
  84. static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE;
  85. static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE;
  86. static VkPipeline g_Pipeline = VK_NULL_HANDLE;
  87. static uint32_t g_Subpass = 0;
  88. static VkShaderModule g_ShaderModuleVert;
  89. static VkShaderModule g_ShaderModuleFrag;
  90. // Font data
  91. static VkSampler g_FontSampler = VK_NULL_HANDLE;
  92. static VkDeviceMemory g_FontMemory = VK_NULL_HANDLE;
  93. static VkImage g_FontImage = VK_NULL_HANDLE;
  94. static VkImageView g_FontView = VK_NULL_HANDLE;
  95. static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE;
  96. static VkBuffer g_UploadBuffer = VK_NULL_HANDLE;
  97. // Forward Declarations
  98. bool ImGui_ImplVulkan_CreateDeviceObjects();
  99. void ImGui_ImplVulkan_DestroyDeviceObjects();
  100. void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator);
  101. void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator);
  102. void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
  103. void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
  104. void ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(VkDevice device, const VkAllocationCallbacks* allocator);
  105. void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count);
  106. void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator);
  107. //-----------------------------------------------------------------------------
  108. // SHADERS
  109. //-----------------------------------------------------------------------------
  110. // Forward Declarations
  111. static void ImGui_ImplVulkan_InitPlatformInterface();
  112. static void ImGui_ImplVulkan_ShutdownPlatformInterface();
  113. // glsl_shader.vert, compiled with:
  114. // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
  115. /*
  116. #version 450 core
  117. layout(location = 0) in vec2 aPos;
  118. layout(location = 1) in vec2 aUV;
  119. layout(location = 2) in vec4 aColor;
  120. layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc;
  121. out gl_PerVertex { vec4 gl_Position; };
  122. layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
  123. void main()
  124. {
  125. Out.Color = aColor;
  126. Out.UV = aUV;
  127. gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1);
  128. }
  129. */
  130. static uint32_t __glsl_shader_vert_spv[] =
  131. {
  132. 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b,
  133. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  134. 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
  135. 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  136. 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
  137. 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
  138. 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
  139. 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
  140. 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c,
  141. 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074,
  142. 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001,
  143. 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b,
  144. 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
  145. 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
  146. 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e,
  147. 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008,
  148. 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
  149. 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017,
  150. 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020,
  151. 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015,
  152. 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020,
  153. 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020,
  154. 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020,
  155. 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020,
  156. 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a,
  157. 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014,
  158. 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f,
  159. 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021,
  160. 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006,
  161. 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,
  162. 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,
  163. 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,
  164. 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,
  165. 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022,
  166. 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008,
  167. 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013,
  168. 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024,
  169. 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006,
  170. 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b,
  171. 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e,
  172. 0x0000002d,0x0000002c,0x000100fd,0x00010038
  173. };
  174. // glsl_shader.frag, compiled with:
  175. // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
  176. /*
  177. #version 450 core
  178. layout(location = 0) out vec4 fColor;
  179. layout(set=0, binding=0) uniform sampler2D sTexture;
  180. layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
  181. void main()
  182. {
  183. fColor = In.Color * texture(sTexture, In.UV.st);
  184. }
  185. */
  186. static uint32_t __glsl_shader_frag_spv[] =
  187. {
  188. 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b,
  189. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  190. 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
  191. 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  192. 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
  193. 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
  194. 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574,
  195. 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,
  196. 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021,
  197. 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
  198. 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,
  199. 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006,
  200. 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001,
  201. 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020,
  202. 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001,
  203. 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
  204. 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000,
  205. 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018,
  206. 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004,
  207. 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d,
  208. 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017,
  209. 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a,
  210. 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085,
  211. 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd,
  212. 0x00010038
  213. };
  214. //-----------------------------------------------------------------------------
  215. // FUNCTIONS
  216. //-----------------------------------------------------------------------------
  217. static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits)
  218. {
  219. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  220. VkPhysicalDeviceMemoryProperties prop;
  221. vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop);
  222. for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
  223. if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1 << i))
  224. return i;
  225. return 0xFFFFFFFF; // Unable to find memoryType
  226. }
  227. static void check_vk_result(VkResult err)
  228. {
  229. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  230. if (v->CheckVkResultFn)
  231. v->CheckVkResultFn(err);
  232. }
  233. static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage)
  234. {
  235. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  236. VkResult err;
  237. if (buffer != VK_NULL_HANDLE)
  238. vkDestroyBuffer(v->Device, buffer, v->Allocator);
  239. if (buffer_memory != VK_NULL_HANDLE)
  240. vkFreeMemory(v->Device, buffer_memory, v->Allocator);
  241. VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment;
  242. VkBufferCreateInfo buffer_info = {};
  243. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  244. buffer_info.size = vertex_buffer_size_aligned;
  245. buffer_info.usage = usage;
  246. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  247. err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer);
  248. check_vk_result(err);
  249. VkMemoryRequirements req;
  250. vkGetBufferMemoryRequirements(v->Device, buffer, &req);
  251. g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
  252. VkMemoryAllocateInfo alloc_info = {};
  253. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  254. alloc_info.allocationSize = req.size;
  255. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  256. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &buffer_memory);
  257. check_vk_result(err);
  258. err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0);
  259. check_vk_result(err);
  260. p_buffer_size = new_size;
  261. }
  262. static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height)
  263. {
  264. // Bind pipeline and descriptor sets:
  265. {
  266. vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  267. VkDescriptorSet desc_set[1] = { g_DescriptorSet };
  268. vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL);
  269. }
  270. // Bind Vertex And Index Buffer:
  271. if (draw_data->TotalVtxCount > 0)
  272. {
  273. VkBuffer vertex_buffers[1] = { rb->VertexBuffer };
  274. VkDeviceSize vertex_offset[1] = { 0 };
  275. vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
  276. vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32);
  277. }
  278. // Setup viewport:
  279. {
  280. VkViewport viewport;
  281. viewport.x = 0;
  282. viewport.y = 0;
  283. viewport.width = (float)fb_width;
  284. viewport.height = (float)fb_height;
  285. viewport.minDepth = 0.0f;
  286. viewport.maxDepth = 1.0f;
  287. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  288. }
  289. // Setup scale and translation:
  290. // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
  291. {
  292. float scale[2];
  293. scale[0] = 2.0f / draw_data->DisplaySize.x;
  294. scale[1] = 2.0f / draw_data->DisplaySize.y;
  295. float translate[2];
  296. translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
  297. translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
  298. vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale);
  299. vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate);
  300. }
  301. }
  302. // Render function
  303. void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline)
  304. {
  305. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  306. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  307. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  308. if (fb_width <= 0 || fb_height <= 0)
  309. return;
  310. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  311. if (pipeline == VK_NULL_HANDLE)
  312. pipeline = g_Pipeline;
  313. // Allocate array to store enough vertex/index buffers. Each unique viewport gets its own storage.
  314. ImGuiViewportDataVulkan* viewport_renderer_data = (ImGuiViewportDataVulkan*)draw_data->OwnerViewport->RendererUserData;
  315. IM_ASSERT(viewport_renderer_data != NULL);
  316. ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &viewport_renderer_data->RenderBuffers;
  317. if (wrb->FrameRenderBuffers == NULL)
  318. {
  319. wrb->Index = 0;
  320. wrb->Count = v->ImageCount;
  321. wrb->FrameRenderBuffers = (ImGui_ImplVulkanH_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count);
  322. memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count);
  323. }
  324. IM_ASSERT(wrb->Count == v->ImageCount);
  325. wrb->Index = (wrb->Index + 1) % wrb->Count;
  326. ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index];
  327. if (draw_data->TotalVtxCount > 0)
  328. {
  329. // Create or resize the vertex/index buffers
  330. size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
  331. size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
  332. if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size)
  333. CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
  334. if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size)
  335. CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
  336. // Upload vertex/index data into a single contiguous GPU buffer
  337. ImDrawVert* vtx_dst = NULL;
  338. ImDrawIdx* idx_dst = NULL;
  339. VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst));
  340. check_vk_result(err);
  341. err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst));
  342. check_vk_result(err);
  343. for (int n = 0; n < draw_data->CmdListsCount; n++)
  344. {
  345. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  346. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  347. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  348. vtx_dst += cmd_list->VtxBuffer.Size;
  349. idx_dst += cmd_list->IdxBuffer.Size;
  350. }
  351. VkMappedMemoryRange range[2] = {};
  352. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  353. range[0].memory = rb->VertexBufferMemory;
  354. range[0].size = VK_WHOLE_SIZE;
  355. range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  356. range[1].memory = rb->IndexBufferMemory;
  357. range[1].size = VK_WHOLE_SIZE;
  358. err = vkFlushMappedMemoryRanges(v->Device, 2, range);
  359. check_vk_result(err);
  360. vkUnmapMemory(v->Device, rb->VertexBufferMemory);
  361. vkUnmapMemory(v->Device, rb->IndexBufferMemory);
  362. }
  363. // Setup desired Vulkan state
  364. ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
  365. // Will project scissor/clipping rectangles into framebuffer space
  366. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  367. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  368. // Render command lists
  369. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  370. int global_vtx_offset = 0;
  371. int global_idx_offset = 0;
  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_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
  384. else
  385. pcmd->UserCallback(cmd_list, pcmd);
  386. }
  387. else
  388. {
  389. // Project scissor/clipping rectangles into framebuffer space
  390. ImVec4 clip_rect;
  391. clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
  392. clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
  393. clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
  394. clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
  395. if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
  396. {
  397. // Negative offsets are illegal for vkCmdSetScissor
  398. if (clip_rect.x < 0.0f)
  399. clip_rect.x = 0.0f;
  400. if (clip_rect.y < 0.0f)
  401. clip_rect.y = 0.0f;
  402. // Apply scissor/clipping rectangle
  403. VkRect2D scissor;
  404. scissor.offset.x = (int32_t)(clip_rect.x);
  405. scissor.offset.y = (int32_t)(clip_rect.y);
  406. scissor.extent.width = (uint32_t)(clip_rect.z - clip_rect.x);
  407. scissor.extent.height = (uint32_t)(clip_rect.w - clip_rect.y);
  408. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  409. // Draw
  410. vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  411. }
  412. }
  413. }
  414. global_idx_offset += cmd_list->IdxBuffer.Size;
  415. global_vtx_offset += cmd_list->VtxBuffer.Size;
  416. }
  417. }
  418. bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
  419. {
  420. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  421. ImGuiIO& io = ImGui::GetIO();
  422. unsigned char* pixels;
  423. int width, height;
  424. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  425. size_t upload_size = width * height * 4 * sizeof(char);
  426. VkResult err;
  427. // Create the Image:
  428. {
  429. VkImageCreateInfo info = {};
  430. info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  431. info.imageType = VK_IMAGE_TYPE_2D;
  432. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  433. info.extent.width = width;
  434. info.extent.height = height;
  435. info.extent.depth = 1;
  436. info.mipLevels = 1;
  437. info.arrayLayers = 1;
  438. info.samples = VK_SAMPLE_COUNT_1_BIT;
  439. info.tiling = VK_IMAGE_TILING_OPTIMAL;
  440. info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  441. info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  442. info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  443. err = vkCreateImage(v->Device, &info, v->Allocator, &g_FontImage);
  444. check_vk_result(err);
  445. VkMemoryRequirements req;
  446. vkGetImageMemoryRequirements(v->Device, g_FontImage, &req);
  447. VkMemoryAllocateInfo alloc_info = {};
  448. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  449. alloc_info.allocationSize = req.size;
  450. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
  451. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &g_FontMemory);
  452. check_vk_result(err);
  453. err = vkBindImageMemory(v->Device, g_FontImage, g_FontMemory, 0);
  454. check_vk_result(err);
  455. }
  456. // Create the Image View:
  457. {
  458. VkImageViewCreateInfo info = {};
  459. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  460. info.image = g_FontImage;
  461. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  462. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  463. info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  464. info.subresourceRange.levelCount = 1;
  465. info.subresourceRange.layerCount = 1;
  466. err = vkCreateImageView(v->Device, &info, v->Allocator, &g_FontView);
  467. check_vk_result(err);
  468. }
  469. // Update the Descriptor Set:
  470. {
  471. VkDescriptorImageInfo desc_image[1] = {};
  472. desc_image[0].sampler = g_FontSampler;
  473. desc_image[0].imageView = g_FontView;
  474. desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  475. VkWriteDescriptorSet write_desc[1] = {};
  476. write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  477. write_desc[0].dstSet = g_DescriptorSet;
  478. write_desc[0].descriptorCount = 1;
  479. write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  480. write_desc[0].pImageInfo = desc_image;
  481. vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, NULL);
  482. }
  483. // Create the Upload Buffer:
  484. {
  485. VkBufferCreateInfo buffer_info = {};
  486. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  487. buffer_info.size = upload_size;
  488. buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  489. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  490. err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &g_UploadBuffer);
  491. check_vk_result(err);
  492. VkMemoryRequirements req;
  493. vkGetBufferMemoryRequirements(v->Device, g_UploadBuffer, &req);
  494. g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
  495. VkMemoryAllocateInfo alloc_info = {};
  496. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  497. alloc_info.allocationSize = req.size;
  498. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  499. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &g_UploadBufferMemory);
  500. check_vk_result(err);
  501. err = vkBindBufferMemory(v->Device, g_UploadBuffer, g_UploadBufferMemory, 0);
  502. check_vk_result(err);
  503. }
  504. // Upload to Buffer:
  505. {
  506. char* map = NULL;
  507. err = vkMapMemory(v->Device, g_UploadBufferMemory, 0, upload_size, 0, (void**)(&map));
  508. check_vk_result(err);
  509. memcpy(map, pixels, upload_size);
  510. VkMappedMemoryRange range[1] = {};
  511. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  512. range[0].memory = g_UploadBufferMemory;
  513. range[0].size = upload_size;
  514. err = vkFlushMappedMemoryRanges(v->Device, 1, range);
  515. check_vk_result(err);
  516. vkUnmapMemory(v->Device, g_UploadBufferMemory);
  517. }
  518. // Copy to Image:
  519. {
  520. VkImageMemoryBarrier copy_barrier[1] = {};
  521. copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  522. copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  523. copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  524. copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  525. copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  526. copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  527. copy_barrier[0].image = g_FontImage;
  528. copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  529. copy_barrier[0].subresourceRange.levelCount = 1;
  530. copy_barrier[0].subresourceRange.layerCount = 1;
  531. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, copy_barrier);
  532. VkBufferImageCopy region = {};
  533. region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  534. region.imageSubresource.layerCount = 1;
  535. region.imageExtent.width = width;
  536. region.imageExtent.height = height;
  537. region.imageExtent.depth = 1;
  538. vkCmdCopyBufferToImage(command_buffer, g_UploadBuffer, g_FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
  539. VkImageMemoryBarrier use_barrier[1] = {};
  540. use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  541. use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  542. use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  543. use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  544. use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  545. use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  546. use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  547. use_barrier[0].image = g_FontImage;
  548. use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  549. use_barrier[0].subresourceRange.levelCount = 1;
  550. use_barrier[0].subresourceRange.layerCount = 1;
  551. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, use_barrier);
  552. }
  553. // Store our identifier
  554. io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontImage;
  555. return true;
  556. }
  557. static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator)
  558. {
  559. // Create the shader modules
  560. if (g_ShaderModuleVert == NULL)
  561. {
  562. VkShaderModuleCreateInfo vert_info = {};
  563. vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  564. vert_info.codeSize = sizeof(__glsl_shader_vert_spv);
  565. vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv;
  566. VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &g_ShaderModuleVert);
  567. check_vk_result(err);
  568. }
  569. if (g_ShaderModuleFrag == NULL)
  570. {
  571. VkShaderModuleCreateInfo frag_info = {};
  572. frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  573. frag_info.codeSize = sizeof(__glsl_shader_frag_spv);
  574. frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv;
  575. VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &g_ShaderModuleFrag);
  576. check_vk_result(err);
  577. }
  578. }
  579. static void ImGui_ImplVulkan_CreateFontSampler(VkDevice device, const VkAllocationCallbacks* allocator)
  580. {
  581. if (g_FontSampler)
  582. return;
  583. VkSamplerCreateInfo info = {};
  584. info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  585. info.magFilter = VK_FILTER_LINEAR;
  586. info.minFilter = VK_FILTER_LINEAR;
  587. info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
  588. info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  589. info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  590. info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  591. info.minLod = -1000;
  592. info.maxLod = 1000;
  593. info.maxAnisotropy = 1.0f;
  594. VkResult err = vkCreateSampler(device, &info, allocator, &g_FontSampler);
  595. check_vk_result(err);
  596. }
  597. static void ImGui_ImplVulkan_CreateDescriptorSetLayout(VkDevice device, const VkAllocationCallbacks* allocator)
  598. {
  599. if (g_DescriptorSetLayout)
  600. return;
  601. ImGui_ImplVulkan_CreateFontSampler(device, allocator);
  602. VkSampler sampler[1] = { g_FontSampler };
  603. VkDescriptorSetLayoutBinding binding[1] = {};
  604. binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  605. binding[0].descriptorCount = 1;
  606. binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
  607. binding[0].pImmutableSamplers = sampler;
  608. VkDescriptorSetLayoutCreateInfo info = {};
  609. info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  610. info.bindingCount = 1;
  611. info.pBindings = binding;
  612. VkResult err = vkCreateDescriptorSetLayout(device, &info, allocator, &g_DescriptorSetLayout);
  613. check_vk_result(err);
  614. }
  615. static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAllocationCallbacks* allocator)
  616. {
  617. if (g_PipelineLayout)
  618. return;
  619. // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
  620. ImGui_ImplVulkan_CreateDescriptorSetLayout(device, allocator);
  621. VkPushConstantRange push_constants[1] = {};
  622. push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
  623. push_constants[0].offset = sizeof(float) * 0;
  624. push_constants[0].size = sizeof(float) * 4;
  625. VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout };
  626. VkPipelineLayoutCreateInfo layout_info = {};
  627. layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  628. layout_info.setLayoutCount = 1;
  629. layout_info.pSetLayouts = set_layout;
  630. layout_info.pushConstantRangeCount = 1;
  631. layout_info.pPushConstantRanges = push_constants;
  632. VkResult err = vkCreatePipelineLayout(device, &layout_info, allocator, &g_PipelineLayout);
  633. check_vk_result(err);
  634. }
  635. static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass)
  636. {
  637. ImGui_ImplVulkan_CreateShaderModules(device, allocator);
  638. VkPipelineShaderStageCreateInfo stage[2] = {};
  639. stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  640. stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  641. stage[0].module = g_ShaderModuleVert;
  642. stage[0].pName = "main";
  643. stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  644. stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  645. stage[1].module = g_ShaderModuleFrag;
  646. stage[1].pName = "main";
  647. VkVertexInputBindingDescription binding_desc[1] = {};
  648. binding_desc[0].stride = sizeof(ImDrawVert);
  649. binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  650. VkVertexInputAttributeDescription attribute_desc[3] = {};
  651. attribute_desc[0].location = 0;
  652. attribute_desc[0].binding = binding_desc[0].binding;
  653. attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
  654. attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
  655. attribute_desc[1].location = 1;
  656. attribute_desc[1].binding = binding_desc[0].binding;
  657. attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
  658. attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
  659. attribute_desc[2].location = 2;
  660. attribute_desc[2].binding = binding_desc[0].binding;
  661. attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
  662. attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
  663. VkPipelineVertexInputStateCreateInfo vertex_info = {};
  664. vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  665. vertex_info.vertexBindingDescriptionCount = 1;
  666. vertex_info.pVertexBindingDescriptions = binding_desc;
  667. vertex_info.vertexAttributeDescriptionCount = 3;
  668. vertex_info.pVertexAttributeDescriptions = attribute_desc;
  669. VkPipelineInputAssemblyStateCreateInfo ia_info = {};
  670. ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  671. ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  672. VkPipelineViewportStateCreateInfo viewport_info = {};
  673. viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  674. viewport_info.viewportCount = 1;
  675. viewport_info.scissorCount = 1;
  676. VkPipelineRasterizationStateCreateInfo raster_info = {};
  677. raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  678. raster_info.polygonMode = VK_POLYGON_MODE_FILL;
  679. raster_info.cullMode = VK_CULL_MODE_NONE;
  680. raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
  681. raster_info.lineWidth = 1.0f;
  682. VkPipelineMultisampleStateCreateInfo ms_info = {};
  683. ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  684. ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT;
  685. VkPipelineColorBlendAttachmentState color_attachment[1] = {};
  686. color_attachment[0].blendEnable = VK_TRUE;
  687. color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
  688. color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  689. color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
  690. color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  691. color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  692. color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
  693. color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  694. VkPipelineDepthStencilStateCreateInfo depth_info = {};
  695. depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  696. VkPipelineColorBlendStateCreateInfo blend_info = {};
  697. blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  698. blend_info.attachmentCount = 1;
  699. blend_info.pAttachments = color_attachment;
  700. VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
  701. VkPipelineDynamicStateCreateInfo dynamic_state = {};
  702. dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  703. dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
  704. dynamic_state.pDynamicStates = dynamic_states;
  705. ImGui_ImplVulkan_CreatePipelineLayout(device, allocator);
  706. VkGraphicsPipelineCreateInfo info = {};
  707. info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  708. info.flags = g_PipelineCreateFlags;
  709. info.stageCount = 2;
  710. info.pStages = stage;
  711. info.pVertexInputState = &vertex_info;
  712. info.pInputAssemblyState = &ia_info;
  713. info.pViewportState = &viewport_info;
  714. info.pRasterizationState = &raster_info;
  715. info.pMultisampleState = &ms_info;
  716. info.pDepthStencilState = &depth_info;
  717. info.pColorBlendState = &blend_info;
  718. info.pDynamicState = &dynamic_state;
  719. info.layout = g_PipelineLayout;
  720. info.renderPass = renderPass;
  721. info.subpass = subpass;
  722. VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline);
  723. check_vk_result(err);
  724. }
  725. bool ImGui_ImplVulkan_CreateDeviceObjects()
  726. {
  727. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  728. VkResult err;
  729. if (!g_FontSampler)
  730. {
  731. VkSamplerCreateInfo info = {};
  732. info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  733. info.magFilter = VK_FILTER_LINEAR;
  734. info.minFilter = VK_FILTER_LINEAR;
  735. info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
  736. info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  737. info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  738. info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  739. info.minLod = -1000;
  740. info.maxLod = 1000;
  741. info.maxAnisotropy = 1.0f;
  742. err = vkCreateSampler(v->Device, &info, v->Allocator, &g_FontSampler);
  743. check_vk_result(err);
  744. }
  745. if (!g_DescriptorSetLayout)
  746. {
  747. VkSampler sampler[1] = {g_FontSampler};
  748. VkDescriptorSetLayoutBinding binding[1] = {};
  749. binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  750. binding[0].descriptorCount = 1;
  751. binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
  752. binding[0].pImmutableSamplers = sampler;
  753. VkDescriptorSetLayoutCreateInfo info = {};
  754. info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  755. info.bindingCount = 1;
  756. info.pBindings = binding;
  757. err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &g_DescriptorSetLayout);
  758. check_vk_result(err);
  759. }
  760. // Create Descriptor Set:
  761. {
  762. VkDescriptorSetAllocateInfo alloc_info = {};
  763. alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  764. alloc_info.descriptorPool = v->DescriptorPool;
  765. alloc_info.descriptorSetCount = 1;
  766. alloc_info.pSetLayouts = &g_DescriptorSetLayout;
  767. err = vkAllocateDescriptorSets(v->Device, &alloc_info, &g_DescriptorSet);
  768. check_vk_result(err);
  769. }
  770. if (!g_PipelineLayout)
  771. {
  772. // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
  773. VkPushConstantRange push_constants[1] = {};
  774. push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
  775. push_constants[0].offset = sizeof(float) * 0;
  776. push_constants[0].size = sizeof(float) * 4;
  777. VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout };
  778. VkPipelineLayoutCreateInfo layout_info = {};
  779. layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  780. layout_info.setLayoutCount = 1;
  781. layout_info.pSetLayouts = set_layout;
  782. layout_info.pushConstantRangeCount = 1;
  783. layout_info.pPushConstantRanges = push_constants;
  784. err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &g_PipelineLayout);
  785. check_vk_result(err);
  786. }
  787. ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline, g_Subpass);
  788. return true;
  789. }
  790. void ImGui_ImplVulkan_DestroyFontUploadObjects()
  791. {
  792. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  793. if (g_UploadBuffer)
  794. {
  795. vkDestroyBuffer(v->Device, g_UploadBuffer, v->Allocator);
  796. g_UploadBuffer = VK_NULL_HANDLE;
  797. }
  798. if (g_UploadBufferMemory)
  799. {
  800. vkFreeMemory(v->Device, g_UploadBufferMemory, v->Allocator);
  801. g_UploadBufferMemory = VK_NULL_HANDLE;
  802. }
  803. }
  804. void ImGui_ImplVulkan_DestroyDeviceObjects()
  805. {
  806. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  807. ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator);
  808. ImGui_ImplVulkan_DestroyFontUploadObjects();
  809. if (g_ShaderModuleVert) { vkDestroyShaderModule(v->Device, g_ShaderModuleVert, v->Allocator); g_ShaderModuleVert = VK_NULL_HANDLE; }
  810. if (g_ShaderModuleFrag) { vkDestroyShaderModule(v->Device, g_ShaderModuleFrag, v->Allocator); g_ShaderModuleFrag = VK_NULL_HANDLE; }
  811. if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; }
  812. if (g_FontImage) { vkDestroyImage(v->Device, g_FontImage, v->Allocator); g_FontImage = VK_NULL_HANDLE; }
  813. if (g_FontMemory) { vkFreeMemory(v->Device, g_FontMemory, v->Allocator); g_FontMemory = VK_NULL_HANDLE; }
  814. if (g_FontSampler) { vkDestroySampler(v->Device, g_FontSampler, v->Allocator); g_FontSampler = VK_NULL_HANDLE; }
  815. if (g_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, g_DescriptorSetLayout, v->Allocator); g_DescriptorSetLayout = VK_NULL_HANDLE; }
  816. if (g_PipelineLayout) { vkDestroyPipelineLayout(v->Device, g_PipelineLayout, v->Allocator); g_PipelineLayout = VK_NULL_HANDLE; }
  817. if (g_Pipeline) { vkDestroyPipeline(v->Device, g_Pipeline, v->Allocator); g_Pipeline = VK_NULL_HANDLE; }
  818. }
  819. bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass)
  820. {
  821. // Setup backend capabilities flags
  822. ImGuiIO& io = ImGui::GetIO();
  823. io.BackendRendererName = "imgui_impl_vulkan";
  824. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  825. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  826. IM_ASSERT(info->Instance != VK_NULL_HANDLE);
  827. IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE);
  828. IM_ASSERT(info->Device != VK_NULL_HANDLE);
  829. IM_ASSERT(info->Queue != VK_NULL_HANDLE);
  830. IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE);
  831. IM_ASSERT(info->MinImageCount >= 2);
  832. IM_ASSERT(info->ImageCount >= info->MinImageCount);
  833. IM_ASSERT(render_pass != VK_NULL_HANDLE);
  834. g_VulkanInitInfo = *info;
  835. g_RenderPass = render_pass;
  836. g_Subpass = info->Subpass;
  837. ImGui_ImplVulkan_CreateDeviceObjects();
  838. // Our render function expect RendererUserData to be storing the window render buffer we need (for the main viewport we won't use ->Window)
  839. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  840. main_viewport->RendererUserData = IM_NEW(ImGuiViewportDataVulkan)();
  841. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  842. ImGui_ImplVulkan_InitPlatformInterface();
  843. return true;
  844. }
  845. void ImGui_ImplVulkan_Shutdown()
  846. {
  847. // First destroy objects in all viewports
  848. ImGui_ImplVulkan_DestroyDeviceObjects();
  849. // Manually delete main viewport render data in-case we haven't initialized for viewports
  850. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  851. if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)main_viewport->RendererUserData)
  852. IM_DELETE(data);
  853. main_viewport->RendererUserData = NULL;
  854. // Clean up windows
  855. ImGui_ImplVulkan_ShutdownPlatformInterface();
  856. }
  857. void ImGui_ImplVulkan_NewFrame()
  858. {
  859. }
  860. void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count)
  861. {
  862. IM_ASSERT(min_image_count >= 2);
  863. if (g_VulkanInitInfo.MinImageCount == min_image_count)
  864. return;
  865. IM_ASSERT(0); // FIXME-VIEWPORT: Unsupported. Need to recreate all swap chains!
  866. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  867. VkResult err = vkDeviceWaitIdle(v->Device);
  868. check_vk_result(err);
  869. ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator);
  870. g_VulkanInitInfo.MinImageCount = min_image_count;
  871. }
  872. //-------------------------------------------------------------------------
  873. // Internal / Miscellaneous Vulkan Helpers
  874. // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.)
  875. //-------------------------------------------------------------------------
  876. // You probably do NOT need to use or care about those functions.
  877. // Those functions only exist because:
  878. // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
  879. // 2) the upcoming multi-viewport feature will need them internally.
  880. // Generally we avoid exposing any kind of superfluous high-level helpers in the backends,
  881. // but it is too much code to duplicate everywhere so we exceptionally expose them.
  882. //
  883. // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.).
  884. // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work.
  885. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions)
  886. //-------------------------------------------------------------------------
  887. VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space)
  888. {
  889. IM_ASSERT(request_formats != NULL);
  890. IM_ASSERT(request_formats_count > 0);
  891. // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
  892. // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
  893. // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
  894. // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
  895. uint32_t avail_count;
  896. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, NULL);
  897. ImVector<VkSurfaceFormatKHR> avail_format;
  898. avail_format.resize((int)avail_count);
  899. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data);
  900. // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
  901. if (avail_count == 1)
  902. {
  903. if (avail_format[0].format == VK_FORMAT_UNDEFINED)
  904. {
  905. VkSurfaceFormatKHR ret;
  906. ret.format = request_formats[0];
  907. ret.colorSpace = request_color_space;
  908. return ret;
  909. }
  910. else
  911. {
  912. // No point in searching another format
  913. return avail_format[0];
  914. }
  915. }
  916. else
  917. {
  918. // Request several formats, the first found will be used
  919. for (int request_i = 0; request_i < request_formats_count; request_i++)
  920. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  921. if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space)
  922. return avail_format[avail_i];
  923. // If none of the requested image formats could be found, use the first available
  924. return avail_format[0];
  925. }
  926. }
  927. VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count)
  928. {
  929. IM_ASSERT(request_modes != NULL);
  930. IM_ASSERT(request_modes_count > 0);
  931. // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
  932. uint32_t avail_count = 0;
  933. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, NULL);
  934. ImVector<VkPresentModeKHR> avail_modes;
  935. avail_modes.resize((int)avail_count);
  936. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data);
  937. //for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  938. // printf("[vulkan] avail_modes[%d] = %d\n", avail_i, avail_modes[avail_i]);
  939. for (int request_i = 0; request_i < request_modes_count; request_i++)
  940. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  941. if (request_modes[request_i] == avail_modes[avail_i])
  942. return request_modes[request_i];
  943. return VK_PRESENT_MODE_FIFO_KHR; // Always available
  944. }
  945. void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator)
  946. {
  947. IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE);
  948. (void)physical_device;
  949. (void)allocator;
  950. // Create Command Buffers
  951. VkResult err;
  952. for (uint32_t i = 0; i < wd->ImageCount; i++)
  953. {
  954. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  955. ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i];
  956. {
  957. VkCommandPoolCreateInfo info = {};
  958. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  959. info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  960. info.queueFamilyIndex = queue_family;
  961. err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool);
  962. check_vk_result(err);
  963. }
  964. {
  965. VkCommandBufferAllocateInfo info = {};
  966. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  967. info.commandPool = fd->CommandPool;
  968. info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  969. info.commandBufferCount = 1;
  970. err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer);
  971. check_vk_result(err);
  972. }
  973. {
  974. VkFenceCreateInfo info = {};
  975. info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  976. info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  977. err = vkCreateFence(device, &info, allocator, &fd->Fence);
  978. check_vk_result(err);
  979. }
  980. {
  981. VkSemaphoreCreateInfo info = {};
  982. info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  983. err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore);
  984. check_vk_result(err);
  985. err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore);
  986. check_vk_result(err);
  987. }
  988. }
  989. }
  990. int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode)
  991. {
  992. if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
  993. return 3;
  994. if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
  995. return 2;
  996. if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
  997. return 1;
  998. IM_ASSERT(0);
  999. return 1;
  1000. }
  1001. // Also destroy old swap chain and in-flight frames data, if any.
  1002. void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count)
  1003. {
  1004. VkResult err;
  1005. VkSwapchainKHR old_swapchain = wd->Swapchain;
  1006. wd->Swapchain = NULL;
  1007. err = vkDeviceWaitIdle(device);
  1008. check_vk_result(err);
  1009. // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one.
  1010. // Destroy old Framebuffer
  1011. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1012. {
  1013. ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
  1014. ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
  1015. }
  1016. IM_FREE(wd->Frames);
  1017. IM_FREE(wd->FrameSemaphores);
  1018. wd->Frames = NULL;
  1019. wd->FrameSemaphores = NULL;
  1020. wd->ImageCount = 0;
  1021. if (wd->RenderPass)
  1022. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  1023. if (wd->Pipeline)
  1024. vkDestroyPipeline(device, wd->Pipeline, allocator);
  1025. // If min image count was not specified, request different count of images dependent on selected present mode
  1026. if (min_image_count == 0)
  1027. min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode);
  1028. // Create Swapchain
  1029. {
  1030. VkSwapchainCreateInfoKHR info = {};
  1031. info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  1032. info.surface = wd->Surface;
  1033. info.minImageCount = min_image_count;
  1034. info.imageFormat = wd->SurfaceFormat.format;
  1035. info.imageColorSpace = wd->SurfaceFormat.colorSpace;
  1036. info.imageArrayLayers = 1;
  1037. info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1038. info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family
  1039. info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  1040. info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1041. info.presentMode = wd->PresentMode;
  1042. info.clipped = VK_TRUE;
  1043. info.oldSwapchain = old_swapchain;
  1044. VkSurfaceCapabilitiesKHR cap;
  1045. err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
  1046. check_vk_result(err);
  1047. if (info.minImageCount < cap.minImageCount)
  1048. info.minImageCount = cap.minImageCount;
  1049. else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount)
  1050. info.minImageCount = cap.maxImageCount;
  1051. if (cap.currentExtent.width == 0xffffffff)
  1052. {
  1053. info.imageExtent.width = wd->Width = w;
  1054. info.imageExtent.height = wd->Height = h;
  1055. }
  1056. else
  1057. {
  1058. info.imageExtent.width = wd->Width = cap.currentExtent.width;
  1059. info.imageExtent.height = wd->Height = cap.currentExtent.height;
  1060. }
  1061. err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain);
  1062. check_vk_result(err);
  1063. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, NULL);
  1064. check_vk_result(err);
  1065. VkImage backbuffers[16] = {};
  1066. IM_ASSERT(wd->ImageCount >= min_image_count);
  1067. IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers));
  1068. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers);
  1069. check_vk_result(err);
  1070. IM_ASSERT(wd->Frames == NULL);
  1071. wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount);
  1072. wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->ImageCount);
  1073. memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount);
  1074. memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->ImageCount);
  1075. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1076. wd->Frames[i].Backbuffer = backbuffers[i];
  1077. }
  1078. if (old_swapchain)
  1079. vkDestroySwapchainKHR(device, old_swapchain, allocator);
  1080. // Create the Render Pass
  1081. {
  1082. VkAttachmentDescription attachment = {};
  1083. attachment.format = wd->SurfaceFormat.format;
  1084. attachment.samples = VK_SAMPLE_COUNT_1_BIT;
  1085. attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1086. attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1087. attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1088. attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1089. attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1090. attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  1091. VkAttachmentReference color_attachment = {};
  1092. color_attachment.attachment = 0;
  1093. color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1094. VkSubpassDescription subpass = {};
  1095. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  1096. subpass.colorAttachmentCount = 1;
  1097. subpass.pColorAttachments = &color_attachment;
  1098. VkSubpassDependency dependency = {};
  1099. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  1100. dependency.dstSubpass = 0;
  1101. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1102. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1103. dependency.srcAccessMask = 0;
  1104. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  1105. VkRenderPassCreateInfo info = {};
  1106. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  1107. info.attachmentCount = 1;
  1108. info.pAttachments = &attachment;
  1109. info.subpassCount = 1;
  1110. info.pSubpasses = &subpass;
  1111. info.dependencyCount = 1;
  1112. info.pDependencies = &dependency;
  1113. err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass);
  1114. check_vk_result(err);
  1115. // We do not create a pipeline by default as this is also used by examples' main.cpp,
  1116. // but secondary viewport in multi-viewport mode may want to create one with:
  1117. //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, g_Subpass);
  1118. }
  1119. // Create The Image Views
  1120. {
  1121. VkImageViewCreateInfo info = {};
  1122. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1123. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  1124. info.format = wd->SurfaceFormat.format;
  1125. info.components.r = VK_COMPONENT_SWIZZLE_R;
  1126. info.components.g = VK_COMPONENT_SWIZZLE_G;
  1127. info.components.b = VK_COMPONENT_SWIZZLE_B;
  1128. info.components.a = VK_COMPONENT_SWIZZLE_A;
  1129. VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
  1130. info.subresourceRange = image_range;
  1131. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1132. {
  1133. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  1134. info.image = fd->Backbuffer;
  1135. err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView);
  1136. check_vk_result(err);
  1137. }
  1138. }
  1139. // Create Framebuffer
  1140. {
  1141. VkImageView attachment[1];
  1142. VkFramebufferCreateInfo info = {};
  1143. info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1144. info.renderPass = wd->RenderPass;
  1145. info.attachmentCount = 1;
  1146. info.pAttachments = attachment;
  1147. info.width = wd->Width;
  1148. info.height = wd->Height;
  1149. info.layers = 1;
  1150. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1151. {
  1152. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  1153. attachment[0] = fd->BackbufferView;
  1154. err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer);
  1155. check_vk_result(err);
  1156. }
  1157. }
  1158. }
  1159. // Create or resize window
  1160. void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count)
  1161. {
  1162. (void)instance;
  1163. ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count);
  1164. ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline);
  1165. ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator);
  1166. }
  1167. void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator)
  1168. {
  1169. vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
  1170. //vkQueueWaitIdle(g_Queue);
  1171. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1172. {
  1173. ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
  1174. ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
  1175. }
  1176. IM_FREE(wd->Frames);
  1177. IM_FREE(wd->FrameSemaphores);
  1178. wd->Frames = NULL;
  1179. wd->FrameSemaphores = NULL;
  1180. vkDestroyPipeline(device, wd->Pipeline, allocator);
  1181. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  1182. vkDestroySwapchainKHR(device, wd->Swapchain, allocator);
  1183. vkDestroySurfaceKHR(instance, wd->Surface, allocator);
  1184. *wd = ImGui_ImplVulkanH_Window();
  1185. }
  1186. void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator)
  1187. {
  1188. vkDestroyFence(device, fd->Fence, allocator);
  1189. vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer);
  1190. vkDestroyCommandPool(device, fd->CommandPool, allocator);
  1191. fd->Fence = VK_NULL_HANDLE;
  1192. fd->CommandBuffer = VK_NULL_HANDLE;
  1193. fd->CommandPool = VK_NULL_HANDLE;
  1194. vkDestroyImageView(device, fd->BackbufferView, allocator);
  1195. vkDestroyFramebuffer(device, fd->Framebuffer, allocator);
  1196. }
  1197. void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator)
  1198. {
  1199. vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator);
  1200. vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator);
  1201. fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE;
  1202. }
  1203. void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
  1204. {
  1205. if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; }
  1206. if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; }
  1207. if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; }
  1208. if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; }
  1209. buffers->VertexBufferSize = 0;
  1210. buffers->IndexBufferSize = 0;
  1211. }
  1212. void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
  1213. {
  1214. for (uint32_t n = 0; n < buffers->Count; n++)
  1215. ImGui_ImplVulkanH_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator);
  1216. IM_FREE(buffers->FrameRenderBuffers);
  1217. buffers->FrameRenderBuffers = NULL;
  1218. buffers->Index = 0;
  1219. buffers->Count = 0;
  1220. }
  1221. void ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(VkDevice device, const VkAllocationCallbacks* allocator)
  1222. {
  1223. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1224. for (int n = 0; n < platform_io.Viewports.Size; n++)
  1225. if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)platform_io.Viewports[n]->RendererUserData)
  1226. ImGui_ImplVulkanH_DestroyWindowRenderBuffers(device, &data->RenderBuffers, allocator);
  1227. }
  1228. //--------------------------------------------------------------------------------------------------------
  1229. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  1230. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  1231. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  1232. //--------------------------------------------------------------------------------------------------------
  1233. static void ImGui_ImplVulkan_CreateWindow(ImGuiViewport* viewport)
  1234. {
  1235. ImGuiViewportDataVulkan* data = IM_NEW(ImGuiViewportDataVulkan)();
  1236. viewport->RendererUserData = data;
  1237. ImGui_ImplVulkanH_Window* wd = &data->Window;
  1238. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  1239. // Create surface
  1240. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1241. VkResult err = (VkResult)platform_io.Platform_CreateVkSurface(viewport, (ImU64)v->Instance, (const void*)v->Allocator, (ImU64*)&wd->Surface);
  1242. check_vk_result(err);
  1243. // Check for WSI support
  1244. VkBool32 res;
  1245. vkGetPhysicalDeviceSurfaceSupportKHR(v->PhysicalDevice, v->QueueFamily, wd->Surface, &res);
  1246. if (res != VK_TRUE)
  1247. {
  1248. IM_ASSERT(0); // Error: no WSI support on physical device
  1249. return;
  1250. }
  1251. // Select Surface Format
  1252. const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM };
  1253. const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
  1254. wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(v->PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace);
  1255. // Select Present Mode
  1256. // FIXME-VULKAN: Even thought mailbox seems to get us maximum framerate with a single window, it halves framerate with a second window etc. (w/ Nvidia and SDK 1.82.1)
  1257. VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR };
  1258. wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(v->PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes));
  1259. //printf("[vulkan] Secondary window selected PresentMode = %d\n", wd->PresentMode);
  1260. // Create SwapChain, RenderPass, Framebuffer, etc.
  1261. wd->ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
  1262. ImGui_ImplVulkanH_CreateOrResizeWindow(v->Instance, v->PhysicalDevice, v->Device, wd, v->QueueFamily, v->Allocator, (int)viewport->Size.x, (int)viewport->Size.y, v->MinImageCount);
  1263. data->WindowOwned = true;
  1264. }
  1265. static void ImGui_ImplVulkan_DestroyWindow(ImGuiViewport* viewport)
  1266. {
  1267. // The main viewport (owned by the application) will always have RendererUserData == NULL since we didn't create the data for it.
  1268. if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData)
  1269. {
  1270. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  1271. if (data->WindowOwned)
  1272. ImGui_ImplVulkanH_DestroyWindow(v->Instance, v->Device, &data->Window, v->Allocator);
  1273. ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &data->RenderBuffers, v->Allocator);
  1274. IM_DELETE(data);
  1275. }
  1276. viewport->RendererUserData = NULL;
  1277. }
  1278. static void ImGui_ImplVulkan_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  1279. {
  1280. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1281. if (data == NULL) // This is NULL for the main viewport (which is left to the user/app to handle)
  1282. return;
  1283. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  1284. data->Window.ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
  1285. ImGui_ImplVulkanH_CreateOrResizeWindow(v->Instance, v->PhysicalDevice, v->Device, &data->Window, v->QueueFamily, v->Allocator, (int)size.x, (int)size.y, v->MinImageCount);
  1286. }
  1287. static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*)
  1288. {
  1289. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1290. ImGui_ImplVulkanH_Window* wd = &data->Window;
  1291. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  1292. VkResult err;
  1293. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex];
  1294. ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[wd->SemaphoreIndex];
  1295. {
  1296. for (;;)
  1297. {
  1298. err = vkWaitForFences(v->Device, 1, &fd->Fence, VK_TRUE, 100);
  1299. if (err == VK_SUCCESS) break;
  1300. if (err == VK_TIMEOUT) continue;
  1301. check_vk_result(err);
  1302. }
  1303. {
  1304. err = vkAcquireNextImageKHR(v->Device, wd->Swapchain, UINT64_MAX, fsd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &wd->FrameIndex);
  1305. check_vk_result(err);
  1306. fd = &wd->Frames[wd->FrameIndex];
  1307. }
  1308. {
  1309. err = vkResetCommandPool(v->Device, fd->CommandPool, 0);
  1310. check_vk_result(err);
  1311. VkCommandBufferBeginInfo info = {};
  1312. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  1313. info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  1314. err = vkBeginCommandBuffer(fd->CommandBuffer, &info);
  1315. check_vk_result(err);
  1316. }
  1317. {
  1318. ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  1319. memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
  1320. VkRenderPassBeginInfo info = {};
  1321. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1322. info.renderPass = wd->RenderPass;
  1323. info.framebuffer = fd->Framebuffer;
  1324. info.renderArea.extent.width = wd->Width;
  1325. info.renderArea.extent.height = wd->Height;
  1326. info.clearValueCount = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? 0 : 1;
  1327. info.pClearValues = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? NULL : &wd->ClearValue;
  1328. vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE);
  1329. }
  1330. }
  1331. ImGui_ImplVulkan_RenderDrawData(viewport->DrawData, fd->CommandBuffer, wd->Pipeline);
  1332. {
  1333. vkCmdEndRenderPass(fd->CommandBuffer);
  1334. {
  1335. VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1336. VkSubmitInfo info = {};
  1337. info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1338. info.waitSemaphoreCount = 1;
  1339. info.pWaitSemaphores = &fsd->ImageAcquiredSemaphore;
  1340. info.pWaitDstStageMask = &wait_stage;
  1341. info.commandBufferCount = 1;
  1342. info.pCommandBuffers = &fd->CommandBuffer;
  1343. info.signalSemaphoreCount = 1;
  1344. info.pSignalSemaphores = &fsd->RenderCompleteSemaphore;
  1345. err = vkEndCommandBuffer(fd->CommandBuffer);
  1346. check_vk_result(err);
  1347. err = vkResetFences(v->Device, 1, &fd->Fence);
  1348. check_vk_result(err);
  1349. err = vkQueueSubmit(v->Queue, 1, &info, fd->Fence);
  1350. check_vk_result(err);
  1351. }
  1352. }
  1353. }
  1354. static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport, void*)
  1355. {
  1356. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1357. ImGui_ImplVulkanH_Window* wd = &data->Window;
  1358. ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
  1359. VkResult err;
  1360. uint32_t present_index = wd->FrameIndex;
  1361. ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[wd->SemaphoreIndex];
  1362. VkPresentInfoKHR info = {};
  1363. info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  1364. info.waitSemaphoreCount = 1;
  1365. info.pWaitSemaphores = &fsd->RenderCompleteSemaphore;
  1366. info.swapchainCount = 1;
  1367. info.pSwapchains = &wd->Swapchain;
  1368. info.pImageIndices = &present_index;
  1369. err = vkQueuePresentKHR(v->Queue, &info);
  1370. check_vk_result(err);
  1371. wd->FrameIndex = (wd->FrameIndex + 1) % wd->ImageCount; // This is for the next vkWaitForFences()
  1372. wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores
  1373. }
  1374. void ImGui_ImplVulkan_InitPlatformInterface()
  1375. {
  1376. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1377. if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  1378. IM_ASSERT(platform_io.Platform_CreateVkSurface != NULL && "Platform needs to setup the CreateVkSurface handler.");
  1379. platform_io.Renderer_CreateWindow = ImGui_ImplVulkan_CreateWindow;
  1380. platform_io.Renderer_DestroyWindow = ImGui_ImplVulkan_DestroyWindow;
  1381. platform_io.Renderer_SetWindowSize = ImGui_ImplVulkan_SetWindowSize;
  1382. platform_io.Renderer_RenderWindow = ImGui_ImplVulkan_RenderWindow;
  1383. platform_io.Renderer_SwapBuffers = ImGui_ImplVulkan_SwapBuffers;
  1384. }
  1385. void ImGui_ImplVulkan_ShutdownPlatformInterface()
  1386. {
  1387. ImGui::DestroyPlatformWindows();
  1388. }