1 | #include "vulkan-game.hpp"
|
---|
2 |
|
---|
3 | #include <array>
|
---|
4 | #include <iostream>
|
---|
5 | #include <set>
|
---|
6 |
|
---|
7 | #include "consts.hpp"
|
---|
8 | #include "logger.hpp"
|
---|
9 |
|
---|
10 | #include "utils.hpp"
|
---|
11 |
|
---|
12 | using namespace std;
|
---|
13 |
|
---|
14 | struct UniformBufferObject {
|
---|
15 | alignas(16) mat4 model;
|
---|
16 | alignas(16) mat4 view;
|
---|
17 | alignas(16) mat4 proj;
|
---|
18 | };
|
---|
19 |
|
---|
20 | VulkanGame::VulkanGame(int maxFramesInFlight) : MAX_FRAMES_IN_FLIGHT(maxFramesInFlight) {
|
---|
21 | gui = nullptr;
|
---|
22 | window = nullptr;
|
---|
23 |
|
---|
24 | currentFrame = 0;
|
---|
25 | framebufferResized = false;
|
---|
26 | }
|
---|
27 |
|
---|
28 | VulkanGame::~VulkanGame() {
|
---|
29 | }
|
---|
30 |
|
---|
31 | void VulkanGame::run(int width, int height, unsigned char guiFlags) {
|
---|
32 | cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
|
---|
33 |
|
---|
34 | cout << "Vulkan Game" << endl;
|
---|
35 |
|
---|
36 | // This gets the runtime version, use SDL_VERSION() for the comppile-time version
|
---|
37 | // TODO: Create a game-gui function to get the gui version and retrieve it that way
|
---|
38 | SDL_GetVersion(&sdlVersion);
|
---|
39 |
|
---|
40 | // TODO: Refactor the logger api to be more flexible,
|
---|
41 | // esp. since gl_log() and gl_log_err() have issues printing anything besides stirngs
|
---|
42 | restart_gl_log();
|
---|
43 | gl_log("starting SDL\n%s.%s.%s",
|
---|
44 | to_string(sdlVersion.major).c_str(),
|
---|
45 | to_string(sdlVersion.minor).c_str(),
|
---|
46 | to_string(sdlVersion.patch).c_str());
|
---|
47 |
|
---|
48 | open_log();
|
---|
49 | get_log() << "starting SDL" << endl;
|
---|
50 | get_log() <<
|
---|
51 | (int)sdlVersion.major << "." <<
|
---|
52 | (int)sdlVersion.minor << "." <<
|
---|
53 | (int)sdlVersion.patch << endl;
|
---|
54 |
|
---|
55 | if (initWindow(width, height, guiFlags) == RTWO_ERROR) {
|
---|
56 | return;
|
---|
57 | }
|
---|
58 |
|
---|
59 | initVulkan();
|
---|
60 | mainLoop();
|
---|
61 | cleanup();
|
---|
62 |
|
---|
63 | close_log();
|
---|
64 | }
|
---|
65 |
|
---|
66 | // TODO: Make some more initi functions, or call this initUI if the
|
---|
67 | // amount of things initialized here keeps growing
|
---|
68 | bool VulkanGame::initWindow(int width, int height, unsigned char guiFlags) {
|
---|
69 | // TODO: Put all fonts, textures, and images in the assets folder
|
---|
70 | gui = new GameGui_SDL();
|
---|
71 |
|
---|
72 | if (gui->init() == RTWO_ERROR) {
|
---|
73 | // TODO: Also print these sorts of errors to the log
|
---|
74 | cout << "UI library could not be initialized!" << endl;
|
---|
75 | cout << gui->getError() << endl;
|
---|
76 | return RTWO_ERROR;
|
---|
77 | }
|
---|
78 |
|
---|
79 | window = (SDL_Window*) gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
|
---|
80 | if (window == nullptr) {
|
---|
81 | cout << "Window could not be created!" << endl;
|
---|
82 | cout << gui->getError() << endl;
|
---|
83 | return RTWO_ERROR;
|
---|
84 | }
|
---|
85 |
|
---|
86 | cout << "Target window size: (" << width << ", " << height << ")" << endl;
|
---|
87 | cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
|
---|
88 |
|
---|
89 | renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
---|
90 | if (renderer == nullptr) {
|
---|
91 | cout << "Renderer could not be created!" << endl;
|
---|
92 | cout << gui->getError() << endl;
|
---|
93 | return RTWO_ERROR;
|
---|
94 | }
|
---|
95 |
|
---|
96 | SDL_VERSION(&sdlVersion);
|
---|
97 |
|
---|
98 | // In SDL 2.0.10 (currently, the latest), SDL_TEXTUREACCESS_TARGET is required to get a transparent overlay working
|
---|
99 | // However, the latest SDL version available through homebrew on Mac is 2.0.9, which requires SDL_TEXTUREACCESS_STREAMING
|
---|
100 | // 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
|
---|
101 | // until the homebrew recipe is updated
|
---|
102 | if (sdlVersion.major == 2 && sdlVersion.minor == 0 && sdlVersion.patch == 9) {
|
---|
103 | uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING,
|
---|
104 | gui->getWindowWidth(), gui->getWindowHeight());
|
---|
105 | } else {
|
---|
106 | uiOverlay = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET,
|
---|
107 | gui->getWindowWidth(), gui->getWindowHeight());
|
---|
108 | }
|
---|
109 |
|
---|
110 | if (uiOverlay == nullptr) {
|
---|
111 | cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << endl;
|
---|
112 | }
|
---|
113 | if (SDL_SetTextureBlendMode(uiOverlay, SDL_BLENDMODE_BLEND) != 0) {
|
---|
114 | cout << "Unable to set texture blend mode! SDL Error: " << SDL_GetError() << endl;
|
---|
115 | }
|
---|
116 |
|
---|
117 | return RTWO_SUCCESS;
|
---|
118 | }
|
---|
119 |
|
---|
120 | void VulkanGame::initVulkan() {
|
---|
121 | const vector<const char*> validationLayers = {
|
---|
122 | "VK_LAYER_KHRONOS_validation"
|
---|
123 | };
|
---|
124 | const vector<const char*> deviceExtensions = {
|
---|
125 | VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
---|
126 | };
|
---|
127 |
|
---|
128 | createVulkanInstance(validationLayers);
|
---|
129 | setupDebugMessenger();
|
---|
130 | createVulkanSurface();
|
---|
131 | pickPhysicalDevice(deviceExtensions);
|
---|
132 | createLogicalDevice(validationLayers, deviceExtensions);
|
---|
133 | createSwapChain();
|
---|
134 | createImageViews();
|
---|
135 | createRenderPass();
|
---|
136 | createCommandPool();
|
---|
137 |
|
---|
138 | createImageResources();
|
---|
139 |
|
---|
140 | createFramebuffers();
|
---|
141 | createUniformBuffers();
|
---|
142 |
|
---|
143 | vector<Vertex> sceneVertices = {
|
---|
144 | {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
145 | {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
146 | {{ 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
147 | {{-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
|
---|
148 |
|
---|
149 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
150 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
151 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
152 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}}
|
---|
153 | };
|
---|
154 | vector<uint16_t> sceneIndices = {
|
---|
155 | 0, 1, 2, 2, 3, 0,
|
---|
156 | 4, 5, 6, 6, 7, 4
|
---|
157 | };
|
---|
158 |
|
---|
159 | graphicsPipelines.push_back(GraphicsPipeline_Vulkan(physicalDevice, device, renderPass,
|
---|
160 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(Vertex)));
|
---|
161 |
|
---|
162 | graphicsPipelines.back().bindData(sceneVertices, sceneIndices, commandPool, graphicsQueue);
|
---|
163 |
|
---|
164 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::pos));
|
---|
165 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&Vertex::color));
|
---|
166 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&Vertex::texCoord));
|
---|
167 |
|
---|
168 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
---|
169 | VK_SHADER_STAGE_VERTEX_BIT, &uniformBufferInfoList);
|
---|
170 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
171 | VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
|
---|
172 |
|
---|
173 | graphicsPipelines.back().createDescriptorSetLayout();
|
---|
174 | graphicsPipelines.back().createPipeline("shaders/scene-vert.spv", "shaders/scene-frag.spv");
|
---|
175 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
176 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
177 |
|
---|
178 | vector<OverlayVertex> overlayVertices = {
|
---|
179 | {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
180 | {{ 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
181 | {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
|
---|
182 | {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}}
|
---|
183 | };
|
---|
184 | vector<uint16_t> overlayIndices = {
|
---|
185 | 0, 1, 2, 2, 3, 0
|
---|
186 | };
|
---|
187 |
|
---|
188 | graphicsPipelines.push_back(GraphicsPipeline_Vulkan(physicalDevice, device, renderPass,
|
---|
189 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, sizeof(OverlayVertex)));
|
---|
190 |
|
---|
191 | graphicsPipelines.back().bindData(overlayVertices, overlayIndices, commandPool, graphicsQueue);
|
---|
192 |
|
---|
193 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&OverlayVertex::pos));
|
---|
194 | graphicsPipelines.back().addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&OverlayVertex::texCoord));
|
---|
195 |
|
---|
196 | graphicsPipelines.back().addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
197 | VK_SHADER_STAGE_FRAGMENT_BIT, &sdlOverlayImageDescriptor);
|
---|
198 |
|
---|
199 | graphicsPipelines.back().createDescriptorSetLayout();
|
---|
200 | graphicsPipelines.back().createPipeline("shaders/overlay-vert.spv", "shaders/overlay-frag.spv");
|
---|
201 | graphicsPipelines.back().createDescriptorPool(swapChainImages);
|
---|
202 | graphicsPipelines.back().createDescriptorSets(swapChainImages);
|
---|
203 |
|
---|
204 | // TODO: Creating the descriptor pool and descriptor sets might need to be redone when the
|
---|
205 | // swap chain is recreated
|
---|
206 |
|
---|
207 | cout << "Created " << graphicsPipelines.size() << " graphics pipelines" << endl;
|
---|
208 |
|
---|
209 | createCommandBuffers();
|
---|
210 |
|
---|
211 | createSyncObjects();
|
---|
212 | }
|
---|
213 |
|
---|
214 | void VulkanGame::mainLoop() {
|
---|
215 | UIEvent e;
|
---|
216 | bool quit = false;
|
---|
217 |
|
---|
218 | while (!quit) {
|
---|
219 | gui->processEvents();
|
---|
220 |
|
---|
221 | while (gui->pollEvent(&e)) {
|
---|
222 | switch(e.type) {
|
---|
223 | case UI_EVENT_QUIT:
|
---|
224 | cout << "Quit event detected" << endl;
|
---|
225 | quit = true;
|
---|
226 | break;
|
---|
227 | case UI_EVENT_WINDOW:
|
---|
228 | cout << "Window event detected" << endl;
|
---|
229 | // Currently unused
|
---|
230 | break;
|
---|
231 | case UI_EVENT_WINDOWRESIZE:
|
---|
232 | cout << "Window resize event detected" << endl;
|
---|
233 | framebufferResized = true;
|
---|
234 | break;
|
---|
235 | case UI_EVENT_KEY:
|
---|
236 | if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
|
---|
237 | quit = true;
|
---|
238 | } else {
|
---|
239 | cout << "Key event detected" << endl;
|
---|
240 | }
|
---|
241 | break;
|
---|
242 | case UI_EVENT_MOUSEBUTTONDOWN:
|
---|
243 | cout << "Mouse button down event detected" << endl;
|
---|
244 | break;
|
---|
245 | case UI_EVENT_MOUSEBUTTONUP:
|
---|
246 | cout << "Mouse button up event detected" << endl;
|
---|
247 | break;
|
---|
248 | case UI_EVENT_MOUSEMOTION:
|
---|
249 | break;
|
---|
250 | case UI_EVENT_UNKNOWN:
|
---|
251 | cout << "Unknown event type: 0x" << hex << e.unknown.eventType << dec << endl;
|
---|
252 | break;
|
---|
253 | default:
|
---|
254 | cout << "Unhandled UI event: " << e.type << endl;
|
---|
255 | }
|
---|
256 | }
|
---|
257 |
|
---|
258 | renderUI();
|
---|
259 | renderScene();
|
---|
260 | }
|
---|
261 |
|
---|
262 | vkDeviceWaitIdle(device);
|
---|
263 | }
|
---|
264 |
|
---|
265 | void VulkanGame::renderUI() {
|
---|
266 | // TODO: Since I currently don't use any other render targets,
|
---|
267 | // I may as well set this once before the render loop
|
---|
268 | SDL_SetRenderTarget(renderer, uiOverlay);
|
---|
269 |
|
---|
270 | SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
|
---|
271 | SDL_RenderClear(renderer);
|
---|
272 |
|
---|
273 | SDL_Rect rect = {280, 220, 100, 100};
|
---|
274 | SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
|
---|
275 | SDL_RenderFillRect(renderer, &rect);
|
---|
276 |
|
---|
277 | SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
|
---|
278 | SDL_RenderDrawLine(renderer, 50, 5, 150, 500);
|
---|
279 |
|
---|
280 | VulkanUtils::populateVulkanImageFromSDLTexture(device, physicalDevice, commandPool, uiOverlay, renderer,
|
---|
281 | sdlOverlayImage, graphicsQueue);
|
---|
282 | }
|
---|
283 |
|
---|
284 | void VulkanGame::renderScene() {
|
---|
285 | vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, numeric_limits<uint64_t>::max());
|
---|
286 |
|
---|
287 | uint32_t imageIndex;
|
---|
288 |
|
---|
289 | VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
|
---|
290 | imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
|
---|
291 |
|
---|
292 | if (result == VK_ERROR_OUT_OF_DATE_KHR) {
|
---|
293 | recreateSwapChain();
|
---|
294 | return;
|
---|
295 | } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
|
---|
296 | throw runtime_error("failed to acquire swap chain image!");
|
---|
297 | }
|
---|
298 |
|
---|
299 | VkSubmitInfo submitInfo = {};
|
---|
300 | submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
---|
301 |
|
---|
302 | VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
|
---|
303 | VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
---|
304 |
|
---|
305 | submitInfo.waitSemaphoreCount = 1;
|
---|
306 | submitInfo.pWaitSemaphores = waitSemaphores;
|
---|
307 | submitInfo.pWaitDstStageMask = waitStages;
|
---|
308 | submitInfo.commandBufferCount = 1;
|
---|
309 | submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
|
---|
310 |
|
---|
311 | VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
|
---|
312 |
|
---|
313 | submitInfo.signalSemaphoreCount = 1;
|
---|
314 | submitInfo.pSignalSemaphores = signalSemaphores;
|
---|
315 |
|
---|
316 | vkResetFences(device, 1, &inFlightFences[currentFrame]);
|
---|
317 |
|
---|
318 | if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
|
---|
319 | throw runtime_error("failed to submit draw command buffer!");
|
---|
320 | }
|
---|
321 |
|
---|
322 | VkPresentInfoKHR presentInfo = {};
|
---|
323 | presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
---|
324 | presentInfo.waitSemaphoreCount = 1;
|
---|
325 | presentInfo.pWaitSemaphores = signalSemaphores;
|
---|
326 |
|
---|
327 | VkSwapchainKHR swapChains[] = { swapChain };
|
---|
328 | presentInfo.swapchainCount = 1;
|
---|
329 | presentInfo.pSwapchains = swapChains;
|
---|
330 | presentInfo.pImageIndices = &imageIndex;
|
---|
331 | presentInfo.pResults = nullptr;
|
---|
332 |
|
---|
333 | result = vkQueuePresentKHR(presentQueue, &presentInfo);
|
---|
334 |
|
---|
335 | if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
|
---|
336 | framebufferResized = false;
|
---|
337 | recreateSwapChain();
|
---|
338 | } else if (result != VK_SUCCESS) {
|
---|
339 | throw runtime_error("failed to present swap chain image!");
|
---|
340 | }
|
---|
341 |
|
---|
342 | currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
|
---|
343 | currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
|
---|
344 | }
|
---|
345 |
|
---|
346 | void VulkanGame::cleanup() {
|
---|
347 | cleanupSwapChain();
|
---|
348 |
|
---|
349 | VulkanUtils::destroyVulkanImage(device, floorTextureImage);
|
---|
350 | VulkanUtils::destroyVulkanImage(device, sdlOverlayImage);
|
---|
351 |
|
---|
352 | vkDestroySampler(device, textureSampler, nullptr);
|
---|
353 |
|
---|
354 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
355 | pipeline.cleanupBuffers();
|
---|
356 | }
|
---|
357 |
|
---|
358 | for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
---|
359 | vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
|
---|
360 | vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
|
---|
361 | vkDestroyFence(device, inFlightFences[i], nullptr);
|
---|
362 | }
|
---|
363 |
|
---|
364 | vkDestroyCommandPool(device, commandPool, nullptr);
|
---|
365 | vkDestroyDevice(device, nullptr);
|
---|
366 | vkDestroySurfaceKHR(instance, surface, nullptr);
|
---|
367 |
|
---|
368 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
369 | VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
|
---|
370 | }
|
---|
371 |
|
---|
372 | vkDestroyInstance(instance, nullptr);
|
---|
373 |
|
---|
374 | // TODO: Check if any of these functions accept null parameters
|
---|
375 | // If they do, I don't need to check for that
|
---|
376 |
|
---|
377 | if (uiOverlay != nullptr) {
|
---|
378 | SDL_DestroyTexture(uiOverlay);
|
---|
379 | uiOverlay = nullptr;
|
---|
380 | }
|
---|
381 |
|
---|
382 | SDL_DestroyRenderer(renderer);
|
---|
383 | renderer = nullptr;
|
---|
384 |
|
---|
385 | gui->destroyWindow();
|
---|
386 | gui->shutdown();
|
---|
387 | delete gui;
|
---|
388 | }
|
---|
389 |
|
---|
390 | void VulkanGame::createVulkanInstance(const vector<const char*> &validationLayers) {
|
---|
391 | if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
|
---|
392 | throw runtime_error("validation layers requested, but not available!");
|
---|
393 | }
|
---|
394 |
|
---|
395 | VkApplicationInfo appInfo = {};
|
---|
396 | appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
---|
397 | appInfo.pApplicationName = "Vulkan Game";
|
---|
398 | appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
399 | appInfo.pEngineName = "No Engine";
|
---|
400 | appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
401 | appInfo.apiVersion = VK_API_VERSION_1_0;
|
---|
402 |
|
---|
403 | VkInstanceCreateInfo createInfo = {};
|
---|
404 | createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
---|
405 | createInfo.pApplicationInfo = &appInfo;
|
---|
406 |
|
---|
407 | vector<const char*> extensions = gui->getRequiredExtensions();
|
---|
408 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
409 | extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
---|
410 | }
|
---|
411 |
|
---|
412 | createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
|
---|
413 | createInfo.ppEnabledExtensionNames = extensions.data();
|
---|
414 |
|
---|
415 | cout << endl << "Extensions:" << endl;
|
---|
416 | for (const char* extensionName : extensions) {
|
---|
417 | cout << extensionName << endl;
|
---|
418 | }
|
---|
419 | cout << endl;
|
---|
420 |
|
---|
421 | VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
|
---|
422 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
423 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
424 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
425 |
|
---|
426 | populateDebugMessengerCreateInfo(debugCreateInfo);
|
---|
427 | createInfo.pNext = &debugCreateInfo;
|
---|
428 | } else {
|
---|
429 | createInfo.enabledLayerCount = 0;
|
---|
430 |
|
---|
431 | createInfo.pNext = nullptr;
|
---|
432 | }
|
---|
433 |
|
---|
434 | if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
|
---|
435 | throw runtime_error("failed to create instance!");
|
---|
436 | }
|
---|
437 | }
|
---|
438 |
|
---|
439 | void VulkanGame::setupDebugMessenger() {
|
---|
440 | if (!ENABLE_VALIDATION_LAYERS) return;
|
---|
441 |
|
---|
442 | VkDebugUtilsMessengerCreateInfoEXT createInfo;
|
---|
443 | populateDebugMessengerCreateInfo(createInfo);
|
---|
444 |
|
---|
445 | if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
|
---|
446 | throw runtime_error("failed to set up debug messenger!");
|
---|
447 | }
|
---|
448 | }
|
---|
449 |
|
---|
450 | void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
|
---|
451 | createInfo = {};
|
---|
452 | createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
---|
453 | 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;
|
---|
454 | 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;
|
---|
455 | createInfo.pfnUserCallback = debugCallback;
|
---|
456 | }
|
---|
457 |
|
---|
458 | VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
|
---|
459 | VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
|
---|
460 | VkDebugUtilsMessageTypeFlagsEXT messageType,
|
---|
461 | const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
|
---|
462 | void* pUserData) {
|
---|
463 | cerr << "validation layer: " << pCallbackData->pMessage << endl;
|
---|
464 |
|
---|
465 | return VK_FALSE;
|
---|
466 | }
|
---|
467 |
|
---|
468 | void VulkanGame::createVulkanSurface() {
|
---|
469 | if (gui->createVulkanSurface(instance, &surface) == RTWO_ERROR) {
|
---|
470 | throw runtime_error("failed to create window surface!");
|
---|
471 | }
|
---|
472 | }
|
---|
473 |
|
---|
474 | void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
|
---|
475 | uint32_t deviceCount = 0;
|
---|
476 | vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
|
---|
477 |
|
---|
478 | if (deviceCount == 0) {
|
---|
479 | throw runtime_error("failed to find GPUs with Vulkan support!");
|
---|
480 | }
|
---|
481 |
|
---|
482 | vector<VkPhysicalDevice> devices(deviceCount);
|
---|
483 | vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
|
---|
484 |
|
---|
485 | cout << endl << "Graphics cards:" << endl;
|
---|
486 | for (const VkPhysicalDevice& device : devices) {
|
---|
487 | if (isDeviceSuitable(device, deviceExtensions)) {
|
---|
488 | physicalDevice = device;
|
---|
489 | break;
|
---|
490 | }
|
---|
491 | }
|
---|
492 | cout << endl;
|
---|
493 |
|
---|
494 | if (physicalDevice == VK_NULL_HANDLE) {
|
---|
495 | throw runtime_error("failed to find a suitable GPU!");
|
---|
496 | }
|
---|
497 | }
|
---|
498 |
|
---|
499 | bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice,
|
---|
500 | const vector<const char*>& deviceExtensions) {
|
---|
501 | VkPhysicalDeviceProperties deviceProperties;
|
---|
502 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
503 |
|
---|
504 | cout << "Device: " << deviceProperties.deviceName << endl;
|
---|
505 |
|
---|
506 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
507 | bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
|
---|
508 | bool swapChainAdequate = false;
|
---|
509 |
|
---|
510 | if (extensionsSupported) {
|
---|
511 | SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
|
---|
512 | swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
|
---|
513 | }
|
---|
514 |
|
---|
515 | VkPhysicalDeviceFeatures supportedFeatures;
|
---|
516 | vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
|
---|
517 |
|
---|
518 | return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
|
---|
519 | }
|
---|
520 |
|
---|
521 | void VulkanGame::createLogicalDevice(
|
---|
522 | const vector<const char*> validationLayers,
|
---|
523 | const vector<const char*>& deviceExtensions) {
|
---|
524 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
525 |
|
---|
526 | vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
|
---|
527 | set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
528 |
|
---|
529 | float queuePriority = 1.0f;
|
---|
530 | for (uint32_t queueFamily : uniqueQueueFamilies) {
|
---|
531 | VkDeviceQueueCreateInfo queueCreateInfo = {};
|
---|
532 | queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
---|
533 | queueCreateInfo.queueFamilyIndex = queueFamily;
|
---|
534 | queueCreateInfo.queueCount = 1;
|
---|
535 | queueCreateInfo.pQueuePriorities = &queuePriority;
|
---|
536 |
|
---|
537 | queueCreateInfoList.push_back(queueCreateInfo);
|
---|
538 | }
|
---|
539 |
|
---|
540 | VkPhysicalDeviceFeatures deviceFeatures = {};
|
---|
541 | deviceFeatures.samplerAnisotropy = VK_TRUE;
|
---|
542 |
|
---|
543 | VkDeviceCreateInfo createInfo = {};
|
---|
544 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
---|
545 | createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
|
---|
546 | createInfo.pQueueCreateInfos = queueCreateInfoList.data();
|
---|
547 |
|
---|
548 | createInfo.pEnabledFeatures = &deviceFeatures;
|
---|
549 |
|
---|
550 | createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
|
---|
551 | createInfo.ppEnabledExtensionNames = deviceExtensions.data();
|
---|
552 |
|
---|
553 | // These fields are ignored by up-to-date Vulkan implementations,
|
---|
554 | // but it's a good idea to set them for backwards compatibility
|
---|
555 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
556 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
557 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
558 | } else {
|
---|
559 | createInfo.enabledLayerCount = 0;
|
---|
560 | }
|
---|
561 |
|
---|
562 | if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
|
---|
563 | throw runtime_error("failed to create logical device!");
|
---|
564 | }
|
---|
565 |
|
---|
566 | vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
|
---|
567 | vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
|
---|
568 | }
|
---|
569 |
|
---|
570 | void VulkanGame::createSwapChain() {
|
---|
571 | SwapChainSupportDetails swapChainSupport = VulkanUtils::querySwapChainSupport(physicalDevice, surface);
|
---|
572 |
|
---|
573 | VkSurfaceFormatKHR surfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(swapChainSupport.formats);
|
---|
574 | VkPresentModeKHR presentMode = VulkanUtils::chooseSwapPresentMode(swapChainSupport.presentModes);
|
---|
575 | VkExtent2D extent = VulkanUtils::chooseSwapExtent(swapChainSupport.capabilities, gui->getWindowWidth(), gui->getWindowHeight());
|
---|
576 |
|
---|
577 | uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
|
---|
578 | if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
|
---|
579 | imageCount = swapChainSupport.capabilities.maxImageCount;
|
---|
580 | }
|
---|
581 |
|
---|
582 | VkSwapchainCreateInfoKHR createInfo = {};
|
---|
583 | createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
---|
584 | createInfo.surface = surface;
|
---|
585 | createInfo.minImageCount = imageCount;
|
---|
586 | createInfo.imageFormat = surfaceFormat.format;
|
---|
587 | createInfo.imageColorSpace = surfaceFormat.colorSpace;
|
---|
588 | createInfo.imageExtent = extent;
|
---|
589 | createInfo.imageArrayLayers = 1;
|
---|
590 | createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
---|
591 |
|
---|
592 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, surface);
|
---|
593 | uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
594 |
|
---|
595 | if (indices.graphicsFamily != indices.presentFamily) {
|
---|
596 | createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
|
---|
597 | createInfo.queueFamilyIndexCount = 2;
|
---|
598 | createInfo.pQueueFamilyIndices = queueFamilyIndices;
|
---|
599 | } else {
|
---|
600 | createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
---|
601 | createInfo.queueFamilyIndexCount = 0;
|
---|
602 | createInfo.pQueueFamilyIndices = nullptr;
|
---|
603 | }
|
---|
604 |
|
---|
605 | createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
|
---|
606 | createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
---|
607 | createInfo.presentMode = presentMode;
|
---|
608 | createInfo.clipped = VK_TRUE;
|
---|
609 | createInfo.oldSwapchain = VK_NULL_HANDLE;
|
---|
610 |
|
---|
611 | if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
|
---|
612 | throw runtime_error("failed to create swap chain!");
|
---|
613 | }
|
---|
614 |
|
---|
615 | vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
|
---|
616 | swapChainImages.resize(imageCount);
|
---|
617 | vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
|
---|
618 |
|
---|
619 | swapChainImageFormat = surfaceFormat.format;
|
---|
620 | swapChainExtent = extent;
|
---|
621 | }
|
---|
622 |
|
---|
623 | void VulkanGame::createImageViews() {
|
---|
624 | swapChainImageViews.resize(swapChainImages.size());
|
---|
625 |
|
---|
626 | for (size_t i = 0; i < swapChainImages.size(); i++) {
|
---|
627 | swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainImageFormat,
|
---|
628 | VK_IMAGE_ASPECT_COLOR_BIT);
|
---|
629 | }
|
---|
630 | }
|
---|
631 |
|
---|
632 | void VulkanGame::createRenderPass() {
|
---|
633 | VkAttachmentDescription colorAttachment = {};
|
---|
634 | colorAttachment.format = swapChainImageFormat;
|
---|
635 | colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
636 | colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
637 | colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
---|
638 | colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
639 | colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
640 | colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
641 | colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
---|
642 |
|
---|
643 | VkAttachmentReference colorAttachmentRef = {};
|
---|
644 | colorAttachmentRef.attachment = 0;
|
---|
645 | colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
---|
646 |
|
---|
647 | VkAttachmentDescription depthAttachment = {};
|
---|
648 | depthAttachment.format = findDepthFormat();
|
---|
649 | depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
650 | depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
651 | depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
652 | depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
653 | depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
654 | depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
655 | depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
656 |
|
---|
657 | VkAttachmentReference depthAttachmentRef = {};
|
---|
658 | depthAttachmentRef.attachment = 1;
|
---|
659 | depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
660 |
|
---|
661 | VkSubpassDescription subpass = {};
|
---|
662 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
---|
663 | subpass.colorAttachmentCount = 1;
|
---|
664 | subpass.pColorAttachments = &colorAttachmentRef;
|
---|
665 | subpass.pDepthStencilAttachment = &depthAttachmentRef;
|
---|
666 |
|
---|
667 | VkSubpassDependency dependency = {};
|
---|
668 | dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
---|
669 | dependency.dstSubpass = 0;
|
---|
670 | dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
671 | dependency.srcAccessMask = 0;
|
---|
672 | dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
673 | dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
|
---|
674 |
|
---|
675 | array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
|
---|
676 | VkRenderPassCreateInfo renderPassInfo = {};
|
---|
677 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
---|
678 | renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
679 | renderPassInfo.pAttachments = attachments.data();
|
---|
680 | renderPassInfo.subpassCount = 1;
|
---|
681 | renderPassInfo.pSubpasses = &subpass;
|
---|
682 | renderPassInfo.dependencyCount = 1;
|
---|
683 | renderPassInfo.pDependencies = &dependency;
|
---|
684 |
|
---|
685 | if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
|
---|
686 | throw runtime_error("failed to create render pass!");
|
---|
687 | }
|
---|
688 | }
|
---|
689 |
|
---|
690 | VkFormat VulkanGame::findDepthFormat() {
|
---|
691 | return VulkanUtils::findSupportedFormat(
|
---|
692 | physicalDevice,
|
---|
693 | { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
|
---|
694 | VK_IMAGE_TILING_OPTIMAL,
|
---|
695 | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
|
---|
696 | );
|
---|
697 | }
|
---|
698 |
|
---|
699 | void VulkanGame::createCommandPool() {
|
---|
700 | QueueFamilyIndices queueFamilyIndices = VulkanUtils::findQueueFamilies(physicalDevice, surface);;
|
---|
701 |
|
---|
702 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
703 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
704 | poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
|
---|
705 | poolInfo.flags = 0;
|
---|
706 |
|
---|
707 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
|
---|
708 | throw runtime_error("failed to create graphics command pool!");
|
---|
709 | }
|
---|
710 | }
|
---|
711 |
|
---|
712 | void VulkanGame::createImageResources() {
|
---|
713 | VulkanUtils::createDepthImage(device, physicalDevice, commandPool, findDepthFormat(), swapChainExtent,
|
---|
714 | depthImage, graphicsQueue);
|
---|
715 |
|
---|
716 | createTextureSampler();
|
---|
717 |
|
---|
718 | VulkanUtils::createVulkanImageFromFile(device, physicalDevice, commandPool, "textures/texture.jpg",
|
---|
719 | floorTextureImage, graphicsQueue);
|
---|
720 |
|
---|
721 | floorTextureImageDescriptor = {};
|
---|
722 | floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
723 | floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
|
---|
724 | floorTextureImageDescriptor.sampler = textureSampler;
|
---|
725 |
|
---|
726 | VulkanUtils::createVulkanImageFromSDLTexture(device, physicalDevice, uiOverlay, sdlOverlayImage);
|
---|
727 |
|
---|
728 | sdlOverlayImageDescriptor = {};
|
---|
729 | sdlOverlayImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
730 | sdlOverlayImageDescriptor.imageView = sdlOverlayImage.imageView;
|
---|
731 | sdlOverlayImageDescriptor.sampler = textureSampler;
|
---|
732 | }
|
---|
733 |
|
---|
734 | void VulkanGame::createTextureSampler() {
|
---|
735 | VkSamplerCreateInfo samplerInfo = {};
|
---|
736 | samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
---|
737 | samplerInfo.magFilter = VK_FILTER_LINEAR;
|
---|
738 | samplerInfo.minFilter = VK_FILTER_LINEAR;
|
---|
739 |
|
---|
740 | samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
741 | samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
742 | samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
743 |
|
---|
744 | samplerInfo.anisotropyEnable = VK_TRUE;
|
---|
745 | samplerInfo.maxAnisotropy = 16;
|
---|
746 | samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
|
---|
747 | samplerInfo.unnormalizedCoordinates = VK_FALSE;
|
---|
748 | samplerInfo.compareEnable = VK_FALSE;
|
---|
749 | samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
|
---|
750 | samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
---|
751 | samplerInfo.mipLodBias = 0.0f;
|
---|
752 | samplerInfo.minLod = 0.0f;
|
---|
753 | samplerInfo.maxLod = 0.0f;
|
---|
754 |
|
---|
755 | if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) {
|
---|
756 | throw runtime_error("failed to create texture sampler!");
|
---|
757 | }
|
---|
758 | }
|
---|
759 |
|
---|
760 | void VulkanGame::createFramebuffers() {
|
---|
761 | swapChainFramebuffers.resize(swapChainImageViews.size());
|
---|
762 |
|
---|
763 | for (size_t i = 0; i < swapChainImageViews.size(); i++) {
|
---|
764 | array<VkImageView, 2> attachments = {
|
---|
765 | swapChainImageViews[i],
|
---|
766 | depthImage.imageView
|
---|
767 | };
|
---|
768 |
|
---|
769 | VkFramebufferCreateInfo framebufferInfo = {};
|
---|
770 | framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
---|
771 | framebufferInfo.renderPass = renderPass;
|
---|
772 | framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
773 | framebufferInfo.pAttachments = attachments.data();
|
---|
774 | framebufferInfo.width = swapChainExtent.width;
|
---|
775 | framebufferInfo.height = swapChainExtent.height;
|
---|
776 | framebufferInfo.layers = 1;
|
---|
777 |
|
---|
778 | if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
|
---|
779 | throw runtime_error("failed to create framebuffer!");
|
---|
780 | }
|
---|
781 | }
|
---|
782 | }
|
---|
783 |
|
---|
784 | void VulkanGame::createUniformBuffers() {
|
---|
785 | VkDeviceSize bufferSize = sizeof(UniformBufferObject);
|
---|
786 |
|
---|
787 | uniformBuffers.resize(swapChainImages.size());
|
---|
788 | uniformBuffersMemory.resize(swapChainImages.size());
|
---|
789 | uniformBufferInfoList.resize(swapChainImages.size());
|
---|
790 |
|
---|
791 | for (size_t i = 0; i < swapChainImages.size(); i++) {
|
---|
792 | VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
---|
793 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
794 | uniformBuffers[i], uniformBuffersMemory[i]);
|
---|
795 |
|
---|
796 | uniformBufferInfoList[i].buffer = uniformBuffers[i];
|
---|
797 | uniformBufferInfoList[i].offset = 0;
|
---|
798 | uniformBufferInfoList[i].range = sizeof(UniformBufferObject);
|
---|
799 | }
|
---|
800 | }
|
---|
801 |
|
---|
802 | void VulkanGame::createCommandBuffers() {
|
---|
803 | commandBuffers.resize(swapChainImages.size());
|
---|
804 |
|
---|
805 | VkCommandBufferAllocateInfo allocInfo = {};
|
---|
806 | allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
---|
807 | allocInfo.commandPool = commandPool;
|
---|
808 | allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
---|
809 | allocInfo.commandBufferCount = (uint32_t) commandBuffers.size();
|
---|
810 |
|
---|
811 | if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
|
---|
812 | throw runtime_error("failed to allocate command buffers!");
|
---|
813 | }
|
---|
814 |
|
---|
815 | for (size_t i = 0; i < commandBuffers.size(); i++) {
|
---|
816 | VkCommandBufferBeginInfo beginInfo = {};
|
---|
817 | beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
---|
818 | beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
|
---|
819 | beginInfo.pInheritanceInfo = nullptr;
|
---|
820 |
|
---|
821 | if (vkBeginCommandBuffer(commandBuffers[i], &beginInfo) != VK_SUCCESS) {
|
---|
822 | throw runtime_error("failed to begin recording command buffer!");
|
---|
823 | }
|
---|
824 |
|
---|
825 | VkRenderPassBeginInfo renderPassInfo = {};
|
---|
826 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
---|
827 | renderPassInfo.renderPass = renderPass;
|
---|
828 | renderPassInfo.framebuffer = swapChainFramebuffers[i];
|
---|
829 | renderPassInfo.renderArea.offset = { 0, 0 };
|
---|
830 | renderPassInfo.renderArea.extent = swapChainExtent;
|
---|
831 |
|
---|
832 | array<VkClearValue, 2> clearValues = {};
|
---|
833 | clearValues[0].color = {{ 0.0f, 0.0f, 0.0f, 1.0f }};
|
---|
834 | clearValues[1].depthStencil = { 1.0f, 0 };
|
---|
835 |
|
---|
836 | renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
|
---|
837 | renderPassInfo.pClearValues = clearValues.data();
|
---|
838 |
|
---|
839 | vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
---|
840 |
|
---|
841 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
842 | pipeline.createRenderCommands(commandBuffers[i], i);
|
---|
843 | }
|
---|
844 |
|
---|
845 | vkCmdEndRenderPass(commandBuffers[i]);
|
---|
846 |
|
---|
847 | if (vkEndCommandBuffer(commandBuffers[i]) != VK_SUCCESS) {
|
---|
848 | throw runtime_error("failed to record command buffer!");
|
---|
849 | }
|
---|
850 | }
|
---|
851 | }
|
---|
852 |
|
---|
853 | void VulkanGame::createSyncObjects() {
|
---|
854 | imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
|
---|
855 | renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
|
---|
856 | inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
|
---|
857 |
|
---|
858 | VkSemaphoreCreateInfo semaphoreInfo = {};
|
---|
859 | semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
|
---|
860 |
|
---|
861 | VkFenceCreateInfo fenceInfo = {};
|
---|
862 | fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
---|
863 | fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
|
---|
864 |
|
---|
865 | for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
|
---|
866 | if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
|
---|
867 | vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
|
---|
868 | vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
|
---|
869 | throw runtime_error("failed to create synchronization objects for a frame!");
|
---|
870 | }
|
---|
871 | }
|
---|
872 | }
|
---|
873 |
|
---|
874 | void VulkanGame::recreateSwapChain() {
|
---|
875 | cout << "Recreating swap chain" << endl;
|
---|
876 | gui->refreshWindowSize();
|
---|
877 |
|
---|
878 | while (gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0 ||
|
---|
879 | (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0) {
|
---|
880 | SDL_WaitEvent(nullptr);
|
---|
881 | gui->refreshWindowSize();
|
---|
882 | }
|
---|
883 |
|
---|
884 | vkDeviceWaitIdle(device);
|
---|
885 |
|
---|
886 | //cleanupSwapChain();
|
---|
887 | }
|
---|
888 |
|
---|
889 | void VulkanGame::cleanupSwapChain() {
|
---|
890 | VulkanUtils::destroyVulkanImage(device, depthImage);
|
---|
891 |
|
---|
892 | for (VkFramebuffer framebuffer : swapChainFramebuffers) {
|
---|
893 | vkDestroyFramebuffer(device, framebuffer, nullptr);
|
---|
894 | }
|
---|
895 |
|
---|
896 | vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
|
---|
897 |
|
---|
898 | for (GraphicsPipeline_Vulkan pipeline : graphicsPipelines) {
|
---|
899 | pipeline.cleanup();
|
---|
900 | }
|
---|
901 |
|
---|
902 | vkDestroyRenderPass(device, renderPass, nullptr);
|
---|
903 |
|
---|
904 | for (VkImageView imageView : swapChainImageViews) {
|
---|
905 | vkDestroyImageView(device, imageView, nullptr);
|
---|
906 | }
|
---|
907 |
|
---|
908 | vkDestroySwapchainKHR(device, swapChain, nullptr);
|
---|
909 |
|
---|
910 | for (size_t i = 0; i < uniformBuffers.size(); i++) {
|
---|
911 | vkDestroyBuffer(device, uniformBuffers[i], nullptr);
|
---|
912 | vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
|
---|
913 | }
|
---|
914 | }
|
---|