Debian Codegraph @

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