[99d44b2] | 1 | #include "vulkan-game.hpp"
|
---|
[850e84c] | 2 |
|
---|
[6fc24c7] | 3 | #include <array>
|
---|
[0df3c9a] | 4 | #include <iostream>
|
---|
[c1c2021] | 5 | #include <set>
|
---|
[0df3c9a] | 6 |
|
---|
[5edbd58] | 7 | #include "consts.hpp"
|
---|
[c559904] | 8 | #include "logger.hpp"
|
---|
[5edbd58] | 9 |
|
---|
[771b33a] | 10 | #include "utils.hpp"
|
---|
[c1d9b2a] | 11 |
|
---|
[0df3c9a] | 12 | using namespace std;
|
---|
| 13 |
|
---|
[b794178] | 14 | struct UniformBufferObject {
|
---|
| 15 | alignas(16) mat4 model;
|
---|
| 16 | alignas(16) mat4 view;
|
---|
| 17 | alignas(16) mat4 proj;
|
---|
| 18 | };
|
---|
| 19 |
|
---|
[99d44b2] | 20 | VulkanGame::VulkanGame() {
|
---|
[0df3c9a] | 21 | gui = nullptr;
|
---|
| 22 | window = nullptr;
|
---|
| 23 | }
|
---|
| 24 |
|
---|
[99d44b2] | 25 | VulkanGame::~VulkanGame() {
|
---|
[0df3c9a] | 26 | }
|
---|
| 27 |
|
---|
[b6e60b4] | 28 | void VulkanGame::run(int width, int height, unsigned char guiFlags) {
|
---|
[2e77b3f] | 29 | cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
|
---|
| 30 |
|
---|
| 31 | cout << "Vulkan Game" << endl;
|
---|
| 32 |
|
---|
[c559904] | 33 | // This gets the runtime version, use SDL_VERSION() for the comppile-time version
|
---|
| 34 | // TODO: Create a game-gui function to get the gui version and retrieve it that way
|
---|
| 35 | SDL_GetVersion(&sdlVersion);
|
---|
| 36 |
|
---|
| 37 | // TODO: Refactor the logger api to be more flexible,
|
---|
| 38 | // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
|
---|
| 39 | restart_gl_log();
|
---|
| 40 | gl_log("starting SDL\n%s.%s.%s",
|
---|
| 41 | to_string(sdlVersion.major).c_str(),
|
---|
| 42 | to_string(sdlVersion.minor).c_str(),
|
---|
| 43 | to_string(sdlVersion.patch).c_str());
|
---|
| 44 |
|
---|
| 45 | open_log();
|
---|
| 46 | get_log() << "starting SDL" << endl;
|
---|
| 47 | get_log() <<
|
---|
| 48 | (int)sdlVersion.major << "." <<
|
---|
| 49 | (int)sdlVersion.minor << "." <<
|
---|
| 50 | (int)sdlVersion.patch << endl;
|
---|
| 51 |
|
---|
[5edbd58] | 52 | if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
|
---|
[0df3c9a] | 53 | return;
|
---|
| 54 | }
|
---|
[b6e60b4] | 55 |
|
---|
[0df3c9a] | 56 | initVulkan();
|
---|
| 57 | mainLoop();
|
---|
| 58 | cleanup();
|
---|
[c559904] | 59 |
|
---|
| 60 | close_log();
|
---|
[0df3c9a] | 61 | }
|
---|
| 62 |
|
---|
[c559904] | 63 | // TODO: Make some more initi functions, or call this initUI if the
|
---|
| 64 | // amount of things initialized here keeps growing
|
---|
[b6e60b4] | 65 | bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
|
---|
[c559904] | 66 | // TODO: Put all fonts, textures, and images in the assets folder
|
---|
[0df3c9a] | 67 | gui = new GameGui_SDL();
|
---|
| 68 |
|
---|
[b6e60b4] | 69 | if (gui->init() == RTWO_ERROR) {
|
---|
[c559904] | 70 | // TODO: Also print these sorts of errors to the log
|
---|
[0df3c9a] | 71 | cout << "UI library could not be initialized!" << endl;
|
---|
[b6e60b4] | 72 | cout << gui->getError() << endl;
|
---|
[0df3c9a] | 73 | return RTWO_ERROR;
|
---|
| 74 | }
|
---|
| 75 |
|
---|
[b6e60b4] | 76 | window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
|
---|
[0df3c9a] | 77 | if (window == nullptr) {
|
---|
| 78 | cout << "Window could not be created!" << endl;
|
---|
[ed7c953] | 79 | cout << gui->getError() << endl;
|
---|
[0df3c9a] | 80 | return RTWO_ERROR;
|
---|
| 81 | }
|
---|
| 82 |
|
---|
[b6e60b4] | 83 | cout << "Target window size: (" << width << ", " << height << ")" << endl;
|
---|
[a6f6833] | 84 | cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
|
---|
[b6e60b4] | 85 |
|
---|
[c1d9b2a] | 86 | renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
---|
| 87 | if (renderer == nullptr) {
|
---|
| 88 | cout << "Renderer could not be created!" << endl;
|
---|
| 89 | cout << gui->getError() << endl;
|
---|
| 90 | return RTWO_ERROR;
|
---|
| 91 | }
|
---|
| 92 |
|
---|
[b794178] | 93 | SDL_VERSION(&sdlVersion);
|
---|
| 94 |
|
---|
| 95 | // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
|
---|
| 96 | // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
|
---|
| 97 | // 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
|
---|
| 98 | // until the homebrew recipe is updated
|
---|
| 99 | if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
|
---|
| 100 | uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING,
|
---|
| 101 | gui->getWindowWidth(), gui->getWindowHeight());
|
---|
| 102 | } else {
|
---|
| 103 | uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,
|
---|
| 104 | gui->getWindowWidth(), gui->getWindowHeight());
|
---|
| 105 | }
|
---|
| 106 |
|
---|
| 107 | if (uiOverlay == nullptr) {
|
---|
| 108 | cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
|
---|
| 109 | }
|
---|
| 110 | if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
|
---|
| 111 | cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
|
---|
| 112 | }
|
---|
| 113 |
|
---|
[0df3c9a] | 114 | return RTWO_SUCCESS;
|
---|
| 115 | }
|
---|
| 116 |
|
---|
[99d44b2] | 117 | void VulkanGame::initVulkan() {
|
---|
[c1d9b2a] | 118 | const vector<const char*> validationLayers = {
|
---|
| 119 | "VK_LAYER_KHRONOS_validation"
|
---|
| 120 | };
|
---|
[fe5c3ba] | 121 | const vector<const char*> deviceExtensions = {
|
---|
| 122 | VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
---|
| 123 | };
|
---|
[c1d9b2a] | 124 |
|
---|
| 125 | createVulkanInstance(validationLayers);
|
---|
| 126 | setupDebugMessenger();
|
---|
[90a424f] | 127 | createVulkanSurface();
|
---|
[fe5c3ba] | 128 | pickPhysicalDevice(deviceExtensions);
|
---|
[c1c2021] | 129 | createLogicalDevice(validationLayers, deviceExtensions);
|
---|
[502bd0b] | 130 | createSwapChain();
|
---|
[f94eea9] | 131 | createImageViews();
|
---|
[6fc24c7] | 132 | createRenderPass();
|
---|
[fa9fa1c] | 133 | createCommandPool();
|
---|
[7d2b0b9] | 134 |
|
---|
[b794178] | 135 | createVulkanResources();
|
---|
| 136 |
|
---|
| 137 | graphicsPipelines.push_back(GraphicsPipeline_Vulkan(device, renderPass, viewport, sizeof(Vertex)));
|
---|
[771b33a] | 138 |
|
---|
| 139 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
|
---|
| 140 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
|
---|
| 141 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
|
---|
| 142 |
|
---|
[b794178] | 143 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
---|
| 144 | VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
|
---|
| 145 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
| 146 | VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
|
---|
| 147 |
|
---|
| 148 | graphicsPipelines.back().createDescriptorSetLayout();
|
---|
[7d2b0b9] | 149 | graphicsPipelines.back().createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
|
---|
[b794178] | 150 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
| 151 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
[7d2b0b9] | 152 |
|
---|
[b794178] | 153 | graphicsPipelines.push_back(GraphicsPipeline_Vulkan(device, renderPass, viewport, sizeof(OverlayVertex)));
|
---|
[771b33a] | 154 |
|
---|
| 155 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
|
---|
| 156 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
|
---|
| 157 |
|
---|
[b794178] | 158 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
| 159 | VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
|
---|
| 160 |
|
---|
| 161 | graphicsPipelines.back().createDescriptorSetLayout();
|
---|
[7d2b0b9] | 162 | graphicsPipelines.back().createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
|
---|
[b794178] | 163 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
| 164 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
[7d2b0b9] | 165 |
|
---|
| 166 | cout << "Created " << graphicsPipelines.size() << " graphics pipelines" << endl;
|
---|
[0df3c9a] | 167 | }
|
---|
| 168 |
|
---|
[99d44b2] | 169 | void VulkanGame::mainLoop() {
|
---|
[f6521fb] | 170 | UIEvent e;
|
---|
[0df3c9a] | 171 | bool quit = false;
|
---|
| 172 |
|
---|
[c1d9b2a] | 173 | SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
---|
| 174 |
|
---|
[0df3c9a] | 175 | while (!quit) {
|
---|
[27c40ce] | 176 | gui->processEvents();
|
---|
| 177 |
|
---|
[f6521fb] | 178 | while (gui->pollEvent(&e)) {
|
---|
| 179 | switch(e.type) {
|
---|
| 180 | case UI_EVENT_QUIT:
|
---|
| 181 | cout << "Quit event detected" << endl;
|
---|
| 182 | quit = true;
|
---|
| 183 | break;
|
---|
| 184 | case UI_EVENT_WINDOW:
|
---|
| 185 | cout << "Window event detected" << endl;
|
---|
| 186 | // Currently unused
|
---|
| 187 | break;
|
---|
[0e09340] | 188 | case UI_EVENT_WINDOWRESIZE:
|
---|
| 189 | cout << "Window resize event detected" << endl;
|
---|
| 190 | framebufferResized = true;
|
---|
| 191 | break;
|
---|
[f6521fb] | 192 | case UI_EVENT_KEY:
|
---|
| 193 | if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
|
---|
| 194 | quit = true;
|
---|
| 195 | } else {
|
---|
| 196 | cout << "Key event detected" << endl;
|
---|
| 197 | }
|
---|
| 198 | break;
|
---|
| 199 | case UI_EVENT_MOUSEBUTTONDOWN:
|
---|
| 200 | cout << "Mouse button down event detected" << endl;
|
---|
| 201 | break;
|
---|
| 202 | case UI_EVENT_MOUSEBUTTONUP:
|
---|
| 203 | cout << "Mouse button up event detected" << endl;
|
---|
| 204 | break;
|
---|
| 205 | case UI_EVENT_MOUSEMOTION:
|
---|
| 206 | break;
|
---|
[a0da009] | 207 | case UI_EVENT_UNKNOWN:
|
---|
| 208 | cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
|
---|
| 209 | break;
|
---|
[c61323a] | 210 | default:
|
---|
| 211 | cout << "Unhandled UI event: " << e.type << endl;
|
---|
[0df3c9a] | 212 | }
|
---|
| 213 | }
|
---|
[c1d9b2a] | 214 |
|
---|
[a0c5f28] | 215 | renderUI();
|
---|
| 216 | renderScene();
|
---|
[0df3c9a] | 217 | }
|
---|
[c1c2021] | 218 |
|
---|
| 219 | vkDeviceWaitIdle(device);
|
---|
[0df3c9a] | 220 | }
|
---|
| 221 |
|
---|
[a0c5f28] | 222 | void VulkanGame::renderUI() {
|
---|
| 223 | SDL_RenderClear(renderer);
|
---|
| 224 | SDL_RenderPresent(renderer);
|
---|
| 225 | }
|
---|
| 226 |
|
---|
| 227 | void VulkanGame::renderScene() {
|
---|
| 228 | }
|
---|
| 229 |
|
---|
[99d44b2] | 230 | void VulkanGame::cleanup() {
|
---|
[c1c2021] | 231 | cleanupSwapChain();
|
---|
| 232 |
|
---|
[e83b155] | 233 | VulkanUtils::destroyVulkanImage(device, floorTextureImage);
|
---|
| 234 | VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
|
---|
| 235 |
|
---|
| 236 | vkDestroySampler(device, textureSampler, nullptr);
|
---|
| 237 |
|
---|
[b794178] | 238 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
| 239 | pipeline.cleanupBuffers();
|
---|
| 240 | }
|
---|
| 241 |
|
---|
[fa9fa1c] | 242 | vkDestroyCommandPool(device, commandPool, nullptr);
|
---|
[c1c2021] | 243 | vkDestroyDevice(device, nullptr);
|
---|
| 244 | vkDestroySurfaceKHR(instance, surface, nullptr);
|
---|
| 245 |
|
---|
[c1d9b2a] | 246 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 247 | VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
|
---|
| 248 | }
|
---|
[c1c2021] | 249 |
|
---|
[c1d9b2a] | 250 | vkDestroyInstance(instance, nullptr);
|
---|
| 251 |
|
---|
[b794178] | 252 | // TODO: Check if any of these functions accept null parameters
|
---|
| 253 | // If they do, I don't need to check for that
|
---|
| 254 |
|
---|
| 255 | if (uiOverlay != nullptr) {
|
---|
| 256 | SDL_DestroyTexture(uiOverlay);
|
---|
| 257 | uiOverlay = nullptr;
|
---|
| 258 | }
|
---|
| 259 |
|
---|
[c1d9b2a] | 260 | SDL_DestroyRenderer(renderer);
|
---|
| 261 | renderer = nullptr;
|
---|
| 262 |
|
---|
[b6e60b4] | 263 | gui->destroyWindow();
|
---|
| 264 | gui->shutdown();
|
---|
[0df3c9a] | 265 | delete gui;
|
---|
[c1d9b2a] | 266 | }
|
---|
| 267 |
|
---|
| 268 | void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
|
---|
| 269 | if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
|
---|
| 270 | throw runtime_error("validation layers requested, but not available!");
|
---|
| 271 | }
|
---|
| 272 |
|
---|
| 273 | VkApplicationInfo appInfo = {};
|
---|
| 274 | appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
---|
| 275 | appInfo.pApplicationName = "Vulkan Game";
|
---|
| 276 | appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
| 277 | appInfo.pEngineName = "No Engine";
|
---|
| 278 | appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
| 279 | appInfo.apiVersion = VK_API_VERSION_1_0;
|
---|
| 280 |
|
---|
| 281 | VkInstanceCreateInfo createInfo = {};
|
---|
| 282 | createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
---|
| 283 | createInfo.pApplicationInfo = &appInfo;
|
---|
| 284 |
|
---|
| 285 | vector<const char*> extensions = gui->getRequiredExtensions();
|
---|
| 286 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 287 | extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
---|
| 288 | }
|
---|
| 289 |
|
---|
| 290 | createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
|
---|
| 291 | createInfo.ppEnabledExtensionNames = extensions.data();
|
---|
| 292 |
|
---|
| 293 | cout << endl << "Extensions:" << endl;
|
---|
| 294 | for (const char* extensionName : extensions) {
|
---|
| 295 | cout << extensionName << endl;
|
---|
| 296 | }
|
---|
| 297 | cout << endl;
|
---|
| 298 |
|
---|
| 299 | VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
|
---|
| 300 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 301 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
| 302 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
| 303 |
|
---|
| 304 | populateDebugMessengerCreateInfo(debugCreateInfo);
|
---|
| 305 | createInfo.pNext = &debugCreateInfo;
|
---|
| 306 | } else {
|
---|
| 307 | createInfo.enabledLayerCount = 0;
|
---|
| 308 |
|
---|
| 309 | createInfo.pNext = nullptr;
|
---|
| 310 | }
|
---|
| 311 |
|
---|
| 312 | if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
|
---|
| 313 | throw runtime_error("failed to create instance!");
|
---|
| 314 | }
|
---|
| 315 | }
|
---|
| 316 |
|
---|
| 317 | void VulkanGame::setupDebugMessenger() {
|
---|
| 318 | if (!ENABLE_VALIDATION_LAYERS) return;
|
---|
| 319 |
|
---|
| 320 | VkDebugUtilsMessengerCreateInfoEXT createInfo;
|
---|
| 321 | populateDebugMessengerCreateInfo(createInfo);
|
---|
| 322 |
|
---|
| 323 | if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
|
---|
| 324 | throw runtime_error("failed to set up debug messenger!");
|
---|
| 325 | }
|
---|
| 326 | }
|
---|
| 327 |
|
---|
| 328 | void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
|
---|
| 329 | createInfo = {};
|
---|
| 330 | createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
---|
| 331 | 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;
|
---|
| 332 | 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;
|
---|
| 333 | createInfo.pfnUserCallback = debugCallback;
|
---|
| 334 | }
|
---|
| 335 |
|
---|
| 336 | VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
|
---|
| 337 | VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
|
---|
| 338 | VkDebugUtilsMessageTypeFlagsEXT messageType,
|
---|
| 339 | const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
|
---|
| 340 | void* pUserData) {
|
---|
| 341 | cerr << "validation layer: " << pCallbackData->pMessage << endl;
|
---|
| 342 |
|
---|
| 343 | return VK_FALSE;
|
---|
| 344 | }
|
---|
[90a424f] | 345 |
|
---|
| 346 | void VulkanGame::createVulkanSurface() {
|
---|
| 347 | if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
|
---|
| 348 | throw runtime_error("failed to create window surface!");
|
---|
| 349 | }
|
---|
| 350 | }
|
---|
| 351 |
|
---|
[fe5c3ba] | 352 | void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
|
---|
[90a424f] | 353 | uint32_t deviceCount = 0;
|
---|
| 354 | vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
|
---|
| 355 |
|
---|
| 356 | if (deviceCount == 0) {
|
---|
| 357 | throw runtime_error("failed to find GPUs with Vulkan support!");
|
---|
| 358 | }
|
---|
| 359 |
|
---|
| 360 | vector<VkPhysicalDevice> devices(deviceCount);
|
---|
| 361 | vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
|
---|
| 362 |
|
---|
| 363 | cout << endl << "Graphics cards:" << endl;
|
---|
| 364 | for (const VkPhysicalDevice& device : devices) {
|
---|
[fe5c3ba] | 365 | if (isDeviceSuitable(device, deviceExtensions)) {
|
---|
[90a424f] | 366 | physicalDevice = device;
|
---|
| 367 | break;
|
---|
| 368 | }
|
---|
| 369 | }
|
---|
| 370 | cout << endl;
|
---|
| 371 |
|
---|
| 372 | if (physicalDevice == VK_NULL_HANDLE) {
|
---|
| 373 | throw runtime_error("failed to find a suitable GPU!");
|
---|
| 374 | }
|
---|
| 375 | }
|
---|
| 376 |
|
---|
[fa9fa1c] | 377 | bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
|
---|
| 378 | const vector<const char*>& deviceExtensions) {
|
---|
[90a424f] | 379 | VkPhysicalDeviceProperties deviceProperties;
|
---|
[fa9fa1c] | 380 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
[90a424f] | 381 |
|
---|
| 382 | cout << "Device: " << deviceProperties.deviceName << endl;
|
---|
| 383 |
|
---|
[fa9fa1c] | 384 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
| 385 | bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
|
---|
[90a424f] | 386 | bool swapChainAdequate = false;
|
---|
| 387 |
|
---|
| 388 | if (extensionsSupported) {
|
---|
[fa9fa1c] | 389 | SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
|
---|
[90a424f] | 390 | swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
|
---|
| 391 | }
|
---|
| 392 |
|
---|
| 393 | VkPhysicalDeviceFeatures supportedFeatures;
|
---|
[fa9fa1c] | 394 | vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
|
---|
[90a424f] | 395 |
|
---|
| 396 | return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
|
---|
[c1c2021] | 397 | }
|
---|
| 398 |
|
---|
| 399 | void VulkanGame::createLogicalDevice(
|
---|
| 400 | const vector<const char*> validationLayers,
|
---|
| 401 | const vector<const char*>& deviceExtensions) {
|
---|
| 402 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
| 403 |
|
---|
[b794178] | 404 | vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
|
---|
[c1c2021] | 405 | set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
| 406 |
|
---|
| 407 | float queuePriority = 1.0f;
|
---|
| 408 | for (uint32_t queueFamily : uniqueQueueFamilies) {
|
---|
| 409 | VkDeviceQueueCreateInfo queueCreateInfo = {};
|
---|
| 410 | queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
---|
| 411 | queueCreateInfo.queueFamilyIndex = queueFamily;
|
---|
| 412 | queueCreateInfo.queueCount = 1;
|
---|
| 413 | queueCreateInfo.pQueuePriorities = &queuePriority;
|
---|
| 414 |
|
---|
[b794178] | 415 | queueCreateInfoList.push_back(queueCreateInfo);
|
---|
[c1c2021] | 416 | }
|
---|
| 417 |
|
---|
| 418 | VkPhysicalDeviceFeatures deviceFeatures = {};
|
---|
| 419 | deviceFeatures.samplerAnisotropy = VK_TRUE;
|
---|
| 420 |
|
---|
| 421 | VkDeviceCreateInfo createInfo = {};
|
---|
| 422 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
---|
[b794178] | 423 | createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
|
---|
| 424 | createInfo.pQueueCreateInfos = queueCreateInfoList.data();
|
---|
[c1c2021] | 425 |
|
---|
| 426 | createInfo.pEnabledFeatures = &deviceFeatures;
|
---|
| 427 |
|
---|
| 428 | createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
|
---|
| 429 | createInfo.ppEnabledExtensionNames = deviceExtensions.data();
|
---|
| 430 |
|
---|
| 431 | // These fields are ignored by up-to-date Vulkan implementations,
|
---|
| 432 | // but it's a good idea to set them for backwards compatibility
|
---|
| 433 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
| 434 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
| 435 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
| 436 | } else {
|
---|
| 437 | createInfo.enabledLayerCount = 0;
|
---|
| 438 | }
|
---|
| 439 |
|
---|
| 440 | if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
|
---|
| 441 | throw runtime_error("failed to create logical device!");
|
---|
| 442 | }
|
---|
| 443 |
|
---|
| 444 | vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
|
---|
| 445 | vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
|
---|
[502bd0b] | 446 | }
|
---|
| 447 |
|
---|
| 448 | void VulkanGame::createSwapChain() {
|
---|
| 449 | SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
|
---|
| 450 |
|
---|
| 451 | VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
|
---|
| 452 | VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
|
---|
| 453 | VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
|
---|
| 454 |
|
---|
| 455 | uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
|
---|
| 456 | if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
|
---|
| 457 | imageCount = swapChainSupport.capabilities.maxImageCount;
|
---|
| 458 | }
|
---|
| 459 |
|
---|
| 460 | VkSwapchainCreateInfoKHR createInfo = {};
|
---|
| 461 | createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
---|
| 462 | createInfo.surface = surface;
|
---|
| 463 | createInfo.minImageCount = imageCount;
|
---|
| 464 | createInfo.imageFormat = surfaceFormat.format;
|
---|
| 465 | createInfo.imageColorSpace = surfaceFormat.colorSpace;
|
---|
| 466 | createInfo.imageExtent = extent;
|
---|
| 467 | createInfo.imageArrayLayers = 1;
|
---|
| 468 | createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
---|
| 469 |
|
---|
| 470 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
| 471 | uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
| 472 |
|
---|
| 473 | if (indices.graphicsFamily != indices.presentFamily) {
|
---|
| 474 | createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
|
---|
| 475 | createInfo.queueFamilyIndexCount = 2;
|
---|
| 476 | createInfo.pQueueFamilyIndices = queueFamilyIndices;
|
---|
[f94eea9] | 477 | } else {
|
---|
[502bd0b] | 478 | createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
---|
| 479 | createInfo.queueFamilyIndexCount = 0;
|
---|
| 480 | createInfo.pQueueFamilyIndices = nullptr;
|
---|
| 481 | }
|
---|
| 482 |
|
---|
| 483 | createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
|
---|
| 484 | createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
---|
| 485 | createInfo.presentMode = presentMode;
|
---|
| 486 | createInfo.clipped = VK_TRUE;
|
---|
| 487 | createInfo.oldSwapchain = VK_NULL_HANDLE;
|
---|
| 488 |
|
---|
| 489 | if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
|
---|
| 490 | throw runtime_error("failed to create swap chain!");
|
---|
| 491 | }
|
---|
| 492 |
|
---|
| 493 | vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
|
---|
| 494 | swapChainImages.resize(imageCount);
|
---|
| 495 | vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
|
---|
| 496 |
|
---|
| 497 | swapChainImageFormat = surfaceFormat.format;
|
---|
[771b33a] | 498 | viewport = { 0, 0, (int)extent.width, (int)extent.height };
|
---|
[f94eea9] | 499 | }
|
---|
| 500 |
|
---|
| 501 | void VulkanGame::createImageViews() {
|
---|
| 502 | swapChainImageViews.resize(swapChainImages.size());
|
---|
| 503 |
|
---|
| 504 | for (size_t i = 0; i < swapChainImages.size(); i++) {
|
---|
| 505 | swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
|
---|
| 506 | VK_IMAGE_ASPECT_COLOR_BIT);
|
---|
| 507 | }
|
---|
| 508 | }
|
---|
| 509 |
|
---|
[6fc24c7] | 510 | void VulkanGame::createRenderPass() {
|
---|
| 511 | VkAttachmentDescription colorAttachment = {};
|
---|
| 512 | colorAttachment.format = swapChainImageFormat;
|
---|
| 513 | colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
| 514 | colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
| 515 | colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
---|
| 516 | colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
| 517 | colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 518 | colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
| 519 | colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
---|
| 520 |
|
---|
| 521 | VkAttachmentReference colorAttachmentRef = {};
|
---|
| 522 | colorAttachmentRef.attachment = 0;
|
---|
| 523 | colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
---|
| 524 |
|
---|
| 525 | VkAttachmentDescription depthAttachment = {};
|
---|
| 526 | depthAttachment.format = findDepthFormat();
|
---|
| 527 | depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
| 528 | depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
| 529 | depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 530 | depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
| 531 | depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
| 532 | depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
| 533 | depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
| 534 |
|
---|
| 535 | VkAttachmentReference depthAttachmentRef = {};
|
---|
| 536 | depthAttachmentRef.attachment = 1;
|
---|
| 537 | depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
| 538 |
|
---|
| 539 | VkSubpassDescription subpass = {};
|
---|
| 540 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
---|
| 541 | subpass.colorAttachmentCount = 1;
|
---|
| 542 | subpass.pColorAttachments = &colorAttachmentRef;
|
---|
| 543 | subpass.pDepthStencilAttachment = &depthAttachmentRef;
|
---|
| 544 |
|
---|
| 545 | VkSubpassDependency dependency = {};
|
---|
| 546 | dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
---|
| 547 | dependency.dstSubpass = 0;
|
---|
| 548 | dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
| 549 | dependency.srcAccessMask = 0;
|
---|
| 550 | dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
| 551 | dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
|
---|
| 552 |
|
---|
| 553 | array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
|
---|
| 554 | VkRenderPassCreateInfo renderPassInfo = {};
|
---|
| 555 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
---|
| 556 | renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
| 557 | renderPassInfo.pAttachments = attachments.data();
|
---|
| 558 | renderPassInfo.subpassCount = 1;
|
---|
| 559 | renderPassInfo.pSubpasses = &subpass;
|
---|
| 560 | renderPassInfo.dependencyCount = 1;
|
---|
| 561 | renderPassInfo.pDependencies = &dependency;
|
---|
| 562 |
|
---|
| 563 | if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
|
---|
| 564 | throw runtime_error("failed to create render pass!");
|
---|
| 565 | }
|
---|
| 566 | }
|
---|
| 567 |
|
---|
| 568 | VkFormat VulkanGame::findDepthFormat() {
|
---|
| 569 | return VulkanUtils::findSupportedFormat(
|
---|
| 570 | physicalDevice,
|
---|
| 571 | { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
|
---|
| 572 | VK_IMAGE_TILING_OPTIMAL,
|
---|
| 573 | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
|
---|
| 574 | );
|
---|
| 575 | }
|
---|
| 576 |
|
---|
[fa9fa1c] | 577 | void VulkanGame::createCommandPool() {
|
---|
| 578 | QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
|
---|
| 579 |
|
---|
| 580 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
| 581 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
| 582 | poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
|
---|
| 583 | poolInfo.flags = 0;
|
---|
| 584 |
|
---|
| 585 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
|
---|
| 586 | throw runtime_error("failed to create graphics command pool!");
|
---|
| 587 | }
|
---|
| 588 | }
|
---|
| 589 |
|
---|
[b794178] | 590 | void VulkanGame::createVulkanResources() {
|
---|
| 591 | createTextureSampler();
|
---|
| 592 | createUniformBuffers();
|
---|
| 593 |
|
---|
| 594 | // TODO: Make sure that Vulkan complains about these images not being destroyed and then destroy them
|
---|
| 595 |
|
---|
| 596 | VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
|
---|
| 597 | floorTextureImage, graphicsQueue);
|
---|
| 598 | VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
|
---|
| 599 |
|
---|
| 600 | floorTextureImageDescriptor = {};
|
---|
| 601 | floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
| 602 | floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
|
---|
| 603 | floorTextureImageDescriptor.sampler = textureSampler;
|
---|
| 604 |
|
---|
| 605 | sdlOverlayImageDescriptor = {};
|
---|
| 606 | sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
| 607 | sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
|
---|
| 608 | sdlOverlayImageDescriptor.sampler = textureSampler;
|
---|
| 609 | }
|
---|
| 610 |
|
---|
| 611 | void VulkanGame::createTextureSampler() {
|
---|
| 612 | VkSamplerCreateInfo samplerInfo = {};
|
---|
| 613 | samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
---|
| 614 | samplerInfo.magFilter = VK_FILTER_LINEAR;
|
---|
| 615 | samplerInfo.minFilter = VK_FILTER_LINEAR;
|
---|
| 616 |
|
---|
| 617 | samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 618 | samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 619 | samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
| 620 |
|
---|
| 621 | samplerInfo.anisotropyEnable = VK_TRUE;
|
---|
| 622 | samplerInfo.maxAnisotropy = 16;
|
---|
| 623 | samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
|
---|
| 624 | samplerInfo.unnormalizedCoordinates = VK_FALSE;
|
---|
| 625 | samplerInfo.compareEnable = VK_FALSE;
|
---|
| 626 | samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
|
---|
| 627 | samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
---|
| 628 | samplerInfo.mipLodBias = 0.0f;
|
---|
| 629 | samplerInfo.minLod = 0.0f;
|
---|
| 630 | samplerInfo.maxLod = 0.0f;
|
---|
| 631 |
|
---|
| 632 | if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
|
---|
| 633 | throw runtime_error("failed to create texture sampler!");
|
---|
| 634 | }
|
---|
| 635 | }
|
---|
| 636 |
|
---|
| 637 | void VulkanGame::createUniformBuffers() {
|
---|
| 638 | VkDeviceSize bufferSize = sizeof(UniformBufferObject);
|
---|
| 639 |
|
---|
| 640 | uniformBuffers.resize(swapChainImages.size());
|
---|
| 641 | uniformBuffersMemory.resize(swapChainImages.size());
|
---|
| 642 | uniformBufferInfoList.resize(swapChainImages.size());
|
---|
| 643 |
|
---|
| 644 | for (size_t i = 0; i < swapChainImages.size(); i++) {
|
---|
| 645 | VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
---|
| 646 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
| 647 | uniformBuffers[i], uniformBuffersMemory[i]);
|
---|
| 648 |
|
---|
| 649 | uniformBufferInfoList[i].buffer = uniformBuffers[i];
|
---|
| 650 | uniformBufferInfoList[i].offset = 0;
|
---|
| 651 | uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
|
---|
| 652 | }
|
---|
| 653 | }
|
---|
| 654 |
|
---|
[f94eea9] | 655 | void VulkanGame::cleanupSwapChain() {
|
---|
[b794178] | 656 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
| 657 | pipeline.cleanup();
|
---|
| 658 | }
|
---|
| 659 |
|
---|
[6fc24c7] | 660 | vkDestroyRenderPass(device, renderPass, nullptr);
|
---|
| 661 |
|
---|
[b794178] | 662 | for (VkImageView imageView : swapChainImageViews) {
|
---|
[f94eea9] | 663 | vkDestroyImageView(device, imageView, nullptr);
|
---|
| 664 | }
|
---|
| 665 |
|
---|
| 666 | vkDestroySwapchainKHR(device, swapChain, nullptr);
|
---|
[e83b155] | 667 |
|
---|
| 668 | for (size_t i = 0; i < swapChainImages.size(); i++) {
|
---|
| 669 | vkDestroyBuffer(device, uniformBuffers[i], nullptr);
|
---|
| 670 | vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
|
---|
| 671 | }
|
---|
[90a424f] | 672 | }
|
---|