25.9 KB、582行 生 Blame 履歴
1// Dear ImGui: standalone example application for SDL3 + Vulkan
2
3// Learn about Dear ImGui:
4// - FAQ https://dearimgui.com/faq
5// - Getting Started https://dearimgui.com/getting-started
6// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
7// - Introduction, links and more at the top of imgui.cpp
8
9// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
10// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
11// You will use those if you want to use this rendering backend in your engine/app.
12// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
13// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
14// Read comments in imgui_impl_vulkan.h.
15
16#include "imgui.h"
17#include "imgui_impl_sdl3.h"
18#include "imgui_impl_vulkan.h"
19#include <stdio.h> // printf, fprintf
20#include <stdlib.h> // abort
21#include <SDL3/SDL.h>
22#include <SDL3/SDL_vulkan.h>
23
24// This example doesn't compile with Emscripten yet! Awaiting SDL3 support.
25#ifdef __EMSCRIPTEN__
26#include "../libs/emscripten/emscripten_mainloop_stub.h"
27#endif
28
29// Volk headers
30#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
31#define VOLK_IMPLEMENTATION
32#include <volk.h>
33#endif
34
35//#define APP_USE_UNLIMITED_FRAME_RATE
36#ifdef _DEBUG
37#define APP_USE_VULKAN_DEBUG_REPORT
38static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE;
39#endif
40
41// Data
42static VkAllocationCallbacks* g_Allocator = nullptr;
43static VkInstance g_Instance = VK_NULL_HANDLE;
44static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE;
45static VkDevice g_Device = VK_NULL_HANDLE;
46static uint32_t g_QueueFamily = (uint32_t)-1;
47static VkQueue g_Queue = VK_NULL_HANDLE;
48static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE;
49static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE;
50
51static ImGui_ImplVulkanH_Window g_MainWindowData;
52static uint32_t g_MinImageCount = 2;
53static bool g_SwapChainRebuild = false;
54
55static void check_vk_result(VkResult err)
56{
57 if (err == VK_SUCCESS)
58 return;
59 fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err);
60 if (err < 0)
61 abort();
62}
63
64#ifdef APP_USE_VULKAN_DEBUG_REPORT
65static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData)
66{
67 (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments
68 fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage);
69 return VK_FALSE;
70}
71#endif // APP_USE_VULKAN_DEBUG_REPORT
72
73static bool IsExtensionAvailable(const ImVector<VkExtensionProperties>& properties, const char* extension)
74{
75 for (const VkExtensionProperties& p : properties)
76 if (strcmp(p.extensionName, extension) == 0)
77 return true;
78 return false;
79}
80
81static void SetupVulkan(ImVector<const char*> instance_extensions)
82{
83 VkResult err;
84#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
85 volkInitialize();
86#endif
87
88 // Create Vulkan Instance
89 {
90 VkInstanceCreateInfo create_info = {};
91 create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
92
93 // Enumerate available extensions
94 uint32_t properties_count;
95 ImVector<VkExtensionProperties> properties;
96 vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, nullptr);
97 properties.resize(properties_count);
98 err = vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, properties.Data);
99 check_vk_result(err);
100
101 // Enable required extensions
102 if (IsExtensionAvailable(properties, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME))
103 instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
104#ifdef VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME
105 if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME))
106 {
107 instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
108 create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
109 }
110#endif
111
112 // Enabling validation layers
113#ifdef APP_USE_VULKAN_DEBUG_REPORT
114 const char* layers[] = { "VK_LAYER_KHRONOS_validation" };
115 create_info.enabledLayerCount = 1;
116 create_info.ppEnabledLayerNames = layers;
117 instance_extensions.push_back("VK_EXT_debug_report");
118#endif
119
120 // Create Vulkan Instance
121 create_info.enabledExtensionCount = (uint32_t)instance_extensions.Size;
122 create_info.ppEnabledExtensionNames = instance_extensions.Data;
123 err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
124 check_vk_result(err);
125#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
126 volkLoadInstance(g_Instance);
127#endif
128
129 // Setup the debug report callback
130#ifdef APP_USE_VULKAN_DEBUG_REPORT
131 auto f_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
132 IM_ASSERT(f_vkCreateDebugReportCallbackEXT != nullptr);
133 VkDebugReportCallbackCreateInfoEXT debug_report_ci = {};
134 debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
135 debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
136 debug_report_ci.pfnCallback = debug_report;
137 debug_report_ci.pUserData = nullptr;
138 err = f_vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport);
139 check_vk_result(err);
140#endif
141 }
142
143 // Select Physical Device (GPU)
144 g_PhysicalDevice = ImGui_ImplVulkanH_SelectPhysicalDevice(g_Instance);
145 IM_ASSERT(g_PhysicalDevice != VK_NULL_HANDLE);
146
147 // Select graphics queue family
148 g_QueueFamily = ImGui_ImplVulkanH_SelectQueueFamilyIndex(g_PhysicalDevice);
149 IM_ASSERT(g_QueueFamily != (uint32_t)-1);
150
151 // Create Logical Device (with 1 queue)
152 {
153 ImVector<const char*> device_extensions;
154 device_extensions.push_back("VK_KHR_swapchain");
155
156 // Enumerate physical device extension
157 uint32_t properties_count;
158 ImVector<VkExtensionProperties> properties;
159 vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, nullptr);
160 properties.resize(properties_count);
161 vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, properties.Data);
162#ifdef VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME
163 if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME))
164 device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME);
165#endif
166
167 const float queue_priority[] = { 1.0f };
168 VkDeviceQueueCreateInfo queue_info[1] = {};
169 queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
170 queue_info[0].queueFamilyIndex = g_QueueFamily;
171 queue_info[0].queueCount = 1;
172 queue_info[0].pQueuePriorities = queue_priority;
173 VkDeviceCreateInfo create_info = {};
174 create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
175 create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]);
176 create_info.pQueueCreateInfos = queue_info;
177 create_info.enabledExtensionCount = (uint32_t)device_extensions.Size;
178 create_info.ppEnabledExtensionNames = device_extensions.Data;
179 err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device);
180 check_vk_result(err);
181 vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue);
182 }
183
184 // Create Descriptor Pool
185 // If you wish to load e.g. additional textures you may need to alter pools sizes and maxSets.
186 {
187 VkDescriptorPoolSize pool_sizes[] =
188 {
189 { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, IMGUI_IMPL_VULKAN_MINIMUM_SAMPLED_IMAGE_POOL_SIZE },
190 { VK_DESCRIPTOR_TYPE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_SAMPLER_POOL_SIZE },
191 };
192 VkDescriptorPoolCreateInfo pool_info = {};
193 pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
194 pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
195 pool_info.maxSets = 0;
196 for (VkDescriptorPoolSize& pool_size : pool_sizes)
197 pool_info.maxSets += pool_size.descriptorCount;
198 pool_info.poolSizeCount = (uint32_t)IM_COUNTOF(pool_sizes);
199 pool_info.pPoolSizes = pool_sizes;
200 err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
201 check_vk_result(err);
202 }
203}
204
205// All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo.
206// Your real engine/app may not use them.
207static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height)
208{
209 // Check for WSI support
210 VkBool32 res;
211 vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface, &res);
212 if (res != VK_TRUE)
213 {
214 fprintf(stderr, "Error no WSI support on physical device 0\n");
215 exit(-1);
216 }
217
218 // Select Surface Format
219 const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM };
220 const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
221 wd->Surface = surface;
222 wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace);
223
224 // Select Present Mode
225#ifdef APP_USE_UNLIMITED_FRAME_RATE
226 VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR };
227#else
228 VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR };
229#endif
230 wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_COUNTOF(present_modes));
231 //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode);
232
233 // Create SwapChain, RenderPass, Framebuffer, etc.
234 IM_ASSERT(g_MinImageCount >= 2);
235 ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, 0);
236}
237
238static void CleanupVulkan()
239{
240 vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
241
242#ifdef APP_USE_VULKAN_DEBUG_REPORT
243 // Remove the debug report callback
244 auto f_vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
245 f_vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator);
246#endif // APP_USE_VULKAN_DEBUG_REPORT
247
248 vkDestroyDevice(g_Device, g_Allocator);
249 vkDestroyInstance(g_Instance, g_Allocator);
250}
251
252static void CleanupVulkanWindow(ImGui_ImplVulkanH_Window* wd)
253{
254 ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator);
255 vkDestroySurfaceKHR(g_Instance, wd->Surface, g_Allocator);
256}
257
258static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data)
259{
260 VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore;
261 VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore;
262 VkResult err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex);
263 if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR)
264 g_SwapChainRebuild = true;
265 if (err == VK_ERROR_OUT_OF_DATE_KHR)
266 return;
267 if (err != VK_SUBOPTIMAL_KHR)
268 check_vk_result(err);
269
270 ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex];
271 {
272 err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking
273 check_vk_result(err);
274
275 err = vkResetFences(g_Device, 1, &fd->Fence);
276 check_vk_result(err);
277 }
278 {
279 err = vkResetCommandPool(g_Device, fd->CommandPool, 0);
280 check_vk_result(err);
281 VkCommandBufferBeginInfo info = {};
282 info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
283 info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
284 err = vkBeginCommandBuffer(fd->CommandBuffer, &info);
285 check_vk_result(err);
286 }
287 {
288 VkRenderPassBeginInfo info = {};
289 info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
290 info.renderPass = wd->RenderPass;
291 info.framebuffer = fd->Framebuffer;
292 info.renderArea.extent.width = wd->Width;
293 info.renderArea.extent.height = wd->Height;
294 info.clearValueCount = 1;
295 info.pClearValues = &wd->ClearValue;
296 vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE);
297 }
298
299 // Record dear imgui primitives into command buffer
300 ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer);
301
302 // Submit command buffer
303 vkCmdEndRenderPass(fd->CommandBuffer);
304 {
305 VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
306 VkSubmitInfo info = {};
307 info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
308 info.waitSemaphoreCount = 1;
309 info.pWaitSemaphores = &image_acquired_semaphore;
310 info.pWaitDstStageMask = &wait_stage;
311 info.commandBufferCount = 1;
312 info.pCommandBuffers = &fd->CommandBuffer;
313 info.signalSemaphoreCount = 1;
314 info.pSignalSemaphores = &render_complete_semaphore;
315
316 err = vkEndCommandBuffer(fd->CommandBuffer);
317 check_vk_result(err);
318 err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence);
319 check_vk_result(err);
320 }
321}
322
323static void FramePresent(ImGui_ImplVulkanH_Window* wd)
324{
325 if (g_SwapChainRebuild)
326 return;
327 VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore;
328 VkPresentInfoKHR info = {};
329 info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
330 info.waitSemaphoreCount = 1;
331 info.pWaitSemaphores = &render_complete_semaphore;
332 info.swapchainCount = 1;
333 info.pSwapchains = &wd->Swapchain;
334 info.pImageIndices = &wd->FrameIndex;
335 VkResult err = vkQueuePresentKHR(g_Queue, &info);
336 if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR)
337 g_SwapChainRebuild = true;
338 if (err == VK_ERROR_OUT_OF_DATE_KHR)
339 return;
340 if (err != VK_SUBOPTIMAL_KHR)
341 check_vk_result(err);
342 wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores
343}
344
345// Main code
346int main(int, char**)
347{
348 // Setup SDL
349 // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function]
350 if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
351 {
352 printf("Error: SDL_Init(): %s\n", SDL_GetError());
353 return 1;
354 }
355
356 // Create window with Vulkan graphics context
357 float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
358 SDL_WindowFlags window_flags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY;
359 SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags);
360 if (window == nullptr)
361 {
362 printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
363 return 1;
364 }
365
366 ImVector<const char*> extensions;
367 {
368 uint32_t sdl_extensions_count = 0;
369 const char* const* sdl_extensions = SDL_Vulkan_GetInstanceExtensions(&sdl_extensions_count);
370 for (uint32_t n = 0; n < sdl_extensions_count; n++)
371 extensions.push_back(sdl_extensions[n]);
372 }
373 SetupVulkan(extensions);
374
375 // Create Window Surface
376 VkSurfaceKHR surface;
377 VkResult err;
378 if (SDL_Vulkan_CreateSurface(window, g_Instance, g_Allocator, &surface) == 0)
379 {
380 printf("Failed to create Vulkan surface.\n");
381 return 1;
382 }
383
384 // Create Framebuffers
385 int w, h;
386 SDL_GetWindowSize(window, &w, &h);
387 ImGui_ImplVulkanH_Window* wd = &g_MainWindowData;
388 SetupVulkanWindow(wd, surface, w, h);
389 SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
390 SDL_ShowWindow(window);
391
392 // Setup Dear ImGui context
393 IMGUI_CHECKVERSION();
394 ImGui::CreateContext();
395 ImGuiIO& io = ImGui::GetIO(); (void)io;
396 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
397 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
398 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
399 io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
400 //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons;
401 //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge;
402
403 // Setup Dear ImGui style
404 ImGui::StyleColorsDark();
405 //ImGui::StyleColorsLight();
406
407 // Setup scaling
408 ImGuiStyle& style = ImGui::GetStyle();
409 style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
410 style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
411 io.ConfigDpiScaleFonts = true; // [Experimental] Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now.
412 io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes.
413
414 // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
415 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
416 {
417 style.WindowRounding = 0.0f;
418 style.Colors[ImGuiCol_WindowBg].w = 1.0f;
419 }
420
421 // Setup Platform/Renderer backends
422 ImGui_ImplSDL3_InitForVulkan(window);
423 ImGui_ImplVulkan_InitInfo init_info = {};
424 //init_info.ApiVersion = VK_API_VERSION_1_3; // Pass in your value of VkApplicationInfo::apiVersion, otherwise will default to header version.
425 init_info.Instance = g_Instance;
426 init_info.PhysicalDevice = g_PhysicalDevice;
427 init_info.Device = g_Device;
428 init_info.QueueFamily = g_QueueFamily;
429 init_info.Queue = g_Queue;
430 init_info.PipelineCache = g_PipelineCache;
431 init_info.DescriptorPool = g_DescriptorPool;
432 init_info.MinImageCount = g_MinImageCount;
433 init_info.ImageCount = wd->ImageCount;
434 init_info.Allocator = g_Allocator;
435 init_info.PipelineInfoMain.RenderPass = wd->RenderPass;
436 init_info.PipelineInfoMain.Subpass = 0;
437 init_info.PipelineInfoMain.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
438 init_info.CheckVkResultFn = check_vk_result;
439 ImGui_ImplVulkan_Init(&init_info);
440
441 // Load Fonts
442 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
443 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
444 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
445 // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
446 // - Read 'docs/FONTS.md' for more instructions and details.
447 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
448 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
449 //style.FontSizeBase = 20.0f;
450 //io.Fonts->AddFontDefaultVector();
451 //io.Fonts->AddFontDefaultBitmap();
452 //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
453 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
454 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
455 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
456 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
457 //IM_ASSERT(font != nullptr);
458
459 // Our state
460 bool show_demo_window = true;
461 bool show_another_window = false;
462 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
463
464 // Main loop
465 bool done = false;
466 while (!done)
467 {
468 // Poll and handle events (inputs, window resize, etc.)
469 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
470 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
471 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
472 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
473 // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function]
474 SDL_Event event;
475 while (SDL_PollEvent(&event))
476 {
477 ImGui_ImplSDL3_ProcessEvent(&event);
478 if (event.type == SDL_EVENT_QUIT)
479 done = true;
480 if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
481 done = true;
482 }
483
484 // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function]
485 if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
486 {
487 SDL_Delay(10);
488 continue;
489 }
490
491 // Resize swap chain?
492 int fb_width, fb_height;
493 SDL_GetWindowSize(window, &fb_width, &fb_height);
494 if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height))
495 {
496 ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount);
497 ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, 0);
498 g_MainWindowData.FrameIndex = 0;
499 g_SwapChainRebuild = false;
500 }
501
502 // Start the Dear ImGui frame
503 ImGui_ImplVulkan_NewFrame();
504 ImGui_ImplSDL3_NewFrame();
505 ImGui::NewFrame();
506
507 // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
508 if (show_demo_window)
509 ImGui::ShowDemoWindow(&show_demo_window);
510
511 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
512 {
513 static float f = 0.0f;
514 static int counter = 0;
515
516 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
517
518 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
519 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
520 ImGui::Checkbox("Another Window", &show_another_window);
521
522 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
523 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
524
525 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
526 counter++;
527 ImGui::SameLine();
528 ImGui::Text("counter = %d", counter);
529
530 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
531 ImGui::End();
532 }
533
534 // 3. Show another simple window.
535 if (show_another_window)
536 {
537 ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
538 ImGui::Text("Hello from another window!");
539 if (ImGui::Button("Close Me"))
540 show_another_window = false;
541 ImGui::End();
542 }
543
544 // Rendering
545 ImGui::Render();
546 ImDrawData* main_draw_data = ImGui::GetDrawData();
547 const bool main_is_minimized = (main_draw_data->DisplaySize.x <= 0.0f || main_draw_data->DisplaySize.y <= 0.0f);
548 wd->ClearValue.color.float32[0] = clear_color.x * clear_color.w;
549 wd->ClearValue.color.float32[1] = clear_color.y * clear_color.w;
550 wd->ClearValue.color.float32[2] = clear_color.z * clear_color.w;
551 wd->ClearValue.color.float32[3] = clear_color.w;
552 if (!main_is_minimized)
553 FrameRender(wd, main_draw_data);
554
555 // Update and Render additional Platform Windows
556 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
557 {
558 ImGui::UpdatePlatformWindows();
559 ImGui::RenderPlatformWindowsDefault();
560 }
561
562 // Present Main Platform Window
563 if (!main_is_minimized)
564 FramePresent(wd);
565 }
566
567 // Cleanup
568 // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function]
569 err = vkDeviceWaitIdle(g_Device);
570 check_vk_result(err);
571 ImGui_ImplVulkan_Shutdown();
572 ImGui_ImplSDL3_Shutdown();
573 ImGui::DestroyContext();
574
575 CleanupVulkanWindow(&g_MainWindowData);
576 CleanupVulkan();
577
578 SDL_DestroyWindow(window);
579 SDL_Quit();
580
581 return 0;
582}