imgui_impl_vulkan.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. // ImGui Renderer for: Vulkan
  2. // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
  3. // Missing features:
  4. // [ ] User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914
  5. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  6. // If you use this binding you'll need to call 5 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXX_CreateFontsTexture(), ImGui_ImplXXXX_NewFrame(), ImGui_ImplXXXX_Render() and ImGui_ImplXXXX_Shutdown().
  7. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  8. // https://github.com/ocornut/imgui
  9. // CHANGELOG
  10. // (minor and older changes stripped away, please see git history for details)
  11. // 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  12. // 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.
  13. // 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology.
  14. // 2018-02-18: Vulkan: Offset projection matrix and clipping rectangle by draw_data->DisplayPos (which will be non-zero for multi-viewport applications).
  15. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself.
  16. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  17. // 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy.
  18. // 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex.
  19. // 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.
  20. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
  21. #include "imgui.h"
  22. #include "imgui_impl_vulkan.h"
  23. #include <stdio.h>
  24. // Vulkan data
  25. static const VkAllocationCallbacks* g_Allocator = NULL;
  26. static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE;
  27. static VkInstance g_Instance = VK_NULL_HANDLE;
  28. static VkDevice g_Device = VK_NULL_HANDLE;
  29. static uint32_t g_QueueFamily = (uint32_t)-1;
  30. static VkQueue g_Queue = VK_NULL_HANDLE;
  31. static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE;
  32. static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE;
  33. static VkRenderPass g_RenderPass = VK_NULL_HANDLE;
  34. static void (*g_CheckVkResultFn)(VkResult err) = NULL;
  35. static VkDeviceSize g_BufferMemoryAlignment = 256;
  36. static VkPipelineCreateFlags g_PipelineCreateFlags = 0;
  37. static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE;
  38. static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE;
  39. static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE;
  40. static VkPipeline g_Pipeline = VK_NULL_HANDLE;
  41. // Frame data
  42. struct FrameDataForRender
  43. {
  44. VkDeviceMemory VertexBufferMemory;
  45. VkDeviceMemory IndexBufferMemory;
  46. VkDeviceSize VertexBufferSize;
  47. VkDeviceSize IndexBufferSize;
  48. VkBuffer VertexBuffer;
  49. VkBuffer IndexBuffer;
  50. };
  51. static int g_FrameIndex = 0;
  52. static FrameDataForRender g_FramesDataBuffers[IMGUI_VK_QUEUED_FRAMES] = {};
  53. // Font data
  54. static VkSampler g_FontSampler = VK_NULL_HANDLE;
  55. static VkDeviceMemory g_FontMemory = VK_NULL_HANDLE;
  56. static VkImage g_FontImage = VK_NULL_HANDLE;
  57. static VkImageView g_FontView = VK_NULL_HANDLE;
  58. static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE;
  59. static VkBuffer g_UploadBuffer = VK_NULL_HANDLE;
  60. // Forward Declarations
  61. static void ImGui_ImplVulkan_InitPlatformInterface();
  62. static void ImGui_ImplVulkan_ShutdownPlatformInterface();
  63. // glsl_shader.vert, compiled with:
  64. // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
  65. static uint32_t __glsl_shader_vert_spv[] =
  66. {
  67. 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b,
  68. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  69. 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
  70. 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  71. 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
  72. 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
  73. 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
  74. 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
  75. 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c,
  76. 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074,
  77. 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001,
  78. 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b,
  79. 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
  80. 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
  81. 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e,
  82. 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008,
  83. 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,
  84. 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017,
  85. 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020,
  86. 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015,
  87. 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020,
  88. 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020,
  89. 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020,
  90. 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020,
  91. 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a,
  92. 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014,
  93. 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f,
  94. 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021,
  95. 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006,
  96. 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,
  97. 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,
  98. 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,
  99. 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,
  100. 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022,
  101. 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008,
  102. 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013,
  103. 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024,
  104. 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006,
  105. 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b,
  106. 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e,
  107. 0x0000002d,0x0000002c,0x000100fd,0x00010038
  108. };
  109. // glsl_shader.frag, compiled with:
  110. // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
  111. static uint32_t __glsl_shader_frag_spv[] =
  112. {
  113. 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b,
  114. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  115. 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
  116. 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  117. 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
  118. 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
  119. 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574,
  120. 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,
  121. 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021,
  122. 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
  123. 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,
  124. 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006,
  125. 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001,
  126. 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020,
  127. 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001,
  128. 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
  129. 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000,
  130. 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018,
  131. 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004,
  132. 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d,
  133. 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017,
  134. 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a,
  135. 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085,
  136. 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd,
  137. 0x00010038
  138. };
  139. static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits)
  140. {
  141. VkPhysicalDeviceMemoryProperties prop;
  142. vkGetPhysicalDeviceMemoryProperties(g_PhysicalDevice, &prop);
  143. for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
  144. if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
  145. return i;
  146. return 0xFFFFFFFF; // Unable to find memoryType
  147. }
  148. static void check_vk_result(VkResult err)
  149. {
  150. if (g_CheckVkResultFn)
  151. g_CheckVkResultFn(err);
  152. }
  153. static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage)
  154. {
  155. VkResult err;
  156. if (buffer != NULL)
  157. vkDestroyBuffer(g_Device, buffer, g_Allocator);
  158. if (buffer_memory)
  159. vkFreeMemory(g_Device, buffer_memory, g_Allocator);
  160. VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment;
  161. VkBufferCreateInfo buffer_info = {};
  162. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  163. buffer_info.size = vertex_buffer_size_aligned;
  164. buffer_info.usage = usage;
  165. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  166. err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &buffer);
  167. check_vk_result(err);
  168. VkMemoryRequirements req;
  169. vkGetBufferMemoryRequirements(g_Device, buffer, &req);
  170. g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
  171. VkMemoryAllocateInfo alloc_info = {};
  172. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  173. alloc_info.allocationSize = req.size;
  174. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  175. err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &buffer_memory);
  176. check_vk_result(err);
  177. err = vkBindBufferMemory(g_Device, buffer, buffer_memory, 0);
  178. check_vk_result(err);
  179. p_buffer_size = new_size;
  180. }
  181. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  182. void ImGui_ImplVulkan_RenderDrawData(VkCommandBuffer command_buffer, ImDrawData* draw_data)
  183. {
  184. VkResult err;
  185. if (draw_data->TotalVtxCount == 0)
  186. return;
  187. FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex];
  188. g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES;
  189. // Create the Vertex and Index buffers:
  190. size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
  191. size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
  192. if (!fd->VertexBuffer || fd->VertexBufferSize < vertex_size)
  193. CreateOrResizeBuffer(fd->VertexBuffer, fd->VertexBufferMemory, fd->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
  194. if (!fd->IndexBuffer || fd->IndexBufferSize < index_size)
  195. CreateOrResizeBuffer(fd->IndexBuffer, fd->IndexBufferMemory, fd->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
  196. // Upload Vertex and index Data:
  197. {
  198. ImDrawVert* vtx_dst;
  199. ImDrawIdx* idx_dst;
  200. err = vkMapMemory(g_Device, fd->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst));
  201. check_vk_result(err);
  202. err = vkMapMemory(g_Device, fd->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst));
  203. check_vk_result(err);
  204. for (int n = 0; n < draw_data->CmdListsCount; n++)
  205. {
  206. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  207. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  208. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  209. vtx_dst += cmd_list->VtxBuffer.Size;
  210. idx_dst += cmd_list->IdxBuffer.Size;
  211. }
  212. VkMappedMemoryRange range[2] = {};
  213. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  214. range[0].memory = fd->VertexBufferMemory;
  215. range[0].size = VK_WHOLE_SIZE;
  216. range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  217. range[1].memory = fd->IndexBufferMemory;
  218. range[1].size = VK_WHOLE_SIZE;
  219. err = vkFlushMappedMemoryRanges(g_Device, 2, range);
  220. check_vk_result(err);
  221. vkUnmapMemory(g_Device, fd->VertexBufferMemory);
  222. vkUnmapMemory(g_Device, fd->IndexBufferMemory);
  223. }
  224. // Bind pipeline and descriptor sets:
  225. {
  226. vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_Pipeline);
  227. VkDescriptorSet desc_set[1] = { g_DescriptorSet };
  228. vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL);
  229. }
  230. // Bind Vertex And Index Buffer:
  231. {
  232. VkBuffer vertex_buffers[1] = { fd->VertexBuffer };
  233. VkDeviceSize vertex_offset[1] = { 0 };
  234. vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
  235. vkCmdBindIndexBuffer(command_buffer, fd->IndexBuffer, 0, VK_INDEX_TYPE_UINT16);
  236. }
  237. // Setup viewport:
  238. {
  239. VkViewport viewport;
  240. viewport.x = 0;
  241. viewport.y = 0;
  242. viewport.width = draw_data->DisplaySize.x;
  243. viewport.height = draw_data->DisplaySize.y;
  244. viewport.minDepth = 0.0f;
  245. viewport.maxDepth = 1.0f;
  246. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  247. }
  248. // Setup scale and translation:
  249. // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  250. {
  251. float scale[2];
  252. scale[0] = 2.0f / draw_data->DisplaySize.x;
  253. scale[1] = 2.0f / draw_data->DisplaySize.y;
  254. float translate[2];
  255. translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
  256. translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
  257. vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale);
  258. vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate);
  259. }
  260. // Render the command lists:
  261. int vtx_offset = 0;
  262. int idx_offset = 0;
  263. ImVec2 display_pos = draw_data->DisplayPos;
  264. for (int n = 0; n < draw_data->CmdListsCount; n++)
  265. {
  266. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  267. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  268. {
  269. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  270. if (pcmd->UserCallback)
  271. {
  272. pcmd->UserCallback(cmd_list, pcmd);
  273. }
  274. else
  275. {
  276. // Apply scissor/clipping rectangle
  277. // FIXME: We could clamp width/height based on clamped min/max values.
  278. VkRect2D scissor;
  279. scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
  280. scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
  281. scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
  282. scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
  283. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  284. // Draw
  285. vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
  286. }
  287. idx_offset += pcmd->ElemCount;
  288. }
  289. vtx_offset += cmd_list->VtxBuffer.Size;
  290. }
  291. }
  292. bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
  293. {
  294. ImGuiIO& io = ImGui::GetIO();
  295. unsigned char* pixels;
  296. int width, height;
  297. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  298. size_t upload_size = width*height*4*sizeof(char);
  299. VkResult err;
  300. // Create the Image:
  301. {
  302. VkImageCreateInfo info = {};
  303. info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  304. info.imageType = VK_IMAGE_TYPE_2D;
  305. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  306. info.extent.width = width;
  307. info.extent.height = height;
  308. info.extent.depth = 1;
  309. info.mipLevels = 1;
  310. info.arrayLayers = 1;
  311. info.samples = VK_SAMPLE_COUNT_1_BIT;
  312. info.tiling = VK_IMAGE_TILING_OPTIMAL;
  313. info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  314. info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  315. info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  316. err = vkCreateImage(g_Device, &info, g_Allocator, &g_FontImage);
  317. check_vk_result(err);
  318. VkMemoryRequirements req;
  319. vkGetImageMemoryRequirements(g_Device, g_FontImage, &req);
  320. VkMemoryAllocateInfo alloc_info = {};
  321. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  322. alloc_info.allocationSize = req.size;
  323. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
  324. err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_FontMemory);
  325. check_vk_result(err);
  326. err = vkBindImageMemory(g_Device, g_FontImage, g_FontMemory, 0);
  327. check_vk_result(err);
  328. }
  329. // Create the Image View:
  330. {
  331. VkImageViewCreateInfo info = {};
  332. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  333. info.image = g_FontImage;
  334. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  335. info.format = VK_FORMAT_R8G8B8A8_UNORM;
  336. info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  337. info.subresourceRange.levelCount = 1;
  338. info.subresourceRange.layerCount = 1;
  339. err = vkCreateImageView(g_Device, &info, g_Allocator, &g_FontView);
  340. check_vk_result(err);
  341. }
  342. // Update the Descriptor Set:
  343. {
  344. VkDescriptorImageInfo desc_image[1] = {};
  345. desc_image[0].sampler = g_FontSampler;
  346. desc_image[0].imageView = g_FontView;
  347. desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  348. VkWriteDescriptorSet write_desc[1] = {};
  349. write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  350. write_desc[0].dstSet = g_DescriptorSet;
  351. write_desc[0].descriptorCount = 1;
  352. write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  353. write_desc[0].pImageInfo = desc_image;
  354. vkUpdateDescriptorSets(g_Device, 1, write_desc, 0, NULL);
  355. }
  356. // Create the Upload Buffer:
  357. {
  358. VkBufferCreateInfo buffer_info = {};
  359. buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  360. buffer_info.size = upload_size;
  361. buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  362. buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  363. err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &g_UploadBuffer);
  364. check_vk_result(err);
  365. VkMemoryRequirements req;
  366. vkGetBufferMemoryRequirements(g_Device, g_UploadBuffer, &req);
  367. g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment;
  368. VkMemoryAllocateInfo alloc_info = {};
  369. alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  370. alloc_info.allocationSize = req.size;
  371. alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
  372. err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_UploadBufferMemory);
  373. check_vk_result(err);
  374. err = vkBindBufferMemory(g_Device, g_UploadBuffer, g_UploadBufferMemory, 0);
  375. check_vk_result(err);
  376. }
  377. // Upload to Buffer:
  378. {
  379. char* map = NULL;
  380. err = vkMapMemory(g_Device, g_UploadBufferMemory, 0, upload_size, 0, (void**)(&map));
  381. check_vk_result(err);
  382. memcpy(map, pixels, upload_size);
  383. VkMappedMemoryRange range[1] = {};
  384. range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  385. range[0].memory = g_UploadBufferMemory;
  386. range[0].size = upload_size;
  387. err = vkFlushMappedMemoryRanges(g_Device, 1, range);
  388. check_vk_result(err);
  389. vkUnmapMemory(g_Device, g_UploadBufferMemory);
  390. }
  391. // Copy to Image:
  392. {
  393. VkImageMemoryBarrier copy_barrier[1] = {};
  394. copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  395. copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  396. copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  397. copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  398. copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  399. copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  400. copy_barrier[0].image = g_FontImage;
  401. copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  402. copy_barrier[0].subresourceRange.levelCount = 1;
  403. copy_barrier[0].subresourceRange.layerCount = 1;
  404. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, copy_barrier);
  405. VkBufferImageCopy region = {};
  406. region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  407. region.imageSubresource.layerCount = 1;
  408. region.imageExtent.width = width;
  409. region.imageExtent.height = height;
  410. region.imageExtent.depth = 1;
  411. vkCmdCopyBufferToImage(command_buffer, g_UploadBuffer, g_FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
  412. VkImageMemoryBarrier use_barrier[1] = {};
  413. use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  414. use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  415. use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  416. use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  417. use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  418. use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  419. use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  420. use_barrier[0].image = g_FontImage;
  421. use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  422. use_barrier[0].subresourceRange.levelCount = 1;
  423. use_barrier[0].subresourceRange.layerCount = 1;
  424. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, use_barrier);
  425. }
  426. // Store our identifier
  427. io.Fonts->TexID = (void *)(intptr_t)g_FontImage;
  428. return true;
  429. }
  430. bool ImGui_ImplVulkan_CreateDeviceObjects()
  431. {
  432. VkResult err;
  433. VkShaderModule vert_module;
  434. VkShaderModule frag_module;
  435. // Create The Shader Modules:
  436. {
  437. VkShaderModuleCreateInfo vert_info = {};
  438. vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  439. vert_info.codeSize = sizeof(__glsl_shader_vert_spv);
  440. vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv;
  441. err = vkCreateShaderModule(g_Device, &vert_info, g_Allocator, &vert_module);
  442. check_vk_result(err);
  443. VkShaderModuleCreateInfo frag_info = {};
  444. frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  445. frag_info.codeSize = sizeof(__glsl_shader_frag_spv);
  446. frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv;
  447. err = vkCreateShaderModule(g_Device, &frag_info, g_Allocator, &frag_module);
  448. check_vk_result(err);
  449. }
  450. if (!g_FontSampler)
  451. {
  452. VkSamplerCreateInfo info = {};
  453. info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  454. info.magFilter = VK_FILTER_LINEAR;
  455. info.minFilter = VK_FILTER_LINEAR;
  456. info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
  457. info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  458. info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  459. info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  460. info.minLod = -1000;
  461. info.maxLod = 1000;
  462. info.maxAnisotropy = 1.0f;
  463. err = vkCreateSampler(g_Device, &info, g_Allocator, &g_FontSampler);
  464. check_vk_result(err);
  465. }
  466. if (!g_DescriptorSetLayout)
  467. {
  468. VkSampler sampler[1] = {g_FontSampler};
  469. VkDescriptorSetLayoutBinding binding[1] = {};
  470. binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  471. binding[0].descriptorCount = 1;
  472. binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
  473. binding[0].pImmutableSamplers = sampler;
  474. VkDescriptorSetLayoutCreateInfo info = {};
  475. info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  476. info.bindingCount = 1;
  477. info.pBindings = binding;
  478. err = vkCreateDescriptorSetLayout(g_Device, &info, g_Allocator, &g_DescriptorSetLayout);
  479. check_vk_result(err);
  480. }
  481. // Create Descriptor Set:
  482. {
  483. VkDescriptorSetAllocateInfo alloc_info = {};
  484. alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  485. alloc_info.descriptorPool = g_DescriptorPool;
  486. alloc_info.descriptorSetCount = 1;
  487. alloc_info.pSetLayouts = &g_DescriptorSetLayout;
  488. err = vkAllocateDescriptorSets(g_Device, &alloc_info, &g_DescriptorSet);
  489. check_vk_result(err);
  490. }
  491. if (!g_PipelineLayout)
  492. {
  493. // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
  494. VkPushConstantRange push_constants[1] = {};
  495. push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
  496. push_constants[0].offset = sizeof(float) * 0;
  497. push_constants[0].size = sizeof(float) * 4;
  498. VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout };
  499. VkPipelineLayoutCreateInfo layout_info = {};
  500. layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  501. layout_info.setLayoutCount = 1;
  502. layout_info.pSetLayouts = set_layout;
  503. layout_info.pushConstantRangeCount = 1;
  504. layout_info.pPushConstantRanges = push_constants;
  505. err = vkCreatePipelineLayout(g_Device, &layout_info, g_Allocator, &g_PipelineLayout);
  506. check_vk_result(err);
  507. }
  508. VkPipelineShaderStageCreateInfo stage[2] = {};
  509. stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  510. stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  511. stage[0].module = vert_module;
  512. stage[0].pName = "main";
  513. stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  514. stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  515. stage[1].module = frag_module;
  516. stage[1].pName = "main";
  517. VkVertexInputBindingDescription binding_desc[1] = {};
  518. binding_desc[0].stride = sizeof(ImDrawVert);
  519. binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  520. VkVertexInputAttributeDescription attribute_desc[3] = {};
  521. attribute_desc[0].location = 0;
  522. attribute_desc[0].binding = binding_desc[0].binding;
  523. attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
  524. attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
  525. attribute_desc[1].location = 1;
  526. attribute_desc[1].binding = binding_desc[0].binding;
  527. attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
  528. attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
  529. attribute_desc[2].location = 2;
  530. attribute_desc[2].binding = binding_desc[0].binding;
  531. attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
  532. attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
  533. VkPipelineVertexInputStateCreateInfo vertex_info = {};
  534. vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  535. vertex_info.vertexBindingDescriptionCount = 1;
  536. vertex_info.pVertexBindingDescriptions = binding_desc;
  537. vertex_info.vertexAttributeDescriptionCount = 3;
  538. vertex_info.pVertexAttributeDescriptions = attribute_desc;
  539. VkPipelineInputAssemblyStateCreateInfo ia_info = {};
  540. ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  541. ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  542. VkPipelineViewportStateCreateInfo viewport_info = {};
  543. viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  544. viewport_info.viewportCount = 1;
  545. viewport_info.scissorCount = 1;
  546. VkPipelineRasterizationStateCreateInfo raster_info = {};
  547. raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  548. raster_info.polygonMode = VK_POLYGON_MODE_FILL;
  549. raster_info.cullMode = VK_CULL_MODE_NONE;
  550. raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
  551. raster_info.lineWidth = 1.0f;
  552. VkPipelineMultisampleStateCreateInfo ms_info = {};
  553. ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  554. ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  555. VkPipelineColorBlendAttachmentState color_attachment[1] = {};
  556. color_attachment[0].blendEnable = VK_TRUE;
  557. color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
  558. color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  559. color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
  560. color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  561. color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  562. color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
  563. color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  564. VkPipelineDepthStencilStateCreateInfo depth_info = {};
  565. depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  566. VkPipelineColorBlendStateCreateInfo blend_info = {};
  567. blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  568. blend_info.attachmentCount = 1;
  569. blend_info.pAttachments = color_attachment;
  570. VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
  571. VkPipelineDynamicStateCreateInfo dynamic_state = {};
  572. dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  573. dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
  574. dynamic_state.pDynamicStates = dynamic_states;
  575. VkGraphicsPipelineCreateInfo info = {};
  576. info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  577. info.flags = g_PipelineCreateFlags;
  578. info.stageCount = 2;
  579. info.pStages = stage;
  580. info.pVertexInputState = &vertex_info;
  581. info.pInputAssemblyState = &ia_info;
  582. info.pViewportState = &viewport_info;
  583. info.pRasterizationState = &raster_info;
  584. info.pMultisampleState = &ms_info;
  585. info.pDepthStencilState = &depth_info;
  586. info.pColorBlendState = &blend_info;
  587. info.pDynamicState = &dynamic_state;
  588. info.layout = g_PipelineLayout;
  589. info.renderPass = g_RenderPass;
  590. err = vkCreateGraphicsPipelines(g_Device, g_PipelineCache, 1, &info, g_Allocator, &g_Pipeline);
  591. check_vk_result(err);
  592. vkDestroyShaderModule(g_Device, vert_module, g_Allocator);
  593. vkDestroyShaderModule(g_Device, frag_module, g_Allocator);
  594. return true;
  595. }
  596. void ImGui_ImplVulkan_InvalidateFontUploadObjects()
  597. {
  598. if (g_UploadBuffer)
  599. {
  600. vkDestroyBuffer(g_Device, g_UploadBuffer, g_Allocator);
  601. g_UploadBuffer = VK_NULL_HANDLE;
  602. }
  603. if (g_UploadBufferMemory)
  604. {
  605. vkFreeMemory(g_Device, g_UploadBufferMemory, g_Allocator);
  606. g_UploadBufferMemory = VK_NULL_HANDLE;
  607. }
  608. }
  609. void ImGui_ImplVulkan_InvalidateDeviceObjects()
  610. {
  611. ImGui_ImplVulkan_InvalidateFontUploadObjects();
  612. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  613. {
  614. FrameDataForRender* fd = &g_FramesDataBuffers[i];
  615. if (fd->VertexBuffer) { vkDestroyBuffer (g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; }
  616. if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; }
  617. if (fd->IndexBuffer) { vkDestroyBuffer (g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; }
  618. if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; }
  619. }
  620. if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; }
  621. if (g_FontImage) { vkDestroyImage(g_Device, g_FontImage, g_Allocator); g_FontImage = VK_NULL_HANDLE; }
  622. if (g_FontMemory) { vkFreeMemory(g_Device, g_FontMemory, g_Allocator); g_FontMemory = VK_NULL_HANDLE; }
  623. if (g_FontSampler) { vkDestroySampler(g_Device, g_FontSampler, g_Allocator); g_FontSampler = VK_NULL_HANDLE; }
  624. if (g_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(g_Device, g_DescriptorSetLayout, g_Allocator); g_DescriptorSetLayout = VK_NULL_HANDLE; }
  625. if (g_PipelineLayout) { vkDestroyPipelineLayout(g_Device, g_PipelineLayout, g_Allocator); g_PipelineLayout = VK_NULL_HANDLE; }
  626. if (g_Pipeline) { vkDestroyPipeline(g_Device, g_Pipeline, g_Allocator); g_Pipeline = VK_NULL_HANDLE; }
  627. }
  628. bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass)
  629. {
  630. IM_ASSERT(info->Instance != NULL);
  631. IM_ASSERT(info->PhysicalDevice != NULL);
  632. IM_ASSERT(info->Device != NULL);
  633. IM_ASSERT(info->Queue != NULL);
  634. IM_ASSERT(info->DescriptorPool != NULL);
  635. IM_ASSERT(render_pass != NULL);
  636. g_Instance = info->Instance;
  637. g_PhysicalDevice = info->PhysicalDevice;
  638. g_Device = info->Device;
  639. g_QueueFamily = info->QueueFamily;
  640. g_Queue = info->Queue;
  641. g_RenderPass = render_pass;
  642. g_PipelineCache = info->PipelineCache;
  643. g_DescriptorPool = info->DescriptorPool;
  644. g_Allocator = info->Allocator;
  645. g_CheckVkResultFn = info->CheckVkResultFn;
  646. ImGuiIO& io = ImGui::GetIO();
  647. ImGui_ImplVulkan_CreateDeviceObjects();
  648. io.ConfigFlags |= ImGuiConfigFlags_RendererHasViewports;
  649. if (io.ConfigFlags & ImGuiConfigFlags_EnableViewports)
  650. ImGui_ImplVulkan_InitPlatformInterface();
  651. return true;
  652. }
  653. void ImGui_ImplVulkan_Shutdown()
  654. {
  655. ImGui_ImplVulkan_ShutdownPlatformInterface();
  656. ImGui_ImplVulkan_InvalidateDeviceObjects();
  657. }
  658. void ImGui_ImplVulkan_NewFrame()
  659. {
  660. }
  661. //-------------------------------------------------------------------------
  662. // Miscellaneous Vulkan Helpers
  663. //-------------------------------------------------------------------------
  664. #include <stdlib.h> // malloc
  665. ImGui_ImplVulkan_FrameData::ImGui_ImplVulkan_FrameData()
  666. {
  667. BackbufferIndex = 0;
  668. CommandPool = VK_NULL_HANDLE;
  669. CommandBuffer = VK_NULL_HANDLE;
  670. Fence = VK_NULL_HANDLE;
  671. ImageAcquiredSemaphore = VK_NULL_HANDLE;
  672. RenderCompleteSemaphore = VK_NULL_HANDLE;
  673. }
  674. ImGui_ImplVulkan_WindowData::ImGui_ImplVulkan_WindowData()
  675. {
  676. Width = Height = 0;
  677. Swapchain = VK_NULL_HANDLE;
  678. Surface = VK_NULL_HANDLE;
  679. memset(&SurfaceFormat, 0, sizeof(SurfaceFormat));
  680. PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR;
  681. RenderPass = VK_NULL_HANDLE;
  682. ClearEnable = true;
  683. memset(&ClearValue, 0, sizeof(ClearValue));
  684. BackBufferCount = 0;
  685. memset(&BackBuffer, 0, sizeof(BackBuffer));
  686. memset(&BackBufferView, 0, sizeof(BackBufferView));
  687. memset(&Framebuffer, 0, sizeof(Framebuffer));
  688. FrameIndex = 0;
  689. }
  690. VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space)
  691. {
  692. IM_ASSERT(request_formats != NULL);
  693. IM_ASSERT(request_formats_count > 0);
  694. // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
  695. // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
  696. // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
  697. // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
  698. uint32_t avail_count;
  699. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, NULL);
  700. ImVector<VkSurfaceFormatKHR> avail_format;
  701. avail_format.resize((int)avail_count);
  702. vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data);
  703. // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
  704. if (avail_count == 1)
  705. {
  706. if (avail_format[0].format == VK_FORMAT_UNDEFINED)
  707. {
  708. VkSurfaceFormatKHR ret;
  709. ret.format = request_formats[0];
  710. ret.colorSpace = request_color_space;
  711. return ret;
  712. }
  713. else
  714. {
  715. // No point in searching another format
  716. return avail_format[0];
  717. }
  718. }
  719. else
  720. {
  721. // Request several formats, the first found will be used
  722. for (int request_i = 0; request_i < request_formats_count; request_i++)
  723. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  724. if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space)
  725. return avail_format[avail_i];
  726. // If none of the requested image formats could be found, use the first available
  727. return avail_format[0];
  728. }
  729. }
  730. VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count)
  731. {
  732. IM_ASSERT(request_modes != NULL);
  733. IM_ASSERT(request_modes_count > 0);
  734. // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
  735. uint32_t avail_count = 0;
  736. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, NULL);
  737. ImVector<VkPresentModeKHR> avail_modes;
  738. avail_modes.resize((int)avail_count);
  739. vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data);
  740. for (int request_i = 0; request_i < request_modes_count; request_i++)
  741. for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++)
  742. if (request_modes[request_i] == avail_modes[avail_i])
  743. return request_modes[request_i];
  744. return VK_PRESENT_MODE_FIFO_KHR; // Always available
  745. }
  746. void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family, ImGui_ImplVulkan_WindowData* wd, const VkAllocationCallbacks* allocator)
  747. {
  748. IM_ASSERT(physical_device != NULL && device != NULL);
  749. (void)allocator;
  750. // Create Command Buffers
  751. VkResult err;
  752. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  753. {
  754. ImGui_ImplVulkan_FrameData* fd = &wd->Frames[i];
  755. {
  756. VkCommandPoolCreateInfo info = {};
  757. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  758. info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  759. info.queueFamilyIndex = queue_family;
  760. err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool);
  761. check_vk_result(err);
  762. }
  763. {
  764. VkCommandBufferAllocateInfo info = {};
  765. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  766. info.commandPool = fd->CommandPool;
  767. info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  768. info.commandBufferCount = 1;
  769. err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer);
  770. check_vk_result(err);
  771. }
  772. {
  773. VkFenceCreateInfo info = {};
  774. info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  775. info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  776. err = vkCreateFence(device, &info, allocator, &fd->Fence);
  777. check_vk_result(err);
  778. }
  779. {
  780. VkSemaphoreCreateInfo info = {};
  781. info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  782. err = vkCreateSemaphore(device, &info, allocator, &fd->ImageAcquiredSemaphore);
  783. check_vk_result(err);
  784. err = vkCreateSemaphore(device, &info, allocator, &fd->RenderCompleteSemaphore);
  785. check_vk_result(err);
  786. }
  787. }
  788. }
  789. int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode)
  790. {
  791. if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
  792. return 3;
  793. if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
  794. return 2;
  795. if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
  796. return 1;
  797. IM_ASSERT(0);
  798. return 1;
  799. }
  800. void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkan_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h)
  801. {
  802. uint32_t min_image_count = 2; // FIXME: this should become a function parameter
  803. VkResult err;
  804. VkSwapchainKHR old_swapchain = wd->Swapchain;
  805. err = vkDeviceWaitIdle(device);
  806. check_vk_result(err);
  807. // Destroy old Framebuffer
  808. for (uint32_t i = 0; i < wd->BackBufferCount; i++)
  809. {
  810. if (wd->BackBufferView[i])
  811. vkDestroyImageView(device, wd->BackBufferView[i], allocator);
  812. if (wd->Framebuffer[i])
  813. vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator);
  814. }
  815. wd->BackBufferCount = 0;
  816. if (wd->RenderPass)
  817. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  818. // If min image count was not specified, request different count of images dependent on selected present mode
  819. if (min_image_count == 0)
  820. min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode);
  821. // Create Swapchain
  822. {
  823. VkSwapchainCreateInfoKHR info = {};
  824. info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  825. info.surface = wd->Surface;
  826. info.minImageCount = min_image_count;
  827. info.imageFormat = wd->SurfaceFormat.format;
  828. info.imageColorSpace = wd->SurfaceFormat.colorSpace;
  829. info.imageArrayLayers = 1;
  830. info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  831. info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family
  832. info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  833. info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  834. info.presentMode = wd->PresentMode;
  835. info.clipped = VK_TRUE;
  836. info.oldSwapchain = old_swapchain;
  837. VkSurfaceCapabilitiesKHR cap;
  838. err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
  839. check_vk_result(err);
  840. if (info.minImageCount < cap.minImageCount)
  841. info.minImageCount = cap.minImageCount;
  842. else if (info.minImageCount > cap.maxImageCount)
  843. info.minImageCount = cap.maxImageCount;
  844. if (cap.currentExtent.width == 0xffffffff)
  845. {
  846. info.imageExtent.width = wd->Width = w;
  847. info.imageExtent.height = wd->Height = h;
  848. }
  849. else
  850. {
  851. info.imageExtent.width = wd->Width = cap.currentExtent.width;
  852. info.imageExtent.height = wd->Height = cap.currentExtent.height;
  853. }
  854. err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain);
  855. check_vk_result(err);
  856. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, NULL);
  857. check_vk_result(err);
  858. err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer);
  859. check_vk_result(err);
  860. }
  861. if (old_swapchain)
  862. vkDestroySwapchainKHR(device, old_swapchain, allocator);
  863. // Create the Render Pass
  864. {
  865. VkAttachmentDescription attachment = {};
  866. attachment.format = wd->SurfaceFormat.format;
  867. attachment.samples = VK_SAMPLE_COUNT_1_BIT;
  868. attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  869. attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  870. attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  871. attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  872. attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  873. attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  874. VkAttachmentReference color_attachment = {};
  875. color_attachment.attachment = 0;
  876. color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  877. VkSubpassDescription subpass = {};
  878. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  879. subpass.colorAttachmentCount = 1;
  880. subpass.pColorAttachments = &color_attachment;
  881. VkRenderPassCreateInfo info = {};
  882. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  883. info.attachmentCount = 1;
  884. info.pAttachments = &attachment;
  885. info.subpassCount = 1;
  886. info.pSubpasses = &subpass;
  887. err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass);
  888. check_vk_result(err);
  889. }
  890. // Create The Image Views
  891. {
  892. VkImageViewCreateInfo info = {};
  893. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  894. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  895. info.format = wd->SurfaceFormat.format;
  896. info.components.r = VK_COMPONENT_SWIZZLE_R;
  897. info.components.g = VK_COMPONENT_SWIZZLE_G;
  898. info.components.b = VK_COMPONENT_SWIZZLE_B;
  899. info.components.a = VK_COMPONENT_SWIZZLE_A;
  900. VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
  901. info.subresourceRange = image_range;
  902. for (uint32_t i = 0; i < wd->BackBufferCount; i++)
  903. {
  904. info.image = wd->BackBuffer[i];
  905. err = vkCreateImageView(device, &info, allocator, &wd->BackBufferView[i]);
  906. check_vk_result(err);
  907. }
  908. }
  909. // Create Framebuffer
  910. {
  911. VkImageView attachment[1];
  912. VkFramebufferCreateInfo info = {};
  913. info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  914. info.renderPass = wd->RenderPass;
  915. info.attachmentCount = 1;
  916. info.pAttachments = attachment;
  917. info.width = wd->Width;
  918. info.height = wd->Height;
  919. info.layers = 1;
  920. for (uint32_t i = 0; i < wd->BackBufferCount; i++)
  921. {
  922. attachment[0] = wd->BackBufferView[i];
  923. err = vkCreateFramebuffer(device, &info, allocator, &wd->Framebuffer[i]);
  924. check_vk_result(err);
  925. }
  926. }
  927. }
  928. void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkan_WindowData* wd, const VkAllocationCallbacks* allocator)
  929. {
  930. vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
  931. //vkQueueWaitIdle(g_Queue);
  932. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  933. {
  934. ImGui_ImplVulkan_FrameData* fd = &wd->Frames[i];
  935. vkDestroyFence(device, fd->Fence, allocator);
  936. vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer);
  937. vkDestroyCommandPool(device, fd->CommandPool, allocator);
  938. vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator);
  939. vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator);
  940. }
  941. for (uint32_t i = 0; i < wd->BackBufferCount; i++)
  942. {
  943. vkDestroyImageView(device, wd->BackBufferView[i], allocator);
  944. vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator);
  945. }
  946. vkDestroyRenderPass(device, wd->RenderPass, allocator);
  947. vkDestroySwapchainKHR(device, wd->Swapchain, allocator);
  948. vkDestroySurfaceKHR(instance, wd->Surface, allocator);
  949. *wd = ImGui_ImplVulkan_WindowData();
  950. }
  951. //--------------------------------------------------------------------------------------------------------
  952. // Platform Interface (Optional, for multi-viewport support)
  953. // FIXME-PLATFORM: Vulkan support unfinished
  954. //--------------------------------------------------------------------------------------------------------
  955. struct ImGuiViewportDataVulkan
  956. {
  957. ImGui_ImplVulkan_WindowData WindowData;
  958. ImGuiViewportDataVulkan() { }
  959. ~ImGuiViewportDataVulkan() { }
  960. };
  961. static void ImGui_ImplVulkan_CreateWindow(ImGuiViewport* viewport)
  962. {
  963. ImGuiViewportDataVulkan* data = IM_NEW(ImGuiViewportDataVulkan)();
  964. viewport->RendererUserData = data;
  965. ImGui_ImplVulkan_WindowData* wd = &data->WindowData;
  966. // Create surface
  967. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  968. VkResult err = (VkResult)platform_io.Platform_CreateVkSurface(viewport, (ImU64)g_Instance, (const void*)g_Allocator, (ImU64*)&wd->Surface);
  969. check_vk_result(err);
  970. // Check for WSI support
  971. VkBool32 res;
  972. vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res);
  973. if (res != VK_TRUE)
  974. {
  975. fprintf(stderr, "Error no WSI support on physical device 0\n");
  976. exit(-1);
  977. }
  978. // Get Surface Format
  979. const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM };
  980. const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
  981. wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace);
  982. // Get Present Mode
  983. VkPresentModeKHR present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR;
  984. wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_mode, 1);
  985. // Create SwapChain, RenderPass, Framebuffer, etc.
  986. wd->ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
  987. ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator);
  988. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, (int)viewport->Size.x, (int)viewport->Size.y);
  989. }
  990. static void ImGui_ImplVulkan_DestroyWindow(ImGuiViewport* viewport)
  991. {
  992. if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData)
  993. {
  994. ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, &data->WindowData, g_Allocator);
  995. IM_DELETE(data);
  996. }
  997. viewport->RendererUserData = NULL;
  998. }
  999. static void ImGui_ImplVulkan_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  1000. {
  1001. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1002. if (data == NULL) // This is NULL for the main viewport (which is left to the user/app to handle)
  1003. return;
  1004. data->WindowData.ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
  1005. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &data->WindowData, g_Allocator, (int)size.x, (int)size.y);
  1006. }
  1007. static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport)
  1008. {
  1009. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1010. ImGui_ImplVulkan_WindowData* wd = &data->WindowData;
  1011. VkResult err;
  1012. {
  1013. ImGui_ImplVulkan_FrameData* fd = &wd->Frames[wd->FrameIndex];
  1014. for (;;)
  1015. {
  1016. err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, 100);
  1017. if (err == VK_SUCCESS) break;
  1018. if (err == VK_TIMEOUT) continue;
  1019. check_vk_result(err);
  1020. }
  1021. {
  1022. err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, fd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &fd->BackbufferIndex);
  1023. check_vk_result(err);
  1024. }
  1025. {
  1026. err = vkResetCommandPool(g_Device, fd->CommandPool, 0);
  1027. check_vk_result(err);
  1028. VkCommandBufferBeginInfo info = {};
  1029. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  1030. info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  1031. err = vkBeginCommandBuffer(fd->CommandBuffer, &info);
  1032. check_vk_result(err);
  1033. }
  1034. {
  1035. ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  1036. memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
  1037. VkRenderPassBeginInfo info = {};
  1038. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1039. info.renderPass = wd->RenderPass;
  1040. info.framebuffer = wd->Framebuffer[fd->BackbufferIndex];
  1041. info.renderArea.extent.width = wd->Width;
  1042. info.renderArea.extent.height = wd->Height;
  1043. info.clearValueCount = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? 0 : 1;
  1044. info.pClearValues = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? NULL : &wd->ClearValue;
  1045. vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE);
  1046. }
  1047. }
  1048. ImGui_ImplVulkan_RenderDrawData(wd->Frames[wd->FrameIndex].CommandBuffer, viewport->DrawData);
  1049. {
  1050. ImGui_ImplVulkan_FrameData* fd = &wd->Frames[wd->FrameIndex];
  1051. vkCmdEndRenderPass(fd->CommandBuffer);
  1052. {
  1053. VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  1054. VkSubmitInfo info = {};
  1055. info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  1056. info.waitSemaphoreCount = 1;
  1057. info.pWaitSemaphores = &fd->ImageAcquiredSemaphore;
  1058. info.pWaitDstStageMask = &wait_stage;
  1059. info.commandBufferCount = 1;
  1060. info.pCommandBuffers = &fd->CommandBuffer;
  1061. info.signalSemaphoreCount = 1;
  1062. info.pSignalSemaphores = &fd->RenderCompleteSemaphore;
  1063. err = vkEndCommandBuffer(fd->CommandBuffer);
  1064. check_vk_result(err);
  1065. err = vkResetFences(g_Device, 1, &fd->Fence);
  1066. check_vk_result(err);
  1067. err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence);
  1068. check_vk_result(err);
  1069. }
  1070. }
  1071. }
  1072. static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport)
  1073. {
  1074. ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData;
  1075. ImGui_ImplVulkan_WindowData* wd = &data->WindowData;
  1076. VkResult err;
  1077. uint32_t PresentIndex = wd->FrameIndex;
  1078. ImGui_ImplVulkan_FrameData* fd = &wd->Frames[PresentIndex];
  1079. VkPresentInfoKHR info = {};
  1080. info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  1081. info.waitSemaphoreCount = 1;
  1082. info.pWaitSemaphores = &fd->RenderCompleteSemaphore;
  1083. info.swapchainCount = 1;
  1084. info.pSwapchains = &wd->Swapchain;
  1085. info.pImageIndices = &fd->BackbufferIndex;
  1086. err = vkQueuePresentKHR(g_Queue, &info);
  1087. check_vk_result(err);
  1088. wd->FrameIndex = (wd->FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES;
  1089. }
  1090. void ImGui_ImplVulkan_InitPlatformInterface()
  1091. {
  1092. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1093. if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_EnableViewports)
  1094. IM_ASSERT(platform_io.Platform_CreateVkSurface != NULL && "Platform needs to setup the CreateVkSurface handler.");
  1095. platform_io.Renderer_CreateWindow = ImGui_ImplVulkan_CreateWindow;
  1096. platform_io.Renderer_DestroyWindow = ImGui_ImplVulkan_DestroyWindow;
  1097. platform_io.Renderer_SetWindowSize = ImGui_ImplVulkan_SetWindowSize;
  1098. platform_io.Renderer_RenderWindow = ImGui_ImplVulkan_RenderWindow;
  1099. platform_io.Renderer_SwapBuffers = ImGui_ImplVulkan_SwapBuffers;
  1100. }
  1101. void ImGui_ImplVulkan_ShutdownPlatformInterface()
  1102. {
  1103. ImGui::DestroyPlatformWindows();
  1104. }