source: opengl-game/vulkan-game.cpp@ cd487fb

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

Replace some couts with runtime_exceptions and, in vulkangame, only call SDL_SetRenderTarget once, during initialization

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