imgui_impl_vulkan.cpp 52 KB

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