source: opengl-game/vulkan-game.cpp@ 5ab1b20

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

Make VulkanGame use the same projection matrix as the original OpenGL game

  • Property mode set to 100644
File size: 38.5 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 init 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 SDL_SetRenderTarget(renderer, uiOverlay);
169
170 return RTWO_SUCCESS;
171}
172
173void VulkanGame::initVulkan() {
174 const vector<const char*> validationLayers = {
175 "VK_LAYER_KHRONOS_validation"
176 };
177 const vector<const char*> deviceExtensions = {
178 VK_KHR_SWAPCHAIN_EXTENSION_NAME
179 };
180
181 createVulkanInstance(validationLayers);
182 setupDebugMessenger();
183 createVulkanSurface();
184 pickPhysicalDevice(deviceExtensions);
185 createLogicalDevice(validationLayers, deviceExtensions);
186 createSwapChain();
187 createImageViews();
188 createRenderPass();
189 createCommandPool();
190
191 createImageResources();
192
193 createFramebuffers();
194 createUniformBuffers();
195
196 modelPipeline = GraphicsPipeline_Vulkan<ModelVertex>(physicalDevice, device, renderPass,
197 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 16, 24);
198
199 modelPipeline.addObject({
200 {{-0.5f, -0.5f, -2.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
201 {{ 0.5f, -0.5f, -2.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
202 {{ 0.5f, 0.5f, -2.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
203 {{-0.5f, 0.5f, -2.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
204 }, {
205 0, 1, 2, 2, 3, 0
206 }, commandPool, graphicsQueue);
207
208 modelPipeline.addObject({
209 {{-0.5f, -0.5f, -1.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
210 {{ 0.5f, -0.5f, -1.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
211 {{ 0.5f, 0.5f, -1.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
212 {{-0.5f, 0.5f, -1.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
213 }, {
214 0, 1, 2, 2, 3, 0
215 }, commandPool, graphicsQueue);
216
217 modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::pos));
218 modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::color));
219 modelPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&ModelVertex::texCoord));
220
221 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
222 VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
223 modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
224 VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
225
226 modelPipeline.createDescriptorSetLayout();
227 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
228 modelPipeline.createDescriptorPool(swapChainImages);
229 modelPipeline.createDescriptorSets(swapChainImages);
230
231 overlayPipeline = GraphicsPipeline_Vulkan<OverlayVertex>(physicalDevice, device, renderPass,
232 { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 4, 6);
233
234 overlayPipeline.addObject({
235 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
236 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
237 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
238 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
239 }, {
240 0, 1, 2, 2, 3, 0
241 }, commandPool, graphicsQueue);
242
243 overlayPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
244 overlayPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
245
246 overlayPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
247 VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
248
249 overlayPipeline.createDescriptorSetLayout();
250 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
251 overlayPipeline.createDescriptorPool(swapChainImages);
252 overlayPipeline.createDescriptorSets(swapChainImages);
253
254 cout << "Created all the graphics pipelines" << endl;
255
256 numPlanes = 2;
257
258 createCommandBuffers();
259
260 createSyncObjects();
261}
262
263void VulkanGame::mainLoop() {
264 UIEvent e;
265 bool quit = false;
266
267 while (!quit) {
268 gui->processEvents();
269
270 while (gui->pollEvent(&e)) {
271 switch(e.type) {
272 case UI_EVENT_QUIT:
273 cout << "Quit event detected" << endl;
274 quit = true;
275 break;
276 case UI_EVENT_WINDOW:
277 cout << "Window event detected" << endl;
278 // Currently unused
279 break;
280 case UI_EVENT_WINDOWRESIZE:
281 cout << "Window resize event detected" << endl;
282 framebufferResized = true;
283 break;
284 case UI_EVENT_KEYDOWN:
285 if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
286 quit = true;
287 } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
288 cout << "Adding a plane" << endl;
289 float zOffset = -2.0f + (0.5f * numPlanes);
290
291 vkDeviceWaitIdle(device);
292 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
293
294 modelPipeline.addObject({
295 {{-0.5f, -0.5f, zOffset}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
296 {{ 0.5f, -0.5f, zOffset}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
297 {{ 0.5f, 0.5f, zOffset}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
298 {{-0.5f, 0.5f, zOffset}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
299 }, {
300 0, 1, 2, 2, 3, 0
301 }, commandPool, graphicsQueue);
302
303 createCommandBuffers();
304
305 numPlanes++;
306 } else {
307 cout << "Key event detected" << endl;
308 }
309 break;
310 case UI_EVENT_KEYUP:
311 break;
312 case UI_EVENT_MOUSEBUTTONDOWN:
313 cout << "Mouse button down event detected" << endl;
314 break;
315 case UI_EVENT_MOUSEBUTTONUP:
316 cout << "Mouse button up event detected" << endl;
317 break;
318 case UI_EVENT_MOUSEMOTION:
319 break;
320 case UI_EVENT_UNKNOWN:
321 cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
322 break;
323 default:
324 cout << "Unhandled UI event: " << e.type << endl;
325 }
326 }
327
328 renderUI();
329 renderScene();
330 }
331
332 vkDeviceWaitIdle(device);
333}
334
335void VulkanGame::renderUI() {
336 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
337 SDL_RenderClear(renderer);
338
339 SDL_Rect rect = {280, 220, 100, 100};
340 SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
341 SDL_RenderFillRect(renderer, &rect);
342
343 rect = {10, 10, 0, 0};
344 SDL_QueryTexture(fontSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
345 SDL_RenderCopy(renderer, fontSDLTexture, nullptr, &rect);
346
347 rect = {10, 80, 0, 0};
348 SDL_QueryTexture(imageSDLTexture, nullptr, nullptr, &(rect.w), &(rect.h));
349 SDL_RenderCopy(renderer, imageSDLTexture, nullptr, &rect);
350
351 SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
352 SDL_RenderDrawLine(renderer, 50, 5, 150, 500);
353
354 VulkanUtils::populateVulkanImageFromSDLTexture(device, physicalDevice, commandPool, uiOverlay, renderer,
355 sdlOverlayImage, graphicsQueue);
356}
357
358void VulkanGame::renderScene() {
359 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
360
361 uint32_t imageIndex;
362
363 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
364 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
365
366 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
367 recreateSwapChain();
368 return;
369 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
370 throw runtime_error("failed to acquire swap chain image!");
371 }
372
373 updateUniformBuffer(imageIndex);
374
375 VkSubmitInfo submitInfo = {};
376 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
377
378 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
379 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
380
381 submitInfo.waitSemaphoreCount = 1;
382 submitInfo.pWaitSemaphores = waitSemaphores;
383 submitInfo.pWaitDstStageMask = waitStages;
384 submitInfo.commandBufferCount = 1;
385 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
386
387 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
388
389 submitInfo.signalSemaphoreCount = 1;
390 submitInfo.pSignalSemaphores = signalSemaphores;
391
392 vkResetFences(device, 1, &inFlightFences[currentFrame]);
393
394 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
395 throw runtime_error("failed to submit draw command buffer!");
396 }
397
398 VkPresentInfoKHR presentInfo = {};
399 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
400 presentInfo.waitSemaphoreCount = 1;
401 presentInfo.pWaitSemaphores = signalSemaphores;
402
403 VkSwapchainKHR swapChains[] = { swapChain };
404 presentInfo.swapchainCount = 1;
405 presentInfo.pSwapchains = swapChains;
406 presentInfo.pImageIndices = &imageIndex;
407 presentInfo.pResults = nullptr;
408
409 result = vkQueuePresentKHR(presentQueue, &presentInfo);
410
411 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
412 framebufferResized = false;
413 recreateSwapChain();
414 } else if (result != VK_SUCCESS) {
415 throw runtime_error("failed to present swap chain image!");
416 }
417
418 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
419 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
420}
421
422void VulkanGame::cleanup() {
423 cleanupSwapChain();
424
425 VulkanUtils::destroyVulkanImage(device, floorTextureImage);
426 VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
427
428 vkDestroySampler(device, textureSampler, nullptr);
429
430 modelPipeline.cleanupBuffers();
431 overlayPipeline.cleanupBuffers();
432
433 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
434 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
435 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
436 vkDestroyFence(device, inFlightFences[i], nullptr);
437 }
438
439 vkDestroyCommandPool(device, commandPool, nullptr);
440 vkDestroyDevice(device, nullptr);
441 vkDestroySurfaceKHR(instance, surface, nullptr);
442
443 if (ENABLE_VALIDATION_LAYERS) {
444 VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
445 }
446
447 vkDestroyInstance(instance, nullptr);
448
449 // TODO: Check if any of these functions accept null parameters
450 // If they do, I don't need to check for that
451
452 if (uiOverlay != nullptr) {
453 SDL_DestroyTexture(uiOverlay);
454 uiOverlay = nullptr;
455 }
456
457 if (fontSDLTexture != nullptr) {
458 SDL_DestroyTexture(fontSDLTexture);
459 fontSDLTexture = nullptr;
460 }
461
462 if (imageSDLTexture != nullptr) {
463 SDL_DestroyTexture(imageSDLTexture);
464 imageSDLTexture = nullptr;
465 }
466
467 TTF_CloseFont(font);
468 font = nullptr;
469
470 SDL_DestroyRenderer(renderer);
471 renderer = nullptr;
472
473 gui->destroyWindow();
474 gui->shutdown();
475 delete gui;
476}
477
478void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
479 if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
480 throw runtime_error("validation layers requested, but not available!");
481 }
482
483 VkApplicationInfo appInfo = {};
484 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
485 appInfo.pApplicationName = "Vulkan Game";
486 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
487 appInfo.pEngineName = "No Engine";
488 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
489 appInfo.apiVersion = VK_API_VERSION_1_0;
490
491 VkInstanceCreateInfo createInfo = {};
492 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
493 createInfo.pApplicationInfo = &appInfo;
494
495 vector<const char*> extensions = gui->getRequiredExtensions();
496 if (ENABLE_VALIDATION_LAYERS) {
497 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
498 }
499
500 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
501 createInfo.ppEnabledExtensionNames = extensions.data();
502
503 cout << endl << "Extensions:" << endl;
504 for (const char* extensionName : extensions) {
505 cout << extensionName << endl;
506 }
507 cout << endl;
508
509 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
510 if (ENABLE_VALIDATION_LAYERS) {
511 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
512 createInfo.ppEnabledLayerNames = validationLayers.data();
513
514 populateDebugMessengerCreateInfo(debugCreateInfo);
515 createInfo.pNext = &debugCreateInfo;
516 } else {
517 createInfo.enabledLayerCount = 0;
518
519 createInfo.pNext = nullptr;
520 }
521
522 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
523 throw runtime_error("failed to create instance!");
524 }
525}
526
527void VulkanGame::setupDebugMessenger() {
528 if (!ENABLE_VALIDATION_LAYERS) return;
529
530 VkDebugUtilsMessengerCreateInfoEXT createInfo;
531 populateDebugMessengerCreateInfo(createInfo);
532
533 if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
534 throw runtime_error("failed to set up debug messenger!");
535 }
536}
537
538void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
539 createInfo = {};
540 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
541 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;
542 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;
543 createInfo.pfnUserCallback = debugCallback;
544}
545
546VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
547 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
548 VkDebugUtilsMessageTypeFlagsEXT messageType,
549 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
550 void* pUserData) {
551 cerr << "validation layer: " << pCallbackData->pMessage << endl;
552
553 return VK_FALSE;
554}
555
556void VulkanGame::createVulkanSurface() {
557 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
558 throw runtime_error("failed to create window surface!");
559 }
560}
561
562void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
563 uint32_t deviceCount = 0;
564 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
565
566 if (deviceCount == 0) {
567 throw runtime_error("failed to find GPUs with Vulkan support!");
568 }
569
570 vector<VkPhysicalDevice> devices(deviceCount);
571 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
572
573 cout << endl << "Graphics cards:" << endl;
574 for (const VkPhysicalDevice& device : devices) {
575 if (isDeviceSuitable(device, deviceExtensions)) {
576 physicalDevice = device;
577 break;
578 }
579 }
580 cout << endl;
581
582 if (physicalDevice == VK_NULL_HANDLE) {
583 throw runtime_error("failed to find a suitable GPU!");
584 }
585}
586
587bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
588 const vector<const char*>& deviceExtensions) {
589 VkPhysicalDeviceProperties deviceProperties;
590 vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
591
592 cout << "Device: " << deviceProperties.deviceName << endl;
593
594 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
595 bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
596 bool swapChainAdequate = false;
597
598 if (extensionsSupported) {
599 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
600 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
601 }
602
603 VkPhysicalDeviceFeatures supportedFeatures;
604 vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
605
606 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
607}
608
609void VulkanGame::createLogicalDevice(
610 const vector<const char*> validationLayers,
611 const vector<const char*>& deviceExtensions) {
612 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
613
614 vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
615 set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
616
617 float queuePriority = 1.0f;
618 for (uint32_t queueFamily : uniqueQueueFamilies) {
619 VkDeviceQueueCreateInfo queueCreateInfo = {};
620 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
621 queueCreateInfo.queueFamilyIndex = queueFamily;
622 queueCreateInfo.queueCount = 1;
623 queueCreateInfo.pQueuePriorities = &queuePriority;
624
625 queueCreateInfoList.push_back(queueCreateInfo);
626 }
627
628 VkPhysicalDeviceFeatures deviceFeatures = {};
629 deviceFeatures.samplerAnisotropy = VK_TRUE;
630
631 VkDeviceCreateInfo createInfo = {};
632 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
633 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
634 createInfo.pQueueCreateInfos = queueCreateInfoList.data();
635
636 createInfo.pEnabledFeatures = &deviceFeatures;
637
638 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
639 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
640
641 // These fields are ignored by up-to-date Vulkan implementations,
642 // but it's a good idea to set them for backwards compatibility
643 if (ENABLE_VALIDATION_LAYERS) {
644 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
645 createInfo.ppEnabledLayerNames = validationLayers.data();
646 } else {
647 createInfo.enabledLayerCount = 0;
648 }
649
650 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
651 throw runtime_error("failed to create logical device!");
652 }
653
654 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
655 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
656}
657
658void VulkanGame::createSwapChain() {
659 SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
660
661 VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
662 VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
663 VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
664
665 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
666 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
667 imageCount = swapChainSupport.capabilities.maxImageCount;
668 }
669
670 VkSwapchainCreateInfoKHR createInfo = {};
671 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
672 createInfo.surface = surface;
673 createInfo.minImageCount = imageCount;
674 createInfo.imageFormat = surfaceFormat.format;
675 createInfo.imageColorSpace = surfaceFormat.colorSpace;
676 createInfo.imageExtent = extent;
677 createInfo.imageArrayLayers = 1;
678 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
679
680 QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
681 uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
682
683 if (indices.graphicsFamily != indices.presentFamily) {
684 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
685 createInfo.queueFamilyIndexCount = 2;
686 createInfo.pQueueFamilyIndices = queueFamilyIndices;
687 } else {
688 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
689 createInfo.queueFamilyIndexCount = 0;
690 createInfo.pQueueFamilyIndices = nullptr;
691 }
692
693 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
694 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
695 createInfo.presentMode = presentMode;
696 createInfo.clipped = VK_TRUE;
697 createInfo.oldSwapchain = VK_NULL_HANDLE;
698
699 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
700 throw runtime_error("failed to create swap chain!");
701 }
702
703 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
704 swapChainImages.resize(imageCount);
705 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
706
707 swapChainImageFormat = surfaceFormat.format;
708 swapChainExtent = extent;
709}
710
711void VulkanGame::createImageViews() {
712 swapChainImageViews.resize(swapChainImages.size());
713
714 for (size_t i = 0; i < swapChainImages.size(); i++) {
715 swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
716 VK_IMAGE_ASPECT_COLOR_BIT);
717 }
718}
719
720void VulkanGame::createRenderPass() {
721 VkAttachmentDescription colorAttachment = {};
722 colorAttachment.format = swapChainImageFormat;
723 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
724 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
725 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
726 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
727 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
728 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
729 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
730
731 VkAttachmentReference colorAttachmentRef = {};
732 colorAttachmentRef.attachment = 0;
733 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
734
735 VkAttachmentDescription depthAttachment = {};
736 depthAttachment.format = findDepthFormat();
737 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
738 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
739 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
740 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
741 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
742 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
743 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
744
745 VkAttachmentReference depthAttachmentRef = {};
746 depthAttachmentRef.attachment = 1;
747 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
748
749 VkSubpassDescription subpass = {};
750 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
751 subpass.colorAttachmentCount = 1;
752 subpass.pColorAttachments = &colorAttachmentRef;
753 subpass.pDepthStencilAttachment = &depthAttachmentRef;
754
755 VkSubpassDependency dependency = {};
756 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
757 dependency.dstSubpass = 0;
758 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
759 dependency.srcAccessMask = 0;
760 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
761 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
762
763 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
764 VkRenderPassCreateInfo renderPassInfo = {};
765 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
766 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
767 renderPassInfo.pAttachments = attachments.data();
768 renderPassInfo.subpassCount = 1;
769 renderPassInfo.pSubpasses = &subpass;
770 renderPassInfo.dependencyCount = 1;
771 renderPassInfo.pDependencies = &dependency;
772
773 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
774 throw runtime_error("failed to create render pass!");
775 }
776}
777
778VkFormat VulkanGame::findDepthFormat() {
779 return VulkanUtils::findSupportedFormat(
780 physicalDevice,
781 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
782 VK_IMAGE_TILING_OPTIMAL,
783 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
784 );
785}
786
787void VulkanGame::createCommandPool() {
788 QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
789
790 VkCommandPoolCreateInfo poolInfo = {};
791 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
792 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
793 poolInfo.flags = 0;
794
795 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
796 throw runtime_error("failed to create graphics command pool!");
797 }
798}
799
800void VulkanGame::createImageResources() {
801 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
802 depthImage, graphicsQueue);
803
804 createTextureSampler();
805
806 VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
807 floorTextureImage, graphicsQueue);
808
809 floorTextureImageDescriptor = {};
810 floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
811 floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
812 floorTextureImageDescriptor.sampler = textureSampler;
813
814 VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
815
816 sdlOverlayImageDescriptor = {};
817 sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
818 sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
819 sdlOverlayImageDescriptor.sampler = textureSampler;
820}
821
822void VulkanGame::createTextureSampler() {
823 VkSamplerCreateInfo samplerInfo = {};
824 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
825 samplerInfo.magFilter = VK_FILTER_LINEAR;
826 samplerInfo.minFilter = VK_FILTER_LINEAR;
827
828 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
829 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
830 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
831
832 samplerInfo.anisotropyEnable = VK_TRUE;
833 samplerInfo.maxAnisotropy = 16;
834 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
835 samplerInfo.unnormalizedCoordinates = VK_FALSE;
836 samplerInfo.compareEnable = VK_FALSE;
837 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
838 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
839 samplerInfo.mipLodBias = 0.0f;
840 samplerInfo.minLod = 0.0f;
841 samplerInfo.maxLod = 0.0f;
842
843 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
844 throw runtime_error("failed to create texture sampler!");
845 }
846}
847
848void VulkanGame::createFramebuffers() {
849 swapChainFramebuffers.resize(swapChainImageViews.size());
850
851 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
852 array<VkImageView, 2> attachments = {
853 swapChainImageViews[i],
854 depthImage.imageView
855 };
856
857 VkFramebufferCreateInfo framebufferInfo = {};
858 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
859 framebufferInfo.renderPass = renderPass;
860 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
861 framebufferInfo.pAttachments = attachments.data();
862 framebufferInfo.width = swapChainExtent.width;
863 framebufferInfo.height = swapChainExtent.height;
864 framebufferInfo.layers = 1;
865
866 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
867 throw runtime_error("failed to create framebuffer!");
868 }
869 }
870}
871
872void VulkanGame::createUniformBuffers() {
873 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
874
875 uniformBuffers.resize(swapChainImages.size());
876 uniformBuffersMemory.resize(swapChainImages.size());
877 uniformBufferInfoList.resize(swapChainImages.size());
878
879 for (size_t i = 0; i < swapChainImages.size(); i++) {
880 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
881 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
882 uniformBuffers[i], uniformBuffersMemory[i]);
883
884 uniformBufferInfoList[i].buffer = uniformBuffers[i];
885 uniformBufferInfoList[i].offset = 0;
886 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
887 }
888}
889
890void VulkanGame::createCommandBuffers() {
891 commandBuffers.resize(swapChainImages.size());
892
893 VkCommandBufferAllocateInfo allocInfo = {};
894 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
895 allocInfo.commandPool = commandPool;
896 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
897 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
898
899 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
900 throw runtime_error("failed to allocate command buffers!");
901 }
902
903 for (size_t i = 0; i < commandBuffers.size(); i++) {
904 VkCommandBufferBeginInfo beginInfo = {};
905 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
906 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
907 beginInfo.pInheritanceInfo = nullptr;
908
909 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
910 throw runtime_error("failed to begin recording command buffer!");
911 }
912
913 VkRenderPassBeginInfo renderPassInfo = {};
914 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
915 renderPassInfo.renderPass = renderPass;
916 renderPassInfo.framebuffer = swapChainFramebuffers[i];
917 renderPassInfo.renderArea.offset = { 0, 0 };
918 renderPassInfo.renderArea.extent = swapChainExtent;
919
920 array<VkClearValue, 2> clearValues = {};
921 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
922 clearValues[1].depthStencil = { 1.0f, 0 };
923
924 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
925 renderPassInfo.pClearValues = clearValues.data();
926
927 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
928
929 modelPipeline.createRenderCommands(commandBuffers[i], i);
930 overlayPipeline.createRenderCommands(commandBuffers[i], i);
931
932 vkCmdEndRenderPass(commandBuffers[i]);
933
934 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
935 throw runtime_error("failed to record command buffer!");
936 }
937 }
938}
939
940void VulkanGame::createSyncObjects() {
941 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
942 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
943 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
944
945 VkSemaphoreCreateInfo semaphoreInfo = {};
946 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
947
948 VkFenceCreateInfo fenceInfo = {};
949 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
950 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
951
952 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
953 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
954 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
955 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
956 throw runtime_error("failed to create synchronization objects for a frame!");
957 }
958 }
959}
960
961// TODO: Fix the crash that happens when alt-tabbing
962void VulkanGame::recreateSwapChain() {
963 cout << "Recreating swap chain" << endl;
964 gui->refreshWindowSize();
965
966 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
967 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
968 SDL_WaitEvent(nullptr);
969 gui->refreshWindowSize();
970 }
971
972 vkDeviceWaitIdle(device);
973
974 cleanupSwapChain();
975
976 createSwapChain();
977 createImageViews();
978 createRenderPass();
979
980 VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
981 depthImage, graphicsQueue);
982 createFramebuffers();
983 createUniformBuffers();
984
985 modelPipeline.updateRenderPass(renderPass);
986 modelPipeline.createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
987 modelPipeline.createDescriptorPool(swapChainImages);
988 modelPipeline.createDescriptorSets(swapChainImages);
989
990 overlayPipeline.updateRenderPass(renderPass);
991 overlayPipeline.createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
992 overlayPipeline.createDescriptorPool(swapChainImages);
993 overlayPipeline.createDescriptorSets(swapChainImages);
994
995 createCommandBuffers();
996}
997
998void VulkanGame::updateUniformBuffer(uint32_t currentImage) {
999 static auto startTime = chrono::high_resolution_clock::now();
1000
1001 auto currentTime = chrono::high_resolution_clock::now();
1002 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
1003
1004 UniformBufferObject ubo = {};
1005 ubo.model = rotate(mat4(1.0f), time * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
1006 ubo.view = lookAt(vec3(0.0f, 2.0f, 2.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
1007 ubo.proj = perspective(radians(FOV_ANGLE), (float)swapChainExtent.width / (float)swapChainExtent.height, NEAR_CLIP, FAR_CLIP);
1008 ubo.proj[1][1] *= -1; // flip the y-axis so that +y is up
1009
1010 void* data;
1011 vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
1012 memcpy(data, &ubo, sizeof(ubo));
1013 vkUnmapMemory(device, uniformBuffersMemory[currentImage]);
1014}
1015
1016void VulkanGame::cleanupSwapChain() {
1017 VulkanUtils::destroyVulkanImage(device, depthImage);
1018
1019 for (VkFramebuffer framebuffer : swapChainFramebuffers) {
1020 vkDestroyFramebuffer(device, framebuffer, nullptr);
1021 }
1022
1023 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
1024
1025 modelPipeline.cleanup();
1026 overlayPipeline.cleanup();
1027
1028 vkDestroyRenderPass(device, renderPass, nullptr);
1029
1030 for (VkImageView imageView : swapChainImageViews) {
1031 vkDestroyImageView(device, imageView, nullptr);
1032 }
1033
1034 vkDestroySwapchainKHR(device, swapChain, nullptr);
1035
1036 for (size_t i = 0; i < uniformBuffers.size(); i++) {
1037 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
1038 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
1039 }
1040}
Note: See TracBrowser for help on using the repository browser.