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