source: opengl-game/vulkan-game.cpp@ 1f25a71

feature/imgui-sdl points-test
Last change on this file since 1f25a71 was 1f25a71, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 5 years ago

In vulkangame, print the SDL version and finish implementing renderUI() to show some test images and text using SDL

  • Property mode set to 100644
File size: 37.3 KB
Line 
1#include "vulkan-game.hpp"
2
3#define GLM_FORCE_RADIANS
4#define GLM_FORCE_DEPTH_ZERO_TO_ONE
5
6#include <glm/gtc/matrix_transform.hpp>
7
8#include <array>
9#include <chrono>
10#include <iostream>
11#include <set>
12
13#include "consts.hpp"
14#include "logger.hpp"
15
16#include "utils.hpp"
17
18using namespace std;
19using namespace glm;
20
21struct UniformBufferObject {
22 alignas(16) mat4 model;
23 alignas(16) mat4 view;
24 alignas(16) mat4 proj;
25};
26
27VulkanGame::VulkanGame(int maxFramesInFlight) : MAX_FRAMES_IN_FLIGHT(maxFramesInFlight) {
28 gui = nullptr;
29 window = nullptr;
30 font = nullptr;
31 fontSDLTexture = nullptr;
32 imageSDLTexture = nullptr;
33
34 currentFrame = 0;
35 framebufferResized = false;
36}
37
38VulkanGame::~VulkanGame() {
39}
40
41void VulkanGame::run(int width, int height, unsigned char guiFlags) {
42 cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
43
44 cout << "Vulkan Game" << endl;
45
46 // This gets the runtime version, use SDL_VERSION() for the comppile-time version
47 // TODO: Create a game-gui function to get the gui version and retrieve it that way
48 SDL_GetVersion(&sdlVersion);
49
50 // TODO: Refactor the logger api to be more flexible,
51 // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
52 restart_gl_log();
53 gl_log("starting SDL\n%s.%s.%s",
54 to_string(sdlVersion.major).c_str(),
55 to_string(sdlVersion.minor).c_str(),
56 to_string(sdlVersion.patch).c_str());
57
58 open_log();
59 get_log() << "starting SDL" << endl;
60 get_log() <<
61 (int)sdlVersion.major << "." <<
62 (int)sdlVersion.minor << "." <<
63 (int)sdlVersion.patch << endl;
64
65 if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
66 return;
67 }
68
69 initVulkan();
70 mainLoop();
71 cleanup();
72
73 close_log();
74}
75
76// TODO: Make some more initi functions, or call this initUI if the
77// amount of things initialized here keeps growing
78bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
79 // TODO: Put all fonts, textures, and images in the assets folder
80 gui = new GameGui_SDL();
81
82 if (gui->init() == RTWO_ERROR) {
83 // TODO: Also print these sorts of errors to the log
84 cout << "UI library could not be initialized!" << endl;
85 cout << gui->getError() << endl;
86 return RTWO_ERROR;
87 }
88
89 window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
90 if (window == nullptr) {
91 cout << "Window could not be created!" << endl;
92 cout << gui->getError() << endl;
93 return RTWO_ERROR;
94 }
95
96 cout << "Target window size: (" << width << ", " << height << ")" << endl;
97 cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
98
99 renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
100 if (renderer == nullptr) {
101 cout << "Renderer could not be created!" << endl;
102 cout << gui->getError() << endl;
103 return RTWO_ERROR;
104 }
105
106 SDL_VERSION(&sdlVersion);
107
108 cout << "SDL " << sdlVersion.major << "." << sdlVersion.minor << "." << sdlVersion.patch << endl;
109
110 font = TTF_OpenFont("assets/fonts/lazy.ttf", 28);
111 if (font == nullptr) {
112 cout << "Failed to load lazy font! SDL_ttf Error: " << TTF_GetError() << endl;
113 return RTWO_ERROR;
114 }
115
116 SDL_Surface* fontSDLSurface = TTF_RenderText_Solid(font, "Great success!", { 255, 255, 255 });
117 if (fontSDLSurface == nullptr) {
118 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
119 return RTWO_ERROR;
120 }
121
122 fontSDLTexture = SDL_CreateTextureFromSurface(renderer, fontSDLSurface);
123 if (fontSDLTexture == nullptr) {
124 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
125 SDL_FreeSurface(fontSDLSurface);
126 return RTWO_ERROR;
127 }
128
129 SDL_FreeSurface(fontSDLSurface);
130
131 // TODO: Load a PNG instead
132 SDL_Surface* imageSDLSurface = SDL_LoadBMP("assets/images/spaceship.bmp");
133 if (imageSDLSurface == nullptr) {
134 cout << "Unable to load image " << "spaceship.bmp" << "! SDL Error: " << SDL_GetError() << endl;
135 return RTWO_ERROR;
136 }
137
138 imageSDLTexture = SDL_CreateTextureFromSurface(renderer, imageSDLSurface);
139 if (imageSDLTexture == nullptr) {
140 cout << "Unable to create texture from BMP surface! SDL Error: " << SDL_GetError() << endl;
141 SDL_FreeSurface(imageSDLSurface);
142 return RTWO_ERROR;
143 }
144
145 SDL_FreeSurface(imageSDLSurface);
146
147 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
148 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
149 // I tried building sdl 2.0.10 (and sdl_image and sdl_ttf) from source on Mac, but had some issues, so this is easier
150 // until the homebrew recipe is updated
151 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
152 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING,
153 gui->getWindowWidth(), gui->getWindowHeight());
154 } else {
155 uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,
156 gui->getWindowWidth(), gui->getWindowHeight());
157 }
158
159 if (uiOverlay == nullptr) {
160 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
161 return RTWO_ERROR;
162 }
163 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
164 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
165 return RTWO_ERROR;
166 }
167
168 return RTWO_SUCCESS;
169}
170
171void VulkanGame::initVulkan() {
172 const vector<const char*> validationLayers = {
173 "VK_LAYER_KHRONOS_validation"
174 };
175 const vector<const char*> deviceExtensions = {
176 VK_KHR_SWAPCHAIN_EXTENSION_NAME
177 };
178
179 createVulkanInstance(validationLayers);
180 setupDebugMessenger();
181 createVulkanSurface();
182 pickPhysicalDevice(deviceExtensions);
183 createLogicalDevice(validationLayers, deviceExtensions);
184 createSwapChain();
185 createImageViews();
186 createRenderPass();
187 createCommandPool();
188
189 createImageResources();
190
191 createFramebuffers();
192 createUniformBuffers();
193
194 vector<Vertex> sceneVertices = {
195 {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
196 {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
197 {{ 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
198 {{-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
199
200 {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
201 {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
202 {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
203 {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
204 };
205 vector<uint16_t> sceneIndices = {
206 0, 1, 2, 2, 3, 0,
207 4, 5, 6, 6, 7, 4
208 };
209
210 graphicsPipelines.push_back(GraphicsPipeline_Vulkan(physicalDevice, device, renderPass,
211 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(Vertex)));
212
213 graphicsPipelines.back().bindData(sceneVertices, sceneIndices, commandPool, graphicsQueue);
214
215 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
216 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
217 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
218
219 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
220 VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
221 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
222 VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
223
224 graphicsPipelines.back().createDescriptorSetLayout();
225 graphicsPipelines.back().createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
226 graphicsPipelines.back().createDescriptorPool(swapChainImages);
227 graphicsPipelines.back().createDescriptorSets(swapChainImages);
228
229 vector<OverlayVertex> overlayVertices = {
230 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
231 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
232 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
233 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
234 };
235 vector<uint16_t> overlayIndices = {
236 0, 1, 2, 2, 3, 0
237 };
238
239 graphicsPipelines.push_back(GraphicsPipeline_Vulkan(physicalDevice, device, renderPass,
240 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(OverlayVertex)));
241
242 graphicsPipelines.back().bindData(overlayVertices, overlayIndices, commandPool, graphicsQueue);
243
244 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
245 graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
246
247 graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
248 VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
249
250 graphicsPipelines.back().createDescriptorSetLayout();
251 graphicsPipelines.back().createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
252 graphicsPipelines.back().createDescriptorPool(swapChainImages);
253 graphicsPipelines.back().createDescriptorSets(swapChainImages);
254
255 // TODO: Creating the descriptor pool and descriptor sets might need to be redone when the
256 // swap chain is recreated
257
258 cout << "Created " << graphicsPipelines.size() << " graphics pipelines" << endl;
259
260 createCommandBuffers();
261
262 createSyncObjects();
263}
264
265void VulkanGame::mainLoop() {
266 UIEvent e;
267 bool quit = false;
268
269 while (!quit) {
270 gui->processEvents();
271
272 while (gui->pollEvent(&e)) {
273 switch(e.type) {
274 case UI_EVENT_QUIT:
275 cout << "Quit event detected" << endl;
276 quit = true;
277 break;
278 case UI_EVENT_WINDOW:
279 cout << "Window event detected" << endl;
280 // Currently unused
281 break;
282 case UI_EVENT_WINDOWRESIZE:
283 cout << "Window resize event detected" << endl;
284 framebufferResized = true;
285 break;
286 case UI_EVENT_KEY:
287 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
288 quit = true;
289 } else {
290 cout << "Key event detected" << endl;
291 }
292 break;
293 case UI_EVENT_MOUSEBUTTONDOWN:
294 cout << "Mouse button down event detected" << endl;
295 break;
296 case UI_EVENT_MOUSEBUTTONUP:
297 cout << "Mouse button up event detected" << endl;
298 break;
299 case UI_EVENT_MOUSEMOTION:
300 break;
301 case UI_EVENT_UNKNOWN:
302 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
303 break;
304 default:
305 cout << "Unhandled UI event: " << e.type << endl;
306 }
307 }
308
309 renderUI();
310 renderScene();
311 }
312
313 vkDeviceWaitIdle(device);
314}
315
316void VulkanGame::renderUI() {
317 // TODO: Since I currently don't use any other render targets,
318 // I may as well set this once before the render loop
319 SDL_SetRenderTarget(renderer, uiOverlay);
320
321 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
322 SDL_RenderClear(renderer);
323
324 SDL_Rect rect = {280, 220, 100, 100};
325 SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
326 SDL_RenderFillRect(renderer, &rect);
327
328 rect = {10, 10, 0, 0};
329 SDL_QueryTexture(fontSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
330 SDL_RenderCopy(renderer, fontSDLTexture, nullptr, &rect);
331
332 rect = {10, 80, 0, 0};
333 SDL_QueryTexture(imageSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
334 SDL_RenderCopy(renderer, imageSDLTexture, nullptr, &rect);
335
336 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
337 SDL_RenderDrawLine(renderer, 50, 5, 150, 500);
338
339 VulkanUtils::populateVulkanImageFromSDLTexture(device, physicalDevice, commandPool, uiOverlay, renderer,
340 sdlOverlayImage, graphicsQueue);
341}
342
343void VulkanGame::renderScene() {
344 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
345
346 uint32_t imageIndex;
347
348 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
349 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
350
351 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
352 recreateSwapChain();
353 return;
354 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
355 throw runtime_error("failed to acquire swap chain image!");
356 }
357
358 updateUniformBuffer(imageIndex);
359
360 VkSubmitInfo submitInfo = {};
361 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
362
363 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
364 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
365
366 submitInfo.waitSemaphoreCount = 1;
367 submitInfo.pWaitSemaphores = waitSemaphores;
368 submitInfo.pWaitDstStageMask = waitStages;
369 submitInfo.commandBufferCount = 1;
370 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
371
372 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
373
374 submitInfo.signalSemaphoreCount = 1;
375 submitInfo.pSignalSemaphores = signalSemaphores;
376
377 vkResetFences(device, 1, &inFlightFences[currentFrame]);
378
379 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
380 throw runtime_error("failed to submit draw command buffer!");
381 }
382
383 VkPresentInfoKHR presentInfo = {};
384 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
385 presentInfo.waitSemaphoreCount = 1;
386 presentInfo.pWaitSemaphores = signalSemaphores;
387
388 VkSwapchainKHR swapChains[] = { swapChain };
389 presentInfo.swapchainCount = 1;
390 presentInfo.pSwapchains = swapChains;
391 presentInfo.pImageIndices = &imageIndex;
392 presentInfo.pResults = nullptr;
393
394 result = vkQueuePresentKHR(presentQueue, &presentInfo);
395
396 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
397 framebufferResized = false;
398 recreateSwapChain();
399 } else if (result != VK_SUCCESS) {
400 throw runtime_error("failed to present swap chain image!");
401 }
402
403 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
404 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
405}
406
407void VulkanGame::cleanup() {
408 cleanupSwapChain();
409
410 VulkanUtils::destroyVulkanImage(device, floorTextureImage);
411 VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
412
413 vkDestroySampler(device, textureSampler, nullptr);
414
415 for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
416 pipeline.cleanupBuffers();
417 }
418
419 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
420 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
421 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
422 vkDestroyFence(device, inFlightFences[i], nullptr);
423 }
424
425 vkDestroyCommandPool(device, commandPool, nullptr);
426 vkDestroyDevice(device, nullptr);
427 vkDestroySurfaceKHR(instance, surface, nullptr);
428
429 if (ENABLE_VALIDATION_LAYERS) {
430 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
431 }
432
433 vkDestroyInstance(instance, nullptr);
434
435 // TODO: Check if any of these functions accept null parameters
436 // If they do, I don't need to check for that
437
438 if (uiOverlay != nullptr) {
439 SDL_DestroyTexture(uiOverlay);
440 uiOverlay = nullptr;
441 }
442
443 if (fontSDLTexture != nullptr) {
444 SDL_DestroyTexture(fontSDLTexture);
445 fontSDLTexture = nullptr;
446 }
447
448 if (imageSDLTexture != nullptr) {
449 SDL_DestroyTexture(imageSDLTexture);
450 imageSDLTexture = nullptr;
451 }
452
453 TTF_CloseFont(font);
454 font = nullptr;
455
456 SDL_DestroyRenderer(renderer);
457 renderer = nullptr;
458
459 gui->destroyWindow();
460 gui->shutdown();
461 delete gui;
462}
463
464void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
465 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
466 throw runtime_error("validation layers requested, but not available!");
467 }
468
469 VkApplicationInfo appInfo = {};
470 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
471 appInfo.pApplicationName = "Vulkan Game";
472 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
473 appInfo.pEngineName = "No Engine";
474 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
475 appInfo.apiVersion = VK_API_VERSION_1_0;
476
477 VkInstanceCreateInfo createInfo = {};
478 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
479 createInfo.pApplicationInfo = &appInfo;
480
481 vector<const char*> extensions = gui->getRequiredExtensions();
482 if (ENABLE_VALIDATION_LAYERS) {
483 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
484 }
485
486 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
487 createInfo.ppEnabledExtensionNames = extensions.data();
488
489 cout << endl << "Extensions:" << endl;
490 for (const char* extensionName : extensions) {
491 cout << extensionName << endl;
492 }
493 cout << endl;
494
495 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
496 if (ENABLE_VALIDATION_LAYERS) {
497 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
498 createInfo.ppEnabledLayerNames = validationLayers.data();
499
500 populateDebugMessengerCreateInfo(debugCreateInfo);
501 createInfo.pNext = &debugCreateInfo;
502 } else {
503 createInfo.enabledLayerCount = 0;
504
505 createInfo.pNext = nullptr;
506 }
507
508 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
509 throw runtime_error("failed to create instance!");
510 }
511}
512
513void VulkanGame::setupDebugMessenger() {
514 if (!ENABLE_VALIDATION_LAYERS) return;
515
516 VkDebugUtilsMessengerCreateInfoEXT createInfo;
517 populateDebugMessengerCreateInfo(createInfo);
518
519 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
520 throw runtime_error("failed to set up debug messenger!");
521 }
522}
523
524void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
525 createInfo = {};
526 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
527 createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
528 createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
529 createInfo.pfnUserCallback = debugCallback;
530}
531
532VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
533 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
534 VkDebugUtilsMessageTypeFlagsEXT messageType,
535 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
536 void* pUserData) {
537 cerr << "validation layer: " << pCallbackData->pMessage << endl;
538
539 return VK_FALSE;
540}
541
542void VulkanGame::createVulkanSurface() {
543 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
544 throw runtime_error("failed to create window surface!");
545 }
546}
547
548void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
549 uint32_t deviceCount = 0;
550 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
551
552 if (deviceCount == 0) {
553 throw runtime_error("failed to find GPUs with Vulkan support!");
554 }
555
556 vector<VkPhysicalDevice> devices(deviceCount);
557 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
558
559 cout << endl << "Graphics cards:" << endl;
560 for (const VkPhysicalDevice& device : devices) {
561 if (isDeviceSuitable(device, deviceExtensions)) {
562 physicalDevice = device;
563 break;
564 }
565 }
566 cout << endl;
567
568 if (physicalDevice == VK_NULL_HANDLE) {
569 throw runtime_error("failed to find a suitable GPU!");
570 }
571}
572
573bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
574 const vector<const char*>& deviceExtensions) {
575 VkPhysicalDeviceProperties deviceProperties;
576 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
577
578 cout << "Device: " << deviceProperties.deviceName << endl;
579
580 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
581 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
582 bool swapChainAdequate = false;
583
584 if (extensionsSupported) {
585 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
586 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
587 }
588
589 VkPhysicalDeviceFeatures supportedFeatures;
590 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
591
592 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
593}
594
595void VulkanGame::createLogicalDevice(
596 const vector<const char*> validationLayers,
597 const vector<const char*>& deviceExtensions) {
598 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
599
600 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
601 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
602
603 float queuePriority = 1.0f;
604 for (uint32_t queueFamily : uniqueQueueFamilies) {
605 VkDeviceQueueCreateInfo queueCreateInfo = {};
606 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
607 queueCreateInfo.queueFamilyIndex = queueFamily;
608 queueCreateInfo.queueCount = 1;
609 queueCreateInfo.pQueuePriorities = &queuePriority;
610
611 queueCreateInfoList.push_back(queueCreateInfo);
612 }
613
614 VkPhysicalDeviceFeatures deviceFeatures = {};
615 deviceFeatures.samplerAnisotropy = VK_TRUE;
616
617 VkDeviceCreateInfo createInfo = {};
618 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
619 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
620 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
621
622 createInfo.pEnabledFeatures = &deviceFeatures;
623
624 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
625 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
626
627 // These fields are ignored by up-to-date Vulkan implementations,
628 // but it's a good idea to set them for backwards compatibility
629 if (ENABLE_VALIDATION_LAYERS) {
630 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
631 createInfo.ppEnabledLayerNames = validationLayers.data();
632 } else {
633 createInfo.enabledLayerCount = 0;
634 }
635
636 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
637 throw runtime_error("failed to create logical device!");
638 }
639
640 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
641 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
642}
643
644void VulkanGame::createSwapChain() {
645 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
646
647 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
648 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
649 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
650
651 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
652 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
653 imageCount = swapChainSupport.capabilities.maxImageCount;
654 }
655
656 VkSwapchainCreateInfoKHR createInfo = {};
657 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
658 createInfo.surface = surface;
659 createInfo.minImageCount = imageCount;
660 createInfo.imageFormat = surfaceFormat.format;
661 createInfo.imageColorSpace = surfaceFormat.colorSpace;
662 createInfo.imageExtent = extent;
663 createInfo.imageArrayLayers = 1;
664 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
665
666 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
667 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
668
669 if (indices.graphicsFamily != indices.presentFamily) {
670 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
671 createInfo.queueFamilyIndexCount = 2;
672 createInfo.pQueueFamilyIndices = queueFamilyIndices;
673 } else {
674 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
675 createInfo.queueFamilyIndexCount = 0;
676 createInfo.pQueueFamilyIndices = nullptr;
677 }
678
679 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
680 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
681 createInfo.presentMode = presentMode;
682 createInfo.clipped = VK_TRUE;
683 createInfo.oldSwapchain = VK_NULL_HANDLE;
684
685 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
686 throw runtime_error("failed to create swap chain!");
687 }
688
689 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
690 swapChainImages.resize(imageCount);
691 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
692
693 swapChainImageFormat = surfaceFormat.format;
694 swapChainExtent = extent;
695}
696
697void VulkanGame::createImageViews() {
698 swapChainImageViews.resize(swapChainImages.size());
699
700 for (size_t i = 0; i < swapChainImages.size(); i++) {
701 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
702 VK_IMAGE_ASPECT_COLOR_BIT);
703 }
704}
705
706void VulkanGame::createRenderPass() {
707 VkAttachmentDescription colorAttachment = {};
708 colorAttachment.format = swapChainImageFormat;
709 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
710 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
711 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
712 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
713 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
714 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
715 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
716
717 VkAttachmentReference colorAttachmentRef = {};
718 colorAttachmentRef.attachment = 0;
719 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
720
721 VkAttachmentDescription depthAttachment = {};
722 depthAttachment.format = findDepthFormat();
723 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
724 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
725 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
726 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
727 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
728 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
729 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
730
731 VkAttachmentReference depthAttachmentRef = {};
732 depthAttachmentRef.attachment = 1;
733 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
734
735 VkSubpassDescription subpass = {};
736 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
737 subpass.colorAttachmentCount = 1;
738 subpass.pColorAttachments = &colorAttachmentRef;
739 subpass.pDepthStencilAttachment = &depthAttachmentRef;
740
741 VkSubpassDependency dependency = {};
742 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
743 dependency.dstSubpass = 0;
744 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
745 dependency.srcAccessMask = 0;
746 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
747 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
748
749 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
750 VkRenderPassCreateInfo renderPassInfo = {};
751 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
752 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
753 renderPassInfo.pAttachments = attachments.data();
754 renderPassInfo.subpassCount = 1;
755 renderPassInfo.pSubpasses = &subpass;
756 renderPassInfo.dependencyCount = 1;
757 renderPassInfo.pDependencies = &dependency;
758
759 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
760 throw runtime_error("failed to create render pass!");
761 }
762}
763
764VkFormat VulkanGame::findDepthFormat() {
765 return VulkanUtils::findSupportedFormat(
766 physicalDevice,
767 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
768 VK_IMAGE_TILING_OPTIMAL,
769 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
770 );
771}
772
773void VulkanGame::createCommandPool() {
774 QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
775
776 VkCommandPoolCreateInfo poolInfo = {};
777 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
778 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
779 poolInfo.flags = 0;
780
781 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
782 throw runtime_error("failed to create graphics command pool!");
783 }
784}
785
786void VulkanGame::createImageResources() {
787 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
788 depthImage, graphicsQueue);
789
790 createTextureSampler();
791
792 VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
793 floorTextureImage, graphicsQueue);
794
795 floorTextureImageDescriptor = {};
796 floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
797 floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
798 floorTextureImageDescriptor.sampler = textureSampler;
799
800 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
801
802 sdlOverlayImageDescriptor = {};
803 sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
804 sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
805 sdlOverlayImageDescriptor.sampler = textureSampler;
806}
807
808void VulkanGame::createTextureSampler() {
809 VkSamplerCreateInfo samplerInfo = {};
810 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
811 samplerInfo.magFilter = VK_FILTER_LINEAR;
812 samplerInfo.minFilter = VK_FILTER_LINEAR;
813
814 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
815 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
816 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
817
818 samplerInfo.anisotropyEnable = VK_TRUE;
819 samplerInfo.maxAnisotropy = 16;
820 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
821 samplerInfo.unnormalizedCoordinates = VK_FALSE;
822 samplerInfo.compareEnable = VK_FALSE;
823 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
824 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
825 samplerInfo.mipLodBias = 0.0f;
826 samplerInfo.minLod = 0.0f;
827 samplerInfo.maxLod = 0.0f;
828
829 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
830 throw runtime_error("failed to create texture sampler!");
831 }
832}
833
834void VulkanGame::createFramebuffers() {
835 swapChainFramebuffers.resize(swapChainImageViews.size());
836
837 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
838 array<VkImageView, 2> attachments = {
839 swapChainImageViews[i],
840 depthImage.imageView
841 };
842
843 VkFramebufferCreateInfo framebufferInfo = {};
844 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
845 framebufferInfo.renderPass = renderPass;
846 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
847 framebufferInfo.pAttachments = attachments.data();
848 framebufferInfo.width = swapChainExtent.width;
849 framebufferInfo.height = swapChainExtent.height;
850 framebufferInfo.layers = 1;
851
852 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
853 throw runtime_error("failed to create framebuffer!");
854 }
855 }
856}
857
858void VulkanGame::createUniformBuffers() {
859 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
860
861 uniformBuffers.resize(swapChainImages.size());
862 uniformBuffersMemory.resize(swapChainImages.size());
863 uniformBufferInfoList.resize(swapChainImages.size());
864
865 for (size_t i = 0; i < swapChainImages.size(); i++) {
866 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
867 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
868 uniformBuffers[i], uniformBuffersMemory[i]);
869
870 uniformBufferInfoList[i].buffer = uniformBuffers[i];
871 uniformBufferInfoList[i].offset = 0;
872 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
873 }
874}
875
876void VulkanGame::createCommandBuffers() {
877 commandBuffers.resize(swapChainImages.size());
878
879 VkCommandBufferAllocateInfo allocInfo = {};
880 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
881 allocInfo.commandPool = commandPool;
882 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
883 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
884
885 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
886 throw runtime_error("failed to allocate command buffers!");
887 }
888
889 for (size_t i = 0; i < commandBuffers.size(); i++) {
890 VkCommandBufferBeginInfo beginInfo = {};
891 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
892 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
893 beginInfo.pInheritanceInfo = nullptr;
894
895 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
896 throw runtime_error("failed to begin recording command buffer!");
897 }
898
899 VkRenderPassBeginInfo renderPassInfo = {};
900 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
901 renderPassInfo.renderPass = renderPass;
902 renderPassInfo.framebuffer = swapChainFramebuffers[i];
903 renderPassInfo.renderArea.offset = { 0, 0 };
904 renderPassInfo.renderArea.extent = swapChainExtent;
905
906 array<VkClearValue, 2> clearValues = {};
907 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
908 clearValues[1].depthStencil = { 1.0f, 0 };
909
910 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
911 renderPassInfo.pClearValues = clearValues.data();
912
913 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
914
915 for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
916 pipeline.createRenderCommands(commandBuffers[i], i);
917 }
918
919 vkCmdEndRenderPass(commandBuffers[i]);
920
921 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
922 throw runtime_error("failed to record command buffer!");
923 }
924 }
925}
926
927void VulkanGame::createSyncObjects() {
928 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
929 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
930 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
931
932 VkSemaphoreCreateInfo semaphoreInfo = {};
933 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
934
935 VkFenceCreateInfo fenceInfo = {};
936 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
937 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
938
939 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
940 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
941 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
942 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
943 throw runtime_error("failed to create synchronization objects for a frame!");
944 }
945 }
946}
947
948void VulkanGame::recreateSwapChain() {
949 cout << "Recreating swap chain" << endl;
950 gui->refreshWindowSize();
951
952 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
953 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
954 SDL_WaitEvent(nullptr);
955 gui->refreshWindowSize();
956 }
957
958 vkDeviceWaitIdle(device);
959
960 //cleanupSwapChain();
961}
962
963void VulkanGame::updateUniformBuffer(uint32_t currentImage) {
964 static auto startTime = chrono::high_resolution_clock::now();
965
966 auto currentTime = chrono::high_resolution_clock::now();
967 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
968
969 UniformBufferObject ubo = {};
970 ubo.model = rotate(mat4(1.0f), time * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
971 ubo.view = lookAt(vec3(0.0f, 2.0f, 2.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
972 ubo.proj = perspective(radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
973 ubo.proj[1][1] *= -1; // flip the y-axis so that +y is up
974
975 void* data;
976 vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
977 memcpy(data, &ubo, sizeof(ubo));
978 vkUnmapMemory(device, uniformBuffersMemory[currentImage]);
979}
980
981void VulkanGame::cleanupSwapChain() {
982 VulkanUtils::destroyVulkanImage(device, depthImage);
983
984 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
985 vkDestroyFramebuffer(device, framebuffer, nullptr);
986 }
987
988 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
989
990 for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
991 pipeline.cleanup();
992 }
993
994 vkDestroyRenderPass(device, renderPass, nullptr);
995
996 for (VkImageView imageView : swapChainImageViews) {
997 vkDestroyImageView(device, imageView, nullptr);
998 }
999
1000 vkDestroySwapchainKHR(device, swapChain, nullptr);
1001
1002 for (size_t i = 0; i < uniformBuffers.size(); i++) {
1003 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
1004 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
1005 }
1006}
Note: See TracBrowser for help on using the repository browser.