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