지금 보일러 플레이트 코드인데도 덩치가 너무 커서 수정하기 슬슬 머리가 아픈데
그렇다고 지금 뭔가 추상화를 하자니 코드에 기능이 뭐가 너무 없음
main.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #pragma once #define VULKAN_HPP_NO_STRUCT_CONSTRUCTORS #define VULKAN_HPP_NO_STRUCT_SETTERS #include <SDL2/SDL.h> #include <SDL2/SDL_vulkan.h> #include <vulkan/vulkan.hpp> #include <vulkan/vulkan.h> #include <iostream> #include <cstdint> #include <exception> #include <stdexcept> #include <vector> #include <format> #include <cassert> #include <fstream> #ifdef NDEBUG constexpr bool isDebug = false; #else constexpr bool isDebug = true; #endif // NDEBUG struct WindowCreateInfo { const char* title; int width; int height; int flags; }; class Application { vk::Instance instance{}; vk::PhysicalDevice physicalDevice{}; vk::Device device{}; vk::Queue graphicsQueue{}; vk::Queue presentQueue{}; vk::CommandPool commandPool{}; vk::CommandBuffer commandBuffer{}; SDL_Window* window{}; VkSurfaceKHR surface{}; vk::SurfaceCapabilitiesKHR surfaceCapabilities{}; vk::SwapchainKHR swapChain{}; std::vector<vk::Image> swapChainImages{}; std::vector<vk::ImageView> swapChainImageViews{}; vk::RenderPass renderPass{}; vk::Pipeline graphicsPipeline{}; std::vector<vk::Framebuffer> framebuffers{}; vk::Semaphore imageAvailableSemaphore{}; vk::Semaphore renderFinishedSemaphore{}; vk::Fence inFlightFence{}; vk::ShaderModule vertexShader; vk::ShaderModule fragmentShader; static const auto imageFormat = vk::Format::eB8G8R8A8Srgb; vk::Instance createInstance(const std::vector<const char*>& layers, const std::vector<const char*>& extensions); vk::Device createDevice(const std::vector<const char*>& extensions); VkSurfaceKHR createSurface() const; vk::SwapchainKHR createSwapChain() const; std::vector<vk::ImageView> getSwapChainImageViews() const; vk::RenderPass createRenderPass() const; vk::ShaderModule loadShaderModule(const char* path) const; vk::Pipeline createGraphicsPipeline() const; std::vector<vk::Framebuffer> createFramebuffers() const; static SDL_Window* createWindow(const WindowCreateInfo& createInfo); void mainLoop(); void recordBuffer(uint32_t imageIndex); void createSyncObjects(); void updateFrame(); void cleanup(); public: void run(); }; | cs |
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | #include "main.h" int SDL_main(int argc, char* argv[]) { Application app; app.run(); return 0; } SDL_Window* Application::createWindow(const WindowCreateInfo& createInfo) { SDL_Window* window; window = SDL_CreateWindow(createInfo.title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, createInfo.width, createInfo.height, static_cast<SDL_WindowFlags>(createInfo.flags)); if (!window) throw std::runtime_error(SDL_GetError()); return window; } void Application::mainLoop() { bool closeWindow = false; SDL_Event e; while (!closeWindow) { while (SDL_PollEvent(&e) > 0) { updateFrame(); SDL_UpdateWindowSurface(window); if (e.type == SDL_QUIT) closeWindow = true; } vkDeviceWaitIdle(device); } } void Application::recordBuffer(uint32_t imageIndex) { using enum vk::SubpassContents; using enum vk::PipelineBindPoint; const vk::CommandBufferBeginInfo bufferBeginInfo{}; const vk::ClearValue clearColor{ { 0.0f, 0.0f, 0.0f, 1.0f } }; const vk::RenderPassBeginInfo renderPassBeginInfo{ .renderPass = renderPass, .framebuffer = framebuffers[imageIndex], .renderArea = { .offset = { 0, 0 }, .extent = surfaceCapabilities.currentExtent }, .clearValueCount = 1, .pClearValues = &clearColor, }; const vk::Viewport viewport{ .x = 0.0f, .y = 0.0f, .width = static_cast<float>(surfaceCapabilities.currentExtent.width), .height = static_cast<float>(surfaceCapabilities.currentExtent.height), .minDepth = 0.0f, .maxDepth = 1.0f, }; vk::Rect2D scissor{ .offset = { 0, 0 }, .extent = surfaceCapabilities.currentExtent, }; commandBuffer.begin(bufferBeginInfo); commandBuffer.beginRenderPass(renderPassBeginInfo, eInline); commandBuffer.bindPipeline(eGraphics, graphicsPipeline); commandBuffer.setViewport(0, viewport); commandBuffer.setScissor(0, scissor); commandBuffer.draw(3, 1, 0, 0); commandBuffer.endRenderPass(); commandBuffer.end(); } void Application::run() { if (SDL_Init(SDL_INIT_VIDEO) < 0) throw std::runtime_error(SDL_GetError()); WindowCreateInfo windowCreateInfo{ .title = "Vulkan with SDL2", .width = 600, .height = 400, .flags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE, }; window = createWindow(windowCreateInfo); const auto instanceLayers = []() { std::vector<const char*> layers; if constexpr (isDebug) layers.push_back("VK_LAYER_KHRONOS_validation"); return layers; }(); const auto instanceExtensions = [this]() { unsigned int count; SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr); std::vector<const char*> extensions(count); SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data()); return extensions; }(); instance = createInstance(instanceLayers, instanceExtensions); physicalDevice = instance.enumeratePhysicalDevices().front(); device = createDevice({ VK_KHR_SWAPCHAIN_EXTENSION_NAME }); graphicsQueue = device.getQueue(0, 0); presentQueue = device.getQueue(0, 0); commandPool = device.createCommandPool({ .flags = vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT), .queueFamilyIndex = 0, }); commandBuffer = device.allocateCommandBuffers({ .commandPool = commandPool, .level = vk::CommandBufferLevel::ePrimary, .commandBufferCount = 1 }).front(); surface = createSurface(); surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface); swapChain = createSwapChain(); swapChainImages = device.getSwapchainImagesKHR(swapChain); swapChainImageViews = getSwapChainImageViews(); renderPass = createRenderPass(); vertexShader = loadShaderModule("./vert.spv"); fragmentShader = loadShaderModule("./frag.spv"); graphicsPipeline = createGraphicsPipeline(); framebuffers = createFramebuffers(); createSyncObjects(); mainLoop(); cleanup(); } vk::Instance Application::createInstance(const std::vector<const char*>& layers, const std::vector<const char*>& extensions) { const vk::ApplicationInfo appInfo{ .apiVersion = VK_API_VERSION_1_3, }; const vk::InstanceCreateInfo createInfo{ .pApplicationInfo = &appInfo, .enabledLayerCount = static_cast<uint32_t>(layers.size()), .ppEnabledLayerNames = layers.data(), .enabledExtensionCount = static_cast<uint32_t>(extensions.size()), .ppEnabledExtensionNames = extensions.data(), }; return vk::createInstance(createInfo); } vk::Device Application::createDevice(const std::vector<const char*>& extensions) { const auto queueFamilyProperties = physicalDevice.getQueueFamilyProperties(); const auto queuePriorities = [&queueFamilyProperties]() { std::vector<std::vector<float>> result(queueFamilyProperties.size()); for (uint32_t i = 0; i < queueFamilyProperties.size(); i++) result[i] = std::vector<float>(queueFamilyProperties[i].queueCount, 1.0); return result; }(); const auto deviceQueueCreateInfos = [&queueFamilyProperties, &queuePriorities]() { std::vector<vk::DeviceQueueCreateInfo> result; for (uint32_t i = 0; i < queueFamilyProperties.size(); i++) { result.push_back({ .queueFamilyIndex = i, .queueCount = queueFamilyProperties[i].queueCount, .pQueuePriorities = queuePriorities[i].data() }); } return result; }(); const vk::DeviceCreateInfo deviceCreateInfo{ .queueCreateInfoCount = static_cast<uint32_t>(deviceQueueCreateInfos.size()), .pQueueCreateInfos = deviceQueueCreateInfos.data(), .enabledExtensionCount = static_cast<uint32_t>(extensions.size()), .ppEnabledExtensionNames = extensions.data(), }; return physicalDevice.createDevice(deviceCreateInfo); } VkSurfaceKHR Application::createSurface() const { VkSurfaceKHR result; if (SDL_Vulkan_CreateSurface(window, instance, &result) == SDL_FALSE) throw std::runtime_error(SDL_GetError()); return result; } vk::SwapchainKHR Application::createSwapChain() const { using enum vk::ColorSpaceKHR; using enum vk::ImageUsageFlagBits; using enum vk::SharingMode; using enum vk::CompositeAlphaFlagBitsKHR; using enum vk::PresentModeKHR; const std::vector<vk::SurfaceFormatKHR> surfaceFormats = physicalDevice.getSurfaceFormatsKHR(surface); const std::vector<vk::PresentModeKHR> surfacePresentModes = physicalDevice.getSurfacePresentModesKHR(surface); uint32_t queueFamilyIndex = 0; const vk::SwapchainCreateInfoKHR createInfo{ .surface = surface, .minImageCount = surfaceCapabilities.minImageCount, .imageFormat = imageFormat, .imageColorSpace = eSrgbNonlinear, .imageExtent = surfaceCapabilities.currentExtent, .imageArrayLayers = surfaceCapabilities.maxImageArrayLayers, .imageUsage = eColorAttachment, .imageSharingMode = eExclusive, .queueFamilyIndexCount = 1, .pQueueFamilyIndices = &queueFamilyIndex, .preTransform = surfaceCapabilities.currentTransform, .compositeAlpha = eOpaque, .presentMode = eMailbox, .clipped = VK_TRUE, }; return device.createSwapchainKHR(createInfo); } std::vector<vk::ImageView> Application::getSwapChainImageViews() const { std::vector<vk::ImageView> imageViews(swapChainImages.size()); vk::ImageViewCreateInfo createInfo{ .viewType = vk::ImageViewType(VK_IMAGE_VIEW_TYPE_2D), .format = vk::Format(imageFormat), .components = { .r = vk::ComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), .g = vk::ComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), .b = vk::ComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), .a = vk::ComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY) }, .subresourceRange = { .aspectMask = vk::ImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1 } }; for (size_t i = 0; i < swapChainImages.size(); i++) { createInfo.image = swapChainImages[i]; imageViews[i] = device.createImageView(createInfo); } return imageViews; } vk::RenderPass Application::createRenderPass() const { const vk::AttachmentDescription colorAttachment{ .format = vk::Format(imageFormat), .samples = vk::SampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT), .loadOp = vk::AttachmentLoadOp(VK_ATTACHMENT_LOAD_OP_CLEAR), .storeOp = vk::AttachmentStoreOp(VK_ATTACHMENT_STORE_OP_STORE), .stencilLoadOp = vk::AttachmentLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE), .stencilStoreOp = vk::AttachmentStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE), .initialLayout = vk::ImageLayout(VK_IMAGE_LAYOUT_UNDEFINED), .finalLayout = vk::ImageLayout(VK_IMAGE_LAYOUT_PRESENT_SRC_KHR), }; const vk::AttachmentReference attachmentReference{ .attachment = 0, .layout = vk::ImageLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL), }; const vk::SubpassDescription subpass{ .pipelineBindPoint = vk::PipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS), .colorAttachmentCount = 1, .pColorAttachments = &attachmentReference, }; const vk::SubpassDependency dependency{ .srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0, .srcStageMask = vk::PipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT), .dstStageMask = vk::PipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT), .dstAccessMask = vk::AccessFlags(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT), }; const vk::RenderPassCreateInfo createInfo{ .attachmentCount = 1, .pAttachments = &colorAttachment, .subpassCount = 1, .pSubpasses = &subpass, .dependencyCount = 1, .pDependencies = &dependency, }; return device.createRenderPass(createInfo); } vk::ShaderModule Application::loadShaderModule(const char* path) const { const std::vector<char> SPIR_V = [path]() { std::ifstream binary(path, std::ios::binary | std::ios::ate); throw std::runtime_error("Failed to open file"); size_t filesize = binary.tellg(); std::vector<char> result(filesize); binary.seekg(0); binary.read(result.data(), filesize); return result; }(); const vk::ShaderModuleCreateInfo createInfo{ .codeSize = SPIR_V.size(), .pCode = reinterpret_cast<const uint32_t*>(SPIR_V.data()), }; return device.createShaderModule(createInfo); } vk::Pipeline Application::createGraphicsPipeline() const { using enum vk::Format; using enum vk::PrimitiveTopology; using enum vk::PolygonMode; using enum vk::CullModeFlagBits; using enum vk::FrontFace; using enum vk::SampleCountFlagBits; using enum vk::ColorComponentFlagBits; using enum vk::LogicOp; using enum vk::DynamicState; using enum vk::Result; const std::vector<vk::PipelineShaderStageCreateInfo> shaderStageCreateInfo{ { .stage = vk::ShaderStageFlagBits::eVertex, .module = vertexShader, .pName = "main", }, { .stage = vk::ShaderStageFlagBits::eFragment, .module = fragmentShader, .pName = "main", } }; const std::vector<vk::VertexInputBindingDescription> vertexInputBindingDescriptions = { { .binding = 0, .stride = 24, // 진짜로 확실한 값인지? .inputRate = vk::VertexInputRate::eVertex, }, }; const std::vector<vk::VertexInputAttributeDescription> vertexInputAttributeDescriptions = { { .location = 0, .binding = 0, .format = eR32G32B32Sfloat, .offset = 0, }, { .location = 1, .binding = 0, .format = eR32G32B32Sfloat, .offset = 12, }, }; const vk::PipelineVertexInputStateCreateInfo vertexInputStateCreateInfo{}; const vk::PipelineInputAssemblyStateCreateInfo inputAssembly{ .topology = eTriangleList, .primitiveRestartEnable = VK_FALSE, }; const vk::PipelineTessellationStateCreateInfo tessellationStateCreateInfo{}; const vk::PipelineRasterizationStateCreateInfo rasterizationStateCreateInfo{ .depthClampEnable = VK_FALSE, .rasterizerDiscardEnable = VK_FALSE, .polygonMode = eFill, .cullMode = eBack, .frontFace = eClockwise, .depthBiasEnable = VK_FALSE, .lineWidth = 1.0f }; const vk::PipelineMultisampleStateCreateInfo multiSampleStateCreateInfo{ .rasterizationSamples = e1, .sampleShadingEnable = VK_FALSE, .alphaToCoverageEnable = VK_FALSE, .alphaToOneEnable = VK_FALSE, }; const vk::PipelineColorBlendAttachmentState colorBlendAttachmentState{ .blendEnable = VK_FALSE, .colorWriteMask = eR | eG | eB | eA, }; const vk::PipelineColorBlendStateCreateInfo colorBlendStateCreateInfo{ .logicOpEnable = VK_FALSE, .logicOp = eNoOp, .attachmentCount = 1, .pAttachments = &colorBlendAttachmentState, .blendConstants = {{0.0f, 0.0f, 0.0f, 0.0f}}, }; const vk::Viewport viewport{ .x = 0, .y = 0, .width = static_cast<float>(surfaceCapabilities.currentExtent.width), .height = static_cast<float>(surfaceCapabilities.currentExtent.height), .minDepth = 0.0, .maxDepth = 1.0, }; const vk::Rect2D scissor{ .offset = {.x = 0, .y = 0}, .extent = surfaceCapabilities.currentExtent, }; const vk::PipelineViewportStateCreateInfo viewportStateCreateInfo{ .viewportCount = 1, .pViewports = &viewport, .scissorCount = 1, .pScissors = &scissor, }; const std::vector<vk::DynamicState> dynamicState{ eViewport, eScissor, }; const vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo{ .dynamicStateCount = static_cast<uint32_t>(dynamicState.size()), .pDynamicStates = dynamicState.data(), }; const vk::PipelineLayout pipelineLayout = device.createPipelineLayout({ .setLayoutCount = 0, .pushConstantRangeCount = 0, }); const vk::GraphicsPipelineCreateInfo createInfo{ .stageCount = static_cast<uint32_t>(shaderStageCreateInfo.size()), .pStages = shaderStageCreateInfo.data(), .pVertexInputState = &vertexInputStateCreateInfo, .pInputAssemblyState = &inputAssembly, .pTessellationState = nullptr, .pViewportState = &viewportStateCreateInfo, .pRasterizationState = &rasterizationStateCreateInfo, .pMultisampleState = &multiSampleStateCreateInfo, .pDepthStencilState = nullptr, .pColorBlendState = &colorBlendStateCreateInfo, .pDynamicState = &dynamicStateCreateInfo, .layout = pipelineLayout, .renderPass = renderPass, .subpass = 0, }; auto [result, value] = device.createGraphicsPipeline({}, createInfo); if (result != eSuccess) throw std::runtime_error("Vulkan GraphicsPipeline creation failure"); device.destroyPipelineLayout(pipelineLayout); return value; } std::vector<vk::Framebuffer> Application::createFramebuffers() const { vk::FramebufferCreateInfo createInfo{ .renderPass = renderPass, .attachmentCount = 1, .width = surfaceCapabilities.currentExtent.width, .height = surfaceCapabilities.currentExtent.height, .layers = 1, }; std::vector<vk::Framebuffer> swapChainFramebuffers(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); i++) { createInfo.pAttachments = &swapChainImageViews[i]; swapChainFramebuffers[i] = device.createFramebuffer(createInfo); } return swapChainFramebuffers; } void Application::updateFrame() { using enum vk::Result; using enum vk::PipelineStageFlagBits; device.waitForFences({ inFlightFence }, VK_TRUE, UINT64_MAX); device.resetFences({ inFlightFence }); auto [statusCode, imageIndex] = device.acquireNextImageKHR(swapChain, UINT64_MAX, imageAvailableSemaphore); commandBuffer.reset(); recordBuffer(imageIndex); constexpr vk::PipelineStageFlags waitStages = eColorAttachmentOutput; vk::SubmitInfo submitInfo{ .waitSemaphoreCount = 1, .pWaitSemaphores = &imageAvailableSemaphore, .pWaitDstStageMask = &waitStages, .commandBufferCount = 1, .pCommandBuffers = &commandBuffer, .signalSemaphoreCount = 1, .pSignalSemaphores = &renderFinishedSemaphore, }; graphicsQueue.submit(submitInfo, inFlightFence); vk::PresentInfoKHR presentInfo{ .waitSemaphoreCount = 1, .pWaitSemaphores = &renderFinishedSemaphore, .swapchainCount = 1, .pSwapchains = &swapChain, .pImageIndices = &imageIndex, }; presentQueue.presentKHR(presentInfo); } void Application::cleanup() { vkDeviceWaitIdle(device); device.destroySemaphore(imageAvailableSemaphore); device.destroySemaphore(renderFinishedSemaphore); device.destroyFence(inFlightFence); for (auto& framebuffer : framebuffers) device.destroyFramebuffer(framebuffer); device.destroyPipeline(graphicsPipeline); device.destroyShaderModule(vertexShader); device.destroyShaderModule(fragmentShader); device.destroyRenderPass(renderPass); for (auto& imageView : swapChainImageViews) device.destroyImageView(imageView); device.destroySwapchainKHR(swapChain); instance.destroySurfaceKHR(surface); device.destroyCommandPool(commandPool); device.destroy(); instance.destroy(); SDL_DestroyWindow(window); SDL_Quit(); } void Application::createSyncObjects() { using enum vk::FenceCreateFlagBits; imageAvailableSemaphore = device.createSemaphore({}); renderFinishedSemaphore = device.createSemaphore({}); inFlightFence = device.createFence({ .flags = eSignaled }); } | cs |