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