4
社区成员
发帖
与我相关
我的任务
分享#version 450
layout(binding = 0) uniform UniformBufferObject {
mat4 model;
mat4 view;
mat4 proj;
} ubo;
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 2) in vec2 inTexCoord;
layout(location = 0) out vec3 fragColor;
layout(location = 1) out vec2 fragTexCoord;
void main() {
gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 0.0, 1.0);
fragColor = inColor;
fragTexCoord = inTexCoord;
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------
#version 450
layout(binding = 1) uniform sampler2D texSampler;
layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;
layout(location = 0) out vec4 outColor;
void main() {
outColor = texture(texSampler, fragTexCoord);
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------
#define GLFW_INCLUDE_VULKAN // 让GLFW自动包含Vulkan头文件
#include <GLFW/glfw3.h> // GLFW窗口库
#include <glm/glm.hpp> // GLM数学库核心
#include <glm/gtc/matrix_transform.hpp> // GLM矩阵变换函数
#define STB_IMAGE_IMPLEMENTATION // 定义此宏以在当前位置生成stb_image的实现代码
#include <stb_image.h> // stb_image图像加载库(单头文件)
#include <iostream> // 标准输入输出流
#include <fstream> // 文件读写
#include <stdexcept> // 标准异常
#include <algorithm> // 算法库
#include <chrono> // 高精度时钟
#include <vector> // 动态数组
#include <cstring> // 内存操作
#include <cstdlib> // 通用工具
#include <cstdint> // 固定宽度整数类型
#include <limits> // 数值极限
#include <array> // 固定大小数组
#include <optional> // 可选值(C++17)
#include <set> // 集合
const uint32_t WIDTH = 800; // 窗口宽度
const uint32_t HEIGHT = 600; // 窗口高度
const int MAX_FRAMES_IN_FLIGHT = 2; // 最大并行帧数(双缓冲)
const std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" }; // 验证层列表
const std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; // 设备扩展列表
#ifdef NDEBUG // 如果是Release模式
const bool enableValidationLayers = false; // 关闭验证层
#else // 如果是Debug模式
const bool enableValidationLayers = true; // 开启验证层
#endif
// 创建调试信使的辅助函数
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); // 获取函数指针
if (func != nullptr) { // 如果获取成功
return func(instance, pCreateInfo, pAllocator, pDebugMessenger); // 调用创建
}
else { // 如果获取失败
return VK_ERROR_EXTENSION_NOT_PRESENT; // 返回扩展不存在错误
}
}
// 销毁调试信使的辅助函数
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); // 获取函数指针
if (func != nullptr) { // 如果获取成功
func(instance, debugMessenger, pAllocator); // 调用销毁
}
}
// 队列族索引结构
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily; // 图形队列族索引
std::optional<uint32_t> presentFamily; // 呈现队列族索引
bool isComplete() { // 检查是否都已找到
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
// 交换链支持详情
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities; // 表面能力
std::vector<VkSurfaceFormatKHR> formats; // 支持的格式列表
std::vector<VkPresentModeKHR> presentModes; // 支持的呈现模式列表
};
// 顶点结构体(包含位置、颜色和纹理坐标)
struct Vertex {
glm::vec2 pos; // 位置(x, y)
glm::vec3 color; // 颜色(r, g, b)
glm::vec2 texCoord; // 纹理坐标(u, v)
// 获取顶点绑定描述
static VkVertexInputBindingDescription getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{}; // 绑定描述
bindingDescription.binding = 0; // 绑定索引0
bindingDescription.stride = sizeof(Vertex); // 步长
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // 逐顶点
return bindingDescription;
}
// 获取顶点属性描述(3个属性:位置、颜色、纹理坐标)
static std::array<VkVertexInputAttributeDescription, 3> getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions{}; // 3个属性
attributeDescriptions[0].binding = 0; // 绑定索引0
attributeDescriptions[0].location = 0; // location = 0
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT; // vec2
attributeDescriptions[0].offset = offsetof(Vertex, pos); // 偏移量
attributeDescriptions[1].binding = 0; // 绑定索引0
attributeDescriptions[1].location = 1; // location = 1
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; // vec3
attributeDescriptions[1].offset = offsetof(Vertex, color); // 偏移量
attributeDescriptions[2].binding = 0; // 绑定索引0
attributeDescriptions[2].location = 2; // location = 2
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; // vec2
attributeDescriptions[2].offset = offsetof(Vertex, texCoord); // 偏移量
return attributeDescriptions;
}
};
// Uniform缓冲对象(模型-视图-投影矩阵)
struct UniformBufferObject {
alignas(16) glm::mat4 model; // 模型矩阵
alignas(16) glm::mat4 view; // 视图矩阵
alignas(16) glm::mat4 proj; // 投影矩阵
};
// 顶点数据(位置、颜色、纹理坐标)
const std::vector<Vertex> vertices = {
{{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {1.0f, 0.0f}}, // 左下:红,纹理(1,0)
{{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f}}, // 右下:绿,纹理(0,0)
{{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}, {0.0f, 1.0f}}, // 右上:蓝,纹理(0,1)
{{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {1.0f, 1.0f}} // 左上:白,纹理(1,1)
};
// 索引数据(两个三角形组成矩形)
const std::vector<uint16_t> indices = {
0, 1, 2, // 第一个三角形
2, 3, 0 // 第二个三角形
};
// 主应用类
class HelloTriangleApplication {
public:
void run() { // 运行入口
initWindow(); // 初始化窗口
initVulkan(); // 初始化Vulkan
mainLoop(); // 主循环
cleanup(); // 清理资源
}
private:
GLFWwindow* window; // GLFW窗口指针
VkInstance instance; // Vulkan实例
VkDebugUtilsMessengerEXT debugMessenger; // 调试信使
VkSurfaceKHR surface; // 窗口表面
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; // 物理设备
VkDevice device; // 逻辑设备
VkQueue graphicsQueue; // 图形队列
VkQueue presentQueue; // 呈现队列
VkSwapchainKHR swapChain; // 交换链
std::vector<VkImage> swapChainImages; // 交换链图像
VkFormat swapChainImageFormat; // 图像格式
VkExtent2D swapChainExtent; // 图像尺寸
std::vector<VkImageView> swapChainImageViews; // 图像视图列表
std::vector<VkFramebuffer> swapChainFramebuffers; // 帧缓冲列表
VkRenderPass renderPass; // 渲染过程
VkDescriptorSetLayout descriptorSetLayout; // 描述符集布局
VkPipelineLayout pipelineLayout; // 管线布局
VkPipeline graphicsPipeline; // 图形管线
VkCommandPool commandPool; // 命令池
VkImage textureImage; // 纹理图像
VkDeviceMemory textureImageMemory; // 纹理图像内存
VkImageView textureImageView; // 纹理图像视图
VkSampler textureSampler; // 纹理采样器
VkBuffer vertexBuffer; // 顶点缓冲
VkDeviceMemory vertexBufferMemory; // 顶点缓冲内存
VkBuffer indexBuffer; // 索引缓冲
VkDeviceMemory indexBufferMemory; // 索引缓冲内存
std::vector<VkBuffer> uniformBuffers; // Uniform缓冲列表
std::vector<VkDeviceMemory> uniformBuffersMemory; // Uniform缓冲内存列表
std::vector<void*> uniformBuffersMapped; // Uniform缓冲映射指针
VkDescriptorPool descriptorPool; // 描述符池
std::vector<VkDescriptorSet> descriptorSets; // 描述符集列表
std::vector<VkCommandBuffer> commandBuffers; // 命令缓冲列表
std::vector<VkSemaphore> imageAvailableSemaphores; // 图像可用信号量
std::vector<VkSemaphore> renderFinishedSemaphores; // 渲染完成信号量
std::vector<VkFence> inFlightFences; // 围栏列表
uint32_t currentFrame = 0; // 当前帧索引
bool framebufferResized = false; // 窗口尺寸变化标志
void initWindow() { // 初始化窗口
glfwInit(); // 初始化GLFW
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // 不创建OpenGL上下文
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr); // 创建窗口
glfwSetWindowUserPointer(window, this); // 保存this指针
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback); // 注册尺寸回调
}
static void framebufferResizeCallback(GLFWwindow* window, int width, int height) { // 静态回调
auto app = reinterpret_cast<HelloTriangleApplication*>(glfwGetWindowUserPointer(window)); // 获取实例
app->framebufferResized = true; // 标记尺寸变化
}
void initVulkan() { // 初始化Vulkan
createInstance(); // 创建实例
setupDebugMessenger(); // 设置调试信使
createSurface(); // 创建表面
pickPhysicalDevice(); // 选择物理设备
createLogicalDevice(); // 创建设备
createSwapChain(); // 创建交换链
createImageViews(); // 创建图像视图
createRenderPass(); // 创建渲染过程
createDescriptorSetLayout(); // 创建描述符集布局
createGraphicsPipeline(); // 创建图形管线
createFramebuffers(); // 创建帧缓冲
createCommandPool(); // 创建命令池
createTextureImage(); // 创建纹理图像
createTextureImageView(); // 创建纹理图像视图
createTextureSampler(); // 创建纹理采样器
createVertexBuffer(); // 创建顶点缓冲
createIndexBuffer(); // 创建索引缓冲
createUniformBuffers(); // 创建Uniform缓冲
createDescriptorPool(); // 创建描述符池
createDescriptorSets(); // 创建描述符集
createCommandBuffers(); // 创建命令缓冲
createSyncObjects(); // 创建同步对象
}
void mainLoop() { // 主循环
while (!glfwWindowShouldClose(window)) { // 窗口未关闭
glfwPollEvents(); // 处理事件
drawFrame(); // 绘制一帧
}
vkDeviceWaitIdle(device); // 等待设备空闲
}
void cleanupSwapChain() { // 清理交换链
for (auto framebuffer : swapChainFramebuffers) { // 遍历帧缓冲
vkDestroyFramebuffer(device, framebuffer, nullptr); // 销毁
}
for (auto imageView : swapChainImageViews) { // 遍历图像视图
vkDestroyImageView(device, imageView, nullptr); // 销毁
}
vkDestroySwapchainKHR(device, swapChain, nullptr); // 销毁交换链
}
void cleanup() { // 清理所有资源
cleanupSwapChain(); // 清理交换链
vkDestroyPipeline(device, graphicsPipeline, nullptr); // 销毁管线
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); // 销毁管线布局
vkDestroyRenderPass(device, renderPass, nullptr); // 销毁渲染过程
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历帧
vkDestroyBuffer(device, uniformBuffers[i], nullptr); // 销毁Uniform缓冲
vkFreeMemory(device, uniformBuffersMemory[i], nullptr); // 释放内存
}
vkDestroyDescriptorPool(device, descriptorPool, nullptr); // 销毁描述符池
vkDestroySampler(device, textureSampler, nullptr); // 销毁采样器
vkDestroyImageView(device, textureImageView, nullptr); // 销毁纹理图像视图
vkDestroyImage(device, textureImage, nullptr); // 销毁纹理图像
vkFreeMemory(device, textureImageMemory, nullptr); // 释放纹理内存
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); // 销毁描述符集布局
vkDestroyBuffer(device, indexBuffer, nullptr); // 销毁索引缓冲
vkFreeMemory(device, indexBufferMemory, nullptr); // 释放索引缓冲内存
vkDestroyBuffer(device, vertexBuffer, nullptr); // 销毁顶点缓冲
vkFreeMemory(device, vertexBufferMemory, nullptr); // 释放顶点缓冲内存
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历帧
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); // 销毁信号量
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); // 销毁信号量
vkDestroyFence(device, inFlightFences[i], nullptr); // 销毁围栏
}
vkDestroyCommandPool(device, commandPool, nullptr); // 销毁命令池
vkDestroyDevice(device, nullptr); // 销毁设备
if (enableValidationLayers) { // 如果启用验证层
DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr); // 销毁调试信使
}
vkDestroySurfaceKHR(instance, surface, nullptr); // 销毁表面
vkDestroyInstance(instance, nullptr); // 销毁实例
glfwDestroyWindow(window); // 销毁窗口
glfwTerminate(); // 终止GLFW
}
void recreateSwapChain() { // 重建交换链
int width = 0, height = 0; // 获取窗口尺寸
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0) { // 如果尺寸无效
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents(); // 等待事件
}
vkDeviceWaitIdle(device); // 等待设备空闲
cleanupSwapChain(); // 清理旧交换链
createSwapChain(); // 重建
createImageViews(); // 重建图像视图
createFramebuffers(); // 重建帧缓冲
}
void createInstance() { // 创建实例
if (enableValidationLayers && !checkValidationLayerSupport()) { // 验证层不可用
throw std::runtime_error("validation layers requested, but not available!"); // 抛异常
}
VkApplicationInfo appInfo{}; // 应用信息
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; // 设置结构体类型
appInfo.pApplicationName = "Hello Triangle"; // 应用名称
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); // 应用版本
appInfo.pEngineName = "No Engine"; // 引擎名称
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); // 引擎版本
appInfo.apiVersion = VK_API_VERSION_1_0; // 使用的Vulkan API版本
VkInstanceCreateInfo createInfo{}; // 实例创建信息
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // 设置结构体类型
createInfo.pApplicationInfo = &appInfo; // 指向应用信息
auto extensions = getRequiredExtensions(); // 获取所需扩展
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); // 扩展数量
createInfo.ppEnabledExtensionNames = extensions.data(); // 扩展名称列表
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{}; // 调试创建信息
if (enableValidationLayers) { // 如果启用验证层
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); // 层数量
createInfo.ppEnabledLayerNames = validationLayers.data(); // 层名称列表
populateDebugMessengerCreateInfo(debugCreateInfo); // 填充调试创建信息
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo; // 链式传递
}
else {
createInfo.enabledLayerCount = 0; // 层数量为0
createInfo.pNext = nullptr; // pNext为空
}
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { // 创建实例
throw std::runtime_error("failed to create instance!"); // 失败抛异常
}
}
void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) { // 填充调试信使创建信息
createInfo = {}; // 将结构体初始化为零
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; // 设置结构体类型
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; // 消息严重级别
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; // 消息类型
createInfo.pfnUserCallback = debugCallback; // 回调函数指针
createInfo.pUserData = nullptr; // 用户数据指针(可选)
}
void setupDebugMessenger() { // 设置调试信使
if (!enableValidationLayers) return; // 如果未启用验证层则返回
VkDebugUtilsMessengerCreateInfoEXT createInfo; // 创建信息
populateDebugMessengerCreateInfo(createInfo); // 填充信息
if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) { // 创建调试信使
throw std::runtime_error("failed to set up debug messenger!"); // 失败抛异常
}
}
void createSurface() { // 创建表面
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { // 创建表面
throw std::runtime_error("failed to create window surface!"); // 失败抛异常
}
}
void pickPhysicalDevice() { // 选择物理设备
uint32_t deviceCount = 0; // 设备数量
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); // 获取设备数量
if (deviceCount == 0) { // 如果没有设备
throw std::runtime_error("failed to find GPUs with Vulkan support!"); // 抛异常
}
std::vector<VkPhysicalDevice> devices(deviceCount); // 设备列表
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()); // 获取设备
for (const auto& device : devices) { // 遍历设备
if (isDeviceSuitable(device)) { // 如果合适
physicalDevice = device; // 选择
break; // 跳出循环
}
}
if (physicalDevice == VK_NULL_HANDLE) { // 如果没有找到合适的设备
throw std::runtime_error("failed to find a suitable GPU!"); // 抛异常
}
}
void createLogicalDevice() { // 创建设备
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); // 查找队列族
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; // 队列创建信息列表
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() }; // 去重
float queuePriority = 1.0f; // 队列优先级
for (uint32_t queueFamily : uniqueQueueFamilies) { // 遍历每个队列族
VkDeviceQueueCreateInfo queueCreateInfo{}; // 队列创建信息
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; // 设置结构体类型
queueCreateInfo.queueFamilyIndex = queueFamily; // 队列族索引
queueCreateInfo.queueCount = 1; // 队列数量
queueCreateInfo.pQueuePriorities = &queuePriority; // 优先级指针
queueCreateInfos.push_back(queueCreateInfo); // 添加到列表
}
VkPhysicalDeviceFeatures deviceFeatures{}; // 设备特性
deviceFeatures.samplerAnisotropy = VK_TRUE; // 启用各向异性过滤
VkDeviceCreateInfo createInfo{}; // 设备创建信息
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; // 设置结构体类型
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); // 队列创建信息数量
createInfo.pQueueCreateInfos = queueCreateInfos.data(); // 队列创建信息指针
createInfo.pEnabledFeatures = &deviceFeatures; // 启用的特性
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); // 扩展数量
createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // 扩展名称列表
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { // 创建设备
throw std::runtime_error("failed to create logical device!"); // 失败抛异常
}
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); // 获取图形队列
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); // 获取呈现队列
}
void createSwapChain() { // 创建交换链
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice); // 查询交换链支持
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); // 选择表面格式
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); // 选择呈现模式
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities); // 选择尺寸
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; // 图像数量=最小+1
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { // 如果超过最大
imageCount = swapChainSupport.capabilities.maxImageCount; // 限制为最大
}
VkSwapchainCreateInfoKHR createInfo{}; // 交换链创建信息
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; // 设置结构体类型
createInfo.surface = surface; // 表面
createInfo.minImageCount = imageCount; // 最小图像数
createInfo.imageFormat = surfaceFormat.format; // 图像格式
createInfo.imageColorSpace = surfaceFormat.colorSpace; // 颜色空间
createInfo.imageExtent = extent; // 图像尺寸
createInfo.imageArrayLayers = 1; // 层数
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // 用作颜色附件
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); // 查找队列族
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; // 队列族数组
if (indices.graphicsFamily != indices.presentFamily) { // 如果队列族不同
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; // 并发共享
createInfo.queueFamilyIndexCount = 2; // 队列族数量
createInfo.pQueueFamilyIndices = queueFamilyIndices; // 队列族索引列表
}
else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // 独占
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform; // 预变换
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // 复合Alpha
createInfo.presentMode = presentMode; // 呈现模式
createInfo.clipped = VK_TRUE; // 启用裁剪
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) { // 创建交换链
throw std::runtime_error("failed to create swap chain!"); // 失败抛异常
}
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr); // 获取图像数量
swapChainImages.resize(imageCount); // 调整大小
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data()); // 获取图像
swapChainImageFormat = surfaceFormat.format; // 保存格式
swapChainExtent = extent; // 保存尺寸
}
void createImageViews() { // 创建图像视图
swapChainImageViews.resize(swapChainImages.size()); // 调整大小
for (size_t i = 0; i < swapChainImages.size(); i++) { // 遍历每个图像
swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat); // 创建图像视图
}
}
void createRenderPass() { // 创建渲染过程
VkAttachmentDescription colorAttachment{}; // 颜色附件描述
colorAttachment.format = swapChainImageFormat; // 格式
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; // 采样数
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // 加载操作:清除
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // 存储操作:存储
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // 模板加载:不关心
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // 模板存储:不关心
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // 初始布局:未定义
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // 最终布局:呈现源
VkAttachmentReference colorAttachmentRef{}; // 颜色附件引用
colorAttachmentRef.attachment = 0; // 附件索引0
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // 布局:颜色附件最优
VkSubpassDescription subpass{}; // 子通道描述
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // 管线绑定点:图形
subpass.colorAttachmentCount = 1; // 颜色附件数量
subpass.pColorAttachments = &colorAttachmentRef; // 颜色附件指针
VkSubpassDependency dependency{}; // 子通道依赖
dependency.srcSubpass = VK_SUBPASS_EXTERNAL; // 源子通道:外部
dependency.dstSubpass = 0; // 目标子通道:0
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // 源阶段
dependency.srcAccessMask = 0; // 源访问掩码
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // 目标阶段
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; // 目标访问掩码
VkRenderPassCreateInfo renderPassInfo{}; // 渲染过程创建信息
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; // 设置结构体类型
renderPassInfo.attachmentCount = 1; // 附件数量
renderPassInfo.pAttachments = &colorAttachment; // 附件指针
renderPassInfo.subpassCount = 1; // 子通道数量
renderPassInfo.pSubpasses = &subpass; // 子通道指针
renderPassInfo.dependencyCount = 1; // 依赖数量
renderPassInfo.pDependencies = &dependency; // 依赖指针
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { // 创建渲染过程
throw std::runtime_error("failed to create render pass!"); // 失败抛异常
}
}
void createDescriptorSetLayout() { // 创建描述符集布局
VkDescriptorSetLayoutBinding uboLayoutBinding{}; // Uniform缓冲绑定
uboLayoutBinding.binding = 0; // 绑定索引0
uboLayoutBinding.descriptorCount = 1; // 描述符数量
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; // 类型:Uniform缓冲
uboLayoutBinding.pImmutableSamplers = nullptr; // 不可变采样器
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // 顶点着色器使用
VkDescriptorSetLayoutBinding samplerLayoutBinding{}; // 采样器绑定
samplerLayoutBinding.binding = 1; // 绑定索引1
samplerLayoutBinding.descriptorCount = 1; // 描述符数量
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // 类型:组合图像采样器
samplerLayoutBinding.pImmutableSamplers = nullptr; // 不可变采样器
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; // 片段着色器使用
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding }; // 绑定数组
VkDescriptorSetLayoutCreateInfo layoutInfo{}; // 描述符集布局创建信息
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; // 设置结构体类型
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); // 绑定数量
layoutInfo.pBindings = bindings.data(); // 绑定指针
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { // 创建布局
throw std::runtime_error("failed to create descriptor set layout!"); // 失败抛异常
}
}
void createGraphicsPipeline() { // 创建图形管线
auto vertShaderCode = readFile("shaders/26_shader_textures.vert.spv"); // 读取顶点着色器
auto fragShaderCode = readFile("shaders/26_shader_textures.frag.spv"); // 读取片段着色器
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode); // 创建顶点着色器模块
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode); // 创建片段着色器模块
VkPipelineShaderStageCreateInfo vertShaderStageInfo{}; // 顶点着色器阶段
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; // 设置结构体类型
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; // 阶段:顶点
vertShaderStageInfo.module = vertShaderModule; // 着色器模块
vertShaderStageInfo.pName = "main"; // 入口函数名
VkPipelineShaderStageCreateInfo fragShaderStageInfo{}; // 片段着色器阶段
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; // 设置结构体类型
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; // 阶段:片段
fragShaderStageInfo.module = fragShaderModule; // 着色器模块
fragShaderStageInfo.pName = "main"; // 入口函数名
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo }; // 阶段数组
VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; // 顶点输入状态
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; // 设置结构体类型
auto bindingDescription = Vertex::getBindingDescription(); // 获取绑定描述
auto attributeDescriptions = Vertex::getAttributeDescriptions(); // 获取属性描述
vertexInputInfo.vertexBindingDescriptionCount = 1; // 绑定描述数量
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); // 属性描述数量
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // 绑定描述指针
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // 属性描述指针
VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; // 输入装配状态
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; // 设置结构体类型
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // 图元类型:三角形列表
inputAssembly.primitiveRestartEnable = VK_FALSE; // 禁用图元重启
VkPipelineViewportStateCreateInfo viewportState{}; // 视口状态
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; // 设置结构体类型
viewportState.viewportCount = 1; // 视口数量
viewportState.scissorCount = 1; // 裁剪矩形数量
VkPipelineRasterizationStateCreateInfo rasterizer{}; // 光栅化状态
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; // 设置结构体类型
rasterizer.depthClampEnable = VK_FALSE; // 禁用深度钳位
rasterizer.rasterizerDiscardEnable = VK_FALSE; // 不丢弃光栅化
rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // 多边形模式:填充
rasterizer.lineWidth = 1.0f; // 线宽
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; // 剔除模式:剔除背面
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; // 正面:逆时针
rasterizer.depthBiasEnable = VK_FALSE; // 禁用深度偏移
VkPipelineMultisampleStateCreateInfo multisampling{}; // 多重采样状态
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; // 设置结构体类型
multisampling.sampleShadingEnable = VK_FALSE; // 禁用采样着色
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // 采样数1
VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // 颜色混合附件
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; // 写入所有通道
colorBlendAttachment.blendEnable = VK_FALSE; // 禁用混合
VkPipelineColorBlendStateCreateInfo colorBlending{}; // 颜色混合状态
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; // 设置结构体类型
colorBlending.logicOpEnable = VK_FALSE; // 禁用逻辑操作
colorBlending.logicOp = VK_LOGIC_OP_COPY; // 逻辑操作:复制
colorBlending.attachmentCount = 1; // 附件数量
colorBlending.pAttachments = &colorBlendAttachment; // 附件指针
colorBlending.blendConstants[0] = 0.0f; // 混合常量R
colorBlending.blendConstants[1] = 0.0f; // 混合常量G
colorBlending.blendConstants[2] = 0.0f; // 混合常量B
colorBlending.blendConstants[3] = 0.0f; // 混合常量A
std::vector<VkDynamicState> dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; // 动态状态列表
VkPipelineDynamicStateCreateInfo dynamicState{}; // 动态状态
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; // 设置结构体类型
dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size()); // 动态状态数量
dynamicState.pDynamicStates = dynamicStates.data(); // 动态状态列表指针
VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; // 管线布局创建信息
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; // 设置结构体类型
pipelineLayoutInfo.setLayoutCount = 1; // 描述符集布局数量
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; // 描述符集布局指针
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { // 创建管线布局
throw std::runtime_error("failed to create pipeline layout!"); // 失败抛异常
}
VkGraphicsPipelineCreateInfo pipelineInfo{}; // 图形管线创建信息
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; // 设置结构体类型
pipelineInfo.stageCount = 2; // 着色器阶段数量
pipelineInfo.pStages = shaderStages; // 阶段指针
pipelineInfo.pVertexInputState = &vertexInputInfo; // 顶点输入状态
pipelineInfo.pInputAssemblyState = &inputAssembly; // 输入装配状态
pipelineInfo.pViewportState = &viewportState; // 视口状态
pipelineInfo.pRasterizationState = &rasterizer; // 光栅化状态
pipelineInfo.pMultisampleState = &multisampling; // 多重采样状态
pipelineInfo.pColorBlendState = &colorBlending; // 颜色混合状态
pipelineInfo.pDynamicState = &dynamicState; // 动态状态
pipelineInfo.layout = pipelineLayout; // 管线布局
pipelineInfo.renderPass = renderPass; // 渲染过程
pipelineInfo.subpass = 0; // 子通道索引
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // 基础管线句柄
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) { // 创建图形管线
throw std::runtime_error("failed to create graphics pipeline!"); // 失败抛异常
}
vkDestroyShaderModule(device, fragShaderModule, nullptr); // 销毁片段着色器模块
vkDestroyShaderModule(device, vertShaderModule, nullptr); // 销毁顶点着色器模块
}
void createFramebuffers() { // 创建帧缓冲
swapChainFramebuffers.resize(swapChainImageViews.size()); // 调整大小
for (size_t i = 0; i < swapChainImageViews.size(); i++) { // 遍历每个图像视图
VkImageView attachments[] = { swapChainImageViews[i] }; // 附件数组
VkFramebufferCreateInfo framebufferInfo{}; // 帧缓冲创建信息
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; // 设置结构体类型
framebufferInfo.renderPass = renderPass; // 渲染过程
framebufferInfo.attachmentCount = 1; // 附件数量
framebufferInfo.pAttachments = attachments; // 附件指针
framebufferInfo.width = swapChainExtent.width; // 宽度
framebufferInfo.height = swapChainExtent.height; // 高度
framebufferInfo.layers = 1; // 层数
if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) { // 创建帧缓冲
throw std::runtime_error("failed to create framebuffer!"); // 失败抛异常
}
}
}
void createCommandPool() { // 创建命令池
QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice); // 查找队列族
VkCommandPoolCreateInfo poolInfo{}; // 命令池创建信息
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; // 设置结构体类型
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // 允许重置命令缓冲
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); // 图形队列族
if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { // 创建命令池
throw std::runtime_error("failed to create graphics command pool!"); // 失败抛异常
}
}
void createTextureImage() { // 创建纹理图像
int texWidth, texHeight, texChannels; // 纹理宽、高、通道数
stbi_uc* pixels = stbi_load("textures/1.jpg", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); // 加载纹理图片
VkDeviceSize imageSize = texWidth * texHeight * 4; // 计算图像大小(RGBA每像素4字节)
if (!pixels) { // 如果加载失败
throw std::runtime_error("failed to load texture image!"); // 抛异常
}
VkBuffer stagingBuffer; // 暂存缓冲
VkDeviceMemory stagingBufferMemory; // 暂存缓冲内存
createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // 创建暂存缓冲
void* data; // 数据指针
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data); // 映射内存
memcpy(data, pixels, static_cast<size_t>(imageSize)); // 拷贝像素数据
vkUnmapMemory(device, stagingBufferMemory); // 取消映射
stbi_image_free(pixels); // 释放stb_image加载的像素数据
createImage(texWidth, texHeight, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, textureImage, textureImageMemory); // 创建纹理图像
transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); // 转换布局:未定义→传输目标
copyBufferToImage(stagingBuffer, textureImage, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight)); // 复制缓冲到图像
transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // 转换布局:传输目标→着色器只读
vkDestroyBuffer(device, stagingBuffer, nullptr); // 销毁暂存缓冲
vkFreeMemory(device, stagingBufferMemory, nullptr); // 释放暂存缓冲内存
}
void createTextureImageView() { // 创建纹理图像视图
textureImageView = createImageView(textureImage, VK_FORMAT_R8G8B8A8_SRGB); // 创建图像视图
}
void createTextureSampler() { // 创建纹理采样器
VkPhysicalDeviceProperties properties{}; // 物理设备属性
vkGetPhysicalDeviceProperties(physicalDevice, &properties); // 获取设备属性
VkSamplerCreateInfo samplerInfo{}; // 采样器创建信息
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; // 设置结构体类型
samplerInfo.magFilter = VK_FILTER_LINEAR; // 放大过滤器:线性
samplerInfo.minFilter = VK_FILTER_LINEAR; // 缩小过滤器:线性
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; // U方向寻址模式:重复
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; // V方向寻址模式:重复
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; // W方向寻址模式:重复
samplerInfo.anisotropyEnable = VK_TRUE; // 启用各向异性过滤
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy; // 最大各向异性值
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; // 边框颜色:不透明黑
samplerInfo.unnormalizedCoordinates = VK_FALSE; // 使用归一化坐标
samplerInfo.compareEnable = VK_FALSE; // 禁用比较
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; // 比较操作:总是通过
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; // Mipmap模式:线性
if (vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) { // 创建采样器
throw std::runtime_error("failed to create texture sampler!"); // 失败抛异常
}
}
VkImageView createImageView(VkImage image, VkFormat format) { // 创建图像视图的辅助函数
VkImageViewCreateInfo viewInfo{}; // 图像视图创建信息
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; // 设置结构体类型
viewInfo.image = image; // 图像
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; // 视图类型:2D
viewInfo.format = format; // 格式
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // 颜色方面
viewInfo.subresourceRange.baseMipLevel = 0; // 基础Mip层级
viewInfo.subresourceRange.levelCount = 1; // Mip层级数量
viewInfo.subresourceRange.baseArrayLayer = 0; // 基础数组层
viewInfo.subresourceRange.layerCount = 1; // 数组层数量
VkImageView imageView; // 图像视图句柄
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS) { // 创建图像视图
throw std::runtime_error("failed to create image view!"); // 失败抛异常
}
return imageView; // 返回图像视图
}
void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory) { // 创建图像
VkImageCreateInfo imageInfo{}; // 图像创建信息
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; // 设置结构体类型
imageInfo.imageType = VK_IMAGE_TYPE_2D; // 图像类型:2D
imageInfo.extent.width = width; // 宽度
imageInfo.extent.height = height; // 高度
imageInfo.extent.depth = 1; // 深度
imageInfo.mipLevels = 1; // Mip层级数
imageInfo.arrayLayers = 1; // 数组层数
imageInfo.format = format; // 格式
imageInfo.tiling = tiling; // 平铺方式
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // 初始布局:未定义
imageInfo.usage = usage; // 用途
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; // 采样数
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // 独占模式
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS) { // 创建图像
throw std::runtime_error("failed to create image!"); // 失败抛异常
}
VkMemoryRequirements memRequirements; // 内存需求
vkGetImageMemoryRequirements(device, image, &memRequirements); // 获取内存需求
VkMemoryAllocateInfo allocInfo{}; // 内存分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; // 设置结构体类型
allocInfo.allocationSize = memRequirements.size; // 分配大小
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); // 内存类型
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS) { // 分配内存
throw std::runtime_error("failed to allocate image memory!"); // 失败抛异常
}
vkBindImageMemory(device, image, imageMemory, 0); // 绑定内存到图像
}
void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) { // 转换图像布局
VkCommandBuffer commandBuffer = beginSingleTimeCommands(); // 开始单次命令缓冲
VkImageMemoryBarrier barrier{}; // 图像内存屏障
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; // 设置结构体类型
barrier.oldLayout = oldLayout; // 旧布局
barrier.newLayout = newLayout; // 新布局
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // 忽略源队列族
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // 忽略目标队列族
barrier.image = image; // 图像
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // 颜色方面
barrier.subresourceRange.baseMipLevel = 0; // 基础Mip层级
barrier.subresourceRange.levelCount = 1; // Mip层级数量
barrier.subresourceRange.baseArrayLayer = 0; // 基础数组层
barrier.subresourceRange.layerCount = 1; // 数组层数量
VkPipelineStageFlags sourceStage; // 源阶段
VkPipelineStageFlags destinationStage; // 目标阶段
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { // 未定义→传输目标
barrier.srcAccessMask = 0; // 源访问掩码
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // 目标访问掩码
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; // 源阶段:管道顶部
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; // 目标阶段:传输
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { // 传输目标→着色器只读
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // 源访问掩码
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; // 目标访问掩码
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; // 源阶段:传输
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; // 目标阶段:片段着色器
}
else {
throw std::invalid_argument("unsupported layout transition!"); // 不支持的布局转换
}
vkCmdPipelineBarrier(commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); // 执行管线屏障
endSingleTimeCommands(commandBuffer); // 结束单次命令缓冲
}
void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) { // 复制缓冲到图像
VkCommandBuffer commandBuffer = beginSingleTimeCommands(); // 开始单次命令缓冲
VkBufferImageCopy region{}; // 缓冲到图像复制区域
region.bufferOffset = 0; // 缓冲偏移
region.bufferRowLength = 0; // 缓冲行长度
region.bufferImageHeight = 0; // 缓冲图像高度
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // 颜色方面
region.imageSubresource.mipLevel = 0; // Mip层级
region.imageSubresource.baseArrayLayer = 0; // 基础数组层
region.imageSubresource.layerCount = 1; // 数组层数量
region.imageOffset = { 0, 0, 0 }; // 图像偏移
region.imageExtent = { width, height, 1 }; // 图像尺寸
vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); // 复制命令
endSingleTimeCommands(commandBuffer); // 结束单次命令缓冲
}
void createVertexBuffer() { // 创建顶点缓冲
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); // 计算缓冲大小
VkBuffer stagingBuffer; // 暂存缓冲
VkDeviceMemory stagingBufferMemory; // 暂存缓冲内存
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // 创建暂存缓冲
void* data; // 数据指针
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); // 映射内存
memcpy(data, vertices.data(), (size_t)bufferSize); // 拷贝顶点数据
vkUnmapMemory(device, stagingBufferMemory); // 取消映射
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); // 创建顶点缓冲
copyBuffer(stagingBuffer, vertexBuffer, bufferSize); // 复制数据
vkDestroyBuffer(device, stagingBuffer, nullptr); // 销毁暂存缓冲
vkFreeMemory(device, stagingBufferMemory, nullptr); // 释放暂存缓冲内存
}
void createIndexBuffer() { // 创建索引缓冲
VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size(); // 计算缓冲大小
VkBuffer stagingBuffer; // 暂存缓冲
VkDeviceMemory stagingBufferMemory; // 暂存缓冲内存
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // 创建暂存缓冲
void* data; // 数据指针
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); // 映射内存
memcpy(data, indices.data(), (size_t)bufferSize); // 拷贝索引数据
vkUnmapMemory(device, stagingBufferMemory); // 取消映射
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); // 创建索引缓冲
copyBuffer(stagingBuffer, indexBuffer, bufferSize); // 复制数据
vkDestroyBuffer(device, stagingBuffer, nullptr); // 销毁暂存缓冲
vkFreeMemory(device, stagingBufferMemory, nullptr); // 释放暂存缓冲内存
}
void createUniformBuffers() { // 创建Uniform缓冲
VkDeviceSize bufferSize = sizeof(UniformBufferObject); // 计算Uniform缓冲大小
uniformBuffers.resize(MAX_FRAMES_IN_FLIGHT); // 调整列表大小
uniformBuffersMemory.resize(MAX_FRAMES_IN_FLIGHT); // 调整内存列表大小
uniformBuffersMapped.resize(MAX_FRAMES_IN_FLIGHT); // 调整映射列表大小
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历每帧
createBuffer(bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uniformBuffers[i], uniformBuffersMemory[i]); // 创建Uniform缓冲
vkMapMemory(device, uniformBuffersMemory[i], 0, bufferSize, 0, &uniformBuffersMapped[i]); // 映射内存
}
}
void createDescriptorPool() { // 创建描述符池
std::array<VkDescriptorPoolSize, 2> poolSizes{}; // 描述符池大小数组
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; // 类型:Uniform缓冲
poolSizes[0].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT); // 描述符数量
poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // 类型:组合图像采样器
poolSizes[1].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT); // 描述符数量
VkDescriptorPoolCreateInfo poolInfo{}; // 描述符池创建信息
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; // 设置结构体类型
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); // 池大小数量
poolInfo.pPoolSizes = poolSizes.data(); // 池大小指针
poolInfo.maxSets = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT); // 最大描述符集数量
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { // 创建描述符池
throw std::runtime_error("failed to create descriptor pool!"); // 失败抛异常
}
}
void createDescriptorSets() { // 创建描述符集
std::vector<VkDescriptorSetLayout> layouts(MAX_FRAMES_IN_FLIGHT, descriptorSetLayout); // 布局列表
VkDescriptorSetAllocateInfo allocInfo{}; // 描述符集分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; // 设置结构体类型
allocInfo.descriptorPool = descriptorPool; // 描述符池
allocInfo.descriptorSetCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT); // 描述符集数量
allocInfo.pSetLayouts = layouts.data(); // 布局指针
descriptorSets.resize(MAX_FRAMES_IN_FLIGHT); // 调整描述符集列表大小
if (vkAllocateDescriptorSets(device, &allocInfo, descriptorSets.data()) != VK_SUCCESS) { // 分配描述符集
throw std::runtime_error("failed to allocate descriptor sets!"); // 失败抛异常
}
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历每帧
VkDescriptorBufferInfo bufferInfo{}; // 描述符缓冲信息
bufferInfo.buffer = uniformBuffers[i]; // Uniform缓冲
bufferInfo.offset = 0; // 偏移
bufferInfo.range = sizeof(UniformBufferObject); // 范围
VkDescriptorImageInfo imageInfo{}; // 描述符图像信息
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // 图像布局:着色器只读
imageInfo.imageView = textureImageView; // 图像视图
imageInfo.sampler = textureSampler; // 采样器
std::array<VkWriteDescriptorSet, 2> descriptorWrites{}; // 描述符写入数组
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; // 设置结构体类型
descriptorWrites[0].dstSet = descriptorSets[i]; // 目标描述符集
descriptorWrites[0].dstBinding = 0; // 目标绑定索引0
descriptorWrites[0].dstArrayElement = 0; // 数组元素索引
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; // 描述符类型
descriptorWrites[0].descriptorCount = 1; // 描述符数量
descriptorWrites[0].pBufferInfo = &bufferInfo; // 缓冲信息指针
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; // 设置结构体类型
descriptorWrites[1].dstSet = descriptorSets[i]; // 目标描述符集
descriptorWrites[1].dstBinding = 1; // 目标绑定索引1
descriptorWrites[1].dstArrayElement = 0; // 数组元素索引
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // 描述符类型
descriptorWrites[1].descriptorCount = 1; // 描述符数量
descriptorWrites[1].pImageInfo = &imageInfo; // 图像信息指针
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); // 更新描述符集
}
}
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { // 创建缓冲
VkBufferCreateInfo bufferInfo{}; // 缓冲创建信息
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; // 设置结构体类型
bufferInfo.size = size; // 大小
bufferInfo.usage = usage; // 用途
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // 独占模式
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { // 创建缓冲
throw std::runtime_error("failed to create buffer!"); // 失败抛异常
}
VkMemoryRequirements memRequirements; // 内存需求
vkGetBufferMemoryRequirements(device, buffer, &memRequirements); // 获取内存需求
VkMemoryAllocateInfo allocInfo{}; // 内存分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; // 设置结构体类型
allocInfo.allocationSize = memRequirements.size; // 分配大小
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); // 内存类型
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { // 分配内存
throw std::runtime_error("failed to allocate buffer memory!"); // 失败抛异常
}
vkBindBufferMemory(device, buffer, bufferMemory, 0); // 绑定内存到缓冲
}
VkCommandBuffer beginSingleTimeCommands() { // 开始单次命令缓冲
VkCommandBufferAllocateInfo allocInfo{}; // 分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; // 设置结构体类型
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; // 主命令缓冲
allocInfo.commandPool = commandPool; // 命令池
allocInfo.commandBufferCount = 1; // 数量1
VkCommandBuffer commandBuffer; // 命令缓冲
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); // 分配
VkCommandBufferBeginInfo beginInfo{}; // 开始信息
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // 设置结构体类型
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // 一次性提交
vkBeginCommandBuffer(commandBuffer, &beginInfo); // 开始记录
return commandBuffer; // 返回命令缓冲
}
void endSingleTimeCommands(VkCommandBuffer commandBuffer) { // 结束单次命令缓冲
vkEndCommandBuffer(commandBuffer); // 结束记录
VkSubmitInfo submitInfo{}; // 提交信息
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; // 设置结构体类型
submitInfo.commandBufferCount = 1; // 命令缓冲数量
submitInfo.pCommandBuffers = &commandBuffer; // 命令缓冲指针
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); // 提交到队列
vkQueueWaitIdle(graphicsQueue); // 等待队列空闲
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); // 释放命令缓冲
}
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { // 复制缓冲
VkCommandBuffer commandBuffer = beginSingleTimeCommands(); // 开始单次命令缓冲
VkBufferCopy copyRegion{}; // 复制区域
copyRegion.size = size; // 大小
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region); // 复制命令
endSingleTimeCommands(commandBuffer); // 结束单次命令缓冲
}
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { // 查找内存类型
VkPhysicalDeviceMemoryProperties memProperties; // 内存属性
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); // 获取
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { // 遍历
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { // 匹配
return i; // 返回索引
}
}
throw std::runtime_error("failed to find suitable memory type!"); // 未找到抛异常
}
void createCommandBuffers() { // 创建命令缓冲
commandBuffers.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
VkCommandBufferAllocateInfo allocInfo{}; // 分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; // 设置结构体类型
allocInfo.commandPool = commandPool; // 命令池
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; // 主命令缓冲
allocInfo.commandBufferCount = (uint32_t)commandBuffers.size(); // 数量
if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { // 分配
throw std::runtime_error("failed to allocate command buffers!"); // 失败抛异常
}
}
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex) { // 记录命令缓冲
VkCommandBufferBeginInfo beginInfo{}; // 开始信息
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // 设置结构体类型
if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) { // 开始记录
throw std::runtime_error("failed to begin recording command buffer!"); // 失败抛异常
}
VkRenderPassBeginInfo renderPassInfo{}; // 渲染过程开始信息
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; // 设置结构体类型
renderPassInfo.renderPass = renderPass; // 渲染过程
renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex]; // 帧缓冲
renderPassInfo.renderArea.offset = { 0, 0 }; // 偏移
renderPassInfo.renderArea.extent = swapChainExtent; // 尺寸
VkClearValue clearColor = { {{0.0f, 0.0f, 0.0f, 1.0f}} }; // 清除颜色:黑色
renderPassInfo.clearValueCount = 1; // 清除值数量
renderPassInfo.pClearValues = &clearColor; // 清除值指针
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); // 开始渲染过程
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); // 绑定管线
VkViewport viewport{}; // 视口
viewport.x = 0.0f; // x起始
viewport.y = 0.0f; // y起始
viewport.width = (float)swapChainExtent.width; // 宽度
viewport.height = (float)swapChainExtent.height; // 高度
viewport.minDepth = 0.0f; // 最小深度
viewport.maxDepth = 1.0f; // 最大深度
vkCmdSetViewport(commandBuffer, 0, 1, &viewport); // 设置视口
VkRect2D scissor{}; // 裁剪矩形
scissor.offset = { 0, 0 }; // 偏移
scissor.extent = swapChainExtent; // 尺寸
vkCmdSetScissor(commandBuffer, 0, 1, &scissor); // 设置裁剪矩形
VkBuffer vertexBuffers[] = { vertexBuffer }; // 顶点缓冲数组
VkDeviceSize offsets[] = { 0 }; // 偏移数组
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); // 绑定顶点缓冲
vkCmdBindIndexBuffer(commandBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT16); // 绑定索引缓冲
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentFrame], 0, nullptr); // 绑定描述符集
vkCmdDrawIndexed(commandBuffer, static_cast<uint32_t>(indices.size()), 1, 0, 0, 0); // 绘制索引
vkCmdEndRenderPass(commandBuffer); // 结束渲染过程
if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) { // 结束记录
throw std::runtime_error("failed to record command buffer!"); // 失败抛异常
}
}
void createSyncObjects() { // 创建同步对象
imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
VkSemaphoreCreateInfo semaphoreInfo{}; // 信号量创建信息
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; // 设置结构体类型
VkFenceCreateInfo fenceInfo{}; // 围栏创建信息
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; // 设置结构体类型
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; // 初始为有信号状态
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历每帧
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || // 创建图像可用信号量
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || // 创建渲染完成信号量
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { // 创建围栏
throw std::runtime_error("failed to create synchronization objects for a frame!"); // 失败抛异常
}
}
}
void updateUniformBuffer(uint32_t currentImage) { // 更新Uniform缓冲
static auto startTime = std::chrono::high_resolution_clock::now(); // 记录开始时间
auto currentTime = std::chrono::high_resolution_clock::now(); // 获取当前时间
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); // 计算运行秒数
UniformBufferObject ubo{}; // Uniform缓冲对象
ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f)); // 模型矩阵:绕Z轴旋转
ubo.view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); // 视图矩阵
ubo.proj = glm::perspective(glm::radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f); // 投影矩阵
ubo.proj[1][1] *= -1; // 翻转Y轴(Vulkan坐标系)
memcpy(uniformBuffersMapped[currentImage], &ubo, sizeof(ubo)); // 拷贝数据到映射内存
}
void drawFrame() { // 绘制一帧
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); // 等待围栏
uint32_t imageIndex; // 图像索引
VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); // 获取下一张图像
if (result == VK_ERROR_OUT_OF_DATE_KHR) { // 如果交换链过时
recreateSwapChain(); // 重建
return; // 返回
}
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { // 其他错误
throw std::runtime_error("failed to acquire swap chain image!"); // 抛异常
}
updateUniformBuffer(currentFrame); // 更新Uniform缓冲
vkResetFences(device, 1, &inFlightFences[currentFrame]); // 重置围栏
vkResetCommandBuffer(commandBuffers[currentFrame], /*VkCommandBufferResetFlagBits*/ 0); // 重置命令缓冲
recordCommandBuffer(commandBuffers[currentFrame], imageIndex); // 记录命令缓冲
VkSubmitInfo submitInfo{}; // 提交信息
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; // 设置结构体类型
VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] }; // 等待信号量
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; // 等待阶段
submitInfo.waitSemaphoreCount = 1; // 等待信号量数量
submitInfo.pWaitSemaphores = waitSemaphores; // 等待信号量指针
submitInfo.pWaitDstStageMask = waitStages; // 等待阶段指针
submitInfo.commandBufferCount = 1; // 命令缓冲数量
submitInfo.pCommandBuffers = &commandBuffers[currentFrame]; // 命令缓冲指针
VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] }; // 信号信号量
submitInfo.signalSemaphoreCount = 1; // 信号信号量数量
submitInfo.pSignalSemaphores = signalSemaphores; // 信号信号量指针
if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) { // 提交
throw std::runtime_error("failed to submit draw command buffer!"); // 失败抛异常
}
VkPresentInfoKHR presentInfo{}; // 呈现信息
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; // 设置结构体类型
presentInfo.waitSemaphoreCount = 1; // 等待信号量数量
presentInfo.pWaitSemaphores = signalSemaphores; // 等待信号量指针
VkSwapchainKHR swapChains[] = { swapChain }; // 交换链数组
presentInfo.swapchainCount = 1; // 交换链数量
presentInfo.pSwapchains = swapChains; // 交换链指针
presentInfo.pImageIndices = &imageIndex; // 图像索引指针
result = vkQueuePresentKHR(presentQueue, &presentInfo); // 呈现
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) { // 需要重建
framebufferResized = false; // 重置标志
recreateSwapChain(); // 重建
}
else if (result != VK_SUCCESS) { // 其他错误
throw std::runtime_error("failed to present swap chain image!"); // 抛异常
}
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; // 切换到下一帧
}
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; // 返回
}
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { // 选择表面格式
for (const auto& availableFormat : availableFormats) { // 遍历
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { // 首选
return availableFormat; // 返回
}
}
return availableFormats[0]; // 返回第一个
}
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { // 选择呈现模式
for (const auto& availablePresentMode : availablePresentModes) { // 遍历
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { // 首选MAILBOX
return availablePresentMode; // 返回
}
}
return VK_PRESENT_MODE_FIFO_KHR; // 否则FIFO
}
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) { // 选择交换链尺寸
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) { // 如果尺寸有效
return capabilities.currentExtent; // 直接返回
}
else {
int width, height; // 窗口尺寸
glfwGetFramebufferSize(window, &width, &height); // 获取
VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; // 实际尺寸
actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width); // 限制宽度
actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height); // 限制高度
return actualExtent; // 返回
}
}
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) { // 查询交换链支持
SwapChainSupportDetails details; // 详情
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // 获取能力
uint32_t formatCount; // 格式数量
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); // 获取数量
if (formatCount != 0) { // 如果有格式
details.formats.resize(formatCount); // 调整大小
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); // 获取格式
}
uint32_t presentModeCount; // 呈现模式数量
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); // 获取数量
if (presentModeCount != 0) { // 如果有模式
details.presentModes.resize(presentModeCount); // 调整大小
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); // 获取模式
}
return details; // 返回
}
bool isDeviceSuitable(VkPhysicalDevice device) { // 判断设备是否合适
QueueFamilyIndices indices = findQueueFamilies(device); // 查找队列族
bool extensionsSupported = checkDeviceExtensionSupport(device); // 检查扩展
bool swapChainAdequate = false; // 交换链是否充分
if (extensionsSupported) { // 如果扩展支持
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device); // 查询交换链
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); // 非空
}
VkPhysicalDeviceFeatures supportedFeatures; // 支持的设备特性
vkGetPhysicalDeviceFeatures(device, &supportedFeatures); // 获取
return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy; // 返回
}
bool checkDeviceExtensionSupport(VkPhysicalDevice device) { // 检查设备扩展支持
uint32_t extensionCount; // 扩展数量
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); // 获取数量
std::vector<VkExtensionProperties> availableExtensions(extensionCount); // 可用扩展列表
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); // 获取
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); // 所需扩展
for (const auto& extension : availableExtensions) { // 遍历
requiredExtensions.erase(extension.extensionName); // 移除已支持的
}
return requiredExtensions.empty(); // 全部支持返回true
}
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { // 查找队列族
QueueFamilyIndices indices; // 索引
uint32_t queueFamilyCount = 0; // 队列族数量
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); // 获取数量
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); // 队列族属性列表
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); // 获取
int i = 0; // 计数器
for (const auto& queueFamily : queueFamilies) { // 遍历
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { // 支持图形
indices.graphicsFamily = i; // 记录图形队列族
}
VkBool32 presentSupport = false; // 呈现支持
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport); // 检查
if (presentSupport) { // 支持呈现
indices.presentFamily = i; // 记录呈现队列族
}
if (indices.isComplete()) { // 都已找到
break; // 跳出
}
i++; // 递增
}
return indices; // 返回
}
std::vector<const char*> getRequiredExtensions() { // 获取所需扩展
uint32_t glfwExtensionCount = 0; // GLFW扩展数量
const char** glfwExtensions; // GLFW扩展列表
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); // 获取
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); // 复制
if (enableValidationLayers) { // 如果启用验证层
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); // 添加调试扩展
}
return extensions; // 返回
}
bool checkValidationLayerSupport() { // 检查验证层支持
uint32_t layerCount; // 层数量
vkEnumerateInstanceLayerProperties(&layerCount, nullptr); // 获取数量
std::vector<VkLayerProperties> availableLayers(layerCount); // 可用层列表
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); // 获取
for (const char* layerName : validationLayers) { // 遍历所需层
bool layerFound = false; // 是否找到
for (const auto& layerProperties : availableLayers) { // 遍历可用层
if (strcmp(layerName, layerProperties.layerName) == 0) { // 比较
layerFound = true; // 找到
break; // 跳出内层循环
}
}
if (!layerFound) { // 未找到
return false; // 返回false
}
}
return true; // 全部找到
}
static std::vector<char> readFile(const std::string& filename) { // 读取文件
std::ifstream file(filename, std::ios::ate | std::ios::binary); // 打开
if (!file.is_open()) { // 打开失败
throw std::runtime_error("failed to open file!"); // 抛异常
}
size_t fileSize = (size_t)file.tellg(); // 文件大小
std::vector<char> buffer(fileSize); // 缓冲
file.seekg(0); // 移动到开头
file.read(buffer.data(), fileSize); // 读取
file.close(); // 关闭
return buffer; // 返回
}
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { // 调试回调
std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl; // 输出验证层消息
return VK_FALSE; // 返回false(不终止)
}
};
int main() { // 主函数
HelloTriangleApplication app; // 创建应用实例
try { // 尝试
app.run(); // 运行应用
} // try结束
catch (const std::exception& e) { // 捕获异常
std::cerr << e.what() << std::endl; // 输出异常信息
return EXIT_FAILURE; // 返回失败
} // catch结束
return EXIT_SUCCESS; // 返回成功
} // main结束