imgui_impl_vulkan.cpp 103 KB

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