imgui_impl_vulkan.cpp 58 KB

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