imgui_impl_vulkan.cpp 51 KB

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