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

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

Make vulkangame compile under Linux

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