imgui_impl_vulkan.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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. // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  7. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
  8. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  10. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  11. // Learn about Dear ImGui:
  12. // - FAQ https://dearimgui.com/faq
  13. // - Getting Started https://dearimgui.com/getting-started
  14. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  15. // - Introduction, links and more at the top of imgui.cpp
  16. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
  17. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
  18. // You will use those if you want to use this rendering backend in your engine/app.
  19. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
  20. // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
  21. // Read comments in imgui_impl_vulkan.h.
  22. // CHANGELOG
  23. // (minor and older changes stripped away, please see git history for details)
  24. // 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples.
  25. // 2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222)
  26. // 2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867)
  27. // 2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  28. // 2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
  29. // 2024-10-07: Vulkan: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  30. // 2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
  31. // 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering.
  32. // 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure.
  33. // 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236)
  34. // 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189).
  35. // 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238)
  36. // 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them.
  37. // 2023-11-29: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075)
  38. // 2023-11-10: *BREAKING CHANGE*: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own command-buffer to upload fonts.
  39. // *BREAKING CHANGE*: Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary as we create and destroy those objects in the backend.
  40. // ImGui_ImplVulkan_CreateFontsTexture() is automatically called by NewFrame() the first time.
  41. // You can call ImGui_ImplVulkan_CreateFontsTexture() again to recreate the font atlas texture.
  42. // Added ImGui_ImplVulkan_DestroyFontsTexture() but you probably never need to call this.
  43. // 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat.
  44. // 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code.
  45. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  46. // 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738).
  47. // 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914).
  48. // 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame.
  49. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  50. // 2021-03-22: Vulkan: Fix mapped memory validation error when buffer sizes are not multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize.
  51. // 2021-02-18: Vulkan: Change blending equation to preserve alpha in output buffer.
  52. // 2021-01-27: Vulkan: Added support for custom function load and IMGUI_IMPL_VULKAN_NO_PROTOTYPES by using ImGui_ImplVulkan_LoadFunctions().
  53. // 2020-11-11: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation.
  54. // 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init).
  55. // 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices.
  56. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices.
  57. // 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.
  58. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  59. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  60. // 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().
  61. // 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper.
  62. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like.
  63. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int).
  64. // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display.
  65. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  66. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case.
  67. // 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends.
  68. // 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example.
  69. // 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  70. // 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.
  71. // 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology.
  72. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself.
  73. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  74. // 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy.
  75. // 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex.
  76. // 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.
  77. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
  78. #include "imgui.h"
  79. #ifndef IMGUI_DISABLE
  80. #include "imgui_impl_vulkan.h"
  81. #include <stdio.h>
  82. #ifndef IM_MAX
  83. #define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B))
  84. #endif
  85. // Visual Studio warnings
  86. #ifdef _MSC_VER
  87. #pragma warning (disable: 4127) // condition expression is constant
  88. #endif
  89. // Forward Declarations
  90. struct ImGui_ImplVulkan_FrameRenderBuffers;
  91. struct ImGui_ImplVulkan_WindowRenderBuffers;
  92. bool ImGui_ImplVulkan_CreateDeviceObjects();
  93. void ImGui_ImplVulkan_DestroyDeviceObjects();
  94. void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
  95. void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
  96. void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator);
  97. void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator);
  98. 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);
  99. void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator);
  100. // Vulkan prototypes for use with custom loaders
  101. // (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h
  102. #if defined(VK_NO_PROTOTYPES) && !defined(VOLK_H_)
  103. #define IMGUI_IMPL_VULKAN_USE_LOADER
  104. static bool g_FunctionsLoaded = false;
  105. #else
  106. static bool g_FunctionsLoaded = true;
  107. #endif
  108. #ifdef IMGUI_IMPL_VULKAN_USE_LOADER
  109. #define IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_MAP_MACRO) \
  110. IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \
  111. IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \
  112. IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \
  113. IMGUI_VULKAN_FUNC_MAP_MACRO(vkBeginCommandBuffer) \
  114. IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \
  115. IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \
  116. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \
  117. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindIndexBuffer) \
  118. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindPipeline) \
  119. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindVertexBuffers) \
  120. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdCopyBufferToImage) \
  121. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdDrawIndexed) \
  122. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPipelineBarrier) \
  123. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPushConstants) \
  124. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetScissor) \
  125. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetViewport) \
  126. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateBuffer) \
  127. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateCommandPool) \
  128. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorPool) \
  129. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorSetLayout) \
  130. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFence) \
  131. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFramebuffer) \
  132. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateGraphicsPipelines) \
  133. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImage) \
  134. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImageView) \
  135. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreatePipelineLayout) \
  136. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateRenderPass) \
  137. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSampler) \
  138. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSemaphore) \
  139. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateShaderModule) \
  140. IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSwapchainKHR) \
  141. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyBuffer) \
  142. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyCommandPool) \
  143. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorPool) \
  144. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorSetLayout) \
  145. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFence) \
  146. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFramebuffer) \
  147. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImage) \
  148. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImageView) \
  149. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipeline) \
  150. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipelineLayout) \
  151. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyRenderPass) \
  152. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySampler) \
  153. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySemaphore) \
  154. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyShaderModule) \
  155. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \
  156. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \
  157. IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \
  158. IMGUI_VULKAN_FUNC_MAP_MACRO(vkEnumeratePhysicalDevices) \
  159. IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \
  160. IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \
  161. IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \
  162. IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \
  163. IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \
  164. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \
  165. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \
  166. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceProperties) \
  167. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceMemoryProperties) \
  168. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceQueueFamilyProperties) \
  169. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \
  170. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceFormatsKHR) \
  171. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \
  172. IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \
  173. IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \
  174. IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \
  175. IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \
  176. IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \
  177. IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \
  178. IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets)
  179. // Define function pointers
  180. #define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func;
  181. IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF)
  182. #undef IMGUI_VULKAN_FUNC_DEF
  183. #endif // IMGUI_IMPL_VULKAN_USE_LOADER
  184. #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
  185. static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR;
  186. static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR;
  187. #endif
  188. // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData()
  189. // [Please zero-clear before use!]
  190. struct ImGui_ImplVulkan_FrameRenderBuffers
  191. {
  192. VkDeviceMemory VertexBufferMemory;
  193. VkDeviceMemory IndexBufferMemory;
  194. VkDeviceSize VertexBufferSize;
  195. VkDeviceSize IndexBufferSize;
  196. VkBuffer VertexBuffer;
  197. VkBuffer IndexBuffer;
  198. };
  199. // Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers
  200. // [Please zero-clear before use!]
  201. struct ImGui_ImplVulkan_WindowRenderBuffers
  202. {
  203. uint32_t Index;
  204. uint32_t Count;
  205. ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers;
  206. };
  207. struct ImGui_ImplVulkan_Texture
  208. {
  209. VkDeviceMemory Memory;
  210. VkImage Image;
  211. VkImageView ImageView;
  212. VkDescriptorSet DescriptorSet;
  213. ImGui_ImplVulkan_Texture() { memset(this, 0, sizeof(*this)); }
  214. };
  215. // Vulkan data
  216. struct ImGui_ImplVulkan_Data
  217. {
  218. ImGui_ImplVulkan_InitInfo VulkanInitInfo;
  219. VkDeviceSize BufferMemoryAlignment;
  220. VkPipelineCreateFlags PipelineCreateFlags;
  221. VkDescriptorSetLayout DescriptorSetLayout;
  222. VkPipelineLayout PipelineLayout;
  223. VkPipeline Pipeline;
  224. VkShaderModule ShaderModuleVert;
  225. VkShaderModule ShaderModuleFrag;
  226. VkDescriptorPool DescriptorPool;
  227. // Texture management
  228. ImGui_ImplVulkan_Texture FontTexture;
  229. VkSampler TexSampler;
  230. VkCommandPool TexCommandPool;
  231. VkCommandBuffer TexCommandBuffer;
  232. // Render buffers for main window
  233. ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers;
  234. ImGui_ImplVulkan_Data()
  235. {
  236. memset((void*)this, 0, sizeof(*this));
  237. BufferMemoryAlignment = 256;
  238. }
  239. };
  240. //-----------------------------------------------------------------------------
  241. // SHADERS
  242. //-----------------------------------------------------------------------------
  243. // backends/vulkan/glsl_shader.vert, compiled with:
  244. // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
  245. /*
  246. #version 450 core
  247. layout(location = 0) in vec2 aPos;
  248. layout(location = 1) in vec2 aUV;
  249. layout(location = 2) in vec4 aColor;
  250. layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc;
  251. out gl_PerVertex { vec4 gl_Position; };
  252. layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
  253. void main()
  254. {
  255. Out.Color = aColor;
  256. Out.UV = aUV;
  257. gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1);
  258. }
  259. */
  260. static uint32_t __glsl_shader_vert_spv[] =
  261. {
  262. 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b,
  263. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  264. 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
  265. 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  266. 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
  267. 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
  268. 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
  269. 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
  270. 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c,
  271. 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074,
  272. 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001,
  273. 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b,
  274. 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
  275. 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
  276. 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e,
  277. 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008,
  278. 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
  279. 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017,
  280. 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020,
  281. 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015,
  282. 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020,
  283. 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020,
  284. 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020,
  285. 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020,
  286. 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a,
  287. 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014,
  288. 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f,
  289. 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021,
  290. 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006,
  291. 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,
  292. 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,
  293. 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,
  294. 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,
  295. 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022,
  296. 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008,
  297. 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013,
  298. 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024,
  299. 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006,
  300. 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b,
  301. 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e,
  302. 0x0000002d,0x0000002c,0x000100fd,0x00010038
  303. };
  304. // backends/vulkan/glsl_shader.frag, compiled with:
  305. // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
  306. /*
  307. #version 450 core
  308. layout(location = 0) out vec4 fColor;
  309. layout(set=0, binding=0) uniform sampler2D sTexture;
  310. layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
  311. void main()
  312. {
  313. fColor = In.Color * texture(sTexture, In.UV.st);
  314. }
  315. */
  316. static uint32_t __glsl_shader_frag_spv[] =
  317. {
  318. 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b,
  319. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  320. 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
  321. 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  322. 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
  323. 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
  324. 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574,
  325. 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,
  326. 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021,
  327. 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
  328. 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,
  329. 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006,
  330. 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001,
  331. 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020,
  332. 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001,
  333. 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
  334. 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000,
  335. 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018,
  336. 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004,
  337. 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d,
  338. 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017,
  339. 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a,
  340. 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085,
  341. 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd,
  342. 0x00010038
  343. };
  344. //-----------------------------------------------------------------------------
  345. // FUNCTIONS
  346. //-----------------------------------------------------------------------------
  347. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  348. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  349. // FIXME: multi-context support is not tested and probably dysfunctional in this backend.
  350. static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData()
  351. {
  352. return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  353. }
  354. static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits)
  355. {
  356. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  357. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  358. VkPhysicalDeviceMemoryProperties prop;
  359. vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop);
  360. for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
  361. if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1 << i))
  362. return i;
  363. return 0xFFFFFFFF; // Unable to find memoryType
  364. }
  365. static void check_vk_result(VkResult err)
  366. {
  367. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  368. if (!bd)
  369. return;
  370. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  371. if (v->CheckVkResultFn)
  372. v->CheckVkResultFn(err);
  373. }
  374. // Same as IM_MEMALIGN(). 'alignment' must be a power of two.
  375. static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize alignment)
  376. {
  377. return (size + alignment - 1) & ~(alignment - 1);
  378. }
  379. static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, VkDeviceSize new_size, VkBufferUsageFlagBits usage)
  380. {
  381. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  382. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  383. VkResult err;
  384. if (buffer != VK_NULL_HANDLE)
  385. vkDestroyBuffer(v->Device, buffer, v->Allocator);
  386. if (buffer_memory != VK_NULL_HANDLE)
  387. vkFreeMemory(v->Device, buffer_memory, v->Allocator);
  388. VkDeviceSize buffer_size_aligned = AlignBufferSize(IM_MAX(v->MinAllocationSize, new_size), bd->BufferMemoryAlignment);
  389. VkBufferCreateInfo buffer_info = {};
  390. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  391. buffer_info.size = buffer_size_aligned;
  392. buffer_info.usage = usage;
  393. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  394. err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer);
  395. check_vk_result(err);
  396. VkMemoryRequirements req;
  397. vkGetBufferMemoryRequirements(v->Device, buffer, &req);
  398. bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment;
  399. VkMemoryAllocateInfo alloc_info = {};
  400. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  401. alloc_info.allocationSize = req.size;
  402. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  403. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &buffer_memory);
  404. check_vk_result(err);
  405. err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0);
  406. check_vk_result(err);
  407. buffer_size = buffer_size_aligned;
  408. }
  409. static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* rb, int fb_width, int fb_height)
  410. {
  411. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  412. // Bind pipeline:
  413. {
  414. vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  415. }
  416. // Bind Vertex And Index Buffer:
  417. if (draw_data->TotalVtxCount > 0)
  418. {
  419. VkBuffer vertex_buffers[1] = { rb->VertexBuffer };
  420. VkDeviceSize vertex_offset[1] = { 0 };
  421. vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
  422. vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32);
  423. }
  424. // Setup viewport:
  425. {
  426. VkViewport viewport;
  427. viewport.x = 0;
  428. viewport.y = 0;
  429. viewport.width = (float)fb_width;
  430. viewport.height = (float)fb_height;
  431. viewport.minDepth = 0.0f;
  432. viewport.maxDepth = 1.0f;
  433. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  434. }
  435. // Setup scale and translation:
  436. // 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.
  437. {
  438. float scale[2];
  439. scale[0] = 2.0f / draw_data->DisplaySize.x;
  440. scale[1] = 2.0f / draw_data->DisplaySize.y;
  441. float translate[2];
  442. translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
  443. translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
  444. vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale);
  445. vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate);
  446. }
  447. }
  448. // Render function
  449. void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline)
  450. {
  451. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  452. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  453. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  454. if (fb_width <= 0 || fb_height <= 0)
  455. return;
  456. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  457. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  458. if (pipeline == VK_NULL_HANDLE)
  459. pipeline = bd->Pipeline;
  460. // Allocate array to store enough vertex/index buffers
  461. ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers;
  462. if (wrb->FrameRenderBuffers == nullptr)
  463. {
  464. wrb->Index = 0;
  465. wrb->Count = v->ImageCount;
  466. wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
  467. memset((void*)wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
  468. }
  469. IM_ASSERT(wrb->Count == v->ImageCount);
  470. wrb->Index = (wrb->Index + 1) % wrb->Count;
  471. ImGui_ImplVulkan_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index];
  472. if (draw_data->TotalVtxCount > 0)
  473. {
  474. // Create or resize the vertex/index buffers
  475. VkDeviceSize vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment);
  476. VkDeviceSize index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment);
  477. if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size)
  478. CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
  479. if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size)
  480. CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
  481. // Upload vertex/index data into a single contiguous GPU buffer
  482. ImDrawVert* vtx_dst = nullptr;
  483. ImDrawIdx* idx_dst = nullptr;
  484. VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)&vtx_dst);
  485. check_vk_result(err);
  486. err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst);
  487. check_vk_result(err);
  488. for (int n = 0; n < draw_data->CmdListsCount; n++)
  489. {
  490. const ImDrawList* draw_list = draw_data->CmdLists[n];
  491. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  492. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  493. vtx_dst += draw_list->VtxBuffer.Size;
  494. idx_dst += draw_list->IdxBuffer.Size;
  495. }
  496. VkMappedMemoryRange range[2] = {};
  497. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  498. range[0].memory = rb->VertexBufferMemory;
  499. range[0].size = VK_WHOLE_SIZE;
  500. range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  501. range[1].memory = rb->IndexBufferMemory;
  502. range[1].size = VK_WHOLE_SIZE;
  503. err = vkFlushMappedMemoryRanges(v->Device, 2, range);
  504. check_vk_result(err);
  505. vkUnmapMemory(v->Device, rb->VertexBufferMemory);
  506. vkUnmapMemory(v->Device, rb->IndexBufferMemory);
  507. }
  508. // Setup desired Vulkan state
  509. ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
  510. // Setup render state structure (for callbacks and custom texture bindings)
  511. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  512. ImGui_ImplVulkan_RenderState render_state;
  513. render_state.CommandBuffer = command_buffer;
  514. render_state.Pipeline = pipeline;
  515. render_state.PipelineLayout = bd->PipelineLayout;
  516. platform_io.Renderer_RenderState = &render_state;
  517. // Will project scissor/clipping rectangles into framebuffer space
  518. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  519. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  520. // Render command lists
  521. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  522. int global_vtx_offset = 0;
  523. int global_idx_offset = 0;
  524. for (int n = 0; n < draw_data->CmdListsCount; n++)
  525. {
  526. const ImDrawList* draw_list = draw_data->CmdLists[n];
  527. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  528. {
  529. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  530. if (pcmd->UserCallback != nullptr)
  531. {
  532. // User callback, registered via ImDrawList::AddCallback()
  533. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  534. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  535. ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
  536. else
  537. pcmd->UserCallback(draw_list, pcmd);
  538. }
  539. else
  540. {
  541. // Project scissor/clipping rectangles into framebuffer space
  542. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  543. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  544. // Clamp to viewport as vkCmdSetScissor() won't accept values that are off bounds
  545. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  546. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  547. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  548. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  549. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  550. continue;
  551. // Apply scissor/clipping rectangle
  552. VkRect2D scissor;
  553. scissor.offset.x = (int32_t)(clip_min.x);
  554. scissor.offset.y = (int32_t)(clip_min.y);
  555. scissor.extent.width = (uint32_t)(clip_max.x - clip_min.x);
  556. scissor.extent.height = (uint32_t)(clip_max.y - clip_min.y);
  557. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  558. // Bind DescriptorSet with font or user texture
  559. VkDescriptorSet desc_set = (VkDescriptorSet)pcmd->GetTexID();
  560. vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, &desc_set, 0, nullptr);
  561. // Draw
  562. vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  563. }
  564. }
  565. global_idx_offset += draw_list->IdxBuffer.Size;
  566. global_vtx_offset += draw_list->VtxBuffer.Size;
  567. }
  568. platform_io.Renderer_RenderState = nullptr;
  569. // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called.
  570. // Our last values will leak into user/application rendering IF:
  571. // - Your app uses a pipeline with VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR dynamic state
  572. // - And you forgot to call vkCmdSetViewport() and vkCmdSetScissor() yourself to explicitly set that state.
  573. // If you use VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR you are responsible for setting the values before rendering.
  574. // In theory we should aim to backup/restore those values but I am not sure this is possible.
  575. // We perform a call to vkCmdSetScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644)
  576. VkRect2D scissor = { { 0, 0 }, { (uint32_t)fb_width, (uint32_t)fb_height } };
  577. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  578. }
  579. bool ImGui_ImplVulkan_CreateFontsTexture()
  580. {
  581. ImGuiIO& io = ImGui::GetIO();
  582. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  583. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  584. VkResult err;
  585. // Destroy existing texture (if any)
  586. if (bd->FontTexture.DescriptorSet)
  587. {
  588. vkQueueWaitIdle(v->Queue);
  589. ImGui_ImplVulkan_DestroyFontsTexture();
  590. }
  591. // Create command pool/buffer
  592. if (bd->TexCommandPool == VK_NULL_HANDLE)
  593. {
  594. VkCommandPoolCreateInfo info = {};
  595. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  596. info.flags = 0;
  597. info.queueFamilyIndex = v->QueueFamily;
  598. vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->TexCommandPool);
  599. }
  600. if (bd->TexCommandBuffer == VK_NULL_HANDLE)
  601. {
  602. VkCommandBufferAllocateInfo info = {};
  603. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  604. info.commandPool = bd->TexCommandPool;
  605. info.commandBufferCount = 1;
  606. err = vkAllocateCommandBuffers(v->Device, &info, &bd->TexCommandBuffer);
  607. check_vk_result(err);
  608. }
  609. // Start command buffer
  610. {
  611. err = vkResetCommandPool(v->Device, bd->TexCommandPool, 0);
  612. check_vk_result(err);
  613. VkCommandBufferBeginInfo begin_info = {};
  614. begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  615. begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  616. err = vkBeginCommandBuffer(bd->TexCommandBuffer, &begin_info);
  617. check_vk_result(err);
  618. }
  619. unsigned char* pixels;
  620. int width, height;
  621. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  622. size_t upload_size = width * height * 4 * sizeof(char);
  623. // Create the Image:
  624. ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture;
  625. {
  626. VkImageCreateInfo info = {};
  627. info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  628. info.imageType = VK_IMAGE_TYPE_2D;
  629. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  630. info.extent.width = width;
  631. info.extent.height = height;
  632. info.extent.depth = 1;
  633. info.mipLevels = 1;
  634. info.arrayLayers = 1;
  635. info.samples = VK_SAMPLE_COUNT_1_BIT;
  636. info.tiling = VK_IMAGE_TILING_OPTIMAL;
  637. info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  638. info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  639. info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  640. err = vkCreateImage(v->Device, &info, v->Allocator, &backend_tex->Image);
  641. check_vk_result(err);
  642. VkMemoryRequirements req;
  643. vkGetImageMemoryRequirements(v->Device, backend_tex->Image, &req);
  644. VkMemoryAllocateInfo alloc_info = {};
  645. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  646. alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size);
  647. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
  648. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &backend_tex->Memory);
  649. check_vk_result(err);
  650. err = vkBindImageMemory(v->Device, backend_tex->Image, backend_tex->Memory, 0);
  651. check_vk_result(err);
  652. }
  653. // Create the Image View:
  654. {
  655. VkImageViewCreateInfo info = {};
  656. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  657. info.image = backend_tex->Image;
  658. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  659. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  660. info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  661. info.subresourceRange.levelCount = 1;
  662. info.subresourceRange.layerCount = 1;
  663. err = vkCreateImageView(v->Device, &info, v->Allocator, &backend_tex->ImageView);
  664. check_vk_result(err);
  665. }
  666. // Create the Descriptor Set:
  667. backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSampler, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
  668. // Create the Upload Buffer:
  669. VkDeviceMemory upload_buffer_memory;
  670. VkBuffer upload_buffer;
  671. {
  672. VkBufferCreateInfo buffer_info = {};
  673. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  674. buffer_info.size = upload_size;
  675. buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  676. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  677. err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer);
  678. check_vk_result(err);
  679. VkMemoryRequirements req;
  680. vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req);
  681. bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment;
  682. VkMemoryAllocateInfo alloc_info = {};
  683. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  684. alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size);
  685. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  686. err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory);
  687. check_vk_result(err);
  688. err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0);
  689. check_vk_result(err);
  690. }
  691. // Upload to Buffer:
  692. {
  693. char* map = nullptr;
  694. err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map));
  695. check_vk_result(err);
  696. memcpy(map, pixels, upload_size);
  697. VkMappedMemoryRange range[1] = {};
  698. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  699. range[0].memory = upload_buffer_memory;
  700. range[0].size = upload_size;
  701. err = vkFlushMappedMemoryRanges(v->Device, 1, range);
  702. check_vk_result(err);
  703. vkUnmapMemory(v->Device, upload_buffer_memory);
  704. }
  705. // Copy to Image:
  706. {
  707. VkImageMemoryBarrier copy_barrier[1] = {};
  708. copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  709. copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  710. copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  711. copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  712. copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  713. copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  714. copy_barrier[0].image = backend_tex->Image;
  715. copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  716. copy_barrier[0].subresourceRange.levelCount = 1;
  717. copy_barrier[0].subresourceRange.layerCount = 1;
  718. vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier);
  719. VkBufferImageCopy region = {};
  720. region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  721. region.imageSubresource.layerCount = 1;
  722. region.imageExtent.width = width;
  723. region.imageExtent.height = height;
  724. region.imageExtent.depth = 1;
  725. vkCmdCopyBufferToImage(bd->TexCommandBuffer, upload_buffer, backend_tex->Image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
  726. VkImageMemoryBarrier use_barrier[1] = {};
  727. use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  728. use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  729. use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  730. use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  731. use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  732. use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  733. use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  734. use_barrier[0].image = backend_tex->Image;
  735. use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  736. use_barrier[0].subresourceRange.levelCount = 1;
  737. use_barrier[0].subresourceRange.layerCount = 1;
  738. vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier);
  739. }
  740. // Store our identifier
  741. io.Fonts->SetTexID((ImTextureID)backend_tex->DescriptorSet);
  742. // End command buffer
  743. VkSubmitInfo end_info = {};
  744. end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  745. end_info.commandBufferCount = 1;
  746. end_info.pCommandBuffers = &bd->TexCommandBuffer;
  747. err = vkEndCommandBuffer(bd->TexCommandBuffer);
  748. check_vk_result(err);
  749. err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE);
  750. check_vk_result(err);
  751. err = vkQueueWaitIdle(v->Queue);
  752. check_vk_result(err);
  753. vkDestroyBuffer(v->Device, upload_buffer, v->Allocator);
  754. vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator);
  755. return true;
  756. }
  757. // You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown().
  758. void ImGui_ImplVulkan_DestroyFontsTexture()
  759. {
  760. ImGuiIO& io = ImGui::GetIO();
  761. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  762. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  763. ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture;
  764. if (backend_tex->DescriptorSet)
  765. {
  766. ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet);
  767. backend_tex->DescriptorSet = VK_NULL_HANDLE;
  768. io.Fonts->SetTexID(0);
  769. }
  770. if (backend_tex->ImageView) { vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); backend_tex->ImageView = VK_NULL_HANDLE; }
  771. if (backend_tex->Image) { vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); backend_tex->Image = VK_NULL_HANDLE; }
  772. if (backend_tex->Memory) { vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); backend_tex->Memory = VK_NULL_HANDLE; }
  773. }
  774. static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator)
  775. {
  776. // Create the shader modules
  777. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  778. if (bd->ShaderModuleVert == VK_NULL_HANDLE)
  779. {
  780. VkShaderModuleCreateInfo vert_info = {};
  781. vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  782. vert_info.codeSize = sizeof(__glsl_shader_vert_spv);
  783. vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv;
  784. VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &bd->ShaderModuleVert);
  785. check_vk_result(err);
  786. }
  787. if (bd->ShaderModuleFrag == VK_NULL_HANDLE)
  788. {
  789. VkShaderModuleCreateInfo frag_info = {};
  790. frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  791. frag_info.codeSize = sizeof(__glsl_shader_frag_spv);
  792. frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv;
  793. VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &bd->ShaderModuleFrag);
  794. check_vk_result(err);
  795. }
  796. }
  797. static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass)
  798. {
  799. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  800. ImGui_ImplVulkan_CreateShaderModules(device, allocator);
  801. VkPipelineShaderStageCreateInfo stage[2] = {};
  802. stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  803. stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  804. stage[0].module = bd->ShaderModuleVert;
  805. stage[0].pName = "main";
  806. stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  807. stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  808. stage[1].module = bd->ShaderModuleFrag;
  809. stage[1].pName = "main";
  810. VkVertexInputBindingDescription binding_desc[1] = {};
  811. binding_desc[0].stride = sizeof(ImDrawVert);
  812. binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  813. VkVertexInputAttributeDescription attribute_desc[3] = {};
  814. attribute_desc[0].location = 0;
  815. attribute_desc[0].binding = binding_desc[0].binding;
  816. attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
  817. attribute_desc[0].offset = offsetof(ImDrawVert, pos);
  818. attribute_desc[1].location = 1;
  819. attribute_desc[1].binding = binding_desc[0].binding;
  820. attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
  821. attribute_desc[1].offset = offsetof(ImDrawVert, uv);
  822. attribute_desc[2].location = 2;
  823. attribute_desc[2].binding = binding_desc[0].binding;
  824. attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
  825. attribute_desc[2].offset = offsetof(ImDrawVert, col);
  826. VkPipelineVertexInputStateCreateInfo vertex_info = {};
  827. vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  828. vertex_info.vertexBindingDescriptionCount = 1;
  829. vertex_info.pVertexBindingDescriptions = binding_desc;
  830. vertex_info.vertexAttributeDescriptionCount = 3;
  831. vertex_info.pVertexAttributeDescriptions = attribute_desc;
  832. VkPipelineInputAssemblyStateCreateInfo ia_info = {};
  833. ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  834. ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  835. VkPipelineViewportStateCreateInfo viewport_info = {};
  836. viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  837. viewport_info.viewportCount = 1;
  838. viewport_info.scissorCount = 1;
  839. VkPipelineRasterizationStateCreateInfo raster_info = {};
  840. raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  841. raster_info.polygonMode = VK_POLYGON_MODE_FILL;
  842. raster_info.cullMode = VK_CULL_MODE_NONE;
  843. raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
  844. raster_info.lineWidth = 1.0f;
  845. VkPipelineMultisampleStateCreateInfo ms_info = {};
  846. ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  847. ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT;
  848. VkPipelineColorBlendAttachmentState color_attachment[1] = {};
  849. color_attachment[0].blendEnable = VK_TRUE;
  850. color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
  851. color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  852. color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
  853. color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
  854. color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  855. color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
  856. color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  857. VkPipelineDepthStencilStateCreateInfo depth_info = {};
  858. depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  859. VkPipelineColorBlendStateCreateInfo blend_info = {};
  860. blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  861. blend_info.attachmentCount = 1;
  862. blend_info.pAttachments = color_attachment;
  863. VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
  864. VkPipelineDynamicStateCreateInfo dynamic_state = {};
  865. dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  866. dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
  867. dynamic_state.pDynamicStates = dynamic_states;
  868. VkGraphicsPipelineCreateInfo info = {};
  869. info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  870. info.flags = bd->PipelineCreateFlags;
  871. info.stageCount = 2;
  872. info.pStages = stage;
  873. info.pVertexInputState = &vertex_info;
  874. info.pInputAssemblyState = &ia_info;
  875. info.pViewportState = &viewport_info;
  876. info.pRasterizationState = &raster_info;
  877. info.pMultisampleState = &ms_info;
  878. info.pDepthStencilState = &depth_info;
  879. info.pColorBlendState = &blend_info;
  880. info.pDynamicState = &dynamic_state;
  881. info.layout = bd->PipelineLayout;
  882. info.renderPass = renderPass;
  883. info.subpass = subpass;
  884. #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
  885. if (bd->VulkanInitInfo.UseDynamicRendering)
  886. {
  887. IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR");
  888. IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be nullptr");
  889. info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo;
  890. info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr.
  891. }
  892. #endif
  893. VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline);
  894. check_vk_result(err);
  895. }
  896. bool ImGui_ImplVulkan_CreateDeviceObjects()
  897. {
  898. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  899. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  900. VkResult err;
  901. if (!bd->TexSampler)
  902. {
  903. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  904. VkSamplerCreateInfo info = {};
  905. info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  906. info.magFilter = VK_FILTER_LINEAR;
  907. info.minFilter = VK_FILTER_LINEAR;
  908. info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
  909. info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  910. info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  911. info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  912. info.minLod = -1000;
  913. info.maxLod = 1000;
  914. info.maxAnisotropy = 1.0f;
  915. err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->TexSampler);
  916. check_vk_result(err);
  917. }
  918. if (!bd->DescriptorSetLayout)
  919. {
  920. VkDescriptorSetLayoutBinding binding[1] = {};
  921. binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  922. binding[0].descriptorCount = 1;
  923. binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
  924. VkDescriptorSetLayoutCreateInfo info = {};
  925. info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  926. info.bindingCount = 1;
  927. info.pBindings = binding;
  928. err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &bd->DescriptorSetLayout);
  929. check_vk_result(err);
  930. }
  931. if (v->DescriptorPoolSize)
  932. {
  933. VkDescriptorPoolSize pool_size = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, v->DescriptorPoolSize };
  934. VkDescriptorPoolCreateInfo pool_info = {};
  935. pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  936. pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
  937. pool_info.maxSets = v->DescriptorPoolSize;
  938. pool_info.poolSizeCount = 1;
  939. pool_info.pPoolSizes = &pool_size;
  940. err = vkCreateDescriptorPool(v->Device, &pool_info, v->Allocator, &bd->DescriptorPool);
  941. check_vk_result(err);
  942. }
  943. if (!bd->PipelineLayout)
  944. {
  945. // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
  946. VkPushConstantRange push_constants[1] = {};
  947. push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
  948. push_constants[0].offset = sizeof(float) * 0;
  949. push_constants[0].size = sizeof(float) * 4;
  950. VkDescriptorSetLayout set_layout[1] = { bd->DescriptorSetLayout };
  951. VkPipelineLayoutCreateInfo layout_info = {};
  952. layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  953. layout_info.setLayoutCount = 1;
  954. layout_info.pSetLayouts = set_layout;
  955. layout_info.pushConstantRangeCount = 1;
  956. layout_info.pPushConstantRanges = push_constants;
  957. err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &bd->PipelineLayout);
  958. check_vk_result(err);
  959. }
  960. ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass);
  961. return true;
  962. }
  963. void ImGui_ImplVulkan_DestroyDeviceObjects()
  964. {
  965. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  966. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  967. ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator);
  968. ImGui_ImplVulkan_DestroyFontsTexture();
  969. if (bd->TexCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->TexCommandPool, 1, &bd->TexCommandBuffer); bd->TexCommandBuffer = VK_NULL_HANDLE; }
  970. if (bd->TexCommandPool) { vkDestroyCommandPool(v->Device, bd->TexCommandPool, v->Allocator); bd->TexCommandPool = VK_NULL_HANDLE; }
  971. if (bd->TexSampler) { vkDestroySampler(v->Device, bd->TexSampler, v->Allocator); bd->TexSampler = VK_NULL_HANDLE; }
  972. if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; }
  973. if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; }
  974. if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; }
  975. if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; }
  976. if (bd->Pipeline) { vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; }
  977. if (bd->DescriptorPool) { vkDestroyDescriptorPool(v->Device, bd->DescriptorPool, v->Allocator); bd->DescriptorPool = VK_NULL_HANDLE; }
  978. }
  979. bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data)
  980. {
  981. // Load function pointers
  982. // You can use the default Vulkan loader using:
  983. // ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); });
  984. // But this would be roughly equivalent to not setting VK_NO_PROTOTYPES.
  985. #ifdef IMGUI_IMPL_VULKAN_USE_LOADER
  986. #define IMGUI_VULKAN_FUNC_LOAD(func) \
  987. func = reinterpret_cast<decltype(func)>(loader_func(#func, user_data)); \
  988. if (func == nullptr) \
  989. return false;
  990. IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_LOAD)
  991. #undef IMGUI_VULKAN_FUNC_LOAD
  992. #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
  993. // Manually load those two (see #5446)
  994. ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(loader_func("vkCmdBeginRenderingKHR", user_data));
  995. ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(loader_func("vkCmdEndRenderingKHR", user_data));
  996. #endif
  997. #else
  998. IM_UNUSED(loader_func);
  999. IM_UNUSED(user_data);
  1000. #endif
  1001. g_FunctionsLoaded = true;
  1002. return true;
  1003. }
  1004. bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info)
  1005. {
  1006. IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!");
  1007. if (info->UseDynamicRendering)
  1008. {
  1009. #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
  1010. #ifndef IMGUI_IMPL_VULKAN_USE_LOADER
  1011. ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR"));
  1012. ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR"));
  1013. #endif
  1014. IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr);
  1015. IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr);
  1016. #else
  1017. IM_ASSERT(0 && "Can't use dynamic rendering when neither VK_VERSION_1_3 or VK_KHR_dynamic_rendering is defined.");
  1018. #endif
  1019. }
  1020. ImGuiIO& io = ImGui::GetIO();
  1021. IMGUI_CHECKVERSION();
  1022. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  1023. // Setup backend capabilities flags
  1024. ImGui_ImplVulkan_Data* bd = IM_NEW(ImGui_ImplVulkan_Data)();
  1025. io.BackendRendererUserData = (void*)bd;
  1026. io.BackendRendererName = "imgui_impl_vulkan";
  1027. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  1028. IM_ASSERT(info->Instance != VK_NULL_HANDLE);
  1029. IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE);
  1030. IM_ASSERT(info->Device != VK_NULL_HANDLE);
  1031. IM_ASSERT(info->Queue != VK_NULL_HANDLE);
  1032. if (info->DescriptorPool != VK_NULL_HANDLE) // Either DescriptorPool or DescriptorPoolSize must be set, not both!
  1033. IM_ASSERT(info->DescriptorPoolSize == 0);
  1034. else
  1035. IM_ASSERT(info->DescriptorPoolSize > 0);
  1036. IM_ASSERT(info->MinImageCount >= 2);
  1037. IM_ASSERT(info->ImageCount >= info->MinImageCount);
  1038. if (info->UseDynamicRendering == false)
  1039. IM_ASSERT(info->RenderPass != VK_NULL_HANDLE);
  1040. bd->VulkanInitInfo = *info;
  1041. ImGui_ImplVulkan_CreateDeviceObjects();
  1042. return true;
  1043. }
  1044. void ImGui_ImplVulkan_Shutdown()
  1045. {
  1046. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  1047. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  1048. ImGuiIO& io = ImGui::GetIO();
  1049. ImGui_ImplVulkan_DestroyDeviceObjects();
  1050. io.BackendRendererName = nullptr;
  1051. io.BackendRendererUserData = nullptr;
  1052. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  1053. IM_DELETE(bd);
  1054. }
  1055. void ImGui_ImplVulkan_NewFrame()
  1056. {
  1057. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  1058. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?");
  1059. if (!bd->FontTexture.DescriptorSet)
  1060. ImGui_ImplVulkan_CreateFontsTexture();
  1061. }
  1062. void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count)
  1063. {
  1064. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  1065. IM_ASSERT(min_image_count >= 2);
  1066. if (bd->VulkanInitInfo.MinImageCount == min_image_count)
  1067. return;
  1068. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  1069. VkResult err = vkDeviceWaitIdle(v->Device);
  1070. check_vk_result(err);
  1071. ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator);
  1072. bd->VulkanInitInfo.MinImageCount = min_image_count;
  1073. }
  1074. // Register a texture by creating a descriptor
  1075. // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem, please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions.
  1076. VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout)
  1077. {
  1078. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  1079. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  1080. VkDescriptorPool pool = bd->DescriptorPool ? bd->DescriptorPool : v->DescriptorPool;
  1081. // Create Descriptor Set:
  1082. VkDescriptorSet descriptor_set;
  1083. {
  1084. VkDescriptorSetAllocateInfo alloc_info = {};
  1085. alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  1086. alloc_info.descriptorPool = pool;
  1087. alloc_info.descriptorSetCount = 1;
  1088. alloc_info.pSetLayouts = &bd->DescriptorSetLayout;
  1089. VkResult err = vkAllocateDescriptorSets(v->Device, &alloc_info, &descriptor_set);
  1090. check_vk_result(err);
  1091. }
  1092. // Update the Descriptor Set:
  1093. {
  1094. VkDescriptorImageInfo desc_image[1] = {};
  1095. desc_image[0].sampler = sampler;
  1096. desc_image[0].imageView = image_view;
  1097. desc_image[0].imageLayout = image_layout;
  1098. VkWriteDescriptorSet write_desc[1] = {};
  1099. write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  1100. write_desc[0].dstSet = descriptor_set;
  1101. write_desc[0].descriptorCount = 1;
  1102. write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  1103. write_desc[0].pImageInfo = desc_image;
  1104. vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, nullptr);
  1105. }
  1106. return descriptor_set;
  1107. }
  1108. void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set)
  1109. {
  1110. ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
  1111. ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
  1112. VkDescriptorPool pool = bd->DescriptorPool ? bd->DescriptorPool : v->DescriptorPool;
  1113. vkFreeDescriptorSets(v->Device, pool, 1, &descriptor_set);
  1114. }
  1115. void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
  1116. {
  1117. if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; }
  1118. if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; }
  1119. if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; }
  1120. if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; }
  1121. buffers->VertexBufferSize = 0;
  1122. buffers->IndexBufferSize = 0;
  1123. }
  1124. void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
  1125. {
  1126. for (uint32_t n = 0; n < buffers->Count; n++)
  1127. ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator);
  1128. IM_FREE(buffers->FrameRenderBuffers);
  1129. buffers->FrameRenderBuffers = nullptr;
  1130. buffers->Index = 0;
  1131. buffers->Count = 0;
  1132. }
  1133. //-------------------------------------------------------------------------
  1134. // Internal / Miscellaneous Vulkan Helpers
  1135. // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.)
  1136. //-------------------------------------------------------------------------
  1137. // You probably do NOT need to use or care about those functions.
  1138. // Those functions only exist because:
  1139. // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
  1140. // 2) the upcoming multi-viewport feature will need them internally.
  1141. // Generally we avoid exposing any kind of superfluous high-level helpers in the backends,
  1142. // but it is too much code to duplicate everywhere so we exceptionally expose them.
  1143. //
  1144. // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.).
  1145. // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work.
  1146. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions)
  1147. //-------------------------------------------------------------------------
  1148. VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space)
  1149. {
  1150. IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!");
  1151. IM_ASSERT(request_formats != nullptr);
  1152. IM_ASSERT(request_formats_count > 0);
  1153. // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
  1154. // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
  1155. // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
  1156. // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
  1157. uint32_t avail_count;
  1158. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, nullptr);
  1159. ImVector<VkSurfaceFormatKHR> avail_format;
  1160. avail_format.resize((int)avail_count);
  1161. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data);
  1162. // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
  1163. if (avail_count == 1)
  1164. {
  1165. if (avail_format[0].format == VK_FORMAT_UNDEFINED)
  1166. {
  1167. VkSurfaceFormatKHR ret;
  1168. ret.format = request_formats[0];
  1169. ret.colorSpace = request_color_space;
  1170. return ret;
  1171. }
  1172. else
  1173. {
  1174. // No point in searching another format
  1175. return avail_format[0];
  1176. }
  1177. }
  1178. else
  1179. {
  1180. // Request several formats, the first found will be used
  1181. for (int request_i = 0; request_i < request_formats_count; request_i++)
  1182. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  1183. if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space)
  1184. return avail_format[avail_i];
  1185. // If none of the requested image formats could be found, use the first available
  1186. return avail_format[0];
  1187. }
  1188. }
  1189. VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count)
  1190. {
  1191. IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!");
  1192. IM_ASSERT(request_modes != nullptr);
  1193. IM_ASSERT(request_modes_count > 0);
  1194. // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
  1195. uint32_t avail_count = 0;
  1196. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, nullptr);
  1197. ImVector<VkPresentModeKHR> avail_modes;
  1198. avail_modes.resize((int)avail_count);
  1199. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data);
  1200. //for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  1201. // printf("[vulkan] avail_modes[%d] = %d\n", avail_i, avail_modes[avail_i]);
  1202. for (int request_i = 0; request_i < request_modes_count; request_i++)
  1203. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  1204. if (request_modes[request_i] == avail_modes[avail_i])
  1205. return request_modes[request_i];
  1206. return VK_PRESENT_MODE_FIFO_KHR; // Always available
  1207. }
  1208. VkPhysicalDevice ImGui_ImplVulkanH_SelectPhysicalDevice(VkInstance instance)
  1209. {
  1210. uint32_t gpu_count;
  1211. VkResult err = vkEnumeratePhysicalDevices(instance, &gpu_count, nullptr);
  1212. check_vk_result(err);
  1213. IM_ASSERT(gpu_count > 0);
  1214. ImVector<VkPhysicalDevice> gpus;
  1215. gpus.resize(gpu_count);
  1216. err = vkEnumeratePhysicalDevices(instance, &gpu_count, gpus.Data);
  1217. check_vk_result(err);
  1218. // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers
  1219. // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple
  1220. // dedicated GPUs) is out of scope of this sample.
  1221. for (VkPhysicalDevice& device : gpus)
  1222. {
  1223. VkPhysicalDeviceProperties properties;
  1224. vkGetPhysicalDeviceProperties(device, &properties);
  1225. if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
  1226. return device;
  1227. }
  1228. // Use first GPU (Integrated) is a Discrete one is not available.
  1229. if (gpu_count > 0)
  1230. return gpus[0];
  1231. return VK_NULL_HANDLE;
  1232. }
  1233. uint32_t ImGui_ImplVulkanH_SelectQueueFamilyIndex(VkPhysicalDevice physical_device)
  1234. {
  1235. uint32_t count;
  1236. vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, nullptr);
  1237. ImVector<VkQueueFamilyProperties> queues_properties;
  1238. queues_properties.resize((int)count);
  1239. vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, queues_properties.Data);
  1240. for (uint32_t i = 0; i < count; i++)
  1241. if (queues_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
  1242. return i;
  1243. return (uint32_t)-1;
  1244. }
  1245. void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator)
  1246. {
  1247. IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE);
  1248. IM_UNUSED(physical_device);
  1249. // Create Command Buffers
  1250. VkResult err;
  1251. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1252. {
  1253. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  1254. {
  1255. VkCommandPoolCreateInfo info = {};
  1256. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  1257. info.flags = 0;
  1258. info.queueFamilyIndex = queue_family;
  1259. err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool);
  1260. check_vk_result(err);
  1261. }
  1262. {
  1263. VkCommandBufferAllocateInfo info = {};
  1264. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  1265. info.commandPool = fd->CommandPool;
  1266. info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  1267. info.commandBufferCount = 1;
  1268. err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer);
  1269. check_vk_result(err);
  1270. }
  1271. {
  1272. VkFenceCreateInfo info = {};
  1273. info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  1274. info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  1275. err = vkCreateFence(device, &info, allocator, &fd->Fence);
  1276. check_vk_result(err);
  1277. }
  1278. }
  1279. for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
  1280. {
  1281. ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i];
  1282. {
  1283. VkSemaphoreCreateInfo info = {};
  1284. info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  1285. err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore);
  1286. check_vk_result(err);
  1287. err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore);
  1288. check_vk_result(err);
  1289. }
  1290. }
  1291. }
  1292. int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode)
  1293. {
  1294. if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
  1295. return 3;
  1296. if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
  1297. return 2;
  1298. if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
  1299. return 1;
  1300. IM_ASSERT(0);
  1301. return 1;
  1302. }
  1303. // Also destroy old swap chain and in-flight frames data, if any.
  1304. 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)
  1305. {
  1306. VkResult err;
  1307. VkSwapchainKHR old_swapchain = wd->Swapchain;
  1308. wd->Swapchain = VK_NULL_HANDLE;
  1309. err = vkDeviceWaitIdle(device);
  1310. check_vk_result(err);
  1311. // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one.
  1312. // Destroy old Framebuffer
  1313. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1314. ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
  1315. for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
  1316. ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
  1317. IM_FREE(wd->Frames);
  1318. IM_FREE(wd->FrameSemaphores);
  1319. wd->Frames = nullptr;
  1320. wd->FrameSemaphores = nullptr;
  1321. wd->ImageCount = 0;
  1322. if (wd->RenderPass)
  1323. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  1324. if (wd->Pipeline)
  1325. vkDestroyPipeline(device, wd->Pipeline, allocator);
  1326. // If min image count was not specified, request different count of images dependent on selected present mode
  1327. if (min_image_count == 0)
  1328. min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode);
  1329. // Create Swapchain
  1330. {
  1331. VkSurfaceCapabilitiesKHR cap;
  1332. err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
  1333. check_vk_result(err);
  1334. VkSwapchainCreateInfoKHR info = {};
  1335. info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  1336. info.surface = wd->Surface;
  1337. info.minImageCount = min_image_count;
  1338. info.imageFormat = wd->SurfaceFormat.format;
  1339. info.imageColorSpace = wd->SurfaceFormat.colorSpace;
  1340. info.imageArrayLayers = 1;
  1341. info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1342. info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family
  1343. info.preTransform = (cap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : cap.currentTransform;
  1344. info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1345. info.presentMode = wd->PresentMode;
  1346. info.clipped = VK_TRUE;
  1347. info.oldSwapchain = old_swapchain;
  1348. if (info.minImageCount < cap.minImageCount)
  1349. info.minImageCount = cap.minImageCount;
  1350. else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount)
  1351. info.minImageCount = cap.maxImageCount;
  1352. if (cap.currentExtent.width == 0xffffffff)
  1353. {
  1354. info.imageExtent.width = wd->Width = w;
  1355. info.imageExtent.height = wd->Height = h;
  1356. }
  1357. else
  1358. {
  1359. info.imageExtent.width = wd->Width = cap.currentExtent.width;
  1360. info.imageExtent.height = wd->Height = cap.currentExtent.height;
  1361. }
  1362. err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain);
  1363. check_vk_result(err);
  1364. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, nullptr);
  1365. check_vk_result(err);
  1366. VkImage backbuffers[16] = {};
  1367. IM_ASSERT(wd->ImageCount >= min_image_count);
  1368. IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers));
  1369. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers);
  1370. check_vk_result(err);
  1371. IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr);
  1372. wd->SemaphoreCount = wd->ImageCount + 1;
  1373. wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount);
  1374. wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount);
  1375. memset((void*)wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount);
  1376. memset((void*)wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount);
  1377. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1378. wd->Frames[i].Backbuffer = backbuffers[i];
  1379. }
  1380. if (old_swapchain)
  1381. vkDestroySwapchainKHR(device, old_swapchain, allocator);
  1382. // Create the Render Pass
  1383. if (wd->UseDynamicRendering == false)
  1384. {
  1385. VkAttachmentDescription attachment = {};
  1386. attachment.format = wd->SurfaceFormat.format;
  1387. attachment.samples = VK_SAMPLE_COUNT_1_BIT;
  1388. attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1389. attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1390. attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1391. attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1392. attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1393. attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  1394. VkAttachmentReference color_attachment = {};
  1395. color_attachment.attachment = 0;
  1396. color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1397. VkSubpassDescription subpass = {};
  1398. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  1399. subpass.colorAttachmentCount = 1;
  1400. subpass.pColorAttachments = &color_attachment;
  1401. VkSubpassDependency dependency = {};
  1402. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  1403. dependency.dstSubpass = 0;
  1404. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1405. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1406. dependency.srcAccessMask = 0;
  1407. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  1408. VkRenderPassCreateInfo info = {};
  1409. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  1410. info.attachmentCount = 1;
  1411. info.pAttachments = &attachment;
  1412. info.subpassCount = 1;
  1413. info.pSubpasses = &subpass;
  1414. info.dependencyCount = 1;
  1415. info.pDependencies = &dependency;
  1416. err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass);
  1417. check_vk_result(err);
  1418. // We do not create a pipeline by default as this is also used by examples' main.cpp,
  1419. // but secondary viewport in multi-viewport mode may want to create one with:
  1420. //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, v->Subpass);
  1421. }
  1422. // Create The Image Views
  1423. {
  1424. VkImageViewCreateInfo info = {};
  1425. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1426. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  1427. info.format = wd->SurfaceFormat.format;
  1428. info.components.r = VK_COMPONENT_SWIZZLE_R;
  1429. info.components.g = VK_COMPONENT_SWIZZLE_G;
  1430. info.components.b = VK_COMPONENT_SWIZZLE_B;
  1431. info.components.a = VK_COMPONENT_SWIZZLE_A;
  1432. VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
  1433. info.subresourceRange = image_range;
  1434. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1435. {
  1436. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  1437. info.image = fd->Backbuffer;
  1438. err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView);
  1439. check_vk_result(err);
  1440. }
  1441. }
  1442. // Create Framebuffer
  1443. if (wd->UseDynamicRendering == false)
  1444. {
  1445. VkImageView attachment[1];
  1446. VkFramebufferCreateInfo info = {};
  1447. info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1448. info.renderPass = wd->RenderPass;
  1449. info.attachmentCount = 1;
  1450. info.pAttachments = attachment;
  1451. info.width = wd->Width;
  1452. info.height = wd->Height;
  1453. info.layers = 1;
  1454. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1455. {
  1456. ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
  1457. attachment[0] = fd->BackbufferView;
  1458. err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer);
  1459. check_vk_result(err);
  1460. }
  1461. }
  1462. }
  1463. // Create or resize window
  1464. 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)
  1465. {
  1466. IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!");
  1467. (void)instance;
  1468. ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count);
  1469. ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator);
  1470. }
  1471. void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator)
  1472. {
  1473. vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
  1474. //vkQueueWaitIdle(bd->Queue);
  1475. for (uint32_t i = 0; i < wd->ImageCount; i++)
  1476. ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
  1477. for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
  1478. ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
  1479. IM_FREE(wd->Frames);
  1480. IM_FREE(wd->FrameSemaphores);
  1481. wd->Frames = nullptr;
  1482. wd->FrameSemaphores = nullptr;
  1483. vkDestroyPipeline(device, wd->Pipeline, allocator);
  1484. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  1485. vkDestroySwapchainKHR(device, wd->Swapchain, allocator);
  1486. vkDestroySurfaceKHR(instance, wd->Surface, allocator);
  1487. *wd = ImGui_ImplVulkanH_Window();
  1488. }
  1489. void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator)
  1490. {
  1491. vkDestroyFence(device, fd->Fence, allocator);
  1492. vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer);
  1493. vkDestroyCommandPool(device, fd->CommandPool, allocator);
  1494. fd->Fence = VK_NULL_HANDLE;
  1495. fd->CommandBuffer = VK_NULL_HANDLE;
  1496. fd->CommandPool = VK_NULL_HANDLE;
  1497. vkDestroyImageView(device, fd->BackbufferView, allocator);
  1498. vkDestroyFramebuffer(device, fd->Framebuffer, allocator);
  1499. }
  1500. void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator)
  1501. {
  1502. vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator);
  1503. vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator);
  1504. fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE;
  1505. }
  1506. //-----------------------------------------------------------------------------
  1507. #endif // #ifndef IMGUI_DISABLE