1 | #include "sdl-game.hpp"
|
---|
2 |
|
---|
3 | #include <array>
|
---|
4 | #include <iostream>
|
---|
5 | #include <set>
|
---|
6 |
|
---|
7 | #include "IMGUI/imgui_impl_sdl.h"
|
---|
8 |
|
---|
9 | #include "logger.hpp"
|
---|
10 | #include "utils.hpp"
|
---|
11 |
|
---|
12 | #include "gui/imgui/button-imgui.hpp"
|
---|
13 |
|
---|
14 | using namespace std;
|
---|
15 |
|
---|
16 | #define IMGUI_UNLIMITED_FRAME_RATE
|
---|
17 |
|
---|
18 | static void check_imgui_vk_result(VkResult res) {
|
---|
19 | if (res == VK_SUCCESS) {
|
---|
20 | return;
|
---|
21 | }
|
---|
22 |
|
---|
23 | ostringstream oss;
|
---|
24 | oss << "[imgui] Vulkan error! VkResult is \"" << VulkanUtils::resultString(res) << "\"" << __LINE__;
|
---|
25 | if (res < 0) {
|
---|
26 | throw runtime_error("Fatal: " + oss.str());
|
---|
27 | } else {
|
---|
28 | cerr << oss.str();
|
---|
29 | }
|
---|
30 | }
|
---|
31 |
|
---|
32 | VKAPI_ATTR VkBool32 VKAPI_CALL VulkanGame::debugCallback(
|
---|
33 | VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
|
---|
34 | VkDebugUtilsMessageTypeFlagsEXT messageType,
|
---|
35 | const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
|
---|
36 | void* pUserData) {
|
---|
37 | cerr << "validation layer: " << pCallbackData->pMessage << endl;
|
---|
38 |
|
---|
39 | // TODO: Figure out what the return value means and if it should always be VK_FALSE
|
---|
40 | return VK_FALSE;
|
---|
41 | }
|
---|
42 |
|
---|
43 | VulkanGame::VulkanGame()
|
---|
44 | : swapChainImageCount(0)
|
---|
45 | , swapChainMinImageCount(0)
|
---|
46 | , swapChainSurfaceFormat({})
|
---|
47 | , swapChainPresentMode(VK_PRESENT_MODE_MAX_ENUM_KHR)
|
---|
48 | , swapChainExtent{ 0, 0 }
|
---|
49 | , swapChain(VK_NULL_HANDLE)
|
---|
50 | , vulkanSurface(VK_NULL_HANDLE)
|
---|
51 | , sdlVersion({ 0, 0, 0 })
|
---|
52 | , instance(VK_NULL_HANDLE)
|
---|
53 | , physicalDevice(VK_NULL_HANDLE)
|
---|
54 | , device(VK_NULL_HANDLE)
|
---|
55 | , debugMessenger(VK_NULL_HANDLE)
|
---|
56 | , resourceCommandPool(VK_NULL_HANDLE)
|
---|
57 | , renderPass(VK_NULL_HANDLE)
|
---|
58 | , graphicsQueue(VK_NULL_HANDLE)
|
---|
59 | , presentQueue(VK_NULL_HANDLE)
|
---|
60 | , depthImage({})
|
---|
61 | , shouldRecreateSwapChain(false)
|
---|
62 | , frameCount(0)
|
---|
63 | , currentFrame(0)
|
---|
64 | , imageIndex(0)
|
---|
65 | , fpsStartTime(0.0f)
|
---|
66 | , curTime(0.0f)
|
---|
67 | , done(false)
|
---|
68 | , currentRenderScreenFn(nullptr)
|
---|
69 | , imguiDescriptorPool(VK_NULL_HANDLE)
|
---|
70 | , gui(nullptr)
|
---|
71 | , window(nullptr)
|
---|
72 | , objects_modelPipeline()
|
---|
73 | , score(0)
|
---|
74 | , fps(0.0f) {
|
---|
75 | }
|
---|
76 |
|
---|
77 | VulkanGame::~VulkanGame() {
|
---|
78 | }
|
---|
79 |
|
---|
80 | void VulkanGame::run(int width, int height, unsigned char guiFlags) {
|
---|
81 | cout << "Vulkan Game" << endl;
|
---|
82 |
|
---|
83 | cout << "DEBUGGING IS " << (ENABLE_VALIDATION_LAYERS ? "ON" : "OFF") << endl;
|
---|
84 |
|
---|
85 | if (initUI(width, height, guiFlags) == RTWO_ERROR) {
|
---|
86 | return;
|
---|
87 | }
|
---|
88 |
|
---|
89 | initVulkan();
|
---|
90 |
|
---|
91 | VkPhysicalDeviceProperties deviceProperties;
|
---|
92 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
93 |
|
---|
94 | objects_modelPipeline = VulkanBuffer<SSBO_ModelObject>(10, deviceProperties.limits.maxStorageBufferRange,
|
---|
95 | deviceProperties.limits.minStorageBufferOffsetAlignment);
|
---|
96 |
|
---|
97 | initImGuiOverlay();
|
---|
98 |
|
---|
99 | // TODO: Figure out how much of ubo creation and associated variables should be in the pipeline class
|
---|
100 | // Maybe combine the ubo-related objects into a new class
|
---|
101 |
|
---|
102 | initGraphicsPipelines();
|
---|
103 |
|
---|
104 | initMatrices();
|
---|
105 |
|
---|
106 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::pos));
|
---|
107 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::color));
|
---|
108 | modelPipeline.addAttribute(VK_FORMAT_R32G32_SFLOAT, offset_of(&ModelVertex::texCoord));
|
---|
109 | modelPipeline.addAttribute(VK_FORMAT_R32G32B32_SFLOAT, offset_of(&ModelVertex::normal));
|
---|
110 | modelPipeline.addAttribute(VK_FORMAT_R32_UINT, offset_of(&ModelVertex::objIndex));
|
---|
111 |
|
---|
112 | createBufferSet(sizeof(UBO_VP_mats),
|
---|
113 | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
114 | uniformBuffers_modelPipeline);
|
---|
115 |
|
---|
116 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
---|
117 | VK_SHADER_STAGE_VERTEX_BIT, &uniformBuffers_modelPipeline.infoSet);
|
---|
118 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
---|
119 | VK_SHADER_STAGE_VERTEX_BIT, &storageBuffers_modelPipeline.infoSet);
|
---|
120 | modelPipeline.addDescriptorInfo(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
---|
121 | VK_SHADER_STAGE_FRAGMENT_BIT, &floorTextureImageDescriptor);
|
---|
122 |
|
---|
123 | SceneObject<ModelVertex, SSBO_ModelObject>* texturedSquare = nullptr;
|
---|
124 |
|
---|
125 | texturedSquare = &addObject(modelObjects, modelPipeline,
|
---|
126 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
127 | addVertexNormals<ModelVertex>({
|
---|
128 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
129 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
130 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
131 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
132 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
133 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0}
|
---|
134 | })),
|
---|
135 | {
|
---|
136 | 0, 1, 2, 3, 4, 5
|
---|
137 | }, objects_modelPipeline, {
|
---|
138 | mat4(1.0f)
|
---|
139 | });
|
---|
140 |
|
---|
141 | texturedSquare->model_base =
|
---|
142 | translate(mat4(1.0f), vec3(0.0f, 0.0f, -2.0f));
|
---|
143 |
|
---|
144 | texturedSquare = &addObject(modelObjects, modelPipeline,
|
---|
145 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
146 | addVertexNormals<ModelVertex>({
|
---|
147 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
|
---|
148 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
|
---|
149 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
150 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
|
---|
151 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}},
|
---|
152 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}}
|
---|
153 | })), {
|
---|
154 | 0, 1, 2, 3, 4, 5
|
---|
155 | }, objects_modelPipeline, {
|
---|
156 | mat4(1.0f)
|
---|
157 | });
|
---|
158 |
|
---|
159 | texturedSquare->model_base =
|
---|
160 | translate(mat4(1.0f), vec3(0.0f, 0.0f, -1.5f));
|
---|
161 |
|
---|
162 | modelPipeline.createDescriptorSetLayout();
|
---|
163 | modelPipeline.createPipeline("shaders/model-vert.spv", "shaders/model-frag.spv");
|
---|
164 | modelPipeline.createDescriptorPool(swapChainImages.size());
|
---|
165 | modelPipeline.createDescriptorSets(swapChainImages.size());
|
---|
166 |
|
---|
167 | currentRenderScreenFn = &VulkanGame::renderMainScreen;
|
---|
168 |
|
---|
169 | ImGuiIO& io = ImGui::GetIO();
|
---|
170 |
|
---|
171 | initGuiValueLists(valueLists);
|
---|
172 |
|
---|
173 | valueLists["stats value list"].push_back(UIValue(UIVALUE_INT, "Score", &score));
|
---|
174 | valueLists["stats value list"].push_back(UIValue(UIVALUE_DOUBLE, "FPS", &fps));
|
---|
175 | valueLists["stats value list"].push_back(UIValue(UIVALUE_DOUBLE, "IMGUI FPS", &io.Framerate));
|
---|
176 |
|
---|
177 | renderLoop();
|
---|
178 | cleanup();
|
---|
179 |
|
---|
180 | close_log();
|
---|
181 | }
|
---|
182 |
|
---|
183 | bool VulkanGame::initUI(int width, int height, unsigned char guiFlags) {
|
---|
184 | // TODO: Create a game-gui function to get the gui version and retrieve it that way
|
---|
185 |
|
---|
186 | SDL_VERSION(&sdlVersion); // This gets the compile-time version
|
---|
187 | SDL_GetVersion(&sdlVersion); // This gets the runtime version
|
---|
188 |
|
---|
189 | cout << "SDL " <<
|
---|
190 | to_string(sdlVersion.major) << "." <<
|
---|
191 | to_string(sdlVersion.minor) << "." <<
|
---|
192 | to_string(sdlVersion.patch) << endl;
|
---|
193 |
|
---|
194 | // TODO: Refactor the logger api to be more flexible,
|
---|
195 | // esp. since gl_log() and gl_log_err() have issues printing anything besides strings
|
---|
196 | restart_gl_log();
|
---|
197 | gl_log("starting SDL\n%s.%s.%s",
|
---|
198 | to_string(sdlVersion.major).c_str(),
|
---|
199 | to_string(sdlVersion.minor).c_str(),
|
---|
200 | to_string(sdlVersion.patch).c_str());
|
---|
201 |
|
---|
202 | // TODO: Use open_Log() and related functions instead of gl_log ones
|
---|
203 | // TODO: In addition, delete the gl_log functions
|
---|
204 | open_log();
|
---|
205 | get_log() << "starting SDL" << endl;
|
---|
206 | get_log() <<
|
---|
207 | (int)sdlVersion.major << "." <<
|
---|
208 | (int)sdlVersion.minor << "." <<
|
---|
209 | (int)sdlVersion.patch << endl;
|
---|
210 |
|
---|
211 | // TODO: Put all fonts, textures, and images in the assets folder
|
---|
212 | gui = new GameGui_SDL();
|
---|
213 |
|
---|
214 | if (gui->init() == RTWO_ERROR) {
|
---|
215 | // TODO: Also print these sorts of errors to the log
|
---|
216 | cout << "UI library could not be initialized!" << endl;
|
---|
217 | cout << gui->getError() << endl;
|
---|
218 | // TODO: Rename RTWO_ERROR to something else
|
---|
219 | return RTWO_ERROR;
|
---|
220 | }
|
---|
221 |
|
---|
222 | window = (SDL_Window*)gui->createWindow("Vulkan Game", width, height, guiFlags & GUI_FLAGS_WINDOW_FULLSCREEN);
|
---|
223 | if (window == nullptr) {
|
---|
224 | cout << "Window could not be created!" << endl;
|
---|
225 | cout << gui->getError() << endl;
|
---|
226 | return RTWO_ERROR;
|
---|
227 | }
|
---|
228 |
|
---|
229 | cout << "Target window size: (" << width << ", " << height << ")" << endl;
|
---|
230 | cout << "Actual window size: (" << gui->getWindowWidth() << ", " << gui->getWindowHeight() << ")" << endl;
|
---|
231 |
|
---|
232 | return RTWO_SUCCESS;
|
---|
233 | }
|
---|
234 |
|
---|
235 | void VulkanGame::initVulkan() {
|
---|
236 | const vector<const char*> validationLayers = {
|
---|
237 | "VK_LAYER_KHRONOS_validation"
|
---|
238 | };
|
---|
239 | const vector<const char*> deviceExtensions = {
|
---|
240 | VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
---|
241 | };
|
---|
242 |
|
---|
243 | createVulkanInstance(validationLayers);
|
---|
244 | setupDebugMessenger();
|
---|
245 | createVulkanSurface();
|
---|
246 | pickPhysicalDevice(deviceExtensions);
|
---|
247 | createLogicalDevice(validationLayers, deviceExtensions);
|
---|
248 | chooseSwapChainProperties();
|
---|
249 | createSwapChain();
|
---|
250 | createImageViews();
|
---|
251 |
|
---|
252 | createResourceCommandPool();
|
---|
253 | createImageResources();
|
---|
254 |
|
---|
255 | createRenderPass();
|
---|
256 | createCommandPools();
|
---|
257 | createFramebuffers();
|
---|
258 | createCommandBuffers();
|
---|
259 | createSyncObjects();
|
---|
260 | }
|
---|
261 |
|
---|
262 | void VulkanGame::initGraphicsPipelines() {
|
---|
263 | modelPipeline = GraphicsPipeline_Vulkan<ModelVertex>(
|
---|
264 | VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, physicalDevice, device, renderPass,
|
---|
265 | { 0, 0, (int)swapChainExtent.width, (int)swapChainExtent.height }, 16, 24);
|
---|
266 |
|
---|
267 | createBufferSet(objects_modelPipeline.capacity * sizeof(SSBO_ModelObject),
|
---|
268 | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT
|
---|
269 | | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
---|
270 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
271 | storageBuffers_modelPipeline);
|
---|
272 | }
|
---|
273 |
|
---|
274 | // TODO: Maybe change the name to initScene() or something similar
|
---|
275 | void VulkanGame::initMatrices() {
|
---|
276 | cam_pos = vec3(0.0f, 0.0f, 2.0f);
|
---|
277 |
|
---|
278 | float cam_yaw = 0.0f;
|
---|
279 | float cam_pitch = -50.0f;
|
---|
280 |
|
---|
281 | mat4 yaw_mat = rotate(mat4(1.0f), radians(-cam_yaw), vec3(0.0f, 1.0f, 0.0f));
|
---|
282 | mat4 pitch_mat = rotate(mat4(1.0f), radians(-cam_pitch), vec3(1.0f, 0.0f, 0.0f));
|
---|
283 |
|
---|
284 | mat4 R_view = pitch_mat * yaw_mat;
|
---|
285 | mat4 T_view = translate(mat4(1.0f), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
|
---|
286 | viewMat = R_view * T_view;
|
---|
287 |
|
---|
288 | projMat = perspective(radians(FOV_ANGLE), (float)swapChainExtent.width / (float)swapChainExtent.height, NEAR_CLIP, FAR_CLIP);
|
---|
289 | projMat[1][1] *= -1; // flip the y-axis so that +y is up
|
---|
290 |
|
---|
291 | object_VP_mats.view = viewMat;
|
---|
292 | object_VP_mats.proj = projMat;
|
---|
293 | }
|
---|
294 |
|
---|
295 | void VulkanGame::renderLoop() {
|
---|
296 | startTime = steady_clock::now();
|
---|
297 | curTime = duration<float, seconds::period>(steady_clock::now() - startTime).count();
|
---|
298 |
|
---|
299 | fpsStartTime = curTime;
|
---|
300 | frameCount = 0;
|
---|
301 |
|
---|
302 | ImGuiIO& io = ImGui::GetIO();
|
---|
303 |
|
---|
304 | done = false;
|
---|
305 | while (!done) {
|
---|
306 |
|
---|
307 | prevTime = curTime;
|
---|
308 | curTime = duration<float, seconds::period>(steady_clock::now() - startTime).count();
|
---|
309 | elapsedTime = curTime - prevTime;
|
---|
310 |
|
---|
311 | if (curTime - fpsStartTime >= 1.0f) {
|
---|
312 | fps = (float)frameCount / (curTime - fpsStartTime);
|
---|
313 |
|
---|
314 | frameCount = 0;
|
---|
315 | fpsStartTime = curTime;
|
---|
316 | }
|
---|
317 |
|
---|
318 | frameCount++;
|
---|
319 |
|
---|
320 | gui->processEvents();
|
---|
321 |
|
---|
322 | UIEvent uiEvent;
|
---|
323 | while (gui->pollEvent(&uiEvent)) {
|
---|
324 | GameEvent& e = uiEvent.event;
|
---|
325 | SDL_Event sdlEvent = uiEvent.rawEvent.sdl;
|
---|
326 |
|
---|
327 | ImGui_ImplSDL2_ProcessEvent(&sdlEvent);
|
---|
328 | if ((e.type == UI_EVENT_MOUSEBUTTONDOWN || e.type == UI_EVENT_MOUSEBUTTONUP || e.type == UI_EVENT_UNKNOWN) &&
|
---|
329 | io.WantCaptureMouse) {
|
---|
330 | if (sdlEvent.type == SDL_MOUSEWHEEL || sdlEvent.type == SDL_MOUSEBUTTONDOWN ||
|
---|
331 | sdlEvent.type == SDL_MOUSEBUTTONUP) {
|
---|
332 | continue;
|
---|
333 | }
|
---|
334 | }
|
---|
335 | if ((e.type == UI_EVENT_KEYDOWN || e.type == UI_EVENT_KEYUP) && io.WantCaptureKeyboard) {
|
---|
336 | if (sdlEvent.type == SDL_KEYDOWN || sdlEvent.type == SDL_KEYUP) {
|
---|
337 | continue;
|
---|
338 | }
|
---|
339 | }
|
---|
340 | if (io.WantTextInput) {
|
---|
341 | // show onscreen keyboard if on mobile
|
---|
342 | }
|
---|
343 |
|
---|
344 | switch (e.type) {
|
---|
345 | case UI_EVENT_QUIT:
|
---|
346 | cout << "Quit event detected" << endl;
|
---|
347 | done = true;
|
---|
348 | break;
|
---|
349 | case UI_EVENT_WINDOWRESIZE:
|
---|
350 | cout << "Window resize event detected" << endl;
|
---|
351 | shouldRecreateSwapChain = true;
|
---|
352 | break;
|
---|
353 | case UI_EVENT_KEYDOWN:
|
---|
354 | if (e.key.repeat) {
|
---|
355 | break;
|
---|
356 | }
|
---|
357 |
|
---|
358 | if (e.key.keycode == SDL_SCANCODE_ESCAPE) {
|
---|
359 | done = true;
|
---|
360 | } else if (e.key.keycode == SDL_SCANCODE_SPACE) {
|
---|
361 | cout << "Adding a plane" << endl;
|
---|
362 | float zOffset = -2.0f + (0.5f * modelObjects.size());
|
---|
363 |
|
---|
364 | SceneObject<ModelVertex, SSBO_ModelObject>& texturedSquare =
|
---|
365 | addObject(modelObjects, modelPipeline,
|
---|
366 | addObjectIndex<ModelVertex>(modelObjects.size(),
|
---|
367 | addVertexNormals<ModelVertex>({
|
---|
368 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
369 | {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
370 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
371 | {{ 0.5f, 0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
372 | {{-0.5f, 0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, 0},
|
---|
373 | {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}, 0}
|
---|
374 | })),
|
---|
375 | {
|
---|
376 | 0, 1, 2, 3, 4, 5
|
---|
377 | }, objects_modelPipeline, {
|
---|
378 | mat4(1.0f)
|
---|
379 | });
|
---|
380 |
|
---|
381 | texturedSquare.model_base =
|
---|
382 | translate(mat4(1.0f), vec3(0.0f, 0.0f, zOffset));
|
---|
383 | // START UNREVIEWED SECTION
|
---|
384 | // END UNREVIEWED SECTION
|
---|
385 | } else {
|
---|
386 | cout << "Key event detected" << endl;
|
---|
387 | }
|
---|
388 | break;
|
---|
389 | case UI_EVENT_KEYUP:
|
---|
390 | // START UNREVIEWED SECTION
|
---|
391 | // END UNREVIEWED SECTION
|
---|
392 | break;
|
---|
393 | case UI_EVENT_WINDOW:
|
---|
394 | case UI_EVENT_MOUSEBUTTONDOWN:
|
---|
395 | case UI_EVENT_MOUSEBUTTONUP:
|
---|
396 | case UI_EVENT_MOUSEMOTION:
|
---|
397 | break;
|
---|
398 | case UI_EVENT_UNHANDLED:
|
---|
399 | cout << "Unhandled event type: 0x" << hex << sdlEvent.type << dec << endl;
|
---|
400 | break;
|
---|
401 | case UI_EVENT_UNKNOWN:
|
---|
402 | default:
|
---|
403 | cout << "Unknown event type: 0x" << hex << sdlEvent.type << dec << endl;
|
---|
404 | break;
|
---|
405 | }
|
---|
406 | }
|
---|
407 |
|
---|
408 | if (shouldRecreateSwapChain) {
|
---|
409 | gui->refreshWindowSize();
|
---|
410 | const bool isMinimized = gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0;
|
---|
411 |
|
---|
412 | if (!isMinimized) {
|
---|
413 | // TODO: This should be used if the min image count changes, presumably because a new surface was created
|
---|
414 | // with a different image count or something like that. Maybe I want to add code to query for a new min image count
|
---|
415 | // during swapchain recreation to take advantage of this
|
---|
416 | ImGui_ImplVulkan_SetMinImageCount(swapChainMinImageCount);
|
---|
417 |
|
---|
418 | recreateSwapChain();
|
---|
419 |
|
---|
420 | shouldRecreateSwapChain = false;
|
---|
421 | }
|
---|
422 | }
|
---|
423 |
|
---|
424 | updateScene();
|
---|
425 |
|
---|
426 | // TODO: Move this into a renderImGuiOverlay() function
|
---|
427 | ImGui_ImplVulkan_NewFrame();
|
---|
428 | ImGui_ImplSDL2_NewFrame(window);
|
---|
429 | ImGui::NewFrame();
|
---|
430 |
|
---|
431 | (this->*currentRenderScreenFn)(gui->getWindowWidth(), gui->getWindowHeight());
|
---|
432 |
|
---|
433 | ImGui::Render();
|
---|
434 |
|
---|
435 | gui->refreshWindowSize();
|
---|
436 | const bool isMinimized = gui->getWindowWidth() == 0 || gui->getWindowHeight() == 0;
|
---|
437 |
|
---|
438 | if (!isMinimized) {
|
---|
439 | renderFrame(ImGui::GetDrawData());
|
---|
440 | presentFrame();
|
---|
441 | }
|
---|
442 | }
|
---|
443 | }
|
---|
444 |
|
---|
445 | void VulkanGame::updateScene() {
|
---|
446 | // TODO: Probably move the resizing to the VulkanBuffer class
|
---|
447 | if (objects_modelPipeline.resized) {
|
---|
448 | resizeBufferSet(storageBuffers_modelPipeline, objects_modelPipeline.memorySize(), resourceCommandPool,
|
---|
449 | graphicsQueue, true);
|
---|
450 |
|
---|
451 | objects_modelPipeline.resize();
|
---|
452 |
|
---|
453 | modelPipeline.updateDescriptorInfo(1, &storageBuffers_modelPipeline.infoSet, swapChainImages.size());
|
---|
454 | }
|
---|
455 |
|
---|
456 | for (size_t i = 0; i < modelObjects.size(); i++) {
|
---|
457 | SceneObject<ModelVertex, SSBO_ModelObject>& obj = modelObjects[i];
|
---|
458 | SSBO_ModelObject& objData = obj.ssbo;
|
---|
459 |
|
---|
460 | // Rotate the textured squares
|
---|
461 | obj.model_transform =
|
---|
462 | translate(mat4(1.0f), vec3(0.0f, -2.0f, -0.0f)) *
|
---|
463 | rotate(mat4(1.0f), curTime * radians(90.0f), vec3(0.0f, 0.0f, 1.0f));
|
---|
464 |
|
---|
465 | objData.model = obj.model_transform * obj.model_base;
|
---|
466 | obj.center = vec3(objData.model * vec4(0.0f, 0.0f, 0.0f, 1.0f));
|
---|
467 |
|
---|
468 | updateBufferSet(storageBuffers_modelPipeline, i, objData);
|
---|
469 | }
|
---|
470 |
|
---|
471 | VulkanUtils::copyDataToMemory(device, &object_VP_mats, uniformBuffers_modelPipeline.memory[imageIndex], 0,
|
---|
472 | sizeof(object_VP_mats), false);
|
---|
473 | }
|
---|
474 |
|
---|
475 | void VulkanGame::cleanup() {
|
---|
476 | // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
|
---|
477 | //vkQueueWaitIdle(g_Queue);
|
---|
478 | VKUTIL_CHECK_RESULT(vkDeviceWaitIdle(device), "failed to wait for device!");
|
---|
479 |
|
---|
480 | cleanupImGuiOverlay();
|
---|
481 |
|
---|
482 | cleanupSwapChain();
|
---|
483 |
|
---|
484 | VulkanUtils::destroyVulkanImage(device, floorTextureImage);
|
---|
485 | // START UNREVIEWED SECTION
|
---|
486 |
|
---|
487 | vkDestroySampler(device, textureSampler, nullptr);
|
---|
488 |
|
---|
489 | modelPipeline.cleanupBuffers();
|
---|
490 |
|
---|
491 | for (size_t i = 0; i < storageBuffers_modelPipeline.buffers.size(); i++) {
|
---|
492 | vkDestroyBuffer(device, storageBuffers_modelPipeline.buffers[i], nullptr);
|
---|
493 | vkFreeMemory(device, storageBuffers_modelPipeline.memory[i], nullptr);
|
---|
494 | }
|
---|
495 |
|
---|
496 | // END UNREVIEWED SECTION
|
---|
497 |
|
---|
498 | vkDestroyCommandPool(device, resourceCommandPool, nullptr);
|
---|
499 |
|
---|
500 | vkDestroyDevice(device, nullptr);
|
---|
501 | vkDestroySurfaceKHR(instance, vulkanSurface, nullptr);
|
---|
502 |
|
---|
503 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
504 | VulkanUtils::destroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
|
---|
505 | }
|
---|
506 |
|
---|
507 | vkDestroyInstance(instance, nullptr);
|
---|
508 |
|
---|
509 | gui->destroyWindow();
|
---|
510 | gui->shutdown();
|
---|
511 | delete gui;
|
---|
512 | }
|
---|
513 |
|
---|
514 | void VulkanGame::createVulkanInstance(const vector<const char*>& validationLayers) {
|
---|
515 | if (ENABLE_VALIDATION_LAYERS && !VulkanUtils::checkValidationLayerSupport(validationLayers)) {
|
---|
516 | throw runtime_error("validation layers requested, but not available!");
|
---|
517 | }
|
---|
518 |
|
---|
519 | VkApplicationInfo appInfo = {};
|
---|
520 | appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
---|
521 | appInfo.pApplicationName = "Vulkan Game";
|
---|
522 | appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
523 | appInfo.pEngineName = "No Engine";
|
---|
524 | appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
---|
525 | appInfo.apiVersion = VK_API_VERSION_1_0;
|
---|
526 |
|
---|
527 | VkInstanceCreateInfo createInfo = {};
|
---|
528 | createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
---|
529 | createInfo.pApplicationInfo = &appInfo;
|
---|
530 |
|
---|
531 | vector<const char*> extensions = gui->getRequiredExtensions();
|
---|
532 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
533 | extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
---|
534 | }
|
---|
535 |
|
---|
536 | createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
|
---|
537 | createInfo.ppEnabledExtensionNames = extensions.data();
|
---|
538 |
|
---|
539 | cout << endl << "Extensions:" << endl;
|
---|
540 | for (const char* extensionName : extensions) {
|
---|
541 | cout << extensionName << endl;
|
---|
542 | }
|
---|
543 | cout << endl;
|
---|
544 |
|
---|
545 | VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
|
---|
546 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
547 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
548 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
549 |
|
---|
550 | populateDebugMessengerCreateInfo(debugCreateInfo);
|
---|
551 | createInfo.pNext = &debugCreateInfo;
|
---|
552 | }
|
---|
553 | else {
|
---|
554 | createInfo.enabledLayerCount = 0;
|
---|
555 |
|
---|
556 | createInfo.pNext = nullptr;
|
---|
557 | }
|
---|
558 |
|
---|
559 | if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
|
---|
560 | throw runtime_error("failed to create instance!");
|
---|
561 | }
|
---|
562 | }
|
---|
563 |
|
---|
564 | void VulkanGame::setupDebugMessenger() {
|
---|
565 | if (!ENABLE_VALIDATION_LAYERS) {
|
---|
566 | return;
|
---|
567 | }
|
---|
568 |
|
---|
569 | VkDebugUtilsMessengerCreateInfoEXT createInfo;
|
---|
570 | populateDebugMessengerCreateInfo(createInfo);
|
---|
571 |
|
---|
572 | if (VulkanUtils::createDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
|
---|
573 | throw runtime_error("failed to set up debug messenger!");
|
---|
574 | }
|
---|
575 | }
|
---|
576 |
|
---|
577 | void VulkanGame::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
|
---|
578 | createInfo = {};
|
---|
579 | createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
---|
580 | 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;
|
---|
581 | 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;
|
---|
582 | createInfo.pfnUserCallback = debugCallback;
|
---|
583 | }
|
---|
584 |
|
---|
585 | void VulkanGame::createVulkanSurface() {
|
---|
586 | if (gui->createVulkanSurface(instance, &vulkanSurface) == RTWO_ERROR) {
|
---|
587 | throw runtime_error("failed to create window surface!");
|
---|
588 | }
|
---|
589 | }
|
---|
590 |
|
---|
591 | void VulkanGame::pickPhysicalDevice(const vector<const char*>& deviceExtensions) {
|
---|
592 | uint32_t deviceCount = 0;
|
---|
593 | // TODO: Check VkResult
|
---|
594 | vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
|
---|
595 |
|
---|
596 | if (deviceCount == 0) {
|
---|
597 | throw runtime_error("failed to find GPUs with Vulkan support!");
|
---|
598 | }
|
---|
599 |
|
---|
600 | vector<VkPhysicalDevice> devices(deviceCount);
|
---|
601 | // TODO: Check VkResult
|
---|
602 | vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
|
---|
603 |
|
---|
604 | cout << endl << "Graphics cards:" << endl;
|
---|
605 | for (const VkPhysicalDevice& device : devices) {
|
---|
606 | if (isDeviceSuitable(device, deviceExtensions)) {
|
---|
607 | physicalDevice = device;
|
---|
608 | break;
|
---|
609 | }
|
---|
610 | }
|
---|
611 | cout << endl;
|
---|
612 |
|
---|
613 | if (physicalDevice == VK_NULL_HANDLE) {
|
---|
614 | throw runtime_error("failed to find a suitable GPU!");
|
---|
615 | }
|
---|
616 | }
|
---|
617 |
|
---|
618 | bool VulkanGame::isDeviceSuitable(VkPhysicalDevice physicalDevice, const vector<const char*>& deviceExtensions) {
|
---|
619 | VkPhysicalDeviceProperties deviceProperties;
|
---|
620 | vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
---|
621 |
|
---|
622 | cout << "Device: " << deviceProperties.deviceName << endl;
|
---|
623 |
|
---|
624 | // TODO: Eventually, maybe let the user pick out of a set of GPUs in case the user does want to use
|
---|
625 | // an integrated GPU. On my laptop, this function returns TRUE for the integrated GPU, but crashes
|
---|
626 | // when trying to use it to render. Maybe I just need to figure out which other extensions and features
|
---|
627 | // to check.
|
---|
628 | if (deviceProperties.deviceType != VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
|
---|
629 | return false;
|
---|
630 | }
|
---|
631 |
|
---|
632 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
633 | bool extensionsSupported = VulkanUtils::checkDeviceExtensionSupport(physicalDevice, deviceExtensions);
|
---|
634 | bool swapChainAdequate = false;
|
---|
635 |
|
---|
636 | if (extensionsSupported) {
|
---|
637 | vector<VkSurfaceFormatKHR> formats = VulkanUtils::querySwapChainFormats(physicalDevice, vulkanSurface);
|
---|
638 | vector<VkPresentModeKHR> presentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, vulkanSurface);
|
---|
639 |
|
---|
640 | swapChainAdequate = !formats.empty() && !presentModes.empty();
|
---|
641 | }
|
---|
642 |
|
---|
643 | VkPhysicalDeviceFeatures supportedFeatures;
|
---|
644 | vkGetPhysicalDeviceFeatures(physicalDevice, &supportedFeatures);
|
---|
645 |
|
---|
646 | return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
|
---|
647 | }
|
---|
648 |
|
---|
649 | void VulkanGame::createLogicalDevice(const vector<const char*>& validationLayers,
|
---|
650 | const vector<const char*>& deviceExtensions) {
|
---|
651 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
652 |
|
---|
653 | if (!indices.isComplete()) {
|
---|
654 | throw runtime_error("failed to find required queue families!");
|
---|
655 | }
|
---|
656 |
|
---|
657 | // TODO: Using separate graphics and present queues currently works, but I should verify that I'm
|
---|
658 | // using them correctly to get the most benefit out of separate queues
|
---|
659 |
|
---|
660 | vector<VkDeviceQueueCreateInfo> queueCreateInfoList;
|
---|
661 | set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
662 |
|
---|
663 | float queuePriority = 1.0f;
|
---|
664 | for (uint32_t queueFamily : uniqueQueueFamilies) {
|
---|
665 | VkDeviceQueueCreateInfo queueCreateInfo = {};
|
---|
666 | queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
---|
667 | queueCreateInfo.queueCount = 1;
|
---|
668 | queueCreateInfo.queueFamilyIndex = queueFamily;
|
---|
669 | queueCreateInfo.pQueuePriorities = &queuePriority;
|
---|
670 |
|
---|
671 | queueCreateInfoList.push_back(queueCreateInfo);
|
---|
672 | }
|
---|
673 |
|
---|
674 | VkPhysicalDeviceFeatures deviceFeatures = {};
|
---|
675 | deviceFeatures.samplerAnisotropy = VK_TRUE;
|
---|
676 |
|
---|
677 | VkDeviceCreateInfo createInfo = {};
|
---|
678 | createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
---|
679 |
|
---|
680 | createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfoList.size());
|
---|
681 | createInfo.pQueueCreateInfos = queueCreateInfoList.data();
|
---|
682 |
|
---|
683 | createInfo.pEnabledFeatures = &deviceFeatures;
|
---|
684 |
|
---|
685 | createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
|
---|
686 | createInfo.ppEnabledExtensionNames = deviceExtensions.data();
|
---|
687 |
|
---|
688 | // These fields are ignored by up-to-date Vulkan implementations,
|
---|
689 | // but it's a good idea to set them for backwards compatibility
|
---|
690 | if (ENABLE_VALIDATION_LAYERS) {
|
---|
691 | createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
|
---|
692 | createInfo.ppEnabledLayerNames = validationLayers.data();
|
---|
693 | }
|
---|
694 | else {
|
---|
695 | createInfo.enabledLayerCount = 0;
|
---|
696 | }
|
---|
697 |
|
---|
698 | if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
|
---|
699 | throw runtime_error("failed to create logical device!");
|
---|
700 | }
|
---|
701 |
|
---|
702 | vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
|
---|
703 | vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
|
---|
704 | }
|
---|
705 |
|
---|
706 | void VulkanGame::chooseSwapChainProperties() {
|
---|
707 | vector<VkSurfaceFormatKHR> availableFormats = VulkanUtils::querySwapChainFormats(physicalDevice, vulkanSurface);
|
---|
708 | vector<VkPresentModeKHR> availablePresentModes = VulkanUtils::querySwapChainPresentModes(physicalDevice, vulkanSurface);
|
---|
709 |
|
---|
710 | // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
|
---|
711 | // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
|
---|
712 | // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
|
---|
713 | // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
|
---|
714 | swapChainSurfaceFormat = VulkanUtils::chooseSwapSurfaceFormat(availableFormats,
|
---|
715 | { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM },
|
---|
716 | VK_COLOR_SPACE_SRGB_NONLINEAR_KHR);
|
---|
717 |
|
---|
718 | #ifdef IMGUI_UNLIMITED_FRAME_RATE
|
---|
719 | vector<VkPresentModeKHR> presentModes{
|
---|
720 | VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR
|
---|
721 | };
|
---|
722 | #else
|
---|
723 | vector<VkPresentModeKHR> presentModes{ VK_PRESENT_MODE_FIFO_KHR };
|
---|
724 | #endif
|
---|
725 |
|
---|
726 | swapChainPresentMode = VulkanUtils::chooseSwapPresentMode(availablePresentModes, presentModes);
|
---|
727 |
|
---|
728 | cout << "[vulkan] Selected PresentMode = " << swapChainPresentMode << endl;
|
---|
729 |
|
---|
730 | VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, vulkanSurface);
|
---|
731 |
|
---|
732 | // If min image count was not specified, request different count of images dependent on selected present mode
|
---|
733 | if (swapChainMinImageCount == 0) {
|
---|
734 | if (swapChainPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
|
---|
735 | swapChainMinImageCount = 3;
|
---|
736 | }
|
---|
737 | else if (swapChainPresentMode == VK_PRESENT_MODE_FIFO_KHR || swapChainPresentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
|
---|
738 | swapChainMinImageCount = 2;
|
---|
739 | }
|
---|
740 | else if (swapChainPresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
|
---|
741 | swapChainMinImageCount = 1;
|
---|
742 | }
|
---|
743 | else {
|
---|
744 | throw runtime_error("unexpected present mode!");
|
---|
745 | }
|
---|
746 | }
|
---|
747 |
|
---|
748 | if (swapChainMinImageCount < capabilities.minImageCount) {
|
---|
749 | swapChainMinImageCount = capabilities.minImageCount;
|
---|
750 | }
|
---|
751 | else if (capabilities.maxImageCount != 0 && swapChainMinImageCount > capabilities.maxImageCount) {
|
---|
752 | swapChainMinImageCount = capabilities.maxImageCount;
|
---|
753 | }
|
---|
754 | }
|
---|
755 |
|
---|
756 | void VulkanGame::createSwapChain() {
|
---|
757 | VkSurfaceCapabilitiesKHR capabilities = VulkanUtils::querySwapChainCapabilities(physicalDevice, vulkanSurface);
|
---|
758 |
|
---|
759 | swapChainExtent = VulkanUtils::chooseSwapExtent(capabilities, gui->getWindowWidth(), gui->getWindowHeight());
|
---|
760 |
|
---|
761 | VkSwapchainCreateInfoKHR createInfo = {};
|
---|
762 | createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
---|
763 | createInfo.surface = vulkanSurface;
|
---|
764 | createInfo.minImageCount = swapChainMinImageCount;
|
---|
765 | createInfo.imageFormat = swapChainSurfaceFormat.format;
|
---|
766 | createInfo.imageColorSpace = swapChainSurfaceFormat.colorSpace;
|
---|
767 | createInfo.imageExtent = swapChainExtent;
|
---|
768 | createInfo.imageArrayLayers = 1;
|
---|
769 | createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
---|
770 |
|
---|
771 | // TODO: Maybe save this result so I don't have to recalculate it every time
|
---|
772 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
773 | uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
|
---|
774 |
|
---|
775 | if (indices.graphicsFamily != indices.presentFamily) {
|
---|
776 | createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
|
---|
777 | createInfo.queueFamilyIndexCount = 2;
|
---|
778 | createInfo.pQueueFamilyIndices = queueFamilyIndices;
|
---|
779 | }
|
---|
780 | else {
|
---|
781 | createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
---|
782 | createInfo.queueFamilyIndexCount = 0;
|
---|
783 | createInfo.pQueueFamilyIndices = nullptr;
|
---|
784 | }
|
---|
785 |
|
---|
786 | createInfo.preTransform = capabilities.currentTransform;
|
---|
787 | createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
---|
788 | createInfo.presentMode = swapChainPresentMode;
|
---|
789 | createInfo.clipped = VK_TRUE;
|
---|
790 | createInfo.oldSwapchain = VK_NULL_HANDLE;
|
---|
791 |
|
---|
792 | if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
|
---|
793 | throw runtime_error("failed to create swap chain!");
|
---|
794 | }
|
---|
795 |
|
---|
796 | if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, nullptr) != VK_SUCCESS) {
|
---|
797 | throw runtime_error("failed to get swap chain image count!");
|
---|
798 | }
|
---|
799 |
|
---|
800 | swapChainImages.resize(swapChainImageCount);
|
---|
801 | if (vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages.data()) != VK_SUCCESS) {
|
---|
802 | throw runtime_error("failed to get swap chain images!");
|
---|
803 | }
|
---|
804 | }
|
---|
805 |
|
---|
806 | void VulkanGame::createImageViews() {
|
---|
807 | swapChainImageViews.resize(swapChainImageCount);
|
---|
808 |
|
---|
809 | for (uint32_t i = 0; i < swapChainImageViews.size(); i++) {
|
---|
810 | swapChainImageViews[i] = VulkanUtils::createImageView(device, swapChainImages[i], swapChainSurfaceFormat.format,
|
---|
811 | VK_IMAGE_ASPECT_COLOR_BIT);
|
---|
812 | }
|
---|
813 | }
|
---|
814 |
|
---|
815 | void VulkanGame::createResourceCommandPool() {
|
---|
816 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
817 |
|
---|
818 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
819 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
820 | poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
|
---|
821 | poolInfo.flags = 0;
|
---|
822 |
|
---|
823 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &resourceCommandPool) != VK_SUCCESS) {
|
---|
824 | throw runtime_error("failed to create resource command pool!");
|
---|
825 | }
|
---|
826 | }
|
---|
827 |
|
---|
828 | void VulkanGame::createImageResources() {
|
---|
829 | VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
|
---|
830 | depthImage, graphicsQueue);
|
---|
831 |
|
---|
832 | createTextureSampler();
|
---|
833 |
|
---|
834 | // TODO: Move all images/textures somewhere into the assets folder
|
---|
835 |
|
---|
836 | VulkanUtils::createVulkanImageFromFile(device, physicalDevice, resourceCommandPool, "textures/texture.jpg",
|
---|
837 | floorTextureImage, graphicsQueue);
|
---|
838 |
|
---|
839 | floorTextureImageDescriptor = {};
|
---|
840 | floorTextureImageDescriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
---|
841 | floorTextureImageDescriptor.imageView = floorTextureImage.imageView;
|
---|
842 | floorTextureImageDescriptor.sampler = textureSampler;
|
---|
843 | }
|
---|
844 |
|
---|
845 | VkFormat VulkanGame::findDepthFormat() {
|
---|
846 | return VulkanUtils::findSupportedFormat(
|
---|
847 | physicalDevice,
|
---|
848 | { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT },
|
---|
849 | VK_IMAGE_TILING_OPTIMAL,
|
---|
850 | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
|
---|
851 | );
|
---|
852 | }
|
---|
853 |
|
---|
854 | void VulkanGame::createRenderPass() {
|
---|
855 | VkAttachmentDescription colorAttachment = {};
|
---|
856 | colorAttachment.format = swapChainSurfaceFormat.format;
|
---|
857 | colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
858 | colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Set to VK_ATTACHMENT_LOAD_OP_DONT_CARE to disable clearing
|
---|
859 | colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
---|
860 | colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
861 | colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
862 | colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
863 | colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
---|
864 |
|
---|
865 | VkAttachmentReference colorAttachmentRef = {};
|
---|
866 | colorAttachmentRef.attachment = 0;
|
---|
867 | colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
---|
868 |
|
---|
869 | VkAttachmentDescription depthAttachment = {};
|
---|
870 | depthAttachment.format = findDepthFormat();
|
---|
871 | depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
|
---|
872 | depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
---|
873 | depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
874 | depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
---|
875 | depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
---|
876 | depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
---|
877 | depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
878 |
|
---|
879 | VkAttachmentReference depthAttachmentRef = {};
|
---|
880 | depthAttachmentRef.attachment = 1;
|
---|
881 | depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
---|
882 |
|
---|
883 | VkSubpassDescription subpass = {};
|
---|
884 | subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
---|
885 | subpass.colorAttachmentCount = 1;
|
---|
886 | subpass.pColorAttachments = &colorAttachmentRef;
|
---|
887 | //subpass.pDepthStencilAttachment = &depthAttachmentRef;
|
---|
888 |
|
---|
889 | VkSubpassDependency dependency = {};
|
---|
890 | dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
---|
891 | dependency.dstSubpass = 0;
|
---|
892 | dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
893 | dependency.srcAccessMask = 0;
|
---|
894 | dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
---|
895 | dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
|
---|
896 |
|
---|
897 | array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
|
---|
898 | VkRenderPassCreateInfo renderPassInfo = {};
|
---|
899 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
---|
900 | renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
901 | renderPassInfo.pAttachments = attachments.data();
|
---|
902 | renderPassInfo.subpassCount = 1;
|
---|
903 | renderPassInfo.pSubpasses = &subpass;
|
---|
904 | renderPassInfo.dependencyCount = 1;
|
---|
905 | renderPassInfo.pDependencies = &dependency;
|
---|
906 |
|
---|
907 | if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
|
---|
908 | throw runtime_error("failed to create render pass!");
|
---|
909 | }
|
---|
910 |
|
---|
911 | // We do not create a pipeline by default as this is also used by examples' main.cpp,
|
---|
912 | // but secondary viewport in multi-viewport mode may want to create one with:
|
---|
913 | //ImGui_ImplVulkan_CreatePipeline(device, g_Allocator, VK_NULL_HANDLE, g_MainWindowData.RenderPass, VK_SAMPLE_COUNT_1_BIT, &g_MainWindowData.Pipeline);
|
---|
914 | }
|
---|
915 |
|
---|
916 | void VulkanGame::createCommandPools() {
|
---|
917 | commandPools.resize(swapChainImageCount);
|
---|
918 |
|
---|
919 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
920 |
|
---|
921 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
922 | VkCommandPoolCreateInfo poolInfo = {};
|
---|
923 | poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
---|
924 | poolInfo.queueFamilyIndex = indices.graphicsFamily.value();
|
---|
925 | poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
---|
926 |
|
---|
927 | if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPools[i]) != VK_SUCCESS) {
|
---|
928 | throw runtime_error("failed to create graphics command pool!");
|
---|
929 | }
|
---|
930 | }
|
---|
931 | }
|
---|
932 |
|
---|
933 | void VulkanGame::createTextureSampler() {
|
---|
934 | VkSamplerCreateInfo samplerInfo = {};
|
---|
935 | samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
---|
936 | samplerInfo.magFilter = VK_FILTER_LINEAR;
|
---|
937 | samplerInfo.minFilter = VK_FILTER_LINEAR;
|
---|
938 |
|
---|
939 | samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
940 | samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
941 | samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
---|
942 |
|
---|
943 | samplerInfo.anisotropyEnable = VK_TRUE;
|
---|
944 | samplerInfo.maxAnisotropy = 16;
|
---|
945 | samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
|
---|
946 | samplerInfo.unnormalizedCoordinates = VK_FALSE;
|
---|
947 | samplerInfo.compareEnable = VK_FALSE;
|
---|
948 | samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
|
---|
949 | samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
|
---|
950 | samplerInfo.mipLodBias = 0.0f;
|
---|
951 | samplerInfo.minLod = 0.0f;
|
---|
952 | samplerInfo.maxLod = 0.0f;
|
---|
953 |
|
---|
954 | VKUTIL_CHECK_RESULT(vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler),
|
---|
955 | "failed to create texture sampler!");
|
---|
956 | }
|
---|
957 |
|
---|
958 | void VulkanGame::createFramebuffers() {
|
---|
959 | swapChainFramebuffers.resize(swapChainImageCount);
|
---|
960 |
|
---|
961 | VkFramebufferCreateInfo framebufferInfo = {};
|
---|
962 | framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
---|
963 | framebufferInfo.renderPass = renderPass;
|
---|
964 | framebufferInfo.width = swapChainExtent.width;
|
---|
965 | framebufferInfo.height = swapChainExtent.height;
|
---|
966 | framebufferInfo.layers = 1;
|
---|
967 |
|
---|
968 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
969 | array<VkImageView, 2> attachments = {
|
---|
970 | swapChainImageViews[i],
|
---|
971 | depthImage.imageView
|
---|
972 | };
|
---|
973 |
|
---|
974 | framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
---|
975 | framebufferInfo.pAttachments = attachments.data();
|
---|
976 |
|
---|
977 | if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
|
---|
978 | throw runtime_error("failed to create framebuffer!");
|
---|
979 | }
|
---|
980 | }
|
---|
981 | }
|
---|
982 |
|
---|
983 | void VulkanGame::createCommandBuffers() {
|
---|
984 | commandBuffers.resize(swapChainImageCount);
|
---|
985 |
|
---|
986 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
987 | VkCommandBufferAllocateInfo allocInfo = {};
|
---|
988 | allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
---|
989 | allocInfo.commandPool = commandPools[i];
|
---|
990 | allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
---|
991 | allocInfo.commandBufferCount = 1;
|
---|
992 |
|
---|
993 | if (vkAllocateCommandBuffers(device, &allocInfo, &commandBuffers[i]) != VK_SUCCESS) {
|
---|
994 | throw runtime_error("failed to allocate command buffer!");
|
---|
995 | }
|
---|
996 | }
|
---|
997 | }
|
---|
998 |
|
---|
999 | void VulkanGame::createSyncObjects() {
|
---|
1000 | imageAcquiredSemaphores.resize(swapChainImageCount);
|
---|
1001 | renderCompleteSemaphores.resize(swapChainImageCount);
|
---|
1002 | inFlightFences.resize(swapChainImageCount);
|
---|
1003 |
|
---|
1004 | VkSemaphoreCreateInfo semaphoreInfo = {};
|
---|
1005 | semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
|
---|
1006 |
|
---|
1007 | VkFenceCreateInfo fenceInfo = {};
|
---|
1008 | fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
---|
1009 | fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
|
---|
1010 |
|
---|
1011 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
1012 | VKUTIL_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAcquiredSemaphores[i]),
|
---|
1013 | "failed to create image acquired sempahore for a frame!");
|
---|
1014 |
|
---|
1015 | VKUTIL_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderCompleteSemaphores[i]),
|
---|
1016 | "failed to create render complete sempahore for a frame!");
|
---|
1017 |
|
---|
1018 | VKUTIL_CHECK_RESULT(vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]),
|
---|
1019 | "failed to create fence for a frame!");
|
---|
1020 | }
|
---|
1021 | }
|
---|
1022 |
|
---|
1023 | void VulkanGame::initImGuiOverlay() {
|
---|
1024 | vector<VkDescriptorPoolSize> pool_sizes {
|
---|
1025 | { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
|
---|
1026 | { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
|
---|
1027 | { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
|
---|
1028 | { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
|
---|
1029 | { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
|
---|
1030 | { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
|
---|
1031 | { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
|
---|
1032 | { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
|
---|
1033 | { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
|
---|
1034 | { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
|
---|
1035 | { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
|
---|
1036 | };
|
---|
1037 |
|
---|
1038 | VkDescriptorPoolCreateInfo pool_info = {};
|
---|
1039 | pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
---|
1040 | pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
|
---|
1041 | pool_info.maxSets = 1000 * pool_sizes.size();
|
---|
1042 | pool_info.poolSizeCount = static_cast<uint32_t>(pool_sizes.size());
|
---|
1043 | pool_info.pPoolSizes = pool_sizes.data();
|
---|
1044 |
|
---|
1045 | VKUTIL_CHECK_RESULT(vkCreateDescriptorPool(device, &pool_info, nullptr, &imguiDescriptorPool),
|
---|
1046 | "failed to create IMGUI descriptor pool!");
|
---|
1047 |
|
---|
1048 | // TODO: Do this in one place and save it instead of redoing it every time I need a queue family index
|
---|
1049 | QueueFamilyIndices indices = VulkanUtils::findQueueFamilies(physicalDevice, vulkanSurface);
|
---|
1050 |
|
---|
1051 | // Setup Dear ImGui context
|
---|
1052 | IMGUI_CHECKVERSION();
|
---|
1053 | ImGui::CreateContext();
|
---|
1054 | ImGuiIO& io = ImGui::GetIO();
|
---|
1055 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
|
---|
1056 | //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
|
---|
1057 |
|
---|
1058 | // Setup Dear ImGui style
|
---|
1059 | ImGui::StyleColorsDark();
|
---|
1060 | //ImGui::StyleColorsClassic();
|
---|
1061 |
|
---|
1062 | // Setup Platform/Renderer bindings
|
---|
1063 | ImGui_ImplSDL2_InitForVulkan(window);
|
---|
1064 | ImGui_ImplVulkan_InitInfo init_info = {};
|
---|
1065 | init_info.Instance = instance;
|
---|
1066 | init_info.PhysicalDevice = physicalDevice;
|
---|
1067 | init_info.Device = device;
|
---|
1068 | init_info.QueueFamily = indices.graphicsFamily.value();
|
---|
1069 | init_info.Queue = graphicsQueue;
|
---|
1070 | init_info.DescriptorPool = imguiDescriptorPool;
|
---|
1071 | init_info.Allocator = nullptr;
|
---|
1072 | init_info.MinImageCount = swapChainMinImageCount;
|
---|
1073 | init_info.ImageCount = swapChainImageCount;
|
---|
1074 | init_info.CheckVkResultFn = check_imgui_vk_result;
|
---|
1075 | ImGui_ImplVulkan_Init(&init_info, renderPass);
|
---|
1076 |
|
---|
1077 | // Load Fonts
|
---|
1078 | // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
---|
1079 | // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
|
---|
1080 | // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
|
---|
1081 | // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
|
---|
1082 | // - Read 'docs/FONTS.md' for more instructions and details.
|
---|
1083 | // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
---|
1084 | //io.Fonts->AddFontDefault();
|
---|
1085 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
|
---|
1086 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
|
---|
1087 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
|
---|
1088 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
|
---|
1089 | //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
---|
1090 | //assert(font != NULL);
|
---|
1091 |
|
---|
1092 | // Upload Fonts
|
---|
1093 |
|
---|
1094 | VkCommandBuffer commandBuffer = VulkanUtils::beginSingleTimeCommands(device, resourceCommandPool);
|
---|
1095 |
|
---|
1096 | ImGui_ImplVulkan_CreateFontsTexture(commandBuffer);
|
---|
1097 |
|
---|
1098 | VulkanUtils::endSingleTimeCommands(device, resourceCommandPool, commandBuffer, graphicsQueue);
|
---|
1099 |
|
---|
1100 | ImGui_ImplVulkan_DestroyFontUploadObjects();
|
---|
1101 | }
|
---|
1102 |
|
---|
1103 | void VulkanGame::cleanupImGuiOverlay() {
|
---|
1104 | ImGui_ImplVulkan_Shutdown();
|
---|
1105 | ImGui_ImplSDL2_Shutdown();
|
---|
1106 | ImGui::DestroyContext();
|
---|
1107 |
|
---|
1108 | vkDestroyDescriptorPool(device, imguiDescriptorPool, nullptr);
|
---|
1109 | }
|
---|
1110 |
|
---|
1111 | void VulkanGame::createBufferSet(VkDeviceSize bufferSize, VkBufferUsageFlags usages, VkMemoryPropertyFlags properties,
|
---|
1112 | BufferSet& set) {
|
---|
1113 | set.usages = usages;
|
---|
1114 | set.properties = properties;
|
---|
1115 |
|
---|
1116 | set.buffers.resize(swapChainImageCount);
|
---|
1117 | set.memory.resize(swapChainImageCount);
|
---|
1118 | set.infoSet.resize(swapChainImageCount);
|
---|
1119 |
|
---|
1120 | for (size_t i = 0; i < swapChainImageCount; i++) {
|
---|
1121 | VulkanUtils::createBuffer(device, physicalDevice, bufferSize, usages, properties, set.buffers[i], set.memory[i]);
|
---|
1122 |
|
---|
1123 | set.infoSet[i].buffer = set.buffers[i];
|
---|
1124 | set.infoSet[i].offset = 0; // This is the offset from the start of the buffer, so always 0 for now
|
---|
1125 | set.infoSet[i].range = bufferSize; // Size of the update starting from offset, or VK_WHOLE_SIZE
|
---|
1126 | }
|
---|
1127 | }
|
---|
1128 |
|
---|
1129 | void VulkanGame::resizeBufferSet(BufferSet& set, VkDeviceSize newSize, VkCommandPool commandPool,
|
---|
1130 | VkQueue graphicsQueue, bool copyData) {
|
---|
1131 | for (size_t i = 0; i < set.buffers.size(); i++) {
|
---|
1132 | VkBuffer newBuffer;
|
---|
1133 | VkDeviceMemory newMemory;
|
---|
1134 |
|
---|
1135 | VulkanUtils::createBuffer(device, physicalDevice, newSize, set.usages, set.properties, newBuffer, newMemory);
|
---|
1136 |
|
---|
1137 | if (copyData) {
|
---|
1138 | VulkanUtils::copyBuffer(device, commandPool, set.buffers[i], newBuffer, 0, 0, set.infoSet[i].range,
|
---|
1139 | graphicsQueue);
|
---|
1140 | }
|
---|
1141 |
|
---|
1142 | vkDestroyBuffer(device, set.buffers[i], nullptr);
|
---|
1143 | vkFreeMemory(device, set.memory[i], nullptr);
|
---|
1144 |
|
---|
1145 | set.buffers[i] = newBuffer;
|
---|
1146 | set.memory[i] = newMemory;
|
---|
1147 |
|
---|
1148 | set.infoSet[i].buffer = set.buffers[i];
|
---|
1149 | set.infoSet[i].offset = 0; // This is the offset from the start of the buffer, so always 0 for now
|
---|
1150 | set.infoSet[i].range = newSize; // Size of the update starting from offset, or VK_WHOLE_SIZE
|
---|
1151 | }
|
---|
1152 | }
|
---|
1153 |
|
---|
1154 | void VulkanGame::renderFrame(ImDrawData* draw_data) {
|
---|
1155 | VkResult result = vkAcquireNextImageKHR(device, swapChain, numeric_limits<uint64_t>::max(),
|
---|
1156 | imageAcquiredSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
|
---|
1157 |
|
---|
1158 | if (result == VK_SUBOPTIMAL_KHR) {
|
---|
1159 | shouldRecreateSwapChain = true;
|
---|
1160 | } else if (result == VK_ERROR_OUT_OF_DATE_KHR) {
|
---|
1161 | shouldRecreateSwapChain = true;
|
---|
1162 | return;
|
---|
1163 | } else {
|
---|
1164 | VKUTIL_CHECK_RESULT(result, "failed to acquire swap chain image!");
|
---|
1165 | }
|
---|
1166 |
|
---|
1167 | VKUTIL_CHECK_RESULT(
|
---|
1168 | vkWaitForFences(device, 1, &inFlightFences[imageIndex], VK_TRUE, numeric_limits<uint64_t>::max()),
|
---|
1169 | "failed waiting for fence!");
|
---|
1170 |
|
---|
1171 | VKUTIL_CHECK_RESULT(vkResetFences(device, 1, &inFlightFences[imageIndex]),
|
---|
1172 | "failed to reset fence!");
|
---|
1173 |
|
---|
1174 | VKUTIL_CHECK_RESULT(vkResetCommandPool(device, commandPools[imageIndex], 0),
|
---|
1175 | "failed to reset command pool!");
|
---|
1176 |
|
---|
1177 | VkCommandBufferBeginInfo beginInfo = {};
|
---|
1178 | beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
---|
1179 | beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
|
---|
1180 |
|
---|
1181 | VKUTIL_CHECK_RESULT(vkBeginCommandBuffer(commandBuffers[imageIndex], &beginInfo),
|
---|
1182 | "failed to begin recording command buffer!");
|
---|
1183 |
|
---|
1184 | VkRenderPassBeginInfo renderPassInfo = {};
|
---|
1185 | renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
---|
1186 | renderPassInfo.renderPass = renderPass;
|
---|
1187 | renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
|
---|
1188 | renderPassInfo.renderArea.offset = { 0, 0 };
|
---|
1189 | renderPassInfo.renderArea.extent = swapChainExtent;
|
---|
1190 |
|
---|
1191 | array<VkClearValue, 2> clearValues = {};
|
---|
1192 | clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
|
---|
1193 | clearValues[1].depthStencil = { 1.0f, 0 };
|
---|
1194 |
|
---|
1195 | renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
|
---|
1196 | renderPassInfo.pClearValues = clearValues.data();
|
---|
1197 |
|
---|
1198 | vkCmdBeginRenderPass(commandBuffers[imageIndex], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
---|
1199 |
|
---|
1200 | // TODO: Find a more elegant, per-screen solution for this
|
---|
1201 | if (currentRenderScreenFn == &VulkanGame::renderGameScreen) {
|
---|
1202 | modelPipeline.createRenderCommands(commandBuffers[imageIndex], imageIndex, {});
|
---|
1203 |
|
---|
1204 |
|
---|
1205 |
|
---|
1206 |
|
---|
1207 | }
|
---|
1208 |
|
---|
1209 | ImGui_ImplVulkan_RenderDrawData(draw_data, commandBuffers[imageIndex]);
|
---|
1210 |
|
---|
1211 | vkCmdEndRenderPass(commandBuffers[imageIndex]);
|
---|
1212 |
|
---|
1213 | VKUTIL_CHECK_RESULT(vkEndCommandBuffer(commandBuffers[imageIndex]),
|
---|
1214 | "failed to record command buffer!");
|
---|
1215 |
|
---|
1216 | VkSemaphore waitSemaphores[] = { imageAcquiredSemaphores[currentFrame] };
|
---|
1217 | VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
---|
1218 | VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
|
---|
1219 |
|
---|
1220 | VkSubmitInfo submitInfo = {};
|
---|
1221 | submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
---|
1222 | submitInfo.waitSemaphoreCount = 1;
|
---|
1223 | submitInfo.pWaitSemaphores = waitSemaphores;
|
---|
1224 | submitInfo.pWaitDstStageMask = waitStages;
|
---|
1225 | submitInfo.commandBufferCount = 1;
|
---|
1226 | submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
|
---|
1227 | submitInfo.signalSemaphoreCount = 1;
|
---|
1228 | submitInfo.pSignalSemaphores = signalSemaphores;
|
---|
1229 |
|
---|
1230 | VKUTIL_CHECK_RESULT(vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[imageIndex]),
|
---|
1231 | "failed to submit draw command buffer!");
|
---|
1232 | }
|
---|
1233 |
|
---|
1234 | void VulkanGame::presentFrame() {
|
---|
1235 | VkSemaphore signalSemaphores[] = { renderCompleteSemaphores[currentFrame] };
|
---|
1236 |
|
---|
1237 | VkPresentInfoKHR presentInfo = {};
|
---|
1238 | presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
---|
1239 | presentInfo.waitSemaphoreCount = 1;
|
---|
1240 | presentInfo.pWaitSemaphores = signalSemaphores;
|
---|
1241 | presentInfo.swapchainCount = 1;
|
---|
1242 | presentInfo.pSwapchains = &swapChain;
|
---|
1243 | presentInfo.pImageIndices = &imageIndex;
|
---|
1244 | presentInfo.pResults = nullptr;
|
---|
1245 |
|
---|
1246 | VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
|
---|
1247 |
|
---|
1248 | if (result == VK_SUBOPTIMAL_KHR) {
|
---|
1249 | shouldRecreateSwapChain = true;
|
---|
1250 | } else if (result == VK_ERROR_OUT_OF_DATE_KHR) {
|
---|
1251 | shouldRecreateSwapChain = true;
|
---|
1252 | return;
|
---|
1253 | } else {
|
---|
1254 | VKUTIL_CHECK_RESULT(result, "failed to present swap chain image!");
|
---|
1255 | }
|
---|
1256 |
|
---|
1257 | currentFrame = (currentFrame + 1) % swapChainImageCount;
|
---|
1258 | }
|
---|
1259 |
|
---|
1260 | void VulkanGame::recreateSwapChain() {
|
---|
1261 | if (vkDeviceWaitIdle(device) != VK_SUCCESS) {
|
---|
1262 | throw runtime_error("failed to wait for device!");
|
---|
1263 | }
|
---|
1264 |
|
---|
1265 | cleanupSwapChain();
|
---|
1266 |
|
---|
1267 | createSwapChain();
|
---|
1268 | createImageViews();
|
---|
1269 |
|
---|
1270 | // The depth buffer does need to be recreated with the swap chain since its dimensions depend on the window size
|
---|
1271 | // and resizing the window is a common reason to recreate the swapchain
|
---|
1272 | VulkanUtils::createDepthImage(device, physicalDevice, resourceCommandPool, findDepthFormat(), swapChainExtent,
|
---|
1273 | depthImage, graphicsQueue);
|
---|
1274 |
|
---|
1275 | createRenderPass();
|
---|
1276 | createCommandPools();
|
---|
1277 | createFramebuffers();
|
---|
1278 | createCommandBuffers();
|
---|
1279 | createSyncObjects();
|
---|
1280 |
|
---|
1281 | // TODO: Move UBO creation/management into GraphicsPipeline_Vulkan, like I did with SSBOs
|
---|
1282 | // TODO: Check if the shader stages and maybe some other properties of the pipeline can be re-used
|
---|
1283 | // instead of recreated every time
|
---|
1284 |
|
---|
1285 | createBufferSet(sizeof(UBO_VP_mats),
|
---|
1286 | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
---|
1287 | uniformBuffers_modelPipeline);
|
---|
1288 |
|
---|
1289 | modelPipeline.updateRenderPass(renderPass);
|
---|
1290 | modelPipeline.createPipeline("shaders/model-vert.spv", "shaders/model-frag.spv");
|
---|
1291 | modelPipeline.createDescriptorPool(swapChainImages.size());
|
---|
1292 | modelPipeline.createDescriptorSets(swapChainImages.size());
|
---|
1293 |
|
---|
1294 | imageIndex = 0;
|
---|
1295 | }
|
---|
1296 |
|
---|
1297 | void VulkanGame::cleanupSwapChain() {
|
---|
1298 | VulkanUtils::destroyVulkanImage(device, depthImage);
|
---|
1299 |
|
---|
1300 | for (VkFramebuffer framebuffer : swapChainFramebuffers) {
|
---|
1301 | vkDestroyFramebuffer(device, framebuffer, nullptr);
|
---|
1302 | }
|
---|
1303 |
|
---|
1304 | for (uint32_t i = 0; i < swapChainImageCount; i++) {
|
---|
1305 | vkFreeCommandBuffers(device, commandPools[i], 1, &commandBuffers[i]);
|
---|
1306 | vkDestroyCommandPool(device, commandPools[i], nullptr);
|
---|
1307 | }
|
---|
1308 |
|
---|
1309 | modelPipeline.cleanup();
|
---|
1310 |
|
---|
1311 | for (size_t i = 0; i < uniformBuffers_modelPipeline.buffers.size(); i++) {
|
---|
1312 | vkDestroyBuffer(device, uniformBuffers_modelPipeline.buffers[i], nullptr);
|
---|
1313 | vkFreeMemory(device, uniformBuffers_modelPipeline.memory[i], nullptr);
|
---|
1314 | }
|
---|
1315 |
|
---|
1316 | for (uint32_t i = 0; i < swapChainImageCount; i++) {
|
---|
1317 | vkDestroySemaphore(device, imageAcquiredSemaphores[i], nullptr);
|
---|
1318 | vkDestroySemaphore(device, renderCompleteSemaphores[i], nullptr);
|
---|
1319 | vkDestroyFence(device, inFlightFences[i], nullptr);
|
---|
1320 | }
|
---|
1321 |
|
---|
1322 | vkDestroyRenderPass(device, renderPass, nullptr);
|
---|
1323 |
|
---|
1324 | for (VkImageView imageView : swapChainImageViews) {
|
---|
1325 | vkDestroyImageView(device, imageView, nullptr);
|
---|
1326 | }
|
---|
1327 |
|
---|
1328 | vkDestroySwapchainKHR(device, swapChain, nullptr);
|
---|
1329 | }
|
---|
1330 |
|
---|
1331 | void VulkanGame::renderMainScreen(int width, int height) {
|
---|
1332 | {
|
---|
1333 | int padding = 4;
|
---|
1334 | ImGui::SetNextWindowPos(vec2(-padding, -padding), ImGuiCond_Once);
|
---|
1335 | ImGui::SetNextWindowSize(vec2(width + 2 * padding, height + 2 * padding), ImGuiCond_Always);
|
---|
1336 | ImGui::Begin("WndMain", nullptr,
|
---|
1337 | ImGuiWindowFlags_NoTitleBar |
|
---|
1338 | ImGuiWindowFlags_NoResize |
|
---|
1339 | ImGuiWindowFlags_NoMove);
|
---|
1340 |
|
---|
1341 | ButtonImGui btn("New Game");
|
---|
1342 |
|
---|
1343 | ImGui::InvisibleButton("", vec2(10, height / 6));
|
---|
1344 | if (btn.draw((width - btn.getWidth()) / 2)) {
|
---|
1345 | goToScreen(&VulkanGame::renderGameScreen);
|
---|
1346 | }
|
---|
1347 |
|
---|
1348 | ButtonImGui btn2("Quit");
|
---|
1349 |
|
---|
1350 | ImGui::InvisibleButton("", vec2(10, 15));
|
---|
1351 | if (btn2.draw((width - btn2.getWidth()) / 2)) {
|
---|
1352 | quitGame();
|
---|
1353 | }
|
---|
1354 |
|
---|
1355 | ImGui::End();
|
---|
1356 | }
|
---|
1357 | }
|
---|
1358 |
|
---|
1359 | void VulkanGame::renderGameScreen(int width, int height) {
|
---|
1360 | {
|
---|
1361 | ImGui::SetNextWindowSize(vec2(130, 65), ImGuiCond_Once);
|
---|
1362 | ImGui::SetNextWindowPos(vec2(10, 50), ImGuiCond_Once);
|
---|
1363 | ImGui::Begin("WndStats", nullptr,
|
---|
1364 | ImGuiWindowFlags_NoTitleBar |
|
---|
1365 | ImGuiWindowFlags_NoResize |
|
---|
1366 | ImGuiWindowFlags_NoMove);
|
---|
1367 |
|
---|
1368 | //ImGui::Text(ImGui::GetIO().Framerate);
|
---|
1369 | renderGuiValueList(valueLists["stats value list"]);
|
---|
1370 |
|
---|
1371 | ImGui::End();
|
---|
1372 | }
|
---|
1373 |
|
---|
1374 | {
|
---|
1375 | ImGui::SetNextWindowSize(vec2(250, 35), ImGuiCond_Once);
|
---|
1376 | ImGui::SetNextWindowPos(vec2(width - 260, 10), ImGuiCond_Always);
|
---|
1377 | ImGui::Begin("WndMenubar", nullptr,
|
---|
1378 | ImGuiWindowFlags_NoTitleBar |
|
---|
1379 | ImGuiWindowFlags_NoResize |
|
---|
1380 | ImGuiWindowFlags_NoMove);
|
---|
1381 | ImGui::InvisibleButton("", vec2(155, 18));
|
---|
1382 | ImGui::SameLine();
|
---|
1383 | if (ImGui::Button("Main Menu")) {
|
---|
1384 | goToScreen(&VulkanGame::renderMainScreen);
|
---|
1385 | }
|
---|
1386 | ImGui::End();
|
---|
1387 | }
|
---|
1388 |
|
---|
1389 | {
|
---|
1390 | ImGui::SetNextWindowSize(vec2(200, 200), ImGuiCond_Once);
|
---|
1391 | ImGui::SetNextWindowPos(vec2(width - 210, 60), ImGuiCond_Always);
|
---|
1392 | ImGui::Begin("WndDebug", nullptr,
|
---|
1393 | ImGuiWindowFlags_NoTitleBar |
|
---|
1394 | ImGuiWindowFlags_NoResize |
|
---|
1395 | ImGuiWindowFlags_NoMove);
|
---|
1396 |
|
---|
1397 | renderGuiValueList(valueLists["debug value list"]);
|
---|
1398 |
|
---|
1399 | ImGui::End();
|
---|
1400 | }
|
---|
1401 | }
|
---|
1402 |
|
---|
1403 | void VulkanGame::initGuiValueLists(map<string, vector<UIValue>>& valueLists) {
|
---|
1404 | valueLists["stats value list"] = vector<UIValue>();
|
---|
1405 | valueLists["debug value list"] = vector<UIValue>();
|
---|
1406 | }
|
---|
1407 |
|
---|
1408 | // TODO: Probably turn this into a UI widget class
|
---|
1409 | void VulkanGame::renderGuiValueList(vector<UIValue>& values) {
|
---|
1410 | float maxWidth = 0.0f;
|
---|
1411 | float cursorStartPos = ImGui::GetCursorPosX();
|
---|
1412 |
|
---|
1413 | for (vector<UIValue>::iterator it = values.begin(); it != values.end(); it++) {
|
---|
1414 | float textWidth = ImGui::CalcTextSize(it->label.c_str()).x;
|
---|
1415 |
|
---|
1416 | if (maxWidth < textWidth)
|
---|
1417 | maxWidth = textWidth;
|
---|
1418 | }
|
---|
1419 |
|
---|
1420 | stringstream ss;
|
---|
1421 |
|
---|
1422 | // TODO: Possibly implement this based on gui/ui-value.hpp instead and use templates
|
---|
1423 | // to keep track of the type. This should make it a bit easier to use and maintain
|
---|
1424 | // Also, implement this in a way that's agnostic to the UI renderer.
|
---|
1425 | for (vector<UIValue>::iterator it = values.begin(); it != values.end(); it++) {
|
---|
1426 | ss.str("");
|
---|
1427 | ss.clear();
|
---|
1428 |
|
---|
1429 | switch (it->type) {
|
---|
1430 | case UIVALUE_INT:
|
---|
1431 | ss << it->label << ": " << *(unsigned int*)it->value;
|
---|
1432 | break;
|
---|
1433 | case UIVALUE_DOUBLE:
|
---|
1434 | ss << it->label << ": " << *(double*)it->value;
|
---|
1435 | break;
|
---|
1436 | }
|
---|
1437 |
|
---|
1438 | float textWidth = ImGui::CalcTextSize(it->label.c_str()).x;
|
---|
1439 |
|
---|
1440 | ImGui::SetCursorPosX(cursorStartPos + maxWidth - textWidth);
|
---|
1441 | //ImGui::Text("%s", ss.str().c_str());
|
---|
1442 | ImGui::Text("%s: %.1f", it->label.c_str(), *(float*)it->value);
|
---|
1443 | }
|
---|
1444 | }
|
---|
1445 |
|
---|
1446 | void VulkanGame::goToScreen(void (VulkanGame::* renderScreenFn)(int width, int height)) {
|
---|
1447 | currentRenderScreenFn = renderScreenFn;
|
---|
1448 |
|
---|
1449 | // TODO: Maybe just set shouldRecreateSwapChain to true instead. Check this render loop logic
|
---|
1450 | // to make sure there'd be no issues
|
---|
1451 | //recreateSwapChain();
|
---|
1452 | }
|
---|
1453 |
|
---|
1454 | void VulkanGame::quitGame() {
|
---|
1455 | done = true;
|
---|
1456 | }
|
---|