source: opengl-game/vulkan-ref.cpp@ 87c8f1a

feature/imgui-sdl points-test
Last change on this file since 87c8f1a was 87c8f1a, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 5 years ago

In vaulkangame, define vertex buffer and index buffer data and transfer it to the gpu

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