source: opengl-game/sdl-game.cpp@ b01b50c

feature/imgui-sdl
Last change on this file since b01b50c was b01b50c, checked in by Dmitry Portnoy <dportnoy@…>, 14 months ago

Rename all BufferSets named storageBuffers_* to objectBuffers_*

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