source: opengl-game/vulkan-ref.cpp@ 40995d3

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

Merge branch 'master' of medievaltech.com:opengl-game

  • Property mode set to 100644
File size: 84.6 KB
RevLine 
[f00ee54]1#define STB_IMAGE_IMPLEMENTATION
2#include "stb_image.h" // TODO: Probably switch to SDL_image
[826df16]3
4//#define _USE_MATH_DEFINES // Will be needed when/if I need to # include <cmath>
[03f4c64]5
6#define GLM_FORCE_RADIANS
[fba08f2]7#define GLM_FORCE_DEPTH_ZERO_TO_ONE
[f00ee54]8
[80edd70]9#include <glm/glm.hpp>
[de32fda]10#include <glm/gtc/matrix_transform.hpp>
[03f4c64]11
12#include <iostream>
[80edd70]13#include <fstream>
14#include <algorithm>
15#include <vector>
16#include <array>
[0e6ecf3]17#include <set>
[80edd70]18#include <optional>
[de32fda]19#include <chrono>
[03f4c64]20
[7fc5e27]21#include "consts.hpp"
[203ab1b]22#include "utils.hpp"
[03f4c64]23
[f00ee54]24#include "game-gui-sdl.hpp"
25
26using namespace std;
27using namespace glm;
[e1a7f5a]28
[826df16]29const int SCREEN_WIDTH = 800;
30const int SCREEN_HEIGHT = 600;
31
[47bff4c]32const int MAX_FRAMES_IN_FLIGHT = 2;
33
[90a424f]34/*** START OF REFACTORED CODE ***/
[826df16]35#ifdef NDEBUG
36 const bool enableValidationLayers = false;
37#else
38 const bool enableValidationLayers = true;
39#endif
40
[bfd620e]41const vector<const char*> validationLayers = {
42 "VK_LAYER_KHRONOS_validation"
43};
44
45const vector<const char*> deviceExtensions = {
46 VK_KHR_SWAPCHAIN_EXTENSION_NAME
47};
48
[909b51a]49struct QueueFamilyIndices {
50 optional<uint32_t> graphicsFamily;
[b3671b5]51 optional<uint32_t> presentFamily;
[909b51a]52
53 bool isComplete() {
[b3671b5]54 return graphicsFamily.has_value() && presentFamily.has_value();
[909b51a]55 }
56};
57
[bfd620e]58struct SwapChainSupportDetails {
59 VkSurfaceCapabilitiesKHR capabilities;
60 vector<VkSurfaceFormatKHR> formats;
61 vector<VkPresentModeKHR> presentModes;
62};
[90a424f]63/*** END OF REFACTORED CODE ***/
[bfd620e]64
[80edd70]65struct Vertex {
[adcd252]66 glm::vec3 pos;
[80edd70]67 glm::vec3 color;
[fba08f2]68 glm::vec2 texCoord;
[f00ee54]69};
[80edd70]70
[f00ee54]71struct OverlayVertex {
72 glm::vec3 pos;
73 glm::vec2 texCoord;
[80edd70]74};
75
[de32fda]76struct UniformBufferObject {
[f00ee54]77 alignas(16) mat4 model;
78 alignas(16) mat4 view;
79 alignas(16) mat4 proj;
[de32fda]80};
81
[721e8be]82struct DescriptorInfo {
83 VkDescriptorType type;
84 VkShaderStageFlags stageFlags;
85
86 vector<VkDescriptorBufferInfo>* bufferDataList;
87 VkDescriptorImageInfo* imageData;
88};
89
[b8b32bd]90struct GraphicsPipelineInfo {
[d22ae72]91 VkPipelineLayout pipelineLayout;
[b8b32bd]92 VkPipeline pipeline;
93
[f00ee54]94 VkVertexInputBindingDescription bindingDescription;
95 vector<VkVertexInputAttributeDescription> attributeDescriptions;
96
[721e8be]97 vector<DescriptorInfo> descriptorInfoList;
98
[d22ae72]99 VkDescriptorPool descriptorPool;
100 VkDescriptorSetLayout descriptorSetLayout;
101 vector<VkDescriptorSet> descriptorSets;
102
[f00ee54]103 size_t numVertices; // Currently unused
[7563b8a]104 size_t vertexCapacity;
[c8b0357]105 VkBuffer vertexBuffer;
106 VkDeviceMemory vertexBufferMemory;
107
[f00ee54]108 size_t numIndices;
[7563b8a]109 size_t indexCapacity;
[c8b0357]110 VkBuffer indexBuffer;
111 VkDeviceMemory indexBufferMemory;
[80edd70]112};
113
[cabdd5c]114/*** START OF REFACTORED CODE ***/
[b6127d2]115VkResult CreateDebugUtilsMessengerEXT(VkInstance instance,
116 const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
117 const VkAllocationCallbacks* pAllocator,
118 VkDebugUtilsMessengerEXT* pDebugMessenger) {
[621664a]119 auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
[b6127d2]120
121 if (func != nullptr) {
122 return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
123 } else {
124 return VK_ERROR_EXTENSION_NOT_PRESENT;
125 }
126}
127
[80de39d]128void DestroyDebugUtilsMessengerEXT(VkInstance instance,
129 VkDebugUtilsMessengerEXT debugMessenger,
130 const VkAllocationCallbacks* pAllocator) {
[621664a]131 auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
[80de39d]132
133 if (func != nullptr) {
134 func(instance, debugMessenger, pAllocator);
135 }
136}
137
[826df16]138class VulkanGame {
139 public:
140 void run() {
141 if (initWindow() == RTWO_ERROR) {
142 return;
143 }
144 initVulkan();
145 mainLoop();
146 cleanup();
147 }
[621664a]148
[826df16]149 private:
[98f3232]150 GameGui* gui = new GameGui_SDL();
[cabdd5c]151
[c8c6da8]152 SDL_version sdlVersion;
[80de39d]153 SDL_Window* window = nullptr;
[5f3dba8]154 SDL_Renderer* gRenderer = nullptr;
[cabdd5c]155/*** END OF REFACTORED CODE ***/
[5f3dba8]156 SDL_Texture* uiOverlay = nullptr;
157
158 TTF_Font* gFont = nullptr;
159 SDL_Texture* uiText = nullptr;
160 SDL_Texture* uiImage = nullptr;
161
[cabdd5c]162/*** START OF REFACTORED CODE ***/
[826df16]163 VkInstance instance;
[b6127d2]164 VkDebugUtilsMessengerEXT debugMessenger;
[b3671b5]165 VkSurfaceKHR surface;
[5f3dba8]166
[909b51a]167 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
168 VkDevice device;
[b3671b5]169
[909b51a]170 VkQueue graphicsQueue;
[b3671b5]171 VkQueue presentQueue;
[826df16]172
[bfd620e]173 VkSwapchainKHR swapChain;
174 vector<VkImage> swapChainImages;
175 VkFormat swapChainImageFormat;
176 VkExtent2D swapChainExtent;
177 vector<VkImageView> swapChainImageViews;
[f94eea9]178/*** END OF REFACTORED CODE ***/
[621664a]179 vector<VkFramebuffer> swapChainFramebuffers;
180
[6fc24c7]181/*** START OF REFACTORED CODE ***/
[be34c9a]182 VkRenderPass renderPass;
[1187ef5]183
[f5d5686]184 VkCommandPool commandPool;
[fa9fa1c]185/*** END OF REFACTORED CODE ***/
[1187ef5]186 vector<VkCommandBuffer> commandBuffers;
187
188 // The images and the sampler are used to store data for specific attributes. I probably
189 // want to keep them separate from the GraphicsPipelineInfo objects and start passing
190 // references to them once I start defining uniform and varying attributes in GraphicsPipelineInfo objects
[f5d5686]191
[adcd252]192 VkImage depthImage;
193 VkDeviceMemory depthImageMemory;
194 VkImageView depthImageView;
195
[f5d5686]196 VkImage textureImage;
197 VkDeviceMemory textureImageMemory;
[fba08f2]198 VkImageView textureImageView;
[69dccfe]199
200 VkImage overlayImage;
201 VkDeviceMemory overlayImageMemory;
202 VkImageView overlayImageView;
203
[e1a7f5a]204 VkImage sdlOverlayImage;
205 VkDeviceMemory sdlOverlayImageMemory;
206 VkImageView sdlOverlayImageView;
207
[fba08f2]208 VkSampler textureSampler;
[f5d5686]209
[1187ef5]210 // These are currently to store the MVP matrix
211 // I should figure out if it makes sense to use them for other uniforms in the future
212 // If not, I should rename them to better indicate their puprose.
213 // I should also decide if I can use these for all shaders, or if I need a separapte set of buffers for each one
[de32fda]214 vector<VkBuffer> uniformBuffers;
215 vector<VkDeviceMemory> uniformBuffersMemory;
216
[721e8be]217 VkDescriptorImageInfo sceneImageInfo;
218 VkDescriptorImageInfo overlayImageInfo;
219
220 vector<VkDescriptorBufferInfo> uniformBufferInfoList;
221
[1187ef5]222 GraphicsPipelineInfo scenePipeline;
223 GraphicsPipelineInfo overlayPipeline;
[47bff4c]224
225 vector<VkSemaphore> imageAvailableSemaphores;
226 vector<VkSemaphore> renderFinishedSemaphores;
227 vector<VkFence> inFlightFences;
228
229 size_t currentFrame = 0;
[ebeb3aa]230
[7563b8a]231 size_t numPlanes = 0; // temp
232
[0e09340]233/*** START OF REFACTORED CODE ***/
[75108ef]234 bool framebufferResized = false;
235
[826df16]236 bool initWindow() {
[7fc5e27]237 if (gui->init() == RTWO_ERROR) {
[826df16]238 cout << "UI library could not be initialized!" << endl;
[5f3dba8]239 cout << SDL_GetError() << endl;
[826df16]240 return RTWO_ERROR;
[5f3dba8]241 }
242 cout << "GUI init succeeded" << endl;
[826df16]243
[91c89f7]244 window = (SDL_Window*) gui->createWindow("Vulkan Game", SCREEN_WIDTH, SCREEN_HEIGHT, true);
[5f3dba8]245 if (window == nullptr) {
246 cout << "Window could not be created!" << endl;
247 return RTWO_ERROR;
248 }
249
250 gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
251 if (gRenderer == nullptr) {
252 cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << endl;
253 return RTWO_ERROR;
254 }
[cabdd5c]255/*** END OF REFACTORED CODE ***/
[5f3dba8]256
[c8c6da8]257 SDL_VERSION(&sdlVersion);
258
259 // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
260 // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
261 // 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
262 // until the homebrew recipe is updated
263 if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
264 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);
265 } else {
266 uiOverlay = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
267 }
268
[5f3dba8]269 if (uiOverlay == nullptr) {
270 cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
271 }
272 if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
273 cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
274 }
275
276 gFont = TTF_OpenFont("fonts/lazy.ttf", 28);
277 if (gFont == nullptr) {
278 cout << "Failed to load lazy font! SDL_ttf Error: " << TTF_GetError() << endl;
279 return RTWO_ERROR;
280 }
281
282 SDL_Color textColor = { 0, 0, 0 };
283
284 SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, "Great sucess!", textColor);
285 if (textSurface == nullptr) {
286 cout << "Unable to render text surface! SDL_ttf Error: " << TTF_GetError() << endl;
287 return RTWO_ERROR;
288 }
289
290 uiText = SDL_CreateTextureFromSurface(gRenderer, textSurface);
291 if (uiText == nullptr) {
292 cout << "Unable to create texture from rendered text! SDL Error: " << SDL_GetError() << endl;
293 SDL_FreeSurface(textSurface);
294 return RTWO_ERROR;
295 }
296
297 SDL_FreeSurface(textSurface);
298
299 // TODO: Load a PNG instead
300 SDL_Surface* uiImageSurface = SDL_LoadBMP("assets/images/spaceship.bmp");
301 if (uiImageSurface == nullptr) {
302 cout << "Unable to load image " << "spaceship.bmp" << "! SDL Error: " << SDL_GetError() << endl;
303 return RTWO_ERROR;
[826df16]304 }
[5f3dba8]305
306 uiImage = SDL_CreateTextureFromSurface(gRenderer, uiImageSurface);
307 if (uiImage == nullptr) {
308 cout << "Unable to create texture from BMP surface! SDL Error: " << SDL_GetError() << endl;
309 SDL_FreeSurface(uiImageSurface);
310 return RTWO_ERROR;
311 }
312
313 SDL_FreeSurface(uiImageSurface);
314
315 return RTWO_SUCCESS;
[826df16]316 }
317
[cabdd5c]318/*** START OF REFACTORED CODE ***/
[826df16]319 void initVulkan() {
320 createInstance();
[7dcd925]321 setupDebugMessenger();
[b3671b5]322 createSurface();
[909b51a]323 pickPhysicalDevice();
324 createLogicalDevice();
[bfd620e]325 createSwapChain();
326 createImageViews();
[be34c9a]327 createRenderPass();
[d22ae72]328
[47bff4c]329 createCommandPool();
[fa9fa1c]330/*** END OF REFACTORED CODE ***/
[1187ef5]331
[a0da009]332 // THIS SECTION IS WHERE TEXTURES ARE CREATED, MAYBE SPLIT IT OFF INTO A SEPARATE FUNCTION
333 // MAY WANT TO CREATE A STRUCT TO HOLD SIMILAR VARIABLES< LIKE THOSE FOR A TEXTURE
334
[69dccfe]335 createImageResources("textures/texture.jpg", textureImage, textureImageMemory, textureImageView);
[e1a7f5a]336 createImageResourcesFromSDLTexture(uiOverlay, sdlOverlayImage, sdlOverlayImageMemory, sdlOverlayImageView);
[fba08f2]337 createTextureSampler();
[c8b0357]338
[721e8be]339 sceneImageInfo = {};
340 sceneImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
341 sceneImageInfo.imageView = textureImageView;
342 sceneImageInfo.sampler = textureSampler;
343
344 overlayImageInfo = {};
345 overlayImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
346 overlayImageInfo.imageView = sdlOverlayImageView;
347 overlayImageInfo.sampler = textureSampler;
348
[a0da009]349 // SHADER-SPECIFIC STUFF STARTS HERE
350
[f00ee54]351 vector<Vertex> sceneVertices = {
[c8b0357]352 {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
353 {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
354 {{ 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
355 {{-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
356
357 {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
358 {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
359 {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
360 {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
[f00ee54]361 };
362 vector<uint16_t> sceneIndices = {
[e5d4aca]363 0, 1, 2, 2, 3, 0,
364 4, 5, 6, 6, 7, 4
[f00ee54]365 };
366
367 initGraphicsPipelineInfo(scenePipeline,
368 sceneVertices.data(), sizeof(Vertex), sceneVertices.size(),
369 sceneIndices.data(), sizeof(uint16_t), sceneIndices.size());
370
371 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
372 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
373 addAttributeDescription(scenePipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
374
[721e8be]375 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList, nullptr);
376 addDescriptorInfo(scenePipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &sceneImageInfo);
377
378 createDescriptorSetLayout(scenePipeline);
[c8b0357]379
[7563b8a]380 numPlanes = 2;
[f00ee54]381
382 vector<OverlayVertex> overlayVertices = {
383 {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
384 {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
385 {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
386 {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
387 };
388 vector<uint16_t> overlayIndices = {
389 0, 1, 2, 2, 3, 0
390 };
391
392 initGraphicsPipelineInfo(overlayPipeline,
393 overlayVertices.data(), sizeof(OverlayVertex), overlayVertices.size(),
394 overlayIndices.data(), sizeof(uint16_t), overlayIndices.size());
395
396 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
397 addAttributeDescription(overlayPipeline, VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
398
[721e8be]399 addDescriptorInfo(overlayPipeline, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr, &overlayImageInfo);
400
401 createDescriptorSetLayout(overlayPipeline);
[c8b0357]402
[e5d4aca]403 createBufferResources();
[d22ae72]404
[47bff4c]405 createSyncObjects();
[826df16]406 }
407
408 void createInstance() {
[b6127d2]409 if (enableValidationLayers && !checkValidationLayerSupport()) {
410 throw runtime_error("validation layers requested, but not available!");
411 }
412
[826df16]413 VkApplicationInfo appInfo = {};
414 appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
415 appInfo.pApplicationName = "Vulkan Game";
416 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
417 appInfo.pEngineName = "No Engine";
418 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
419 appInfo.apiVersion = VK_API_VERSION_1_0;
420
421 VkInstanceCreateInfo createInfo = {};
422 createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
423 createInfo.pApplicationInfo = &appInfo;
424
[a8f0577]425 vector<const char*> extensions = getRequiredExtensions();
[b6127d2]426 createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
427 createInfo.ppEnabledExtensionNames = extensions.data();
[826df16]428
[8667f76]429 cout << endl << "Extensions:" << endl;
[b3671b5]430 for (const char* extensionName : extensions) {
431 cout << extensionName << endl;
432 }
433 cout << endl;
434
[80de39d]435 VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
[b6127d2]436 if (enableValidationLayers) {
437 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
438 createInfo.ppEnabledLayerNames = validationLayers.data();
[80de39d]439
440 populateDebugMessengerCreateInfo(debugCreateInfo);
441 createInfo.pNext = &debugCreateInfo;
[b6127d2]442 } else {
443 createInfo.enabledLayerCount = 0;
[80de39d]444
445 createInfo.pNext = nullptr;
[b6127d2]446 }
[826df16]447
448 if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
449 throw runtime_error("failed to create instance!");
450 }
451 }
452
[621664a]453 bool checkValidationLayerSupport() {
454 uint32_t layerCount;
455 vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
456
457 vector<VkLayerProperties> availableLayers(layerCount);
458 vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
459
460 for (const char* layerName : validationLayers) {
461 bool layerFound = false;
462
463 for (const auto& layerProperties : availableLayers) {
464 if (strcmp(layerName, layerProperties.layerName) == 0) {
465 layerFound = true;
466 break;
467 }
468 }
469
470 if (!layerFound) {
471 return false;
472 }
473 }
474
475 return true;
476 }
477
[cabdd5c]478/*** START OF REFACTORED CODE ***/
[621664a]479 vector<const char*> getRequiredExtensions() {
[7fc5e27]480 vector<const char*> extensions = gui->getRequiredExtensions();
[621664a]481
482 if (enableValidationLayers) {
483 extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
484 }
485
486 return extensions;
487 }
488
[80de39d]489 void setupDebugMessenger() {
490 if (!enableValidationLayers) return;
491
492 VkDebugUtilsMessengerCreateInfoEXT createInfo;
493 populateDebugMessengerCreateInfo(createInfo);
[b6127d2]494
495 if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
[621664a]496 throw runtime_error("failed to set up debug messenger!");
[b6127d2]497 }
498 }
499
[621664a]500 void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
501 createInfo = {};
502 createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
503 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;
504 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;
505 createInfo.pfnUserCallback = debugCallback;
506 }
507
[b3671b5]508 void createSurface() {
[7fc5e27]509 if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
[b3671b5]510 throw runtime_error("failed to create window surface!");
511 }
512 }
513
[909b51a]514 void pickPhysicalDevice() {
515 uint32_t deviceCount = 0;
516 vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
517
518 if (deviceCount == 0) {
519 throw runtime_error("failed to find GPUs with Vulkan support!");
520 }
521
522 vector<VkPhysicalDevice> devices(deviceCount);
523 vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
524
525 cout << endl << "Graphics cards:" << endl;
526 for (const VkPhysicalDevice& device : devices) {
527 if (isDeviceSuitable(device)) {
528 physicalDevice = device;
529 break;
530 }
531 }
532 cout << endl;
533
534 if (physicalDevice == VK_NULL_HANDLE) {
535 throw runtime_error("failed to find a suitable GPU!");
536 }
537 }
538
539 bool isDeviceSuitable(VkPhysicalDevice device) {
540 VkPhysicalDeviceProperties deviceProperties;
541 vkGetPhysicalDeviceProperties(device, &deviceProperties);
542
543 cout << "Device: " << deviceProperties.deviceName << endl;
544
545 QueueFamilyIndices indices = findQueueFamilies(device);
[bfd620e]546 bool extensionsSupported = checkDeviceExtensionSupport(device);
547 bool swapChainAdequate = false;
548
549 if (extensionsSupported) {
550 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
551 swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
552 }
553
[fba08f2]554 VkPhysicalDeviceFeatures supportedFeatures;
555 vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
556
557 return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
[bfd620e]558 }
559
560 bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
561 uint32_t extensionCount;
562 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
563
564 vector<VkExtensionProperties> availableExtensions(extensionCount);
565 vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
566
567 set<string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
568
569 for (const auto& extension : availableExtensions) {
570 requiredExtensions.erase(extension.extensionName);
571 }
572
573 return requiredExtensions.empty();
[909b51a]574 }
575
576 void createLogicalDevice() {
577 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
578
[b3671b5]579 vector<VkDeviceQueueCreateInfo> queueCreateInfos;
580 set<uint32_t> uniqueQueueFamilies = {indices.graphicsFamily.value(), indices.presentFamily.value()};
[909b51a]581
582 float queuePriority = 1.0f;
[b3671b5]583 for (uint32_t queueFamily : uniqueQueueFamilies) {
584 VkDeviceQueueCreateInfo queueCreateInfo = {};
585 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
586 queueCreateInfo.queueFamilyIndex = queueFamily;
587 queueCreateInfo.queueCount = 1;
588 queueCreateInfo.pQueuePriorities = &queuePriority;
589
590 queueCreateInfos.push_back(queueCreateInfo);
591 }
[909b51a]592
593 VkPhysicalDeviceFeatures deviceFeatures = {};
[fba08f2]594 deviceFeatures.samplerAnisotropy = VK_TRUE;
[909b51a]595
596 VkDeviceCreateInfo createInfo = {};
597 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
[621664a]598 createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
[b3671b5]599 createInfo.pQueueCreateInfos = queueCreateInfos.data();
[909b51a]600
601 createInfo.pEnabledFeatures = &deviceFeatures;
602
[bfd620e]603 createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
604 createInfo.ppEnabledExtensionNames = deviceExtensions.data();
[909b51a]605
606 // These fields are ignored by up-to-date Vulkan implementations,
607 // but it's a good idea to set them for backwards compatibility
608 if (enableValidationLayers) {
609 createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
610 createInfo.ppEnabledLayerNames = validationLayers.data();
611 } else {
612 createInfo.enabledLayerCount = 0;
613 }
614
615 if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
616 throw runtime_error("failed to create logical device!");
617 }
618
619 vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
[b3671b5]620 vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
[909b51a]621 }
622
[621664a]623 void createSwapChain() {
624 SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
[a8f0577]625
[621664a]626 VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
627 VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
628 VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
[a8f0577]629
[621664a]630 uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
631 if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
632 imageCount = swapChainSupport.capabilities.maxImageCount;
[a8f0577]633 }
634
[621664a]635 VkSwapchainCreateInfoKHR createInfo = {};
636 createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
637 createInfo.surface = surface;
638 createInfo.minImageCount = imageCount;
639 createInfo.imageFormat = surfaceFormat.format;
640 createInfo.imageColorSpace = surfaceFormat.colorSpace;
641 createInfo.imageExtent = extent;
642 createInfo.imageArrayLayers = 1;
643 createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
[909b51a]644
[621664a]645 QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
646 uint32_t queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()};
[b3671b5]647
[621664a]648 if (indices.graphicsFamily != indices.presentFamily) {
649 createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
650 createInfo.queueFamilyIndexCount = 2;
651 createInfo.pQueueFamilyIndices = queueFamilyIndices;
652 } else {
653 createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
654 createInfo.queueFamilyIndexCount = 0;
655 createInfo.pQueueFamilyIndices = nullptr;
656 }
[b3671b5]657
[621664a]658 createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
659 createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
660 createInfo.presentMode = presentMode;
661 createInfo.clipped = VK_TRUE;
662 createInfo.oldSwapchain = VK_NULL_HANDLE;
[909b51a]663
[621664a]664 if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
665 throw runtime_error("failed to create swap chain!");
[909b51a]666 }
667
[621664a]668 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
669 swapChainImages.resize(imageCount);
670 vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
671
672 swapChainImageFormat = surfaceFormat.format;
673 swapChainExtent = extent;
[909b51a]674 }
675
[bfd620e]676 SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
677 SwapChainSupportDetails details;
678
679 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
680
681 uint32_t formatCount;
682 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
683
684 if (formatCount != 0) {
685 details.formats.resize(formatCount);
686 vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
687 }
688
689 uint32_t presentModeCount;
690 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
691
692 if (presentModeCount != 0) {
693 details.presentModes.resize(presentModeCount);
694 vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
695 }
696
697 return details;
698 }
699
700 VkSurfaceFormatKHR chooseSwapSurfaceFormat(const vector<VkSurfaceFormatKHR>& availableFormats) {
701 for (const auto& availableFormat : availableFormats) {
702 if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
703 return availableFormat;
704 }
705 }
706
707 return availableFormats[0];
708 }
709
710 VkPresentModeKHR chooseSwapPresentMode(const vector<VkPresentModeKHR>& availablePresentModes) {
711 VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
712
713 for (const auto& availablePresentMode : availablePresentModes) {
714 if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
715 return availablePresentMode;
[621664a]716 }
717 else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
[bfd620e]718 bestMode = availablePresentMode;
719 }
720 }
721
722 return bestMode;
723 }
724
725 VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
726 if (capabilities.currentExtent.width != numeric_limits<uint32_t>::max()) {
727 return capabilities.currentExtent;
[cabdd5c]728 } else {
[75108ef]729 VkExtent2D actualExtent = {
[cabdd5c]730 static_cast<uint32_t>(gui->getWindowWidth()),
731 static_cast<uint32_t>(gui->getWindowHeight())
[75108ef]732 };
[bfd620e]733
[f00ee54]734 actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
735 actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
[bfd620e]736
737 return actualExtent;
738 }
739 }
740
741 void createImageViews() {
742 swapChainImageViews.resize(swapChainImages.size());
743
[621664a]744 for (size_t i = 0; i < swapChainImages.size(); i++) {
[adcd252]745 swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
[bfd620e]746 }
747 }
748
[be34c9a]749 void createRenderPass() {
750 VkAttachmentDescription colorAttachment = {};
751 colorAttachment.format = swapChainImageFormat;
752 colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
753 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
754 colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
755 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
756 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
757 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
758 colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
759
760 VkAttachmentReference colorAttachmentRef = {};
761 colorAttachmentRef.attachment = 0;
762 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
763
[adcd252]764 VkAttachmentDescription depthAttachment = {};
765 depthAttachment.format = findDepthFormat();
766 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
767 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
768 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
769 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
770 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
771 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
772 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
773
774 VkAttachmentReference depthAttachmentRef = {};
775 depthAttachmentRef.attachment = 1;
776 depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
777
[be34c9a]778 VkSubpassDescription subpass = {};
779 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
780 subpass.colorAttachmentCount = 1;
781 subpass.pColorAttachments = &colorAttachmentRef;
[adcd252]782 subpass.pDepthStencilAttachment = &depthAttachmentRef;
[be34c9a]783
[621664a]784 VkSubpassDependency dependency = {};
[47bff4c]785 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
786 dependency.dstSubpass = 0;
787 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
788 dependency.srcAccessMask = 0;
789 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
790 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
791
[adcd252]792 array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
[be34c9a]793 VkRenderPassCreateInfo renderPassInfo = {};
794 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
[adcd252]795 renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
796 renderPassInfo.pAttachments = attachments.data();
[be34c9a]797 renderPassInfo.subpassCount = 1;
798 renderPassInfo.pSubpasses = &subpass;
[47bff4c]799 renderPassInfo.dependencyCount = 1;
800 renderPassInfo.pDependencies = &dependency;
[be34c9a]801
802 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
803 throw runtime_error("failed to create render pass!");
804 }
805 }
[6fc24c7]806/*** END OF REFACTORED CODE ***/
[be34c9a]807
[f00ee54]808 void initGraphicsPipelineInfo(GraphicsPipelineInfo& info,
809 const void* vertexData, int vertexSize, size_t numVertices,
810 const void* indexData, int indexSize, size_t numIndices) {
811 // Since there is only one array of vertex data, we use binding = 0
812 // I'll probably do that for the foreseeable future
813 // I can calculate the stride myself given info about all the varying attributes
814
815 info.bindingDescription.binding = 0;
816 info.bindingDescription.stride = vertexSize;
817 info.bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
818
819 info.numVertices = numVertices;
[7563b8a]820 info.vertexCapacity = numVertices * 2;
821 createVertexBuffer(info, vertexData, vertexSize);
[f00ee54]822
823 info.numIndices = numIndices;
[7563b8a]824 info.indexCapacity = numIndices * 2;
825 createIndexBuffer(info, indexData, indexSize);
[f00ee54]826 }
827
828 void addAttributeDescription(GraphicsPipelineInfo& info, VkFormat format, size_t offset) {
829 VkVertexInputAttributeDescription attributeDesc = {};
830
831 attributeDesc.binding = 0;
832 attributeDesc.location = info.attributeDescriptions.size();
833 attributeDesc.format = format;
834 attributeDesc.offset = offset;
835
836 info.attributeDescriptions.push_back(attributeDesc);
837 }
838
[721e8be]839 void addDescriptorInfo(GraphicsPipelineInfo& info, VkDescriptorType type, VkShaderStageFlags stageFlags, vector<VkDescriptorBufferInfo>* bufferData, VkDescriptorImageInfo* imageData) {
840 info.descriptorInfoList.push_back({ type, stageFlags, bufferData, imageData });
841 }
842
843 void createDescriptorSetLayout(GraphicsPipelineInfo& info) {
844 vector<VkDescriptorSetLayoutBinding> bindings(info.descriptorInfoList.size());
845
846 for (size_t i = 0; i < bindings.size(); i++) {
847 bindings[i].binding = i;
848 bindings[i].descriptorCount = 1;
849 bindings[i].descriptorType = info.descriptorInfoList[i].type;
850 bindings[i].stageFlags = info.descriptorInfoList[i].stageFlags;
851 bindings[i].pImmutableSamplers = nullptr;
852 }
853
854 VkDescriptorSetLayoutCreateInfo layoutInfo = {};
855 layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
856 layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
857 layoutInfo.pBindings = bindings.data();
858
859 if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &info.descriptorSetLayout) != VK_SUCCESS) {
860 throw runtime_error("failed to create descriptor set layout!");
861 }
862 }
863
[d22ae72]864 void createGraphicsPipeline(string vertShaderFile, string fragShaderFile, GraphicsPipelineInfo& info) {
[b8b32bd]865 auto vertShaderCode = readFile(vertShaderFile);
866 auto fragShaderCode = readFile(fragShaderFile);
[e09ad38]867
868 VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
869 VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
870
871 VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
872 vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
873 vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
874 vertShaderStageInfo.module = vertShaderModule;
875 vertShaderStageInfo.pName = "main";
876
877 VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
878 fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
879 fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
880 fragShaderStageInfo.module = fragShaderModule;
881 fragShaderStageInfo.pName = "main";
882
883 VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
884
[84216c7]885 VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
886 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
[80edd70]887
888 vertexInputInfo.vertexBindingDescriptionCount = 1;
[f00ee54]889 vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(info.attributeDescriptions.size());
890 vertexInputInfo.pVertexBindingDescriptions = &info.bindingDescription;
891 vertexInputInfo.pVertexAttributeDescriptions = info.attributeDescriptions.data();
[84216c7]892
893 VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
894 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
895 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
896 inputAssembly.primitiveRestartEnable = VK_FALSE;
897
898 VkViewport viewport = {};
899 viewport.x = 0.0f;
900 viewport.y = 0.0f;
901 viewport.width = (float) swapChainExtent.width;
902 viewport.height = (float) swapChainExtent.height;
903 viewport.minDepth = 0.0f;
904 viewport.maxDepth = 1.0f;
905
906 VkRect2D scissor = {};
907 scissor.offset = { 0, 0 };
908 scissor.extent = swapChainExtent;
909
910 VkPipelineViewportStateCreateInfo viewportState = {};
911 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
912 viewportState.viewportCount = 1;
913 viewportState.pViewports = &viewport;
914 viewportState.scissorCount = 1;
915 viewportState.pScissors = &scissor;
916
917 VkPipelineRasterizationStateCreateInfo rasterizer = {};
918 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
919 rasterizer.depthClampEnable = VK_FALSE;
920 rasterizer.rasterizerDiscardEnable = VK_FALSE;
921 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
922 rasterizer.lineWidth = 1.0f;
923 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
[c7fb883]924 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
[621664a]925 rasterizer.depthBiasEnable = VK_FALSE;
[84216c7]926
927 VkPipelineMultisampleStateCreateInfo multisampling = {};
928 multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
929 multisampling.sampleShadingEnable = VK_FALSE;
930 multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
931
932 VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
933 colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
[69dccfe]934 colorBlendAttachment.blendEnable = VK_TRUE;
935 colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
936 colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
937 colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
938 colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
939 colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
940 colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
[84216c7]941
942 VkPipelineColorBlendStateCreateInfo colorBlending = {};
943 colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
944 colorBlending.logicOpEnable = VK_FALSE;
945 colorBlending.logicOp = VK_LOGIC_OP_COPY;
946 colorBlending.attachmentCount = 1;
947 colorBlending.pAttachments = &colorBlendAttachment;
948 colorBlending.blendConstants[0] = 0.0f;
949 colorBlending.blendConstants[1] = 0.0f;
950 colorBlending.blendConstants[2] = 0.0f;
951 colorBlending.blendConstants[3] = 0.0f;
952
[adcd252]953 VkPipelineDepthStencilStateCreateInfo depthStencil = {};
954 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
955 depthStencil.depthTestEnable = VK_TRUE;
956 depthStencil.depthWriteEnable = VK_TRUE;
957 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
958 depthStencil.depthBoundsTestEnable = VK_FALSE;
959 depthStencil.minDepthBounds = 0.0f;
960 depthStencil.maxDepthBounds = 1.0f;
961 depthStencil.stencilTestEnable = VK_FALSE;
962 depthStencil.front = {};
963 depthStencil.back = {};
964
[84216c7]965 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
966 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
[de32fda]967 pipelineLayoutInfo.setLayoutCount = 1;
[d22ae72]968 pipelineLayoutInfo.pSetLayouts = &info.descriptorSetLayout;
[84216c7]969 pipelineLayoutInfo.pushConstantRangeCount = 0;
970
[d22ae72]971 if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &info.pipelineLayout) != VK_SUCCESS) {
[84216c7]972 throw runtime_error("failed to create pipeline layout!");
973 }
974
[fd70015]975 VkGraphicsPipelineCreateInfo pipelineInfo = {};
976 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
977 pipelineInfo.stageCount = 2;
978 pipelineInfo.pStages = shaderStages;
979 pipelineInfo.pVertexInputState = &vertexInputInfo;
980 pipelineInfo.pInputAssemblyState = &inputAssembly;
981 pipelineInfo.pViewportState = &viewportState;
982 pipelineInfo.pRasterizationState = &rasterizer;
983 pipelineInfo.pMultisampleState = &multisampling;
[adcd252]984 pipelineInfo.pDepthStencilState = &depthStencil;
[fd70015]985 pipelineInfo.pColorBlendState = &colorBlending;
986 pipelineInfo.pDynamicState = nullptr;
[d22ae72]987 pipelineInfo.layout = info.pipelineLayout;
[fd70015]988 pipelineInfo.renderPass = renderPass;
989 pipelineInfo.subpass = 0;
990 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
991 pipelineInfo.basePipelineIndex = -1;
992
[d22ae72]993 if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &info.pipeline) != VK_SUCCESS) {
[fd70015]994 throw runtime_error("failed to create graphics pipeline!");
995 }
996
[e09ad38]997 vkDestroyShaderModule(device, vertShaderModule, nullptr);
998 vkDestroyShaderModule(device, fragShaderModule, nullptr);
999 }
1000
1001 VkShaderModule createShaderModule(const vector<char>& code) {
1002 VkShaderModuleCreateInfo createInfo = {};
1003 createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1004 createInfo.codeSize = code.size();
1005 createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
1006
1007 VkShaderModule shaderModule;
1008 if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
1009 throw runtime_error("failed to create shader module!");
1010 }
1011
1012 return shaderModule;
[4befb76]1013 }
1014
[ebeb3aa]1015 void createFramebuffers() {
1016 swapChainFramebuffers.resize(swapChainImageViews.size());
1017
1018 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
[adcd252]1019 array <VkImageView, 2> attachments = {
1020 swapChainImageViews[i],
1021 depthImageView
[ebeb3aa]1022 };
1023
1024 VkFramebufferCreateInfo framebufferInfo = {};
1025 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1026 framebufferInfo.renderPass = renderPass;
[adcd252]1027 framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
1028 framebufferInfo.pAttachments = attachments.data();
[ebeb3aa]1029 framebufferInfo.width = swapChainExtent.width;
1030 framebufferInfo.height = swapChainExtent.height;
1031 framebufferInfo.layers = 1;
1032
1033 if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
1034 throw runtime_error("failed to create framebuffer!");
1035 }
1036 }
1037 }
1038
[fa9fa1c]1039/*** START OF REFACTORED CODE ***/
[47bff4c]1040 void createCommandPool() {
1041 QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
1042
1043 VkCommandPoolCreateInfo poolInfo = {};
1044 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1045 poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
1046 poolInfo.flags = 0;
1047
1048 if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
[621664a]1049 throw runtime_error("failed to create graphics command pool!");
[47bff4c]1050 }
1051 }
1052
[621664a]1053 QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) {
1054 QueueFamilyIndices indices;
1055
1056 uint32_t queueFamilyCount = 0;
1057 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
1058
1059 vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1060 vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
1061
1062 int i = 0;
1063 for (const auto& queueFamily : queueFamilies) {
1064 if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
1065 indices.graphicsFamily = i;
1066 }
1067
1068 VkBool32 presentSupport = false;
1069 vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
1070
1071 if (queueFamily.queueCount > 0 && presentSupport) {
1072 indices.presentFamily = i;
1073 }
1074
1075 if (indices.isComplete()) {
1076 break;
1077 }
1078
1079 i++;
1080 }
1081
1082 return indices;
1083 }
[90a424f]1084/*** END OF REFACTORED CODE ***/
[621664a]1085
[adcd252]1086 void createDepthResources() {
1087 VkFormat depthFormat = findDepthFormat();
1088
1089 createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL,
1090 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depthImage, depthImageMemory);
1091 depthImageView = createImageView(depthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
1092
1093 transitionImageLayout(depthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1094 }
1095
[6fc24c7]1096/*** START OF REFACTORED CODE ***/
[adcd252]1097 VkFormat findDepthFormat() {
1098 return findSupportedFormat(
1099 { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
1100 VK_IMAGE_TILING_OPTIMAL,
1101 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
1102 );
1103 }
1104
1105 VkFormat findSupportedFormat(const vector<VkFormat>& candidates, VkImageTiling tiling,
1106 VkFormatFeatureFlags features) {
1107 for (VkFormat format : candidates) {
1108 VkFormatProperties props;
1109 vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
1110
1111 if (tiling == VK_IMAGE_TILING_LINEAR &&
1112 (props.linearTilingFeatures & features) == features) {
1113 return format;
1114 } else if (tiling == VK_IMAGE_TILING_OPTIMAL &&
1115 (props.optimalTilingFeatures & features) == features) {
1116 return format;
1117 }
1118 }
1119
1120 throw runtime_error("failed to find supported format!");
1121 }
[6fc24c7]1122/*** END OF REFACTORED CODE ***/
[adcd252]1123
1124 bool hasStencilComponent(VkFormat format) {
1125 return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
1126 }
1127
[69dccfe]1128 void createImageResources(string filename, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
[eea05dd]1129 int texWidth, texHeight, texChannels;
1130
[69dccfe]1131 stbi_uc* pixels = stbi_load(filename.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
[eea05dd]1132 VkDeviceSize imageSize = texWidth * texHeight * 4;
1133
1134 if (!pixels) {
1135 throw runtime_error("failed to load texture image!");
1136 }
1137
1138 VkBuffer stagingBuffer;
1139 VkDeviceMemory stagingBufferMemory;
1140
1141 createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1142 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1143 stagingBuffer, stagingBufferMemory);
1144
1145 void* data;
1146
1147 vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
1148 memcpy(data, pixels, static_cast<size_t>(imageSize));
1149 vkUnmapMemory(device, stagingBufferMemory);
1150
1151 stbi_image_free(pixels);
1152
1153 createImage(texWidth, texHeight, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1154 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
[69dccfe]1155 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
[eea05dd]1156
[69dccfe]1157 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1158 copyBufferToImage(stagingBuffer, image, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
1159 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
[eea05dd]1160
1161 vkDestroyBuffer(device, stagingBuffer, nullptr);
[f5d5686]1162 vkFreeMemory(device, stagingBufferMemory, nullptr);
[69dccfe]1163
1164 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
[eea05dd]1165 }
1166
[e1a7f5a]1167 void createImageResourcesFromSDLTexture(SDL_Texture* texture, VkImage& image, VkDeviceMemory& imageMemory, VkImageView& view) {
1168 int a, w, h;
1169
1170 // I only need this here for the width and height, which are constants, so just use those instead
1171 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1172
1173 createImage(w, h, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
1174 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
1175 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, image, imageMemory);
1176
1177 view = createImageView(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
1178 }
1179
1180 void populateImageFromSDLTexture(SDL_Texture* texture, VkImage& image) {
[f00ee54]1181 int a, w, h;
[e1a7f5a]1182
1183 SDL_QueryTexture(texture, nullptr, &a, &w, &h);
1184
1185 VkDeviceSize imageSize = w * h * 4;
1186 unsigned char* pixels = new unsigned char[imageSize];
1187
1188 SDL_RenderReadPixels(gRenderer, nullptr, SDL_PIXELFORMAT_ABGR8888, pixels, w * 4);
1189
1190 VkBuffer stagingBuffer;
1191 VkDeviceMemory stagingBufferMemory;
1192
1193 createBuffer(imageSize,
1194 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1195 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
1196 stagingBuffer, stagingBufferMemory);
1197
1198 void* data;
1199
1200 vkMapMemory(device, stagingBufferMemory, 0, VK_WHOLE_SIZE, 0, &data);
1201 memcpy(data, pixels, static_cast<size_t>(imageSize));
1202
1203 VkMappedMemoryRange mappedMemoryRange = {};
1204 mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1205 mappedMemoryRange.memory = stagingBufferMemory;
1206 mappedMemoryRange.offset = 0;
1207 mappedMemoryRange.size = VK_WHOLE_SIZE;
1208
1209 // TODO: Should probably check that the function succeeded
1210 vkFlushMappedMemoryRanges(device, 1, &mappedMemoryRange);
1211 vkUnmapMemory(device, stagingBufferMemory);
1212
[8a40f4b]1213 delete[] pixels;
1214
[e1a7f5a]1215 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
1216 copyBufferToImage(stagingBuffer, image, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
1217 transitionImageLayout(image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
1218
1219 vkDestroyBuffer(device, stagingBuffer, nullptr);
1220 vkFreeMemory(device, stagingBufferMemory, nullptr);
1221 }
1222
[621664a]1223 void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage,
1224 VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory) {
[eea05dd]1225 VkImageCreateInfo imageInfo = {};
1226 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1227 imageInfo.imageType = VK_IMAGE_TYPE_2D;
1228 imageInfo.extent.width = width;
1229 imageInfo.extent.height = height;
1230 imageInfo.extent.depth = 1;
1231 imageInfo.mipLevels = 1;
1232 imageInfo.arrayLayers = 1;
1233 imageInfo.format = format;
1234 imageInfo.tiling = tiling;
1235 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1236 imageInfo.usage = usage;
1237 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
1238 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1239
1240 if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS) {
1241 throw runtime_error("failed to create image!");
1242 }
1243
1244 VkMemoryRequirements memRequirements;
1245 vkGetImageMemoryRequirements(device, image, &memRequirements);
1246
[621664a]1247 VkMemoryAllocateInfo allocInfo = {};
[eea05dd]1248 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1249 allocInfo.allocationSize = memRequirements.size;
1250 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
1251
1252 if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS) {
1253 throw runtime_error("failed to allocate image memory!");
1254 }
1255
1256 vkBindImageMemory(device, image, imageMemory, 0);
1257 }
1258
[621664a]1259 void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) {
[eea05dd]1260 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1261
1262 VkImageMemoryBarrier barrier = {};
1263 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1264 barrier.oldLayout = oldLayout;
1265 barrier.newLayout = newLayout;
1266 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1267 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1268 barrier.image = image;
[adcd252]1269
1270 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
1271 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1272
1273 if (hasStencilComponent(format)) {
1274 barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
1275 }
1276 } else {
1277 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1278 }
1279
[eea05dd]1280 barrier.subresourceRange.baseMipLevel = 0;
1281 barrier.subresourceRange.levelCount = 1;
1282 barrier.subresourceRange.baseArrayLayer = 0;
1283 barrier.subresourceRange.layerCount = 1;
[f5d5686]1284
1285 VkPipelineStageFlags sourceStage;
1286 VkPipelineStageFlags destinationStage;
[eea05dd]1287
1288 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
1289 barrier.srcAccessMask = 0;
1290 barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1291
1292 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1293 destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
1294 } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
1295 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1296 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
1297
1298 sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
1299 destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
[adcd252]1300 } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
1301 barrier.srcAccessMask = 0;
1302 barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
1303
1304 sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1305 destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
[eea05dd]1306 } else {
1307 throw invalid_argument("unsupported layout transition!");
1308 }
1309
1310 vkCmdPipelineBarrier(
1311 commandBuffer,
[f5d5686]1312 sourceStage, destinationStage,
[eea05dd]1313 0,
1314 0, nullptr,
1315 0, nullptr,
1316 1, &barrier
1317 );
1318
1319 endSingleTimeCommands(commandBuffer);
1320 }
1321
1322 void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) {
1323 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1324
1325 VkBufferImageCopy region = {};
1326 region.bufferOffset = 0;
1327 region.bufferRowLength = 0;
1328 region.bufferImageHeight = 0;
1329 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1330 region.imageSubresource.mipLevel = 0;
1331 region.imageSubresource.baseArrayLayer = 0;
1332 region.imageSubresource.layerCount = 1;
1333 region.imageOffset = { 0, 0, 0 };
1334 region.imageExtent = { width, height, 1 };
1335
1336 vkCmdCopyBufferToImage(
1337 commandBuffer,
1338 buffer,
1339 image,
1340 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1341 1,
1342 &region
1343 );
1344
1345 endSingleTimeCommands(commandBuffer);
1346 }
1347
[f94eea9]1348/*** START OF REFACTORED CODE ***/
[adcd252]1349 VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) {
[fba08f2]1350 VkImageViewCreateInfo viewInfo = {};
1351 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1352 viewInfo.image = image;
1353 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
1354 viewInfo.format = format;
1355
1356 viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
1357 viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
1358 viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
1359 viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
1360
[adcd252]1361 viewInfo.subresourceRange.aspectMask = aspectFlags;
[fba08f2]1362 viewInfo.subresourceRange.baseMipLevel = 0;
1363 viewInfo.subresourceRange.levelCount = 1;
1364 viewInfo.subresourceRange.baseArrayLayer = 0;
1365 viewInfo.subresourceRange.layerCount = 1;
1366
1367 VkImageView imageView;
1368 if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS) {
1369 throw runtime_error("failed to create texture image view!");
1370 }
1371
1372 return imageView;
1373 }
[f94eea9]1374/*** END OF REFACTORED CODE ***/
[fba08f2]1375
1376 void createTextureSampler() {
1377 VkSamplerCreateInfo samplerInfo = {};
1378 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1379 samplerInfo.magFilter = VK_FILTER_LINEAR;
1380 samplerInfo.minFilter = VK_FILTER_LINEAR;
1381
1382 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1383 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1384 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1385
1386 samplerInfo.anisotropyEnable = VK_TRUE;
1387 samplerInfo.maxAnisotropy = 16;
1388 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1389 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1390 samplerInfo.compareEnable = VK_FALSE;
1391 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1392 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1393 samplerInfo.mipLodBias = 0.0f;
1394 samplerInfo.minLod = 0.0f;
1395 samplerInfo.maxLod = 0.0f;
1396
1397 if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
1398 throw runtime_error("failed to create texture sampler!");
1399 }
1400 }
1401
[7563b8a]1402 void createVertexBuffer(GraphicsPipelineInfo& info, const void* vertexData, int vertexSize) {
1403 VkDeviceSize bufferSize = info.numVertices * vertexSize;
1404 VkDeviceSize bufferCapacity = info.vertexCapacity * vertexSize;
1405
[d9ef6ab]1406 VkBuffer stagingBuffer;
1407 VkDeviceMemory stagingBufferMemory;
[621664a]1408 createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
[d9ef6ab]1409 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1410 stagingBuffer, stagingBufferMemory);
1411
1412 void* data;
1413 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
[f00ee54]1414 memcpy(data, vertexData, (size_t) bufferSize);
[d9ef6ab]1415 vkUnmapMemory(device, stagingBufferMemory);
1416
[7563b8a]1417 createBuffer(bufferCapacity, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
[f00ee54]1418 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, info.vertexBuffer, info.vertexBufferMemory);
[d9ef6ab]1419
[7563b8a]1420 copyBuffer(stagingBuffer, info.vertexBuffer, 0, 0, bufferSize);
[d9ef6ab]1421
1422 vkDestroyBuffer(device, stagingBuffer, nullptr);
1423 vkFreeMemory(device, stagingBufferMemory, nullptr);
1424 }
1425
[7563b8a]1426 void createIndexBuffer(GraphicsPipelineInfo& info, const void* indexData, int indexSize) {
1427 VkDeviceSize bufferSize = info.numIndices * indexSize;
1428 VkDeviceSize bufferCapacity = info.indexCapacity * indexSize;
1429
[cae7a2c]1430 VkBuffer stagingBuffer;
1431 VkDeviceMemory stagingBufferMemory;
1432 createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1433 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1434 stagingBuffer, stagingBufferMemory);
1435
1436 void* data;
1437 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
[f00ee54]1438 memcpy(data, indexData, (size_t) bufferSize);
[cae7a2c]1439 vkUnmapMemory(device, stagingBufferMemory);
1440
[7563b8a]1441 createBuffer(bufferCapacity, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
[f00ee54]1442 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, info.indexBuffer, info.indexBufferMemory);
[cae7a2c]1443
[7563b8a]1444 copyBuffer(stagingBuffer, info.indexBuffer, 0, 0, bufferSize);
[cae7a2c]1445
1446 vkDestroyBuffer(device, stagingBuffer, nullptr);
1447 vkFreeMemory(device, stagingBufferMemory, nullptr);
1448 }
1449
[621664a]1450 void createUniformBuffers() {
1451 VkDeviceSize bufferSize = sizeof(UniformBufferObject);
1452
1453 uniformBuffers.resize(swapChainImages.size());
1454 uniformBuffersMemory.resize(swapChainImages.size());
[721e8be]1455 uniformBufferInfoList.resize(swapChainImages.size());
[621664a]1456
1457 for (size_t i = 0; i < swapChainImages.size(); i++) {
1458 createBuffer(bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
1459 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1460 uniformBuffers[i], uniformBuffersMemory[i]);
[721e8be]1461
1462 uniformBufferInfoList[i].buffer = uniformBuffers[i];
1463 uniformBufferInfoList[i].offset = 0;
1464 uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
[621664a]1465 }
1466 }
1467
1468 void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) {
[80edd70]1469 VkBufferCreateInfo bufferInfo = {};
1470 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
[d9ef6ab]1471 bufferInfo.size = size;
1472 bufferInfo.usage = usage;
[80edd70]1473 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1474
[d9ef6ab]1475 if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) {
1476 throw runtime_error("failed to create buffer!");
[80edd70]1477 }
1478
[d9ef6ab]1479 VkMemoryRequirements memRequirements;
1480 vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
[80edd70]1481
1482 VkMemoryAllocateInfo allocInfo = {};
1483 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
[d9ef6ab]1484 allocInfo.allocationSize = memRequirements.size;
1485 allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
[621664a]1486
[d9ef6ab]1487 if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) {
1488 throw runtime_error("failed to allocate buffer memory!");
[80edd70]1489 }
1490
[d9ef6ab]1491 vkBindBufferMemory(device, buffer, bufferMemory, 0);
1492 }
[80edd70]1493
[7563b8a]1494 void copyDataToBuffer(const void* srcData, VkBuffer dst, VkDeviceSize dstOffset, VkDeviceSize dataSize) {
1495 VkBuffer stagingBuffer;
1496 VkDeviceMemory stagingBufferMemory;
1497 createBuffer(dataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1498 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1499 stagingBuffer, stagingBufferMemory);
1500
1501 void* data;
1502 vkMapMemory(device, stagingBufferMemory, 0, dataSize, 0, &data);
1503 memcpy(data, srcData, (size_t) dataSize);
1504 vkUnmapMemory(device, stagingBufferMemory);
1505
1506 copyBuffer(stagingBuffer, dst, 0, dstOffset, dataSize);
1507
1508 vkDestroyBuffer(device, stagingBuffer, nullptr);
1509 vkFreeMemory(device, stagingBufferMemory, nullptr);
1510 }
1511
1512 void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize srcOffset, VkDeviceSize dstOffset,
1513 VkDeviceSize size) {
[eea05dd]1514 VkCommandBuffer commandBuffer = beginSingleTimeCommands();
1515
[7563b8a]1516 VkBufferCopy copyRegion = { srcOffset, dstOffset, size };
[eea05dd]1517 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
1518
1519 endSingleTimeCommands(commandBuffer);
1520 }
1521
1522 VkCommandBuffer beginSingleTimeCommands() {
[d9ef6ab]1523 VkCommandBufferAllocateInfo allocInfo = {};
1524 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1525 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1526 allocInfo.commandPool = commandPool;
1527 allocInfo.commandBufferCount = 1;
1528
1529 VkCommandBuffer commandBuffer;
1530 vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
1531
1532 VkCommandBufferBeginInfo beginInfo = {};
1533 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1534 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1535
1536 vkBeginCommandBuffer(commandBuffer, &beginInfo);
1537
[eea05dd]1538 return commandBuffer;
1539 }
[d9ef6ab]1540
[eea05dd]1541 void endSingleTimeCommands(VkCommandBuffer commandBuffer) {
[d9ef6ab]1542 vkEndCommandBuffer(commandBuffer);
1543
1544 VkSubmitInfo submitInfo = {};
1545 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1546 submitInfo.commandBufferCount = 1;
1547 submitInfo.pCommandBuffers = &commandBuffer;
1548
1549 vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
1550 vkQueueWaitIdle(graphicsQueue);
1551
1552 vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
[80edd70]1553 }
1554
1555 uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) {
1556 VkPhysicalDeviceMemoryProperties memProperties;
1557 vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
1558
1559 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
1560 if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) {
1561 return i;
1562 }
1563 }
1564
1565 throw runtime_error("failed to find suitable memory type!");
1566 }
1567
[721e8be]1568 void createDescriptorPool(GraphicsPipelineInfo& info) {
1569 vector<VkDescriptorPoolSize> poolSizes(info.descriptorInfoList.size());
[c7fb883]1570
[721e8be]1571 for (size_t i = 0; i < poolSizes.size(); i++) {
1572 poolSizes[i].type = info.descriptorInfoList[i].type;
1573 poolSizes[i].descriptorCount = static_cast<uint32_t>(swapChainImages.size());
[c7fb883]1574 }
[e5d4aca]1575
1576 VkDescriptorPoolCreateInfo poolInfo = {};
1577 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1578 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
1579 poolInfo.pPoolSizes = poolSizes.data();
1580 poolInfo.maxSets = static_cast<uint32_t>(swapChainImages.size());
1581
1582 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &info.descriptorPool) != VK_SUCCESS) {
1583 throw runtime_error("failed to create descriptor pool!");
1584 }
1585 }
1586
[721e8be]1587 void createDescriptorSets(GraphicsPipelineInfo& info) {
[e5d4aca]1588 vector<VkDescriptorSetLayout> layouts(swapChainImages.size(), info.descriptorSetLayout);
1589
1590 VkDescriptorSetAllocateInfo allocInfo = {};
1591 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1592 allocInfo.descriptorPool = info.descriptorPool;
1593 allocInfo.descriptorSetCount = static_cast<uint32_t>(swapChainImages.size());
1594 allocInfo.pSetLayouts = layouts.data();
1595
1596 info.descriptorSets.resize(swapChainImages.size());
1597 if (vkAllocateDescriptorSets(device, &allocInfo, info.descriptorSets.data()) != VK_SUCCESS) {
1598 throw runtime_error("failed to allocate descriptor sets!");
1599 }
1600
1601 for (size_t i = 0; i < swapChainImages.size(); i++) {
[721e8be]1602 vector<VkWriteDescriptorSet> descriptorWrites(info.descriptorInfoList.size());
1603
1604 for (size_t j = 0; j < descriptorWrites.size(); j++) {
1605 descriptorWrites[j].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1606 descriptorWrites[j].dstSet = info.descriptorSets[i];
1607 descriptorWrites[j].dstBinding = j;
1608 descriptorWrites[j].dstArrayElement = 0;
1609 descriptorWrites[j].descriptorType = info.descriptorInfoList[j].type;
1610 descriptorWrites[j].descriptorCount = 1;
1611 descriptorWrites[j].pBufferInfo = nullptr;
1612 descriptorWrites[j].pImageInfo = nullptr;
1613 descriptorWrites[j].pTexelBufferView = nullptr;
1614
1615 switch (descriptorWrites[j].descriptorType) {
1616 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1617 descriptorWrites[j].pBufferInfo = &(*info.descriptorInfoList[j].bufferDataList)[i];
1618 break;
1619 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
1620 descriptorWrites[j].pImageInfo = info.descriptorInfoList[j].imageData;
1621 break;
1622 default:
1623 cout << "Unknown descriptor type: " << descriptorWrites[j].descriptorType << endl;
1624 }
1625 }
[e5d4aca]1626
1627 vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
1628 }
1629 }
1630
[47bff4c]1631 void createCommandBuffers() {
1632 commandBuffers.resize(swapChainFramebuffers.size());
1633
1634 VkCommandBufferAllocateInfo allocInfo = {};
1635 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1636 allocInfo.commandPool = commandPool;
1637 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
[621664a]1638 allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
[47bff4c]1639
1640 if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
[621664a]1641 throw runtime_error("failed to allocate command buffers!");
[47bff4c]1642 }
1643
1644 for (size_t i = 0; i < commandBuffers.size(); i++) {
1645 VkCommandBufferBeginInfo beginInfo = {};
1646 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1647 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
1648 beginInfo.pInheritanceInfo = nullptr;
1649
1650 if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
1651 throw runtime_error("failed to begin recording command buffer!");
1652 }
1653
1654 VkRenderPassBeginInfo renderPassInfo = {};
1655 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1656 renderPassInfo.renderPass = renderPass;
1657 renderPassInfo.framebuffer = swapChainFramebuffers[i];
1658 renderPassInfo.renderArea.offset = { 0, 0 };
1659 renderPassInfo.renderArea.extent = swapChainExtent;
1660
[adcd252]1661 array<VkClearValue, 2> clearValues = {};
[f00ee54]1662 clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
[adcd252]1663 clearValues[1].depthStencil = { 1.0f, 0 };
1664
1665 renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
1666 renderPassInfo.pClearValues = clearValues.data();
[47bff4c]1667
1668 vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
[621664a]1669
[d22ae72]1670 createGraphicsPipelineCommands(scenePipeline, i);
1671 createGraphicsPipelineCommands(overlayPipeline, i);
[621664a]1672
[47bff4c]1673 vkCmdEndRenderPass(commandBuffers[i]);
1674
1675 if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
1676 throw runtime_error("failed to record command buffer!");
1677 }
1678 }
1679 }
1680
[1187ef5]1681 void createGraphicsPipelineCommands(GraphicsPipelineInfo& info, uint32_t currentImage) {
1682 vkCmdBindPipeline(commandBuffers[currentImage], VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline);
1683 vkCmdBindDescriptorSets(commandBuffers[currentImage], VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipelineLayout, 0, 1,
1684 &info.descriptorSets[currentImage], 0, nullptr);
[d22ae72]1685
1686 VkBuffer vertexBuffers[] = { info.vertexBuffer };
1687 VkDeviceSize offsets[] = { 0 };
[1187ef5]1688 vkCmdBindVertexBuffers(commandBuffers[currentImage], 0, 1, vertexBuffers, offsets);
[d22ae72]1689
[1187ef5]1690 vkCmdBindIndexBuffer(commandBuffers[currentImage], info.indexBuffer, 0, VK_INDEX_TYPE_UINT16);
[d22ae72]1691
[1187ef5]1692 vkCmdDrawIndexed(commandBuffers[currentImage], static_cast<uint32_t>(info.numIndices), 1, 0, 0, 0);
[d22ae72]1693 }
1694
[47bff4c]1695 void createSyncObjects() {
1696 imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
1697 renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
1698 inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
1699
1700 VkSemaphoreCreateInfo semaphoreInfo = {};
1701 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
1702
1703 VkFenceCreateInfo fenceInfo = {};
1704 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1705 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1706
1707 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1708 if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
[1187ef5]1709 vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
1710 vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
[47bff4c]1711 throw runtime_error("failed to create synchronization objects for a frame!");
1712 }
1713 }
1714 }
1715
[7563b8a]1716 bool addObjectToScene(GraphicsPipelineInfo& info,
1717 const void* vertexData, int vertexSize, size_t numVertices,
1718 vector<uint16_t>& indices, size_t numIndices) {
1719 int indexSize = sizeof(uint16_t);
1720
1721 for (uint16_t& idx : indices) {
1722 idx += info.numVertices;
1723 }
1724
1725 if (info.numVertices + numVertices > info.vertexCapacity) {
1726 cout << "ERROR: Need to resize vertex buffers" << endl;
1727 } else if (info.numIndices + numIndices > info.indexCapacity) {
1728 cout << "ERROR: Need to resize index buffers" << endl;
1729 } else {
1730 cout << "Added object to scene" << endl;
1731
1732 copyDataToBuffer(vertexData, info.vertexBuffer, info.numVertices * vertexSize, numVertices * vertexSize);
1733 info.numVertices += numVertices;
1734
1735 copyDataToBuffer(indices.data(), info.indexBuffer, info.numIndices * indexSize, numIndices * indexSize);
1736 info.numIndices += numIndices;
1737
1738 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
1739 createCommandBuffers();
1740
1741 return true;
1742 }
1743
1744 return false;
1745 }
1746
[c1c2021]1747/*** START OF REFACTORED CODE ***/
[826df16]1748 void mainLoop() {
1749 // TODO: Create some generic event-handling functions in game-gui-*
1750 SDL_Event e;
1751 bool quit = false;
1752
[7dcd925]1753 while (!quit) {
[826df16]1754 while (SDL_PollEvent(&e)) {
1755 if (e.type == SDL_QUIT) {
1756 quit = true;
1757 }
1758 if (e.type == SDL_KEYDOWN) {
[7563b8a]1759 if (e.key.keysym.sym == SDLK_SPACE) {
1760 float zOffset = -0.5f + (0.5f * numPlanes);
1761 vector<Vertex> vertices = {
1762 {{-0.5f, -0.5f, zOffset}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
1763 {{ 0.5f, -0.5f, zOffset}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
1764 {{ 0.5f, 0.5f, zOffset}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
1765 {{-0.5f, 0.5f, zOffset}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
1766 };
1767 vector<uint16_t> indices = {
1768 0, 1, 2, 2, 3, 0
1769 };
1770
1771 if (addObjectToScene(scenePipeline,
1772 vertices.data(), sizeof(Vertex), vertices.size(),
1773 indices, indices.size())) {
1774 numPlanes++;
1775 }
1776 } else if (e.key.keysym.sym == SDLK_ESCAPE) {
[91c89f7]1777 quit = true;
1778 }
[826df16]1779 }
1780 if (e.type == SDL_MOUSEBUTTONDOWN) {
1781 quit = true;
1782 }
[75108ef]1783 if (e.type == SDL_WINDOWEVENT) {
[1187ef5]1784 if (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED ||
1785 e.window.event == SDL_WINDOWEVENT_MINIMIZED) {
[75108ef]1786 framebufferResized = true;
1787 }
1788 }
[47bff4c]1789 }
[321272c]1790
[5f3dba8]1791 drawUI();
[e1a7f5a]1792
1793 drawFrame();
[47bff4c]1794 }
1795
1796 vkDeviceWaitIdle(device);
1797 }
1798
1799 void drawFrame() {
[f94eea9]1800/*** END OF REFACTORED CODE ***/
[47bff4c]1801 vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
1802
1803 uint32_t imageIndex;
1804
[621664a]1805 VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
1806 imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
[75108ef]1807
1808 if (result == VK_ERROR_OUT_OF_DATE_KHR) {
1809 recreateSwapChain();
1810 return;
1811 } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
1812 throw runtime_error("failed to acquire swap chain image!");
1813 }
[47bff4c]1814
[de32fda]1815 updateUniformBuffer(imageIndex);
1816
[47bff4c]1817 VkSubmitInfo submitInfo = {};
1818 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1819
1820 VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
1821 VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
1822
1823 submitInfo.waitSemaphoreCount = 1;
1824 submitInfo.pWaitSemaphores = waitSemaphores;
1825 submitInfo.pWaitDstStageMask = waitStages;
1826 submitInfo.commandBufferCount = 1;
1827 submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
1828
1829 VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
1830
1831 submitInfo.signalSemaphoreCount = 1;
1832 submitInfo.pSignalSemaphores = signalSemaphores;
1833
[75108ef]1834 vkResetFences(device, 1, &inFlightFences[currentFrame]);
1835
[47bff4c]1836 if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
1837 throw runtime_error("failed to submit draw command buffer!");
[bfd620e]1838 }
[47bff4c]1839
1840 VkPresentInfoKHR presentInfo = {};
1841 presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
1842 presentInfo.waitSemaphoreCount = 1;
1843 presentInfo.pWaitSemaphores = signalSemaphores;
1844
1845 VkSwapchainKHR swapChains[] = { swapChain };
1846 presentInfo.swapchainCount = 1;
1847 presentInfo.pSwapchains = swapChains;
1848 presentInfo.pImageIndices = &imageIndex;
1849 presentInfo.pResults = nullptr;
1850
[75108ef]1851 result = vkQueuePresentKHR(presentQueue, &presentInfo);
1852
1853 if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
1854 framebufferResized = false;
1855 recreateSwapChain();
1856 } else if (result != VK_SUCCESS) {
1857 throw runtime_error("failed to present swap chain image!");
1858 }
[47bff4c]1859
1860 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
[fba08f2]1861 currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
[f94eea9]1862/*** START OF REFACTORED CODE ***/
[826df16]1863 }
1864
[5f3dba8]1865 void drawUI() {
[f94eea9]1866/*** END OF REFACTORED CODE ***/
[e1a7f5a]1867 // TODO: Since I currently don't use any other render targets,
1868 // I may as well set this once before the render loop
[5f3dba8]1869 SDL_SetRenderTarget(gRenderer, uiOverlay);
1870
[5936c58]1871 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0x00);
[5f3dba8]1872 SDL_RenderClear(gRenderer);
1873
1874 SDL_Rect rect;
1875
1876 rect = {280, 220, 100, 100};
[5936c58]1877 SDL_SetRenderDrawColor(gRenderer, 0x00, 0xFF, 0x00, 0xFF);
[5f3dba8]1878 SDL_RenderFillRect(gRenderer, &rect);
1879 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x9F, 0x9F, 0xFF);
1880
1881 rect = {10, 10, 0, 0};
1882 SDL_QueryTexture(uiText, nullptr, nullptr, &(rect.w), &(rect.h));
1883 SDL_RenderCopy(gRenderer, uiText, nullptr, &rect);
1884
1885 rect = {10, 80, 0, 0};
1886 SDL_QueryTexture(uiImage, nullptr, nullptr, &(rect.w), &(rect.h));
1887 SDL_RenderCopy(gRenderer, uiImage, nullptr, &rect);
1888
[5936c58]1889 SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0xFF, 0xFF);
[5f3dba8]1890 SDL_RenderDrawLine(gRenderer, 50, 5, 150, 500);
1891
[e1a7f5a]1892 populateImageFromSDLTexture(uiOverlay, sdlOverlayImage);
[f94eea9]1893/*** START OF REFACTORED CODE ***/
[5f3dba8]1894 }
[f94eea9]1895/*** END OF REFACTORED CODE ***/
[5f3dba8]1896
[de32fda]1897 void updateUniformBuffer(uint32_t currentImage) {
1898 static auto startTime = chrono::high_resolution_clock::now();
1899
1900 auto currentTime = chrono::high_resolution_clock::now();
1901 float time = chrono::duration<float, chrono::seconds::period>(currentTime - startTime).count();
1902
1903 UniformBufferObject ubo = {};
[f00ee54]1904 ubo.model = rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
1905 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));
1906 ubo.proj = perspective(radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
[4f63fa8]1907 ubo.proj[1][1] *= -1; // flip the y-axis so that +y is up
[fba08f2]1908
[de32fda]1909 void* data;
1910 vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
1911 memcpy(data, &ubo, sizeof(ubo));
1912 vkUnmapMemory(device, uniformBuffersMemory[currentImage]);
1913 }
1914
[621664a]1915 void recreateSwapChain() {
[cabdd5c]1916 gui->refreshWindowSize();
[621664a]1917
[cabdd5c]1918 while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
[621664a]1919 (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
1920 SDL_WaitEvent(nullptr);
[cabdd5c]1921 gui->refreshWindowSize();
[621664a]1922 }
1923
1924 vkDeviceWaitIdle(device);
1925
1926 cleanupSwapChain();
1927
1928 createSwapChain();
1929 createImageViews();
1930 createRenderPass();
[d22ae72]1931
[e5d4aca]1932 createBufferResources();
1933 }
[d22ae72]1934
[e5d4aca]1935 void createBufferResources() {
[adcd252]1936 createDepthResources();
[621664a]1937 createFramebuffers();
1938 createUniformBuffers();
[d22ae72]1939
[e5d4aca]1940 createGraphicsPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv", scenePipeline);
[721e8be]1941 createDescriptorPool(scenePipeline);
1942 createDescriptorSets(scenePipeline);
[d22ae72]1943
[e5d4aca]1944 createGraphicsPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv", overlayPipeline);
[721e8be]1945 createDescriptorPool(overlayPipeline);
1946 createDescriptorSets(overlayPipeline);
[d22ae72]1947
[621664a]1948 createCommandBuffers();
1949 }
1950
[c1c2021]1951/*** START OF REFACTORED CODE ***/
[826df16]1952 void cleanup() {
[75108ef]1953 cleanupSwapChain();
[c1c2021]1954/*** END OF REFACTORED CODE ***/
[75108ef]1955
[fba08f2]1956 vkDestroySampler(device, textureSampler, nullptr);
[69dccfe]1957
[fba08f2]1958 vkDestroyImageView(device, textureImageView, nullptr);
[eea05dd]1959 vkDestroyImage(device, textureImage, nullptr);
[f5d5686]1960 vkFreeMemory(device, textureImageMemory, nullptr);
[eea05dd]1961
[69dccfe]1962 vkDestroyImageView(device, overlayImageView, nullptr);
1963 vkDestroyImage(device, overlayImage, nullptr);
1964 vkFreeMemory(device, overlayImageMemory, nullptr);
1965
[e1a7f5a]1966 vkDestroyImageView(device, sdlOverlayImageView, nullptr);
1967 vkDestroyImage(device, sdlOverlayImage, nullptr);
1968 vkFreeMemory(device, sdlOverlayImageMemory, nullptr);
1969
[d22ae72]1970 cleanupPipelineBuffers(scenePipeline);
1971 cleanupPipelineBuffers(overlayPipeline);
[80edd70]1972
[47bff4c]1973 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
1974 vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
[621664a]1975 vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
[47bff4c]1976 vkDestroyFence(device, inFlightFences[i], nullptr);
1977 }
1978
[c1c2021]1979/*** START OF REFACTORED CODE ***/
[fa9fa1c]1980 vkDestroyCommandPool(device, commandPool, nullptr);
[909b51a]1981 vkDestroyDevice(device, nullptr);
[cabdd5c]1982 vkDestroySurfaceKHR(instance, surface, nullptr);
[909b51a]1983
[80de39d]1984 if (enableValidationLayers) {
1985 DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
1986 }
1987
[826df16]1988 vkDestroyInstance(instance, nullptr);
[cabdd5c]1989/*** END OF REFACTORED CODE ***/
[826df16]1990
[5f3dba8]1991 // TODO: Check if any of these functions accept null parameters
1992 // If they do, I don't need to check for that
1993
1994 if (uiOverlay != nullptr) {
1995 SDL_DestroyTexture(uiOverlay);
1996 uiOverlay = nullptr;
1997 }
1998
1999 TTF_CloseFont(gFont);
2000 gFont = nullptr;
2001
2002 if (uiText != nullptr) {
2003 SDL_DestroyTexture(uiText);
2004 uiText = nullptr;
2005 }
2006
2007 if (uiImage != nullptr) {
2008 SDL_DestroyTexture(uiImage);
2009 uiImage = nullptr;
2010 }
2011
[cabdd5c]2012/*** START OF REFACTORED CODE ***/
[5f3dba8]2013 SDL_DestroyRenderer(gRenderer);
2014 gRenderer = nullptr;
2015
[7fc5e27]2016 gui->destroyWindow();
2017 gui->shutdown();
[98f3232]2018 delete gui;
[826df16]2019 }
[e09ad38]2020
[621664a]2021 void cleanupSwapChain() {
[c1c2021]2022/*** END OF REFACTORED CODE ***/
[adcd252]2023 vkDestroyImageView(device, depthImageView, nullptr);
2024 vkDestroyImage(device, depthImage, nullptr);
2025 vkFreeMemory(device, depthImageMemory, nullptr);
2026
[621664a]2027 for (auto framebuffer : swapChainFramebuffers) {
2028 vkDestroyFramebuffer(device, framebuffer, nullptr);
2029 }
2030
2031 vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
2032
[d22ae72]2033 cleanupPipeline(scenePipeline);
2034 cleanupPipeline(overlayPipeline);
[b8b32bd]2035
[6fc24c7]2036/*** START OF REFACTORED CODE ***/
[621664a]2037 vkDestroyRenderPass(device, renderPass, nullptr);
2038
2039 for (auto imageView : swapChainImageViews) {
2040 vkDestroyImageView(device, imageView, nullptr);
2041 }
2042
2043 vkDestroySwapchainKHR(device, swapChain, nullptr);
[502bd0b]2044/*** END OF REFACTORED CODE ***/
[621664a]2045
2046 for (size_t i = 0; i < swapChainImages.size(); i++) {
2047 vkDestroyBuffer(device, uniformBuffers[i], nullptr);
2048 vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
2049 }
[c1c2021]2050/*** START OF REFACTORED CODE ***/
[d22ae72]2051 }
[c1c2021]2052/*** END OF REFACTORED CODE ***/
[d22ae72]2053
2054 void cleanupPipeline(GraphicsPipelineInfo& pipeline) {
2055 vkDestroyPipeline(device, pipeline.pipeline, nullptr);
2056 vkDestroyDescriptorPool(device, pipeline.descriptorPool, nullptr);
2057 vkDestroyPipelineLayout(device, pipeline.pipelineLayout, nullptr);
2058 }
2059
2060 void cleanupPipelineBuffers(GraphicsPipelineInfo& pipeline) {
2061 vkDestroyDescriptorSetLayout(device, pipeline.descriptorSetLayout, nullptr);
[621664a]2062
[d22ae72]2063 vkDestroyBuffer(device, pipeline.vertexBuffer, nullptr);
2064 vkFreeMemory(device, pipeline.vertexBufferMemory, nullptr);
2065 vkDestroyBuffer(device, pipeline.indexBuffer, nullptr);
2066 vkFreeMemory(device, pipeline.indexBufferMemory, nullptr);
[621664a]2067 }
2068
[e09ad38]2069 static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
[621664a]2070 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
2071 VkDebugUtilsMessageTypeFlagsEXT messageType,
2072 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
2073 void* pUserData) {
[e09ad38]2074 cerr << "validation layer: " << pCallbackData->pMessage << endl;
2075
2076 return VK_FALSE;
[0e6ecf3]2077 }
[e09ad38]2078
2079 static vector<char> readFile(const string& filename) {
2080 ifstream file(filename, ios::ate | ios::binary);
2081
2082 if (!file.is_open()) {
2083 throw runtime_error("failed to open file!");
2084 }
2085
[621664a]2086 size_t fileSize = (size_t) file.tellg();
[e09ad38]2087 vector<char> buffer(fileSize);
2088
2089 file.seekg(0);
2090 file.read(buffer.data(), fileSize);
2091
2092 file.close();
2093
2094 return buffer;
2095 }
[826df16]2096};
2097
[cabdd5c]2098/*** START OF REFACTORED CODE ***/
[1c6cd5e]2099int main(int argc, char* argv[]) {
[826df16]2100
[b6127d2]2101#ifdef NDEBUG
2102 cout << "DEBUGGING IS OFF" << endl;
2103#else
2104 cout << "DEBUGGING IS ON" << endl;
2105#endif
[a8f0577]2106
[826df16]2107 cout << "Starting Vulkan game..." << endl;
2108
2109 VulkanGame game;
2110
2111 try {
2112 game.run();
2113 } catch (const exception& e) {
2114 cerr << e.what() << endl;
2115 return EXIT_FAILURE;
2116 }
[03f4c64]2117
[826df16]2118 cout << "Finished running the game" << endl;
[03f4c64]2119
[826df16]2120 return EXIT_SUCCESS;
[03f4c64]2121}
[cabdd5c]2122/*** END OF REFACTORED CODE ***/
Note: See TracBrowser for help on using the repository browser.