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