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