imgui_impl_vulkan.cpp 100 KB

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