Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_vulkan.cpp

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