main.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. // ImGui - standalone example application for Glfw + Vulkan, using programmable pipeline
  2. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  3. #include <imgui.h>
  4. #include <stdio.h> // printf, fprintf
  5. #include <stdlib.h> // abort
  6. #define GLFW_INCLUDE_NONE
  7. #define GLFW_INCLUDE_VULKAN
  8. #include <GLFW/glfw3.h>
  9. #include "imgui_impl_glfw_vulkan.h"
  10. #define IMGUI_MAX_POSSIBLE_BACK_BUFFERS 16
  11. #define IMGUI_UNLIMITED_FRAME_RATE
  12. //#define IMGUI_VULKAN_DEBUG_REPORT
  13. static VkAllocationCallbacks* g_Allocator = NULL;
  14. static VkInstance g_Instance = VK_NULL_HANDLE;
  15. static VkSurfaceKHR g_Surface = VK_NULL_HANDLE;
  16. static VkPhysicalDevice g_Gpu = VK_NULL_HANDLE;
  17. static VkDevice g_Device = VK_NULL_HANDLE;
  18. static VkSwapchainKHR g_Swapchain = VK_NULL_HANDLE;
  19. static VkRenderPass g_RenderPass = VK_NULL_HANDLE;
  20. static uint32_t g_QueueFamily = 0;
  21. static VkQueue g_Queue = VK_NULL_HANDLE;
  22. static VkDebugReportCallbackEXT g_Debug_Report = VK_NULL_HANDLE;
  23. static VkSurfaceFormatKHR g_SurfaceFormat;
  24. static VkImageSubresourceRange g_ImageRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
  25. static VkPresentModeKHR g_PresentMode;
  26. static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE;
  27. static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE;
  28. static int fb_width, fb_height;
  29. static uint32_t g_BackBufferIndex = 0;
  30. static uint32_t g_BackBufferCount = 0;
  31. static VkImage g_BackBuffer[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  32. static VkImageView g_BackBufferView[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  33. static VkFramebuffer g_Framebuffer[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
  34. static uint32_t g_FrameIndex = 0;
  35. static VkCommandPool g_CommandPool[IMGUI_VK_QUEUED_FRAMES];
  36. static VkCommandBuffer g_CommandBuffer[IMGUI_VK_QUEUED_FRAMES];
  37. static VkFence g_Fence[IMGUI_VK_QUEUED_FRAMES];
  38. static VkSemaphore g_Semaphore[IMGUI_VK_QUEUED_FRAMES];
  39. static VkClearValue g_ClearValue = {};
  40. static void check_vk_result(VkResult err)
  41. {
  42. if (err == 0) return;
  43. printf("VkResult %d\n", err);
  44. if (err < 0)
  45. abort();
  46. }
  47. static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
  48. {
  49. VkResult err;
  50. VkSwapchainKHR old_swapchain = g_Swapchain;
  51. err = vkDeviceWaitIdle(g_Device);
  52. check_vk_result(err);
  53. // Destroy old Framebuffer:
  54. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  55. if (g_BackBufferView[i])
  56. vkDestroyImageView(g_Device, g_BackBufferView[i], g_Allocator);
  57. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  58. if (g_Framebuffer[i])
  59. vkDestroyFramebuffer(g_Device, g_Framebuffer[i], g_Allocator);
  60. if (g_RenderPass)
  61. vkDestroyRenderPass(g_Device, g_RenderPass, g_Allocator);
  62. // Create Swapchain:
  63. {
  64. VkSwapchainCreateInfoKHR info = {};
  65. info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  66. info.surface = g_Surface;
  67. info.imageFormat = g_SurfaceFormat.format;
  68. info.imageColorSpace = g_SurfaceFormat.colorSpace;
  69. info.imageArrayLayers = 1;
  70. info.imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  71. info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  72. info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  73. info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  74. info.presentMode = g_PresentMode;
  75. info.clipped = VK_TRUE;
  76. info.oldSwapchain = old_swapchain;
  77. VkSurfaceCapabilitiesKHR cap;
  78. err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_Gpu, g_Surface, &cap);
  79. check_vk_result(err);
  80. if (cap.maxImageCount > 0)
  81. info.minImageCount = (cap.minImageCount + 2 < cap.maxImageCount) ? (cap.minImageCount + 2) : cap.maxImageCount;
  82. else
  83. info.minImageCount = cap.minImageCount + 2;
  84. if (cap.currentExtent.width == 0xffffffff)
  85. {
  86. fb_width = w;
  87. fb_height = h;
  88. info.imageExtent.width = fb_width;
  89. info.imageExtent.height = fb_height;
  90. }
  91. else
  92. {
  93. fb_width = cap.currentExtent.width;
  94. fb_height = cap.currentExtent.height;
  95. info.imageExtent.width = fb_width;
  96. info.imageExtent.height = fb_height;
  97. }
  98. err = vkCreateSwapchainKHR(g_Device, &info, g_Allocator, &g_Swapchain);
  99. check_vk_result(err);
  100. err = vkGetSwapchainImagesKHR(g_Device, g_Swapchain, &g_BackBufferCount, NULL);
  101. check_vk_result(err);
  102. err = vkGetSwapchainImagesKHR(g_Device, g_Swapchain, &g_BackBufferCount, g_BackBuffer);
  103. check_vk_result(err);
  104. }
  105. if (old_swapchain)
  106. vkDestroySwapchainKHR(g_Device, old_swapchain, g_Allocator);
  107. // Create the Render Pass:
  108. {
  109. VkAttachmentDescription attachment = {};
  110. attachment.format = g_SurfaceFormat.format;
  111. attachment.samples = VK_SAMPLE_COUNT_1_BIT;
  112. attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  113. attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  114. attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  115. attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  116. attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  117. attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  118. VkAttachmentReference color_attachment = {};
  119. color_attachment.attachment = 0;
  120. color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  121. VkSubpassDescription subpass = {};
  122. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  123. subpass.colorAttachmentCount = 1;
  124. subpass.pColorAttachments = &color_attachment;
  125. VkRenderPassCreateInfo info = {};
  126. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  127. info.attachmentCount = 1;
  128. info.pAttachments = &attachment;
  129. info.subpassCount = 1;
  130. info.pSubpasses = &subpass;
  131. err = vkCreateRenderPass(g_Device, &info, g_Allocator, &g_RenderPass);
  132. check_vk_result(err);
  133. }
  134. // Create The Image Views
  135. {
  136. VkImageViewCreateInfo info = {};
  137. info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  138. info.viewType = VK_IMAGE_VIEW_TYPE_2D;
  139. info.format = g_SurfaceFormat.format;
  140. info.components.r = VK_COMPONENT_SWIZZLE_R;
  141. info.components.g = VK_COMPONENT_SWIZZLE_G;
  142. info.components.b = VK_COMPONENT_SWIZZLE_B;
  143. info.components.a = VK_COMPONENT_SWIZZLE_A;
  144. info.subresourceRange = g_ImageRange;
  145. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  146. {
  147. info.image = g_BackBuffer[i];
  148. err = vkCreateImageView(g_Device, &info, g_Allocator, &g_BackBufferView[i]);
  149. check_vk_result(err);
  150. }
  151. }
  152. // Create Framebuffer:
  153. {
  154. VkImageView attachment[1];
  155. VkFramebufferCreateInfo info = {};
  156. info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  157. info.renderPass = g_RenderPass;
  158. info.attachmentCount = 1;
  159. info.pAttachments = attachment;
  160. info.width = fb_width;
  161. info.height = fb_height;
  162. info.layers = 1;
  163. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  164. {
  165. attachment[0] = g_BackBufferView[i];
  166. err = vkCreateFramebuffer(g_Device, &info, g_Allocator, &g_Framebuffer[i]);
  167. check_vk_result(err);
  168. }
  169. }
  170. }
  171. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  172. static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(
  173. VkDebugReportFlagsEXT, //flags,
  174. VkDebugReportObjectTypeEXT objectType,
  175. uint64_t, //object,
  176. size_t, //location,
  177. int32_t, //messageCode,
  178. const char*, //pLayerPrefix,
  179. const char* pMessage,
  180. void*) //pUserData)
  181. {
  182. printf( "ObjectType : %i\nMessage : %s\n\n", objectType, pMessage );
  183. return VK_FALSE;
  184. }
  185. #endif // IMGUI_VULKAN_DEBUG_REPORT
  186. static void setup_vulkan(GLFWwindow* window)
  187. {
  188. VkResult err;
  189. // Create Vulkan Instance
  190. {
  191. uint32_t extensions_count;
  192. const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&extensions_count);
  193. VkInstanceCreateInfo create_info = {};
  194. create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  195. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  196. // enabling multiple validation layers grouped as lunarg standard validation
  197. const char* layers[] = {"VK_LAYER_LUNARG_standard_validation"};
  198. create_info.enabledLayerCount = 1;
  199. create_info.ppEnabledLayerNames = layers;
  200. // need additional storage for char pointer to debug report extension
  201. const char** extensions = (const char**)malloc(sizeof(const char*) * (extensions_count + 1));
  202. for (size_t i = 0; i < extensions_count; i++)
  203. extensions[i] = glfw_extensions[i];
  204. extensions[ extensions_count ] = "VK_EXT_debug_report";
  205. create_info.enabledExtensionCount = extensions_count+1;
  206. create_info.ppEnabledExtensionNames = extensions;
  207. #else
  208. create_info.enabledExtensionCount = extensions_count;
  209. create_info.ppEnabledExtensionNames = glfw_extensions;
  210. #endif // IMGUI_VULKAN_DEBUG_REPORT
  211. err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
  212. check_vk_result(err);
  213. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  214. free(extensions);
  215. // create the debug report callback
  216. VkDebugReportCallbackCreateInfoEXT debug_report_ci ={};
  217. debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  218. debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
  219. debug_report_ci.pfnCallback = debug_report;
  220. debug_report_ci.pUserData = NULL;
  221. // get the proc address of the function pointer, required for used extensions
  222. PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT =
  223. (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
  224. err = vkCreateDebugReportCallbackEXT( g_Instance, &debug_report_ci, g_Allocator, &g_Debug_Report );
  225. check_vk_result( err );
  226. #endif // IMGUI_VULKAN_DEBUG_REPORT
  227. }
  228. // Create Window Surface
  229. {
  230. err = glfwCreateWindowSurface(g_Instance, window, g_Allocator, &g_Surface);
  231. check_vk_result(err);
  232. }
  233. // Get GPU
  234. {
  235. uint32_t gpu_count;
  236. err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL);
  237. check_vk_result(err);
  238. if( gpu_count == 1 ) { // only one gpu, assume it has a graphics queue family and use it
  239. err = vkEnumeratePhysicalDevices( g_Instance, &gpu_count, &g_Gpu );
  240. check_vk_result( err );
  241. } else {
  242. VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count);
  243. err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus);
  244. check_vk_result(err);
  245. // here a number > 1 of GPUs got reported, you should find the best fit GPU for your purpose
  246. // e.g. VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU if available, or with the greatest memory available, etc.
  247. // for sake of simplicity we'll just take the first one, assuming it has a graphics queue family
  248. g_Gpu = gpus[0];
  249. free(gpus);
  250. }
  251. }
  252. // Get queue
  253. {
  254. uint32_t count;
  255. vkGetPhysicalDeviceQueueFamilyProperties(g_Gpu, &count, NULL);
  256. VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count);
  257. vkGetPhysicalDeviceQueueFamilyProperties(g_Gpu, &count, queues);
  258. for (uint32_t i = 0; i < count; i++)
  259. {
  260. if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
  261. {
  262. g_QueueFamily = i;
  263. break;
  264. }
  265. }
  266. free(queues);
  267. }
  268. // Check for WSI support
  269. {
  270. VkBool32 res;
  271. vkGetPhysicalDeviceSurfaceSupportKHR(g_Gpu, g_QueueFamily, g_Surface, &res);
  272. if (res != VK_TRUE)
  273. {
  274. fprintf(stderr, "Error no WSI support on physical device 0\n");
  275. exit(-1);
  276. }
  277. }
  278. // Get Surface Format
  279. {
  280. // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
  281. // Assuming that the default behaviour is without setting this bit, there is no need for seperate Spapchain image and image view format
  282. // additionally severeal new color spaces were introduced with Vulkan Spec v1.0.40
  283. // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used
  284. uint32_t count;
  285. vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, NULL);
  286. VkSurfaceFormatKHR *formats = (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR) * count);
  287. vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, formats);
  288. // first check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
  289. if (count == 1)
  290. {
  291. if( formats[0].format == VK_FORMAT_UNDEFINED )
  292. {
  293. g_SurfaceFormat.format = VK_FORMAT_B8G8R8A8_UNORM;
  294. g_SurfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
  295. }
  296. else
  297. { // no point in searching another format
  298. g_SurfaceFormat = formats[0];
  299. }
  300. }
  301. else
  302. {
  303. // request several formats, the first found will be used
  304. VkFormat requestSurfaceImageFormat[] = {VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM};
  305. VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
  306. bool requestedFound = false;
  307. for (size_t i = 0; i < sizeof(requestSurfaceImageFormat) / sizeof(requestSurfaceImageFormat[0]); i++)
  308. {
  309. if( requestedFound ) {
  310. break;
  311. }
  312. for (uint32_t j = 0; j < count; j++)
  313. {
  314. if (formats[j].format == requestSurfaceImageFormat[i] && formats[j].colorSpace == requestSurfaceColorSpace)
  315. {
  316. g_SurfaceFormat = formats[j];
  317. requestedFound = true;
  318. }
  319. }
  320. }
  321. // if none of the requested image formats could be found, use the first available
  322. if (!requestedFound)
  323. {
  324. g_SurfaceFormat = formats[0];
  325. }
  326. }
  327. free(formats);
  328. }
  329. // Get Present Mode
  330. {
  331. // Requst a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
  332. #ifdef IMGUI_UNLIMITED_FRAME_RATE
  333. g_PresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
  334. #else
  335. g_PresentMode = VK_PRESENT_MODE_FIFO_KHR;
  336. #endif
  337. uint32_t count = 0;
  338. vkGetPhysicalDeviceSurfacePresentModesKHR( g_Gpu, g_Surface, &count, nullptr );
  339. VkPresentModeKHR* presentModes = ( VkPresentModeKHR* )malloc( sizeof( VkQueueFamilyProperties ) * count );
  340. vkGetPhysicalDeviceSurfacePresentModesKHR( g_Gpu, g_Surface, &count, presentModes );
  341. bool presentModeAvailable = false;
  342. for (size_t i = 0; i < count; i++)
  343. {
  344. if (presentModes[i] == g_PresentMode)
  345. {
  346. presentModeAvailable = true;
  347. break;
  348. }
  349. }
  350. if( !presentModeAvailable )
  351. g_PresentMode = VK_PRESENT_MODE_FIFO_KHR; // allways available
  352. }
  353. // Create Logical Device
  354. {
  355. int device_extension_count = 1;
  356. const char* device_extensions[] = {"VK_KHR_swapchain"};
  357. const uint32_t queue_index = 0;
  358. const uint32_t queue_count = 1;
  359. const float queue_priority[] = {1.0f};
  360. VkDeviceQueueCreateInfo queue_info[1] = {};
  361. queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  362. queue_info[0].queueFamilyIndex = g_QueueFamily;
  363. queue_info[0].queueCount = queue_count;
  364. queue_info[0].pQueuePriorities = queue_priority;
  365. VkDeviceCreateInfo create_info = {};
  366. create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  367. create_info.queueCreateInfoCount = sizeof(queue_info)/sizeof(queue_info[0]);
  368. create_info.pQueueCreateInfos = queue_info;
  369. create_info.enabledExtensionCount = device_extension_count;
  370. create_info.ppEnabledExtensionNames = device_extensions;
  371. err = vkCreateDevice(g_Gpu, &create_info, g_Allocator, &g_Device);
  372. check_vk_result(err);
  373. vkGetDeviceQueue(g_Device, g_QueueFamily, queue_index, &g_Queue);
  374. }
  375. // Create Framebuffers
  376. {
  377. int w, h;
  378. glfwGetFramebufferSize(window, &w, &h);
  379. resize_vulkan(window, w, h);
  380. glfwSetFramebufferSizeCallback(window, resize_vulkan);
  381. }
  382. // Create Command Buffers
  383. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  384. {
  385. {
  386. VkCommandPoolCreateInfo info = {};
  387. info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  388. info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  389. info.queueFamilyIndex = g_QueueFamily;
  390. err = vkCreateCommandPool(g_Device, &info, g_Allocator, &g_CommandPool[i]);
  391. check_vk_result(err);
  392. }
  393. {
  394. VkCommandBufferAllocateInfo info = {};
  395. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  396. info.commandPool = g_CommandPool[i];
  397. info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  398. info.commandBufferCount = 1;
  399. err = vkAllocateCommandBuffers(g_Device, &info, &g_CommandBuffer[i]);
  400. check_vk_result(err);
  401. }
  402. {
  403. VkFenceCreateInfo info = {};
  404. info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  405. info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  406. err = vkCreateFence(g_Device, &info, g_Allocator, &g_Fence[i]);
  407. check_vk_result(err);
  408. }
  409. {
  410. VkSemaphoreCreateInfo info = {};
  411. info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  412. err = vkCreateSemaphore(g_Device, &info, g_Allocator, &g_Semaphore[i]);
  413. check_vk_result(err);
  414. }
  415. }
  416. // Create Descriptor Pool
  417. {
  418. VkDescriptorPoolSize pool_size[11] =
  419. {
  420. { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
  421. { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
  422. { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
  423. { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
  424. { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
  425. { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
  426. { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
  427. { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
  428. { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
  429. { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
  430. { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
  431. };
  432. VkDescriptorPoolCreateInfo pool_info = {};
  433. pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  434. pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
  435. pool_info.maxSets = 1000 * 11;
  436. pool_info.poolSizeCount = 11;
  437. pool_info.pPoolSizes = pool_size;
  438. err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
  439. check_vk_result(err);
  440. }
  441. }
  442. static void cleanup_vulkan()
  443. {
  444. vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
  445. for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++)
  446. {
  447. vkDestroyFence(g_Device, g_Fence[i], g_Allocator);
  448. vkFreeCommandBuffers(g_Device, g_CommandPool[i], 1, &g_CommandBuffer[i]);
  449. vkDestroyCommandPool(g_Device, g_CommandPool[i], g_Allocator);
  450. vkDestroySemaphore(g_Device, g_Semaphore[i], g_Allocator);
  451. }
  452. for (uint32_t i = 0; i < g_BackBufferCount; i++)
  453. {
  454. vkDestroyImageView(g_Device, g_BackBufferView[i], g_Allocator);
  455. vkDestroyFramebuffer(g_Device, g_Framebuffer[i], g_Allocator);
  456. }
  457. vkDestroyRenderPass(g_Device, g_RenderPass, g_Allocator);
  458. vkDestroySwapchainKHR(g_Device, g_Swapchain, g_Allocator);
  459. vkDestroySurfaceKHR(g_Instance, g_Surface, g_Allocator);
  460. #ifdef IMGUI_VULKAN_DEBUG_REPORT
  461. // get the proc address of the function pointer, required for used extensions
  462. auto vkDestroyDebugReportCallbackEXT =
  463. (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
  464. vkDestroyDebugReportCallbackEXT(g_Instance, g_Debug_Report, g_Allocator);
  465. #endif // IMGUI_VULKAN_DEBUG_REPORT
  466. vkDestroyDevice(g_Device, g_Allocator);
  467. vkDestroyInstance(g_Instance, g_Allocator);
  468. }
  469. static void frame_begin()
  470. {
  471. VkResult err;
  472. while (true)
  473. {
  474. err = vkWaitForFences(g_Device, 1, &g_Fence[g_FrameIndex], VK_TRUE, 100);
  475. if (err == VK_SUCCESS) break;
  476. if (err == VK_TIMEOUT) continue;
  477. check_vk_result(err);
  478. }
  479. {
  480. err = vkAcquireNextImageKHR(g_Device, g_Swapchain, UINT64_MAX, g_Semaphore[g_FrameIndex], VK_NULL_HANDLE, &g_BackBufferIndex);
  481. check_vk_result(err);
  482. }
  483. {
  484. err = vkResetCommandPool(g_Device, g_CommandPool[g_FrameIndex], 0);
  485. check_vk_result(err);
  486. VkCommandBufferBeginInfo info = {};
  487. info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  488. info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  489. err = vkBeginCommandBuffer(g_CommandBuffer[g_FrameIndex], &info);
  490. check_vk_result(err);
  491. }
  492. {
  493. VkRenderPassBeginInfo info = {};
  494. info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  495. info.renderPass = g_RenderPass;
  496. info.framebuffer = g_Framebuffer[g_BackBufferIndex];
  497. info.renderArea.extent.width = fb_width;
  498. info.renderArea.extent.height = fb_height;
  499. info.clearValueCount = 1;
  500. info.pClearValues = &g_ClearValue;
  501. vkCmdBeginRenderPass(g_CommandBuffer[g_FrameIndex], &info, VK_SUBPASS_CONTENTS_INLINE);
  502. }
  503. }
  504. static void frame_end()
  505. {
  506. VkResult err;
  507. vkCmdEndRenderPass(g_CommandBuffer[g_FrameIndex]);
  508. {
  509. VkImageMemoryBarrier barrier = {};
  510. barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  511. barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  512. barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
  513. barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  514. barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  515. barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  516. barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  517. barrier.image = g_BackBuffer[g_BackBufferIndex];
  518. barrier.subresourceRange = g_ImageRange;
  519. vkCmdPipelineBarrier(g_CommandBuffer[g_FrameIndex], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &barrier);
  520. }
  521. {
  522. VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  523. VkSubmitInfo info = {};
  524. info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  525. info.waitSemaphoreCount = 1;
  526. info.pWaitSemaphores = &g_Semaphore[g_FrameIndex];
  527. info.pWaitDstStageMask = &wait_stage;
  528. info.commandBufferCount = 1;
  529. info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
  530. err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
  531. check_vk_result(err);
  532. err = vkResetFences(g_Device, 1, &g_Fence[g_FrameIndex]);
  533. check_vk_result(err);
  534. err = vkQueueSubmit(g_Queue, 1, &info, g_Fence[g_FrameIndex]);
  535. check_vk_result(err);
  536. }
  537. {
  538. VkResult res;
  539. VkSwapchainKHR swapchains[1] = {g_Swapchain};
  540. uint32_t indices[1] = {g_BackBufferIndex};
  541. VkPresentInfoKHR info = {};
  542. info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  543. info.swapchainCount = 1;
  544. info.pSwapchains = swapchains;
  545. info.pImageIndices = indices;
  546. info.pResults = &res;
  547. err = vkQueuePresentKHR(g_Queue, &info);
  548. check_vk_result(err);
  549. check_vk_result(res);
  550. }
  551. g_FrameIndex = (g_FrameIndex+1) % IMGUI_VK_QUEUED_FRAMES;
  552. }
  553. static void error_callback(int error, const char* description)
  554. {
  555. fprintf(stderr, "Error %d: %s\n", error, description);
  556. }
  557. int main(int, char**)
  558. {
  559. // Setup window
  560. glfwSetErrorCallback(error_callback);
  561. if (!glfwInit())
  562. return 1;
  563. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  564. GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui Vulkan example", NULL, NULL);
  565. // Setup Vulkan
  566. if (!glfwVulkanSupported())
  567. {
  568. printf("GLFW: Vulkan Not Supported\n");
  569. return 1;
  570. }
  571. setup_vulkan(window);
  572. // Setup ImGui binding
  573. ImGui_ImplGlfwVulkan_Init_Data init_data = {};
  574. init_data.allocator = g_Allocator;
  575. init_data.gpu = g_Gpu;
  576. init_data.device = g_Device;
  577. init_data.render_pass = g_RenderPass;
  578. init_data.pipeline_cache = g_PipelineCache;
  579. init_data.descriptor_pool = g_DescriptorPool;
  580. init_data.check_vk_result = check_vk_result;
  581. ImGui_ImplGlfwVulkan_Init(window, true, &init_data);
  582. // Load Fonts
  583. // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
  584. //ImGuiIO& io = ImGui::GetIO();
  585. //io.Fonts->AddFontDefault();
  586. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
  587. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
  588. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
  589. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
  590. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  591. // Upload Fonts
  592. {
  593. VkResult err;
  594. err = vkResetCommandPool(g_Device, g_CommandPool[g_FrameIndex], 0);
  595. check_vk_result(err);
  596. VkCommandBufferBeginInfo begin_info = {};
  597. begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  598. begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  599. err = vkBeginCommandBuffer(g_CommandBuffer[g_FrameIndex], &begin_info);
  600. check_vk_result(err);
  601. ImGui_ImplGlfwVulkan_CreateFontsTexture(g_CommandBuffer[g_FrameIndex]);
  602. VkSubmitInfo end_info = {};
  603. end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  604. end_info.commandBufferCount = 1;
  605. end_info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
  606. err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
  607. check_vk_result(err);
  608. err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE);
  609. check_vk_result(err);
  610. err = vkDeviceWaitIdle(g_Device);
  611. check_vk_result(err);
  612. ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
  613. }
  614. bool show_test_window = true;
  615. bool show_another_window = false;
  616. ImVec4 clear_color = ImColor(114, 144, 154);
  617. // Main loop
  618. while (!glfwWindowShouldClose(window))
  619. {
  620. glfwPollEvents();
  621. ImGui_ImplGlfwVulkan_NewFrame();
  622. // 1. Show a simple window
  623. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  624. {
  625. static float f = 0.0f;
  626. ImGui::Text("Hello, world!");
  627. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  628. ImGui::ColorEdit3("clear color", (float*)&clear_color);
  629. if (ImGui::Button("Test Window")) show_test_window ^= 1;
  630. if (ImGui::Button("Another Window")) show_another_window ^= 1;
  631. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  632. }
  633. // 2. Show another simple window, this time using an explicit Begin/End pair
  634. if (show_another_window)
  635. {
  636. ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
  637. ImGui::Begin("Another Window", &show_another_window);
  638. ImGui::Text("Hello");
  639. ImGui::End();
  640. }
  641. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  642. if (show_test_window)
  643. {
  644. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
  645. ImGui::ShowTestWindow(&show_test_window);
  646. }
  647. g_ClearValue.color.float32[0] = clear_color.x;
  648. g_ClearValue.color.float32[1] = clear_color.y;
  649. g_ClearValue.color.float32[2] = clear_color.z;
  650. g_ClearValue.color.float32[3] = clear_color.w;
  651. frame_begin();
  652. ImGui_ImplGlfwVulkan_Render(g_CommandBuffer[g_FrameIndex]);
  653. frame_end();
  654. }
  655. // Cleanup
  656. VkResult err = vkDeviceWaitIdle(g_Device);
  657. check_vk_result(err);
  658. ImGui_ImplGlfwVulkan_Shutdown();
  659. cleanup_vulkan();
  660. glfwTerminate();
  661. return 0;
  662. }