imgui_impl_vulkan.cpp 61 KB

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