抽象vulkan 基类,梳理代码。

This commit is contained in:
xsl
2025-10-17 15:20:23 +08:00
parent 25fd704a3f
commit a392206f96
4 changed files with 362 additions and 323 deletions
+8 -91
View File
@@ -1,106 +1,28 @@
#pragma once
#ifdef _WIN32
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#else
#include <vulkan/vulkan.h>
#endif
#include <fstream>
#include <iostream>
#include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <vector>
#include <optional>
#include <set>
#include <assert.h>
#include <vulkan/vulkan_structs.hpp>
#define VK_CHECK(x) \
do \
{ \
VkResult err = x; \
if (err) \
{ \
assert(false); \
} \
} while (0)
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
#include "AppBase.h"
class Application
class Application : public AppBase
{
private:
std::vector<char> readFile(const std::string &enginePath)
{
std::ifstream file{enginePath, std::ios::ate | std::ios::binary};
if (!file.is_open())
{
throw std::runtime_error("failed to open file: " + enginePath);
}
size_t fileSize = static_cast<size_t>(file.tellg());
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return buffer;
}
VkShaderModule createShaderModule(const std::vector<char> &code)
{
VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = code.size();
createInfo.pCode = reinterpret_cast<const uint32_t *>(code.data());
VkShaderModule shaderModule;
if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS)
{
throw std::runtime_error("failed to create shader module!");
}
return shaderModule;
}
public:
void run();
private:
#ifdef _WIN32
GLFWwindow *window;
#endif
VkInstance instance;
protected:
void initVulkan();
void initWindow();
void createSurface();
void initVulkan();
void mainLoop();
void cleanup();
void createInstance();
void createImageViews();
void createFramebuffers();
void createCommandPool();
void createCommandBuffer();
void setupDebugMessenger();
void pickPhysicalDevice();
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device);
bool isDeviceSuitable(VkPhysicalDevice device);
bool checkSwapChainSupport(VkPhysicalDevice device);
bool checkDeviceExtensionSupport(VkPhysicalDevice device);
bool checkValidationLayerSupport();
void createLogicalDevice();
void createSwapChain();
void createPipelineLayout();
@@ -129,10 +51,5 @@ private:
VkSemaphore renderFinishedSemaphore; // 渲染完成信号量
VkFence inFlightFence; // 同步栅栏
VkQueue presentQueue; // 呈现队列
VkDebugUtilsMessengerEXT debugMessenger;
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const uint32_t kWidth = 480;
const uint32_t kHeight = 480;
};