[99d44b2] | 1 | #include "vulkan-game.hpp"
|
---|
[850e84c] | 2 |
|
---|
[cc4a8b5] | 3 | #define GLM_FORCE_RADIANS
|
---|
| 4 | #define GLM_FORCE_DEPTH_ZERO_TO_ONE
|
---|
| 5 |
|
---|
| 6 | #include <glm/gtc/matrix_transform.hpp>
|
---|
| 7 |
|
---|
[6fc24c7] | 8 | #include <array>
|
---|
[f985231] | 9 | #include <chrono>
|
---|
[0df3c9a] | 10 | #include <iostream>
|
---|
[c1c2021] | 11 | #include <set>
|
---|
[0df3c9a] | 12 |
|
---|
[5edbd58] | 13 | #include "consts.hpp"
|
---|
[c559904] | 14 | #include "logger.hpp"
|
---|
[5edbd58] | 15 |
|
---|
[771b33a] | 16 | #include "utils.hpp"
|
---|
[c1d9b2a] | 17 |
|
---|
[0df3c9a] | 18 | using namespace std;
|
---|
[cc4a8b5] | 19 | using namespace glm;
|
---|
[0df3c9a] | 20 |
|
---|
[b794178] | 21 | struct UniformBufferObject {
|
---|
| 22 | alignas(16) mat4 model;
|
---|
| 23 | alignas(16) mat4 view;
|
---|
| 24 | alignas(16) mat4 proj;
|
---|
| 25 | };
|
---|
| 26 |
|
---|
[34bdf3a] | 27 | VulkanGame::VulkanGame(int maxFramesInFlight) : MAX_FRAMES_IN_FLIGHT(maxFramesInFlight) {
|
---|
[0df3c9a] | 28 | gui = nullptr;
|
---|
| 29 | window = nullptr;
|
---|
[87c8f1a] | 30 |
|
---|
| 31 | currentFrame = 0;
|
---|
| 32 | framebufferResized = false;
|
---|
[0df3c9a] | 33 | }
|
---|
| 34 |
|
---|
[99d44b2] | 35 | VulkanGame::~VulkanGame() {
|
---|
[0df3c9a] | 36 | }
|
---|
| 37 |
|
---|
[b6e60b4] | 38 | void VulkanGame::run(int width, int height, unsigned char guiFlags) {
|
---|
[2e77b3f] | 39 | cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
|
---|
| 40 |
|
---|
| 41 | cout << "Vulkan Game" << endl;
|
---|
| 42 |
|
---|
[c559904] | 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 |
|
---|
[5edbd58] | 62 | if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
|
---|
[0df3c9a] | 63 | return;
|
---|
| 64 | }
|
---|
[b6e60b4] | 65 |
|
---|
[0df3c9a] | 66 | initVulkan();
|
---|
| 67 | mainLoop();
|
---|
| 68 | cleanup();
|
---|
[c559904] | 69 |
|
---|
| 70 | close_log();
|
---|
[0df3c9a] | 71 | }
|
---|
| 72 |
|
---|
[c559904] | 73 | // TODO: Make some more initi functions, or call this initUI if the
|
---|
| 74 | // amount of things initialized here keeps growing
|
---|
[b6e60b4] | 75 | bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
|
---|
[c559904] | 76 | // TODO: Put all fonts, textures, and images in the assets folder
|
---|
[0df3c9a] | 77 | gui = new GameGui_SDL();
|
---|
| 78 |
|
---|
[b6e60b4] | 79 | if (gui->init() == RTWO_ERROR) {
|
---|
[c559904] | 80 | // TODO: Also print these sorts of errors to the log
|
---|
[0df3c9a] | 81 | cout << "UI library could not be initialized!" << endl;
|
---|
[b6e60b4] | 82 | cout << gui->getError() << endl;
|
---|
[0df3c9a] | 83 | return RTWO_ERROR;
|
---|
| 84 | }
|
---|
| 85 |
|
---|
[b6e60b4] | 86 | window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
|
---|
[0df3c9a] | 87 | if (window == nullptr) {
|
---|
| 88 | cout << "Window could not be created!" << endl;
|
---|
[ed7c953] | 89 | cout << gui->getError() << endl;
|
---|
[0df3c9a] | 90 | return RTWO_ERROR;
|
---|
| 91 | }
|
---|
| 92 |
|
---|
[b6e60b4] | 93 | cout << "Target window size: (" << width << ", " << height << ")" << endl;
|
---|
[a6f6833] | 94 | cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
|
---|
[b6e60b4] | 95 |
|
---|
[c1d9b2a] | 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 |
|
---|
[b794178] | 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 |
|
---|
[0df3c9a] | 124 | return RTWO_SUCCESS;
|
---|
| 125 | }
|
---|
| 126 |
|
---|
[99d44b2] | 127 | void VulkanGame::initVulkan() {
|
---|
[c1d9b2a] | 128 | const vector<const char*> validationLayers = {
|
---|
| 129 | "VK_LAYER_KHRONOS_validation"
|
---|
| 130 | };
|
---|
[fe5c3ba] | 131 | const vector<const char*> deviceExtensions = {
|
---|
| 132 | VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
---|
| 133 | };
|
---|
[c1d9b2a] | 134 |
|
---|
| 135 | createVulkanInstance(validationLayers);
|
---|
| 136 | setupDebugMessenger();
|
---|
[90a424f] | 137 | createVulkanSurface();
|
---|
[fe5c3ba] | 138 | pickPhysicalDevice(deviceExtensions);
|
---|
[c1c2021] | 139 | createLogicalDevice(validationLayers, deviceExtensions);
|
---|
[502bd0b] | 140 | createSwapChain();
|
---|
[f94eea9] | 141 | createImageViews();
|
---|
[6fc24c7] | 142 | createRenderPass();
|
---|
[fa9fa1c] | 143 | createCommandPool();
|
---|
[7d2b0b9] | 144 |
|
---|
[603b5bc] | 145 | createImageResources();
|
---|
[b794178] | 146 |
|
---|
[603b5bc] | 147 | createFramebuffers();
|
---|
| 148 | createUniformBuffers();
|
---|
| 149 |
|
---|
[87c8f1a] | 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,
|
---|
[603b5bc] | 167 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(Vertex)));
|
---|
[771b33a] | 168 |
|
---|
[87c8f1a] | 169 | graphicsPipelines.back().bindData(sceneVertices, sceneIndices, commandPool, graphicsQueue);
|
---|
| 170 |
|
---|
[771b33a] | 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 |
|
---|
[b794178] | 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();
|
---|
[7d2b0b9] | 181 | graphicsPipelines.back().createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
|
---|
[b794178] | 182 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
| 183 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
[7d2b0b9] | 184 |
|
---|
[87c8f1a] | 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,
|
---|
[603b5bc] | 196 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(OverlayVertex)));
|
---|
[771b33a] | 197 |
|
---|
[87c8f1a] | 198 | graphicsPipelines.back().bindData(overlayVertices, overlayIndices, commandPool, graphicsQueue);
|
---|
| 199 |
|
---|
[771b33a] | 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 |
|
---|
[b794178] | 203 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
| 204 | VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
|
---|
| 205 |
|
---|
| 206 | graphicsPipelines.back().createDescriptorSetLayout();
|
---|
[7d2b0b9] | 207 | graphicsPipelines.back().createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
|
---|
[b794178] | 208 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
| 209 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
[7d2b0b9] | 210 |
|
---|
[603b5bc] | 211 | // TODO: Creating the descriptor pool and descriptor sets might need to be redone when the
|
---|
| 212 | // swap chain is recreated
|
---|
| 213 |
|
---|
[7d2b0b9] | 214 | cout << "Created " << graphicsPipelines.size() << " graphics pipelines" << endl;
|
---|
[34bdf3a] | 215 |
|
---|
| 216 | createCommandBuffers();
|
---|
| 217 |
|
---|
| 218 | createSyncObjects();
|
---|
[0df3c9a] | 219 | }
|
---|
| 220 |
|
---|
[99d44b2] | 221 | void VulkanGame::mainLoop() {
|
---|
[f6521fb] | 222 | UIEvent e;
|
---|
[0df3c9a] | 223 | bool quit = false;
|
---|
| 224 |
|
---|
| 225 | while (!quit) {
|
---|
[27c40ce] | 226 | gui->processEvents();
|
---|
| 227 |
|
---|
[f6521fb] | 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;
|
---|
[0e09340] | 238 | case UI_EVENT_WINDOWRESIZE:
|
---|
| 239 | cout << "Window resize event detected" << endl;
|
---|
| 240 | framebufferResized = true;
|
---|
| 241 | break;
|
---|
[f6521fb] | 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;
|
---|
[a0da009] | 257 | case UI_EVENT_UNKNOWN:
|
---|
| 258 | cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
|
---|
| 259 | break;
|
---|
[c61323a] | 260 | default:
|
---|
| 261 | cout << "Unhandled UI event: " << e.type << endl;
|
---|
[0df3c9a] | 262 | }
|
---|
| 263 | }
|
---|
[c1d9b2a] | 264 |
|
---|
[a0c5f28] | 265 | renderUI();
|
---|
| 266 | renderScene();
|
---|
[0df3c9a] | 267 | }
|
---|
[c1c2021] | 268 |
|
---|
| 269 | vkDeviceWaitIdle(device);
|
---|
[0df3c9a] | 270 | }
|
---|
| 271 |
|
---|
[a0c5f28] | 272 | void VulkanGame::renderUI() {
|
---|
[d2d9286] | 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);
|
---|
[a0c5f28] | 278 | SDL_RenderClear(renderer);
|
---|
[d2d9286] | 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);
|
---|
[a0c5f28] | 289 | }
|
---|
| 290 |
|
---|
| 291 | void VulkanGame::renderScene() {
|
---|
[87c8f1a] | 292 | vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
|
---|
| 293 |
|
---|
| 294 | uint32_t imageIndex;
|
---|
| 295 |
|
---|
[d2d9286] | 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 |
|
---|
[f985231] | 306 | updateUniformBuffer(imageIndex);
|
---|
| 307 |
|
---|
[d2d9286] | 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 |
|
---|
[87c8f1a] | 351 | currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
|
---|
| 352 | currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
|
---|
[a0c5f28] | 353 | }
|
---|
| 354 |
|
---|
[99d44b2] | 355 | void VulkanGame::cleanup() {
|
---|
[c1c2021] | 356 | cleanupSwapChain();
|
---|
| 357 |
|
---|
[e83b155] | 358 | VulkanUtils::destroyVulkanImage(device, floorTextureImage);
|
---|
| 359 | VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
|
---|
| 360 |
|
---|
| 361 | vkDestroySampler(device, textureSampler, nullptr);
|
---|
| 362 |
|
---|
[b794178] | 363 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
| 364 | pipeline.cleanupBuffers();
|
---|
| 365 | }
|
---|
| 366 |
|
---|
[34bdf3a] | 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 |
|
---|
[fa9fa1c] | 373 | vkDestroyCommandPool(device, commandPool, nullptr);
|
---|
[c1c2021] | 374 | vkDestroyDevice(device, nullptr);
|
---|
| 375 | vkDestroySurfaceKHR(instance, surface, nullptr);
|
---|
| 376 |
|
---|
[c1d9b2a] | 377 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 378 | VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
|
---|
| 379 | }
|
---|
[c1c2021] | 380 |
|
---|
[c1d9b2a] | 381 | vkDestroyInstance(instance, nullptr);
|
---|
| 382 |
|
---|
[b794178] | 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 |
|
---|
[c1d9b2a] | 391 | SDL_DestroyRenderer(renderer);
|
---|
| 392 | renderer = nullptr;
|
---|
| 393 |
|
---|
[b6e60b4] | 394 | gui->destroyWindow();
|
---|
| 395 | gui->shutdown();
|
---|
[0df3c9a] | 396 | delete gui;
|
---|
[c1d9b2a] | 397 | }
|
---|
| 398 |
|
---|
| 399 | void 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 |
|
---|
| 448 | void 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 |
|
---|
| 459 | void 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 |
|
---|
| 467 | VKAPI_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 | }
|
---|
[90a424f] | 476 |
|
---|
| 477 | void VulkanGame::createVulkanSurface() {
|
---|
| 478 | if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
|
---|
| 479 | throw runtime_error("failed to create window surface!");
|
---|
| 480 | }
|
---|
| 481 | }
|
---|
| 482 |
|
---|
[fe5c3ba] | 483 | void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
|
---|
[90a424f] | 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) {
|
---|
[fe5c3ba] | 496 | if (isDeviceSuitable(device, deviceExtensions)) {
|
---|
[90a424f] | 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 |
|
---|
[fa9fa1c] | 508 | bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
|
---|
| 509 | const vector<const char*>& deviceExtensions) {
|
---|
[90a424f] | 510 | VkPhysicalDeviceProperties deviceProperties;
|
---|
[fa9fa1c] | 511 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
[90a424f] | 512 |
|
---|
| 513 | cout << "Device: " << deviceProperties.deviceName << endl;
|
---|
| 514 |
|
---|
[fa9fa1c] | 515 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
| 516 | bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
|
---|
[90a424f] | 517 | bool swapChainAdequate = false;
|
---|
| 518 |
|
---|
| 519 | if (extensionsSupported) {
|
---|
[fa9fa1c] | 520 | SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
|
---|
[90a424f] | 521 | swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
|
---|
| 522 | }
|
---|
| 523 |
|
---|
| 524 | VkPhysicalDeviceFeatures supportedFeatures;
|
---|
[fa9fa1c] | 525 | vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
|
---|
[90a424f] | 526 |
|
---|
| 527 | return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
|
---|
[c1c2021] | 528 | }
|
---|
| 529 |
|
---|
| 530 | void VulkanGame::createLogicalDevice(
|
---|
| 531 | const vector<const char*> validationLayers,
|
---|
| 532 | const vector<const char*>& deviceExtensions) {
|
---|
| 533 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
| 534 |
|
---|
[b794178] | 535 | vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
|
---|
[c1c2021] | 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 |
|
---|
[b794178] | 546 | queueCreateInfoList.push_back(queueCreateInfo);
|
---|
[c1c2021] | 547 | }
|
---|
| 548 |
|
---|
| 549 | VkPhysicalDeviceFeatures deviceFeatures = {};
|
---|
| 550 | deviceFeatures.samplerAnisotropy = VK_TRUE;
|
---|
| 551 |
|
---|
| 552 | VkDeviceCreateInfo createInfo = {};
|
---|
| 553 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
---|
[b794178] | 554 | createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
|
---|
| 555 | createInfo.pQueueCreateInfos = queueCreateInfoList.data();
|
---|
[c1c2021] | 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);
|
---|
[502bd0b] | 577 | }
|
---|
| 578 |
|
---|
| 579 | void 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;
|
---|
[f94eea9] | 608 | } else {
|
---|
[502bd0b] | 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;
|
---|
[603b5bc] | 629 | swapChainExtent = extent;
|
---|
[f94eea9] | 630 | }
|
---|
| 631 |
|
---|
| 632 | void 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 |
|
---|
[6fc24c7] | 641 | void 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 |
|
---|
| 699 | VkFormat 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 |
|
---|
[fa9fa1c] | 708 | void 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 |
|
---|
[603b5bc] | 721 | void VulkanGame::createImageResources() {
|
---|
| 722 | VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
|
---|
| 723 | depthImage, graphicsQueue);
|
---|
[b794178] | 724 |
|
---|
[603b5bc] | 725 | createTextureSampler();
|
---|
[b794178] | 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 |
|
---|
[603b5bc] | 735 | VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
|
---|
| 736 |
|
---|
[b794178] | 737 | sdlOverlayImageDescriptor = {};
|
---|
| 738 | sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
| 739 | sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
|
---|
| 740 | sdlOverlayImageDescriptor.sampler = textureSampler;
|
---|
| 741 | }
|
---|
| 742 |
|
---|
| 743 | void 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 |
|
---|
[603b5bc] | 769 | void 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 |
|
---|
[b794178] | 793 | void 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 |
|
---|
[603b5bc] | 811 | void 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 |
|
---|
[34bdf3a] | 862 | void 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 |
|
---|
[d2d9286] | 883 | void 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 |
|
---|
[f985231] | 898 | void 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 = {};
|
---|
[cc4a8b5] | 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));
|
---|
[f985231] | 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 |
|
---|
[f94eea9] | 916 | void VulkanGame::cleanupSwapChain() {
|
---|
[603b5bc] | 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 |
|
---|
[b794178] | 925 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
| 926 | pipeline.cleanup();
|
---|
| 927 | }
|
---|
| 928 |
|
---|
[6fc24c7] | 929 | vkDestroyRenderPass(device, renderPass, nullptr);
|
---|
| 930 |
|
---|
[b794178] | 931 | for (VkImageView imageView : swapChainImageViews) {
|
---|
[f94eea9] | 932 | vkDestroyImageView(device, imageView, nullptr);
|
---|
| 933 | }
|
---|
| 934 |
|
---|
| 935 | vkDestroySwapchainKHR(device, swapChain, nullptr);
|
---|
[e83b155] | 936 |
|
---|
[603b5bc] | 937 | for (size_t i = 0; i < uniformBuffers.size(); i++) {
|
---|
[e83b155] | 938 | vkDestroyBuffer(device, uniformBuffers[i], nullptr);
|
---|
| 939 | vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
|
---|
| 940 | }
|
---|
[cc4a8b5] | 941 | }
|
---|