3410 lines
116 KiB
C++
3410 lines
116 KiB
C++
#include "dl_vk.h"
|
||
|
||
#include <set>
|
||
|
||
namespace dl
|
||
{
|
||
VK* g_vk = nullptr;
|
||
|
||
void VK::_check_extension()
|
||
{
|
||
LogLimit l;
|
||
|
||
uint32_t extensionCount = 0;
|
||
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
|
||
|
||
if (extensionCount == 0)
|
||
{
|
||
log_err0("extensionCount 为0!");
|
||
return;
|
||
}
|
||
else
|
||
log_msg("{} extensions supported", extensionCount);
|
||
|
||
_allExtension.resize(extensionCount);
|
||
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, _allExtension.data());
|
||
|
||
log("available extensions:");
|
||
for (auto& iter : _allExtension)
|
||
{
|
||
log(iter.extensionName);
|
||
}
|
||
}
|
||
|
||
void VK::_create_instance()
|
||
{
|
||
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;
|
||
|
||
VkInstanceCreateInfo createInfo{};
|
||
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||
createInfo.pApplicationInfo = &appInfo;
|
||
|
||
auto extensions = _get_required_extensions();
|
||
createInfo.enabledExtensionCount = (uint32_t)extensions.size();
|
||
createInfo.ppEnabledExtensionNames = extensions.data();
|
||
|
||
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
|
||
if (ENABLE_VALIDATION_LAYERS)
|
||
{
|
||
createInfo.enabledLayerCount = static_cast<uint32_t>(_allValidationLayer.size());
|
||
createInfo.ppEnabledLayerNames = _allValidationLayer.data();
|
||
|
||
PopulateDebugMessengerCreateInfo(debugCreateInfo);
|
||
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
|
||
}
|
||
else
|
||
{
|
||
createInfo.enabledLayerCount = 0;
|
||
createInfo.pNext = nullptr;
|
||
}
|
||
|
||
if (vkCreateInstance(&createInfo, nullptr, &_instance) != VK_SUCCESS)
|
||
{
|
||
log_err0("vkCreateInstance 失败!");
|
||
}
|
||
}
|
||
|
||
void VK::_check_layer()
|
||
{
|
||
uint32_t layerCount;
|
||
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
|
||
|
||
_allLayer.resize(layerCount);
|
||
vkEnumerateInstanceLayerProperties(&layerCount, _allLayer.data());
|
||
|
||
//打印所有layer
|
||
LogLimit l;
|
||
log("available layers:");
|
||
for (auto& iter : _allLayer)
|
||
{
|
||
log(iter.layerName);
|
||
}
|
||
}
|
||
|
||
bool VK::_check_validation_layer()
|
||
{
|
||
//检查layer支持,不支持直接错误
|
||
bool support = true;
|
||
for (const char* layerName : _allValidationLayer)
|
||
{
|
||
bool layerFound = false;
|
||
|
||
for (const auto& layerProperties : _allLayer)
|
||
{
|
||
if (strcmp(layerName, layerProperties.layerName) == 0)
|
||
{
|
||
layerFound = true;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (!layerFound)
|
||
{
|
||
support = false;
|
||
break;
|
||
}
|
||
}
|
||
|
||
//验证层开启 且不支持
|
||
if (ENABLE_VALIDATION_LAYERS && !support)
|
||
{
|
||
log_err0("验证层不支持!");
|
||
return false;
|
||
}
|
||
return ENABLE_VALIDATION_LAYERS;
|
||
}
|
||
|
||
void VK::_create_physical_device()
|
||
{
|
||
uint32_t deviceCount = 0;
|
||
vkEnumeratePhysicalDevices(_instance, &deviceCount, nullptr);
|
||
|
||
if (deviceCount == 0)
|
||
{
|
||
log_err0("没有物理设备支持!");
|
||
return;
|
||
}
|
||
_allPhysicalDevice.resize(deviceCount);
|
||
vkEnumeratePhysicalDevices(_instance, &deviceCount, _allPhysicalDevice.data());
|
||
|
||
//获得支持特性的设备
|
||
_physicalDevice = VK_NULL_HANDLE;
|
||
for (auto& iter : _allPhysicalDevice)
|
||
{
|
||
if (_is_device_suitable(iter))
|
||
{
|
||
_physicalDevice = iter;
|
||
_msaaSamples = GetMaxUsableSampleCount();
|
||
break;
|
||
}
|
||
}
|
||
if (_physicalDevice == VK_NULL_HANDLE)
|
||
{
|
||
log_err0("没有物理设备支持所要求的特性!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
bool VK::_is_device_suitable(VkPhysicalDevice device)
|
||
{
|
||
//队列族
|
||
QueueFamilyIndices indices = _find_queue_families(device);
|
||
|
||
//扩展
|
||
bool extensionsSupported = _check_device_extension(device);
|
||
|
||
//交换链
|
||
bool swapChainAdequate = false;
|
||
if (extensionsSupported)
|
||
{
|
||
SwapChainSupportDetails swapChainSupport = _query_swap_chain_support(device);
|
||
swapChainAdequate = !swapChainSupport._formats.empty() && !swapChainSupport._presentModes.empty();
|
||
}
|
||
|
||
VkPhysicalDeviceFeatures supportedFeatures;
|
||
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
|
||
|
||
VkPhysicalDeviceProperties properties{};
|
||
vkGetPhysicalDeviceProperties(device, &properties);
|
||
|
||
uint32_t cb_size = properties.limits.maxPushConstantsSize;
|
||
|
||
return indices.IsComplete()
|
||
&& extensionsSupported
|
||
&& swapChainAdequate
|
||
&& supportedFeatures.samplerAnisotropy
|
||
&& supportedFeatures.fillModeNonSolid;// 非填充模式支持
|
||
}
|
||
|
||
QueueFamilyIndices VK::_find_queue_families(VkPhysicalDevice device)
|
||
{
|
||
QueueFamilyIndices indices;
|
||
|
||
uint32_t queueFamilyCount = 0;
|
||
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
|
||
|
||
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
|
||
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
|
||
|
||
//至少一个支持VK_QUEUE_GRAPHICS_BIT
|
||
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;
|
||
}
|
||
|
||
void VK::_create_logical_device()
|
||
{
|
||
QueueFamilyIndices indices = _find_queue_families(_physicalDevice);
|
||
|
||
VkDeviceQueueCreateInfo queueCreateInfo{};
|
||
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||
queueCreateInfo.queueFamilyIndex = indices._graphicsFamily.value();
|
||
queueCreateInfo.queueCount = 1;
|
||
//对列优先级
|
||
float queuePriority = 1.0f;
|
||
queueCreateInfo.pQueuePriorities = &queuePriority;
|
||
|
||
//物理设备特性
|
||
VkPhysicalDeviceFeatures deviceFeatures{};
|
||
deviceFeatures.samplerAnisotropy = VK_TRUE;
|
||
if (B_OPEN_SAMPLE_SHADING)
|
||
deviceFeatures.sampleRateShading = VK_TRUE;
|
||
deviceFeatures.fillModeNonSolid = VK_TRUE;
|
||
|
||
VkDeviceCreateInfo createInfo{};
|
||
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||
createInfo.pQueueCreateInfos = &queueCreateInfo;
|
||
createInfo.queueCreateInfoCount = 1;
|
||
|
||
createInfo.pEnabledFeatures = &deviceFeatures;
|
||
|
||
//设备扩展
|
||
createInfo.enabledExtensionCount = static_cast<uint32_t>(_allDeviceExtension.size());
|
||
createInfo.ppEnabledExtensionNames = _allDeviceExtension.data();
|
||
|
||
//验证层
|
||
if (_check_validation_layer())
|
||
{
|
||
createInfo.enabledLayerCount = static_cast<uint32_t>(_allValidationLayer.size());
|
||
createInfo.ppEnabledLayerNames = _allValidationLayer.data();
|
||
}
|
||
else
|
||
{
|
||
createInfo.enabledLayerCount = 0;
|
||
}
|
||
//创建呈现队列
|
||
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
|
||
std::set<uint32_t> uniqueQueueFamilies = {
|
||
indices._graphicsFamily.value(), indices._presentFamily.value()
|
||
};
|
||
|
||
float queuePriority1 = 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 = &queuePriority1;
|
||
queueCreateInfos.push_back(queueCreateInfo);
|
||
}
|
||
|
||
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
|
||
createInfo.pQueueCreateInfos = queueCreateInfos.data();
|
||
|
||
if (vkCreateDevice(_physicalDevice, &createInfo, nullptr, &_device) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建逻辑设备失败!");
|
||
}
|
||
//从device获得图形队列
|
||
vkGetDeviceQueue(_device, indices._graphicsFamily.value(), 0, &_graphicsQueue);
|
||
|
||
//从device获得呈现队列
|
||
vkGetDeviceQueue(_device, indices._presentFamily.value(), 0, &_presentQueue);
|
||
}
|
||
|
||
bool VK::_check_device_extension(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(_allDeviceExtension.begin(), _allDeviceExtension.end());
|
||
|
||
for (const auto& extension : availableExtensions) {
|
||
requiredExtensions.erase(extension.extensionName);
|
||
}
|
||
|
||
return requiredExtensions.empty();
|
||
}
|
||
|
||
|
||
void VK::_create_surface(GLFWwindow* window)
|
||
{
|
||
#if (DL_PLATFORM == DL_PLATFORM_ANDROID)
|
||
VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo;
|
||
surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
|
||
|
||
//创建新的窗口用于视频显示
|
||
ANativeWindow*& native_window = window->_window;
|
||
native_window = ANativeWindow_fromSurface(env, surface);
|
||
//设置窗口属性
|
||
ANativeWindow_setBuffersGeometry(native_window, 800, 600, WINDOW_FORMAT_RGBA_8888);
|
||
|
||
surfaceCreateInfo.window = native_window;
|
||
if(vkCreateAndroidSurfaceKHR(_instance, &surfaceCreateInfo, nullptr, &_surface) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建窗口表面失败!");
|
||
}
|
||
#else
|
||
if (glfwCreateWindowSurface(_instance, window, nullptr, &_surface) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建窗口表面失败!");
|
||
}
|
||
#endif
|
||
}
|
||
|
||
void VK::_create_swap_chain(GLFWwindow* window)
|
||
{
|
||
SwapChainSupportDetails swapChainSupport = _query_swap_chain_support(_physicalDevice);
|
||
|
||
VkSurfaceFormatKHR surfaceFormat = _choose_swap_surface_format(swapChainSupport._formats);
|
||
VkPresentModeKHR presentMode = _choose_swap_present_mode(swapChainSupport._presentModes);
|
||
VkExtent2D extent = _choose_swap_extent(swapChainSupport._capabilities, window);
|
||
|
||
uint32_t imageCount = swapChainSupport._capabilities.minImageCount + 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
|
||
| VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||
//截图必须依赖 VK_IMAGE_USAGE_TRANSFER_SRC_BIT
|
||
|
||
QueueFamilyIndices indices = _find_queue_families(_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.queueFamilyIndexCount = 0; // Optional
|
||
createInfo.pQueueFamilyIndices = nullptr; // Optional
|
||
}
|
||
createInfo.preTransform = swapChainSupport._capabilities.currentTransform;
|
||
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
||
createInfo.presentMode = presentMode;
|
||
createInfo.clipped = VK_TRUE;
|
||
createInfo.oldSwapchain = VK_NULL_HANDLE;
|
||
|
||
if (vkCreateSwapchainKHR(_device, &createInfo, nullptr, &_swapChain) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建交换链失败!");
|
||
return;
|
||
}
|
||
//获取交换链图像
|
||
vkGetSwapchainImagesKHR(_device, _swapChain, &imageCount, nullptr);
|
||
_allImageSwapChain.resize(imageCount);
|
||
vkGetSwapchainImagesKHR(_device, _swapChain, &imageCount, _allImageSwapChain.data());
|
||
|
||
_formatSwapChainImage = surfaceFormat.format;
|
||
_extentSwapChain = extent;
|
||
}
|
||
|
||
SwapChainSupportDetails VK::_query_swap_chain_support(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);
|
||
|
||
// 安卓模拟器不会返回有效值
|
||
assert(presentModeCount < 1024);
|
||
if (presentModeCount != 0)
|
||
{
|
||
details._presentModes.resize(presentModeCount);
|
||
vkGetPhysicalDeviceSurfacePresentModesKHR(device, _surface, &presentModeCount, details._presentModes.data());
|
||
}
|
||
|
||
return details;
|
||
}
|
||
|
||
VkSurfaceFormatKHR VK::_choose_swap_surface_format(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 VK::_choose_swap_present_mode(const std::vector<VkPresentModeKHR>& availablePresentModes)
|
||
{
|
||
for (const auto& availablePresentMode : availablePresentModes)
|
||
{
|
||
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
|
||
{//优先三重缓冲
|
||
return availablePresentMode;
|
||
}
|
||
}
|
||
return VK_PRESENT_MODE_FIFO_KHR;//必定支持的模式
|
||
}
|
||
|
||
VkExtent2D VK::_choose_swap_extent(const VkSurfaceCapabilitiesKHR& capabilities,
|
||
GLFWwindow* window)
|
||
{
|
||
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;
|
||
}
|
||
}
|
||
|
||
void VK::_create_image_view()
|
||
{
|
||
_allImageViewSwapChain.resize(_allImageSwapChain.size());
|
||
for (size_t i = 0; i < _allImageSwapChain.size(); ++i)
|
||
{
|
||
_allImageViewSwapChain[i] = CreateImageView(_allImageSwapChain[i],
|
||
_formatSwapChainImage, VK_IMAGE_ASPECT_COLOR_BIT, 1);
|
||
}
|
||
}
|
||
|
||
VkShaderModule VK::CreateShaderModule(Buffer& buf)
|
||
{
|
||
VkShaderModuleCreateInfo createInfo{};
|
||
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
|
||
createInfo.codeSize = buf.size();
|
||
createInfo.pCode = (const uint32_t*)buf.data();
|
||
|
||
VkShaderModule shaderModule;
|
||
if (vkCreateShaderModule(_device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建shader模块失败!");
|
||
return {};
|
||
}
|
||
return shaderModule;
|
||
}
|
||
|
||
void VK::_create_render_pass()
|
||
{
|
||
//color
|
||
VkAttachmentDescription colorAttachment{};
|
||
colorAttachment.format = _formatSwapChainImage;
|
||
colorAttachment.samples = _msaaSamples;
|
||
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_COLOR_ATTACHMENT_OPTIMAL;
|
||
|
||
VkAttachmentReference colorAttachmentRef{};
|
||
colorAttachmentRef.attachment = 0;
|
||
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||
//depth
|
||
VkAttachmentDescription depthAttachment{};
|
||
depthAttachment.format = FindDepthFormat();
|
||
depthAttachment.samples = _msaaSamples;
|
||
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
||
|
||
VkAttachmentReference depthAttachmentRef{};
|
||
depthAttachmentRef.attachment = 1;
|
||
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
||
//color resolve
|
||
VkAttachmentDescription colorAttachmentResolve{};
|
||
colorAttachmentResolve.format = _formatSwapChainImage;
|
||
colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT;
|
||
colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||
colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||
colorAttachmentResolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||
colorAttachmentResolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||
colorAttachmentResolve.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||
colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
||
|
||
VkAttachmentReference colorAttachmentResolveRef{};
|
||
colorAttachmentResolveRef.attachment = 2;
|
||
colorAttachmentResolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||
|
||
VkSubpassDescription subpass{};
|
||
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
||
subpass.colorAttachmentCount = 1;
|
||
subpass.pColorAttachments = &colorAttachmentRef;
|
||
subpass.pDepthStencilAttachment = &depthAttachmentRef;
|
||
subpass.pResolveAttachments = &colorAttachmentResolveRef;
|
||
|
||
//子流程依赖
|
||
VkSubpassDependency dependency{};
|
||
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
||
dependency.dstSubpass = 0;
|
||
dependency.srcAccessMask = 0;
|
||
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
|
||
| VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
|
||
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
|
||
| VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
|
||
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
|
||
| VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
|
||
|
||
//渲染流程
|
||
std::array<VkAttachmentDescription, 3> attachments = {
|
||
colorAttachment, depthAttachment, colorAttachmentResolve };
|
||
VkRenderPassCreateInfo renderPassInfo{};
|
||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
||
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
||
renderPassInfo.pAttachments = attachments.data();
|
||
renderPassInfo.subpassCount = 1;
|
||
renderPassInfo.pSubpasses = &subpass;
|
||
renderPassInfo.dependencyCount = 1;
|
||
renderPassInfo.pDependencies = &dependency;
|
||
|
||
if (vkCreateRenderPass(_device, &renderPassInfo, nullptr, &_renderPass) != VK_SUCCESS)
|
||
{
|
||
log_damage0("渲染流程创建失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_create_graphics_pipeline()
|
||
{
|
||
//加载shader文件
|
||
Buffer vertShaderCode = File::GetBuffer("shader/vert.spv");
|
||
Buffer fragShaderCode = File::GetBuffer("shader/frag.spv");
|
||
//创建shader模块
|
||
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 };
|
||
|
||
//顶点输入状态
|
||
auto bindingDescription = Vertex::getBindingDescription();
|
||
auto attributeDescriptions = Vertex::getAttributeDescriptions();
|
||
|
||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||
vertexInputInfo.vertexBindingDescriptionCount = 1;
|
||
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // Optional
|
||
vertexInputInfo.vertexAttributeDescriptionCount = (uint32_t)attributeDescriptions.size();
|
||
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // Optional
|
||
|
||
//顶点装配状态
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||
inputAssembly.primitiveRestartEnable = VK_FALSE;
|
||
|
||
//管线动态状态
|
||
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();
|
||
|
||
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;
|
||
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
|
||
rasterizer.depthBiasClamp = 0.0f; // Optional
|
||
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
|
||
|
||
//多重采样状态
|
||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||
multisampling.sampleShadingEnable = VK_FALSE;
|
||
multisampling.rasterizationSamples = _msaaSamples;
|
||
multisampling.minSampleShading = 1.0f; // Optional
|
||
multisampling.pSampleMask = nullptr; // Optional
|
||
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
|
||
multisampling.alphaToOneEnable = VK_FALSE; // Optional
|
||
if (B_OPEN_SAMPLE_SHADING)
|
||
{
|
||
multisampling.sampleShadingEnable = VK_TRUE;
|
||
// min fraction for sample shading; closer to one is smooth
|
||
multisampling.minSampleShading = .2f;
|
||
}
|
||
//混合模式
|
||
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_TRUE;
|
||
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
|
||
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
|
||
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
|
||
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
|
||
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
|
||
|
||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||
colorBlending.logicOpEnable = VK_FALSE;//启用后会禁用前者
|
||
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
|
||
colorBlending.attachmentCount = 1;
|
||
colorBlending.pAttachments = &colorBlendAttachment;
|
||
colorBlending.blendConstants[0] = 0.0f; // Optional
|
||
colorBlending.blendConstants[1] = 0.0f; // Optional
|
||
colorBlending.blendConstants[2] = 0.0f; // Optional
|
||
colorBlending.blendConstants[3] = 0.0f; // Optional
|
||
|
||
//推送常量区
|
||
VkPushConstantRange pushConstantRange{};
|
||
pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
pushConstantRange.offset = 0;
|
||
pushConstantRange.size = sizeof(PushConstantData);
|
||
|
||
//管线布局
|
||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||
pipelineLayoutInfo.setLayoutCount = 1; // Optional
|
||
pipelineLayoutInfo.pSetLayouts = &_descriptorSetLayout; // Optional
|
||
pipelineLayoutInfo.pushConstantRangeCount = 1;
|
||
pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
|
||
|
||
if (vkCreatePipelineLayout(_device, &pipelineLayoutInfo, nullptr, &_pipelineLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建管线布局失败!");
|
||
return;
|
||
}
|
||
|
||
//深度模板状态
|
||
VkPipelineDepthStencilStateCreateInfo depthStencil{};
|
||
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
|
||
depthStencil.depthTestEnable = VK_TRUE;
|
||
depthStencil.depthWriteEnable = VK_TRUE;
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
|
||
depthStencil.depthBoundsTestEnable = VK_FALSE;
|
||
depthStencil.minDepthBounds = 0.0f; // Optional
|
||
depthStencil.maxDepthBounds = 1.0f; // Optional
|
||
depthStencil.stencilTestEnable = VK_FALSE;
|
||
depthStencil.front = {}; // Optional
|
||
depthStencil.back = {}; // Optional
|
||
|
||
//图形管线
|
||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||
pipelineInfo.stageCount = 2;
|
||
pipelineInfo.pStages = shaderStages;//引用shader
|
||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||
pipelineInfo.pViewportState = &viewportState;
|
||
pipelineInfo.pRasterizationState = &rasterizer;
|
||
pipelineInfo.pMultisampleState = &multisampling;
|
||
pipelineInfo.pDepthStencilState = &depthStencil;
|
||
pipelineInfo.pColorBlendState = &colorBlending;
|
||
pipelineInfo.pDynamicState = &dynamicState;
|
||
pipelineInfo.layout = _pipelineLayout;//布局
|
||
pipelineInfo.renderPass = _renderPass;//渲染流程
|
||
pipelineInfo.subpass = 0;
|
||
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional
|
||
pipelineInfo.basePipelineIndex = -1; // Optional
|
||
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &_graphicsPipeline) != VK_SUCCESS)
|
||
{
|
||
log_damage0("图形管线创建失败!");
|
||
return;
|
||
}
|
||
|
||
//资源释放
|
||
vkDestroyShaderModule(_device, fragShaderModule, nullptr);
|
||
vkDestroyShaderModule(_device, vertShaderModule, nullptr);
|
||
}
|
||
|
||
void VK::_create_graphics_pipeline_bone()
|
||
{
|
||
//加载shader文件
|
||
Buffer vertShaderCode = File::GetBuffer("shader/vert_bone.spv");
|
||
Buffer fragShaderCode = File::GetBuffer("shader/frag_bone.spv");
|
||
//创建shader模块
|
||
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 };
|
||
|
||
//顶点输入状态
|
||
auto bindingDescription = VertexBone::getBindingDescription();
|
||
auto attributeDescriptions = VertexBone::getAttributeDescriptions();
|
||
|
||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||
vertexInputInfo.vertexBindingDescriptionCount = 1;
|
||
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // Optional
|
||
vertexInputInfo.vertexAttributeDescriptionCount = (uint32_t)attributeDescriptions.size();
|
||
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // Optional
|
||
|
||
//顶点装配状态
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||
inputAssembly.primitiveRestartEnable = VK_FALSE;
|
||
|
||
//管线动态状态
|
||
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();
|
||
|
||
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;
|
||
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
|
||
rasterizer.depthBiasClamp = 0.0f; // Optional
|
||
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
|
||
|
||
//多重采样状态
|
||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||
multisampling.sampleShadingEnable = VK_FALSE;
|
||
multisampling.rasterizationSamples = _msaaSamples;
|
||
multisampling.minSampleShading = 1.0f; // Optional
|
||
multisampling.pSampleMask = nullptr; // Optional
|
||
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
|
||
multisampling.alphaToOneEnable = VK_FALSE; // Optional
|
||
if (B_OPEN_SAMPLE_SHADING)
|
||
{
|
||
multisampling.sampleShadingEnable = VK_TRUE;
|
||
// min fraction for sample shading; closer to one is smooth
|
||
multisampling.minSampleShading = .2f;
|
||
}
|
||
//混合模式
|
||
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_TRUE;
|
||
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
|
||
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
|
||
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
|
||
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
|
||
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
|
||
|
||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||
colorBlending.logicOpEnable = VK_FALSE;//启用后会禁用前者
|
||
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
|
||
colorBlending.attachmentCount = 1;
|
||
colorBlending.pAttachments = &colorBlendAttachment;
|
||
colorBlending.blendConstants[0] = 0.0f; // Optional
|
||
colorBlending.blendConstants[1] = 0.0f; // Optional
|
||
colorBlending.blendConstants[2] = 0.0f; // Optional
|
||
colorBlending.blendConstants[3] = 0.0f; // Optional
|
||
|
||
//推送常量区
|
||
VkPushConstantRange pushConstantRange{};
|
||
pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
pushConstantRange.offset = 0;
|
||
pushConstantRange.size = sizeof(PushConstantData);
|
||
|
||
std::array<VkDescriptorSetLayout, 2> dsp_set_layout = {
|
||
_descriptorSetLayout,
|
||
_descriptorSetLayoutBone
|
||
};
|
||
//管线布局
|
||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||
pipelineLayoutInfo.setLayoutCount = 2; // Optional
|
||
pipelineLayoutInfo.pSetLayouts = dsp_set_layout.data(); // Optional
|
||
pipelineLayoutInfo.pushConstantRangeCount = 1;
|
||
pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
|
||
|
||
if (vkCreatePipelineLayout(_device, &pipelineLayoutInfo, nullptr, &_pipelineLayoutBone) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建管线布局失败!");
|
||
return;
|
||
}
|
||
|
||
//深度模板状态
|
||
VkPipelineDepthStencilStateCreateInfo depthStencil{};
|
||
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
|
||
depthStencil.depthTestEnable = VK_TRUE;
|
||
depthStencil.depthWriteEnable = VK_TRUE;
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
|
||
depthStencil.depthBoundsTestEnable = VK_FALSE;
|
||
depthStencil.minDepthBounds = 0.0f; // Optional
|
||
depthStencil.maxDepthBounds = 1.0f; // Optional
|
||
depthStencil.stencilTestEnable = VK_FALSE;
|
||
depthStencil.front = {}; // Optional
|
||
depthStencil.back = {}; // Optional
|
||
|
||
//图形管线
|
||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||
pipelineInfo.stageCount = 2;
|
||
pipelineInfo.pStages = shaderStages;//引用shader
|
||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||
pipelineInfo.pViewportState = &viewportState;
|
||
pipelineInfo.pRasterizationState = &rasterizer;
|
||
pipelineInfo.pMultisampleState = &multisampling;
|
||
pipelineInfo.pDepthStencilState = &depthStencil;
|
||
pipelineInfo.pColorBlendState = &colorBlending;
|
||
pipelineInfo.pDynamicState = &dynamicState;
|
||
pipelineInfo.layout = _pipelineLayoutBone;//布局
|
||
pipelineInfo.renderPass = _renderPass;//渲染流程
|
||
pipelineInfo.subpass = 0;
|
||
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional
|
||
pipelineInfo.basePipelineIndex = -1; // Optional
|
||
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &_graphicsPipelineBone) != VK_SUCCESS)
|
||
{
|
||
log_damage0("图形管线创建失败!");
|
||
return;
|
||
}
|
||
|
||
//资源释放
|
||
vkDestroyShaderModule(_device, fragShaderModule, nullptr);
|
||
vkDestroyShaderModule(_device, vertShaderModule, nullptr);
|
||
}
|
||
|
||
void VK::_create_frame_buffer()
|
||
{
|
||
_allFrameBufferSwapChain.resize(_allImageViewSwapChain.size());
|
||
|
||
//
|
||
for (size_t i = 0; i < _allImageViewSwapChain.size(); i++)
|
||
{
|
||
std::array<VkImageView, 3> attachments = {
|
||
_colorImageView,
|
||
_depthImageView,
|
||
_allImageViewSwapChain[i]
|
||
};
|
||
|
||
VkFramebufferCreateInfo framebufferInfo{};
|
||
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||
framebufferInfo.renderPass = _renderPass;//应用绘制流程
|
||
framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
||
framebufferInfo.pAttachments = attachments.data();
|
||
framebufferInfo.width = _extentSwapChain.width;
|
||
framebufferInfo.height = _extentSwapChain.height;
|
||
framebufferInfo.layers = 1;
|
||
|
||
if (vkCreateFramebuffer(_device, &framebufferInfo, nullptr, &_allFrameBufferSwapChain[i]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建帧缓冲区失败!");
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
void VK::_create_command_pool()
|
||
{
|
||
QueueFamilyIndices queueFamilyIndices = _find_queue_families(_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)
|
||
{
|
||
log_damage0("创建命令池失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_create_command_buffer()
|
||
{
|
||
_allCommandBuffer.resize(NUM_MAX_FRAME_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)NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
if (vkAllocateCommandBuffers(_device, &allocInfo,
|
||
&_allCommandBuffer[_currentFrame]) != VK_SUCCESS)
|
||
{
|
||
log("创建命令缓冲区失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_record_command_buffer(VkCommandBuffer command_buffer, uint32_t index_image,
|
||
const std::vector<DrawCall>& list_dc, const std::vector<DrawCall>& list_dc_translucent)
|
||
{
|
||
VkCommandBufferBeginInfo beginInfo{};
|
||
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||
beginInfo.flags = 0; // Optional
|
||
beginInfo.pInheritanceInfo = nullptr; // Optional
|
||
|
||
//开始记录
|
||
if (vkBeginCommandBuffer(command_buffer, &beginInfo) != VK_SUCCESS)
|
||
{
|
||
log_damage0("记录命令缓冲区失败!(Begin)");
|
||
return;
|
||
}
|
||
|
||
//渲染流程Begin
|
||
VkRenderPassBeginInfo renderPassInfo{};
|
||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||
renderPassInfo.renderPass = _renderPass;
|
||
renderPassInfo.framebuffer = _allFrameBufferSwapChain[index_image];
|
||
renderPassInfo.renderArea.offset = { 0, 0 };
|
||
renderPassInfo.renderArea.extent = _extentSwapChain;
|
||
//清屏
|
||
std::array<VkClearValue, 2> clearValues{};
|
||
clearValues[0].color = { {0.0f, 0.0f, 0.0f, 1.0f} };
|
||
clearValues[1].depthStencil = { 1.0f, 0 };
|
||
|
||
renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
|
||
renderPassInfo.pClearValues = clearValues.data();
|
||
|
||
//开始
|
||
vkCmdBeginRenderPass(command_buffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||
|
||
|
||
//设置视口与裁剪
|
||
VkViewport viewport{};
|
||
viewport.x = 0.0f;
|
||
viewport.y = 0.0f;
|
||
viewport.width = (float)_extentSwapChain.width;
|
||
viewport.height = (float)_extentSwapChain.height;
|
||
viewport.minDepth = 0.0f;
|
||
viewport.maxDepth = 1.0f;
|
||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||
|
||
VkRect2D scissor{};
|
||
scissor.offset = { 0, 0 };
|
||
scissor.extent = _extentSwapChain;
|
||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||
|
||
|
||
//FactoryImp* imp = g_factory->GetImp();
|
||
////3d
|
||
//for (std::vector<Model*>& mul : imp->_allMulModel)
|
||
//{
|
||
// for (Model* model : mul)
|
||
// {
|
||
// RenderModel(command_buffer, model);
|
||
// }
|
||
//}
|
||
_curPushConstant = 1;
|
||
//--------------------------------2d---------------------------------------
|
||
// 单个dc
|
||
auto fn_render_dc = [&](const std::vector<DrawCall>& list_dc)
|
||
{
|
||
for (const DrawCall& dc : list_dc)
|
||
{
|
||
// 设置视口
|
||
if (dc._viewport)
|
||
{
|
||
VkViewport viewport{};
|
||
viewport.x = (*dc._viewport)[0];
|
||
viewport.y = (*dc._viewport)[1];
|
||
viewport.width = (*dc._viewport)[2];
|
||
viewport.height = (*dc._viewport)[3];
|
||
viewport.minDepth = 0.0f;
|
||
viewport.maxDepth = 1.0f;
|
||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||
}
|
||
else
|
||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||
|
||
// 设置裁剪
|
||
if (dc._scissorRect)
|
||
{
|
||
VkRect2D scissor{};
|
||
scissor.offset = { (*dc._scissorRect)[0], (*dc._scissorRect)[1] };
|
||
scissor.extent = { (uint32_t)(*dc._scissorRect)[2], (uint32_t)(*dc._scissorRect)[3] };
|
||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||
}
|
||
else
|
||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||
|
||
// 设置贴图
|
||
uint32_t offset_tex = (uint32_t)(dc._canvas->_id * NUM_MAX_FRAME_IN_FLIGHT
|
||
+ _currentFrame);
|
||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||
_2d._pipelineLayout, 0, 1, &_2d._descriptorSets[offset_tex], 0, nullptr);
|
||
|
||
// 推送常量(变换)
|
||
size_t id_coor = dc._rootCoor ? dc._rootCoor->GetRootIndex() : 0;
|
||
vkCmdPushConstants(command_buffer, _2d._pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT,
|
||
0, sizeof(VK2D::CBO), &_2d._allCBO[id_coor]);
|
||
|
||
// 绑定顶点缓冲区
|
||
VkBuffer vertexBuffers[] = { dc._canvas->_vertexBuffer };
|
||
VkDeviceSize offsets[] = { 0 };
|
||
vkCmdBindVertexBuffers(command_buffer, 0, 1, vertexBuffers, offsets);
|
||
|
||
// 绘制(注意与3d不同)
|
||
vkCmdDrawIndexed(command_buffer,
|
||
(uint32_t)((dc._end - dc._beg) / 2 * 3), 1,
|
||
0, (int32_t)dc._beg, 0);
|
||
}
|
||
};
|
||
|
||
|
||
//------------------2d 不透明----------------
|
||
if (!list_dc.empty())
|
||
{
|
||
// 绑定管线
|
||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _2d._graphicsPipeline);
|
||
// 绑定索引缓冲
|
||
vkCmdBindIndexBuffer(command_buffer, _2d._indexBuffer, 0, VK_INDEX_TYPE_UINT32);
|
||
fn_render_dc(list_dc);
|
||
}
|
||
//--------------------gfx 不透明----------------
|
||
// 设置视口
|
||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||
// 设置裁剪
|
||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||
|
||
// 绑定顶点缓冲区
|
||
for (std::size_t i = 0; i < 4; ++i)
|
||
{
|
||
// 绑定管线
|
||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _gfx._vecGraphicsPipeline[i]);
|
||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||
_gfx._pipelineLayout, 0, 1, &_gfx._descriptorSets[0], 0, nullptr);
|
||
VertexBuffer& vb = _gfx._arrVB[i];
|
||
VkBuffer vertexBuffers[] = { vb._vertexBuffer };
|
||
VkDeviceSize offsets[] = { 0 };
|
||
vkCmdBindVertexBuffers(command_buffer, 0, 1, vertexBuffers, offsets);
|
||
|
||
//绘制
|
||
// 绘制
|
||
vkCmdDraw(command_buffer, vb._index, 1, 0, 0);
|
||
}
|
||
//--------------------2d 透明----------------------
|
||
if (!list_dc_translucent.empty())
|
||
{
|
||
// 绑定管线
|
||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _2d._graphicsPipelineTrans);
|
||
if (list_dc.empty())
|
||
{// 前面被绑,这里绑一次
|
||
// 绑定索引缓冲
|
||
vkCmdBindIndexBuffer(command_buffer, _2d._indexBuffer, 0, VK_INDEX_TYPE_UINT32);
|
||
}
|
||
fn_render_dc(list_dc_translucent);
|
||
}
|
||
|
||
//--------------------gfx 透明----------------
|
||
// 设置视口
|
||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||
// 设置裁剪
|
||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||
|
||
//绑定顶点缓冲区
|
||
for (std::size_t i = 4; i < 8; ++i)
|
||
{
|
||
//绑定管线
|
||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, _gfx._vecGraphicsPipeline[i]);
|
||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||
_gfx._pipelineLayout, 0, 1, &_gfx._descriptorSets[0], 0, nullptr);
|
||
VertexBuffer& vb = _gfx._arrVB[i];
|
||
VkBuffer vertexBuffers[] = { vb._vertexBuffer };
|
||
VkDeviceSize offsets[] = { 0 };
|
||
vkCmdBindVertexBuffers(command_buffer, 0, 1, vertexBuffers, offsets);
|
||
|
||
//绘制
|
||
vkCmdDraw(command_buffer, vb._index, 1, 0, 0);
|
||
}
|
||
|
||
//结束
|
||
vkCmdEndRenderPass(command_buffer);
|
||
|
||
//结束记录
|
||
if (vkEndCommandBuffer(command_buffer) != VK_SUCCESS)
|
||
{
|
||
log_damage0("记录命令缓冲区失败!(End)");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::Render(GLFWwindow* window,
|
||
const std::vector<DrawCall>& list_dc, const std::vector<DrawCall>& list_dc_translucent)
|
||
{
|
||
constexpr auto TIME_OUT = std::numeric_limits<uint64_t>::max();
|
||
vkWaitForFences(_device, 1, &_allFenceInFlight[_currentFrame], VK_TRUE, TIME_OUT);
|
||
vkResetFences(_device, 1, &_allFenceInFlight[_currentFrame]);
|
||
//获得交换链图像
|
||
uint32_t index_image;
|
||
VkResult result = vkAcquireNextImageKHR(_device, _swapChain, TIME_OUT,
|
||
_allSemaphoreImageAvailable[_currentFrame], VK_NULL_HANDLE, &index_image);
|
||
if (result == VK_ERROR_OUT_OF_DATE_KHR)
|
||
{//重建交换链
|
||
_rebuild_swap_chain(window);
|
||
return;
|
||
}
|
||
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
|
||
{
|
||
log_damage0("获取交换链图像失败!");
|
||
return;
|
||
}
|
||
//只有在我们提交工作时才重置围栏
|
||
vkResetFences(_device, 1, &_allFenceInFlight[_currentFrame]);
|
||
|
||
//更新统一缓冲
|
||
_update_uniform_buffer(_currentFrame);
|
||
|
||
//记录命令
|
||
vkResetCommandBuffer(_allCommandBuffer[_currentFrame], 0);
|
||
|
||
|
||
_record_command_buffer(_allCommandBuffer[_currentFrame], index_image,
|
||
list_dc, list_dc_translucent);
|
||
|
||
|
||
VkSubmitInfo submitInfo{};
|
||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||
//提交命令
|
||
VkSemaphore waitSemaphores[] = { _allSemaphoreImageAvailable[_currentFrame] };
|
||
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
||
submitInfo.waitSemaphoreCount = 1;
|
||
submitInfo.pWaitSemaphores = waitSemaphores;
|
||
submitInfo.pWaitDstStageMask = waitStages;
|
||
submitInfo.commandBufferCount = 1;
|
||
submitInfo.pCommandBuffers = &_allCommandBuffer[_currentFrame];
|
||
//设置完成信号量
|
||
VkSemaphore signalSemaphores[] = { _allSemaphoreRenderFinished[_currentFrame] };
|
||
submitInfo.signalSemaphoreCount = 1;
|
||
submitInfo.pSignalSemaphores = signalSemaphores;
|
||
//提交
|
||
if (vkQueueSubmit(_graphicsQueue, 1, &submitInfo, _allFenceInFlight[_currentFrame]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("命令缓冲区提交失败!");
|
||
return;
|
||
}
|
||
//呈现
|
||
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 = &index_image;
|
||
presentInfo.pResults = nullptr; // Optional
|
||
|
||
result = vkQueuePresentKHR(_presentQueue, &presentInfo);
|
||
if (result == VK_ERROR_OUT_OF_DATE_KHR
|
||
|| result == VK_SUBOPTIMAL_KHR
|
||
|| _bFrameBufferResize)
|
||
{
|
||
_bFrameBufferResize = false;
|
||
_rebuild_swap_chain(window);
|
||
}
|
||
else if (result != VK_SUCCESS)
|
||
{
|
||
log_damage0("呈现交换链图像失败!");
|
||
return;
|
||
}
|
||
|
||
_currentFrame = (_currentFrame + 1) % NUM_MAX_FRAME_IN_FLIGHT;
|
||
}
|
||
|
||
void VK::_create_sync_objects()
|
||
{
|
||
_allSemaphoreImageAvailable.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
_allSemaphoreRenderFinished.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
_allFenceInFlight.resize(NUM_MAX_FRAME_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 < NUM_MAX_FRAME_IN_FLIGHT; ++i)
|
||
{
|
||
if (vkCreateSemaphore(_device, &semaphoreInfo, nullptr, &_allSemaphoreImageAvailable[i]) != VK_SUCCESS
|
||
|| vkCreateSemaphore(_device, &semaphoreInfo, nullptr, &_allSemaphoreRenderFinished[i]) != VK_SUCCESS
|
||
|| vkCreateFence(_device, &fenceInfo, nullptr, &_allFenceInFlight[i]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("同步对象创建失败!");
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
std::vector<const char*> VK::_get_required_extensions()
|
||
{
|
||
uint32_t glfwExtensionCount = 0;
|
||
const char** glfwExtensions;
|
||
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
|
||
|
||
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
|
||
|
||
if (ENABLE_VALIDATION_LAYERS)
|
||
{
|
||
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||
}
|
||
|
||
return extensions;
|
||
}
|
||
|
||
void VK::_release_swap_chain()
|
||
{
|
||
vkDestroyImageView(_device, _depthImageView, nullptr);
|
||
vkDestroyImage(_device, _depthImage, nullptr);
|
||
vkFreeMemory(_device, _depthImageMemory, nullptr);
|
||
|
||
vkDestroyImageView(_device, _colorImageView, nullptr);
|
||
vkDestroyImage(_device, _colorImage, nullptr);
|
||
vkFreeMemory(_device, _colorImageMemory, nullptr);
|
||
|
||
for (auto framebuffer : _allFrameBufferSwapChain)
|
||
{
|
||
vkDestroyFramebuffer(_device, framebuffer, nullptr);
|
||
}
|
||
for (auto image_view : _allImageViewSwapChain)
|
||
{
|
||
vkDestroyImageView(_device, image_view, nullptr);
|
||
}
|
||
vkDestroySwapchainKHR(_device, _swapChain, nullptr);
|
||
}
|
||
|
||
void VK::_rebuild_swap_chain(GLFWwindow* window)
|
||
{
|
||
//最小化则等待
|
||
int width = 0, height = 0;
|
||
glfwGetFramebufferSize(window, &width, &height);
|
||
while (width == 0 || height == 0)
|
||
{
|
||
glfwGetFramebufferSize(window, &width, &height);
|
||
glfwWaitEvents();
|
||
}
|
||
|
||
vkDeviceWaitIdle(_device);
|
||
|
||
_release_swap_chain();
|
||
|
||
_create_swap_chain(window);
|
||
_create_image_view();
|
||
_create_color_resources();
|
||
_create_depth_resources();
|
||
_create_frame_buffer();
|
||
}
|
||
|
||
|
||
void VK::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)
|
||
{
|
||
log_err0("创建缓冲区失败!");
|
||
return;
|
||
}
|
||
|
||
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)
|
||
{
|
||
log_err0("分配缓冲区内存失败!");
|
||
return;
|
||
}
|
||
|
||
vkBindBufferMemory(_device, buffer, bufferMemory, 0);
|
||
}
|
||
|
||
void VK::CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
|
||
{
|
||
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
|
||
|
||
VkBufferCopy copyRegion{};
|
||
copyRegion.size = size;
|
||
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
|
||
|
||
EndSingleTimeCommands(commandBuffer);
|
||
}
|
||
|
||
void VK::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 = CallbackDebug;
|
||
}
|
||
|
||
uint32_t VK::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;
|
||
}
|
||
}
|
||
|
||
log_damage0("未找到合适的内存类型");
|
||
return 0;
|
||
}
|
||
|
||
void VK::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;
|
||
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 VK::CreateImage(uint32_t w, uint32_t h, uint32_t mip_level, VkSampleCountFlagBits numSamples,
|
||
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;
|
||
imageInfo.extent.width = w;
|
||
imageInfo.extent.height = h;
|
||
imageInfo.extent.depth = 1;
|
||
imageInfo.mipLevels = mip_level;
|
||
imageInfo.arrayLayers = 1;
|
||
imageInfo.format = format;
|
||
imageInfo.tiling = tiling;
|
||
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||
imageInfo.usage = usage;
|
||
imageInfo.samples = numSamples;
|
||
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||
|
||
if (vkCreateImage(_device, &imageInfo, nullptr, &image) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建图像失败!");
|
||
return;
|
||
}
|
||
|
||
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)
|
||
{
|
||
log_err0("分配图像内存失败!");
|
||
return;
|
||
}
|
||
|
||
vkBindImageMemory(_device, image, imageMemory, 0);
|
||
}
|
||
|
||
size_t VK::CreateTextureReal(Image* image, bool delete_image)
|
||
{
|
||
assert(image);
|
||
|
||
Texture tex;
|
||
|
||
Size size = image->GetSize();
|
||
//mipmap数
|
||
tex._mipLevel = (uint32_t)(floor(log2(Select::Max(size)))) + 1;
|
||
|
||
VkDeviceSize imageSize = image->GetSizeByte();
|
||
//复制到暂存缓冲
|
||
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, image->GetBuffer(), (size_t)imageSize);
|
||
vkUnmapMemory(_device, stagingBufferMemory);
|
||
|
||
if (delete_image)
|
||
delete image;
|
||
//创建显存图像,VK_IMAGE_USAGE_TRANSFER_SRC_BIT用于生成mipmap
|
||
CreateImage((uint32_t)size[0], (uint32_t)size[1], tex._mipLevel, VK_SAMPLE_COUNT_1_BIT,
|
||
VK_FORMAT_R8G8B8A8_SRGB,
|
||
VK_IMAGE_TILING_OPTIMAL,
|
||
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
|
||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
|
||
tex._textureImage, tex._textureImageMemory);
|
||
//转换状态 为 复制目标
|
||
TransitionImageLayout(tex._textureImage, VK_FORMAT_R8G8B8A8_SRGB,
|
||
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||
tex._mipLevel);
|
||
//暂存缓冲 -> 显存缓冲
|
||
CopyBufferToImage(stagingBuffer, tex._textureImage,
|
||
(uint32_t)size[0], (uint32_t)size[1]);
|
||
|
||
//生成mipmap,并 转换状态 为 着色器资源
|
||
GenerateMipmaps(tex._textureImage, VK_FORMAT_R8G8B8A8_SRGB,
|
||
(int32_t)size[0], (int32_t)size[1], tex._mipLevel);
|
||
|
||
|
||
vkDestroyBuffer(_device, stagingBuffer, nullptr);
|
||
vkFreeMemory(_device, stagingBufferMemory, nullptr);
|
||
|
||
tex._textureImageView = CreateImageView(tex._textureImage,
|
||
VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, tex._mipLevel);
|
||
|
||
_allTexture3D.push_back(tex);
|
||
return _allTexture3D.size() - 1;
|
||
}
|
||
|
||
|
||
VkImageView VK::CreateImageView(VkImage image, VkFormat format,
|
||
VkImageAspectFlags aspectFlags, uint32_t mip_level)
|
||
{
|
||
VkImageViewCreateInfo viewInfo{};
|
||
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
|
||
viewInfo.image = image;
|
||
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||
viewInfo.format = format;
|
||
viewInfo.subresourceRange.aspectMask = aspectFlags;
|
||
viewInfo.subresourceRange.baseMipLevel = 0;
|
||
viewInfo.subresourceRange.levelCount = mip_level;
|
||
viewInfo.subresourceRange.baseArrayLayer = 0;
|
||
viewInfo.subresourceRange.layerCount = 1;
|
||
|
||
VkImageView imageView;
|
||
if (vkCreateImageView(_device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建图像视图失败!");
|
||
return 0;
|
||
}
|
||
return imageView;
|
||
}
|
||
|
||
VkCommandBuffer VK::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;
|
||
|
||
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 VK::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 VK::TransitionImageLayout(VkImage image, VkFormat format,
|
||
VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mip_level)
|
||
{
|
||
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;
|
||
barrier.subresourceRange.levelCount = mip_level;
|
||
barrier.subresourceRange.baseArrayLayer = 0;
|
||
barrier.subresourceRange.layerCount = 1;
|
||
barrier.srcAccessMask = 0; // TODO
|
||
barrier.dstAccessMask = 0; // TODO
|
||
|
||
//
|
||
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
|
||
{
|
||
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||
if (HasStencilComponent(format))
|
||
{
|
||
barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||
}
|
||
//管线阶段掩码
|
||
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 if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED
|
||
&& newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
|
||
{
|
||
barrier.srcAccessMask = 0;
|
||
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
|
||
}
|
||
else if (oldLayout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
|
||
&& newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL)
|
||
{//交换链 -> 复制源
|
||
barrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
}
|
||
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
|
||
&& newLayout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)
|
||
{//复制源 -> 交换链
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
}
|
||
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
|
||
&& newLayout == VK_IMAGE_LAYOUT_GENERAL)
|
||
{//复制目标 -> 生成
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
}
|
||
else if (oldLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
|
||
&& newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL)
|
||
{//着色器资源 -> 复制源
|
||
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
}
|
||
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
|
||
&& newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
|
||
{//复制源 -> 着色器资源
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||
|
||
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
|
||
}
|
||
else
|
||
{
|
||
log_err0("不支持的转换!");
|
||
return;
|
||
}
|
||
vkCmdPipelineBarrier(
|
||
commandBuffer,
|
||
sourceStage, destinationStage,
|
||
0,
|
||
0, nullptr,
|
||
0, nullptr,
|
||
1, &barrier
|
||
);
|
||
EndSingleTimeCommands(commandBuffer);
|
||
}
|
||
|
||
void VK::_create_descriptor_set_layout()
|
||
{
|
||
//ubo
|
||
VkDescriptorSetLayoutBinding uboLayoutBinding{};
|
||
uboLayoutBinding.binding = 0;
|
||
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
uboLayoutBinding.descriptorCount = 1;
|
||
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
uboLayoutBinding.pImmutableSamplers = nullptr; // Optional
|
||
//ubo material
|
||
VkDescriptorSetLayoutBinding uboLayoutBinding1{};
|
||
uboLayoutBinding1.binding = 1;
|
||
uboLayoutBinding1.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
uboLayoutBinding1.descriptorCount = 1;
|
||
uboLayoutBinding1.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;//像素着色器可见
|
||
uboLayoutBinding1.pImmutableSamplers = nullptr; // Optional
|
||
//漫反射贴图
|
||
VkDescriptorSetLayoutBinding texLayoutBinding0{};
|
||
texLayoutBinding0.binding = 2;
|
||
texLayoutBinding0.descriptorCount = 1;
|
||
texLayoutBinding0.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
texLayoutBinding0.pImmutableSamplers = nullptr;
|
||
texLayoutBinding0.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||
//法线贴图
|
||
VkDescriptorSetLayoutBinding texLayoutBinding1{};
|
||
texLayoutBinding1.binding = 3;
|
||
texLayoutBinding1.descriptorCount = 1;
|
||
texLayoutBinding1.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
texLayoutBinding1.pImmutableSamplers = nullptr;
|
||
texLayoutBinding1.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||
|
||
std::array<VkDescriptorSetLayoutBinding, 4> bindings = {
|
||
uboLayoutBinding, uboLayoutBinding1,
|
||
texLayoutBinding0, texLayoutBinding1
|
||
};
|
||
|
||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||
layoutInfo.bindingCount = (uint32_t)bindings.size();
|
||
layoutInfo.pBindings = bindings.data();
|
||
|
||
if (vkCreateDescriptorSetLayout(_device, &layoutInfo, nullptr,
|
||
&_descriptorSetLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建描述符集合失败!");
|
||
return;
|
||
}
|
||
}
|
||
void VK::_create_descriptor_set_layout_bone()
|
||
{
|
||
//ubo bone
|
||
VkDescriptorSetLayoutBinding uboLayoutBinding2{};
|
||
uboLayoutBinding2.binding = 0;
|
||
uboLayoutBinding2.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
uboLayoutBinding2.descriptorCount = 1;
|
||
uboLayoutBinding2.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
uboLayoutBinding2.pImmutableSamplers = nullptr; // Optional
|
||
|
||
std::array<VkDescriptorSetLayoutBinding, 1> bindings = {
|
||
uboLayoutBinding2
|
||
};
|
||
|
||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||
layoutInfo.bindingCount = (uint32_t)bindings.size();
|
||
layoutInfo.pBindings = bindings.data();
|
||
|
||
if (vkCreateDescriptorSetLayout(_device, &layoutInfo, nullptr,
|
||
&_descriptorSetLayoutBone) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建描述符集合失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
|
||
void VK::_create_uniform_buffers()
|
||
{
|
||
VkDeviceSize bufferSize = sizeof(UniformBufferObject);
|
||
|
||
_uniformBuffers.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
_uniformBuffersMemory.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_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]);
|
||
}
|
||
//
|
||
VkDeviceSize bufferSize1 = sizeof(Material);
|
||
constexpr size_t num = NUM_MAX_MATERIAL;
|
||
|
||
_ubMaterial.resize(num);
|
||
_ubMaterialMemory.resize(num);
|
||
|
||
for (size_t i = 0; i < num; i++)
|
||
{
|
||
CreateBuffer(bufferSize1,
|
||
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
||
_ubMaterial[i], _ubMaterialMemory[i]);
|
||
}
|
||
}
|
||
|
||
void VK::_create_ub_bone()
|
||
{
|
||
VkDeviceSize bufferSize = sizeof(UboBone);
|
||
constexpr size_t num = NUM_MAX_FRAME_IN_FLIGHT * NUM_MAX_BONE;
|
||
|
||
_ubBone.resize(num);
|
||
_ubBoneMemory.resize(num);
|
||
_mapBoneUse.resize(NUM_MAX_BONE, false);
|
||
|
||
for (size_t i = 0; i < num; i++)
|
||
{
|
||
CreateBuffer(bufferSize,
|
||
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
||
_ubBone[i], _ubBoneMemory[i]);
|
||
}
|
||
}
|
||
|
||
|
||
void VK::_create_descriptor_pool()
|
||
{
|
||
std::array<VkDescriptorPoolSize, 4> poolSizes{};
|
||
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[0].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[1].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
poolSizes[2].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[3].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
poolSizes[3].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
|
||
VkDescriptorPoolCreateInfo poolInfo{};
|
||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||
poolInfo.poolSizeCount = (uint32_t)poolSizes.size();
|
||
poolInfo.pPoolSizes = poolSizes.data();
|
||
poolInfo.maxSets = (uint32_t)(poolSizes.size() * NUM_MAX_DESCRIPTOR_POOL);//NUM_MAX_DESCRIPTOR_POOL
|
||
|
||
if (vkCreateDescriptorPool(_device, &poolInfo, nullptr, &_descriptorPool) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建描述符池失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_create_descriptor_pool_bone()
|
||
{
|
||
std::array<VkDescriptorPoolSize, 5> poolSizes{};
|
||
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[0].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[1].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
poolSizes[2].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[3].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
poolSizes[3].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
poolSizes[4].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[4].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL;
|
||
|
||
VkDescriptorPoolCreateInfo poolInfo{};
|
||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||
poolInfo.poolSizeCount = (uint32_t)poolSizes.size();
|
||
poolInfo.pPoolSizes = poolSizes.data();
|
||
poolInfo.maxSets = (uint32_t)(poolSizes.size() * NUM_MAX_DESCRIPTOR_POOL);
|
||
|
||
if (vkCreateDescriptorPool(_device, &poolInfo, nullptr, &_descriptorPoolBone) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建描述符池失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_create_descriptor_sets()
|
||
{
|
||
size_t num = NUM_MAX_PRIMITIVE * NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
std::vector<VkDescriptorSetLayout> layouts(num, _descriptorSetLayout);
|
||
VkDescriptorSetAllocateInfo allocInfo{};
|
||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||
allocInfo.descriptorPool = _descriptorPool;
|
||
allocInfo.descriptorSetCount = (uint32_t)num;
|
||
allocInfo.pSetLayouts = layouts.data();
|
||
|
||
_descriptorSets.resize(num);
|
||
if (vkAllocateDescriptorSets(_device, &allocInfo, _descriptorSets.data()) != VK_SUCCESS)
|
||
{
|
||
log_err0("分配描述符集失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_create_descriptor_sets_bone()
|
||
{
|
||
size_t num = NUM_MAX_BONE * NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
std::vector<VkDescriptorSetLayout> layouts(num, _descriptorSetLayoutBone);
|
||
VkDescriptorSetAllocateInfo allocInfo{};
|
||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||
allocInfo.descriptorPool = _descriptorPoolBone;
|
||
allocInfo.descriptorSetCount = (uint32_t)num;
|
||
allocInfo.pSetLayouts = layouts.data();
|
||
|
||
_descriptorSetsBone.resize(num);
|
||
if (vkAllocateDescriptorSets(_device, &allocInfo, _descriptorSetsBone.data()) != VK_SUCCESS)
|
||
{
|
||
log_err0("分配描述符集失败!");
|
||
return;
|
||
}
|
||
|
||
//立马绑定
|
||
for (size_t j = 0; j < NUM_MAX_BONE; ++j)
|
||
{
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
size_t index = j * NUM_MAX_FRAME_IN_FLIGHT + i;
|
||
//ubo bone
|
||
VkDescriptorBufferInfo bufferInfo2{};
|
||
bufferInfo2.buffer = _ubBone[index];
|
||
bufferInfo2.offset = 0;
|
||
bufferInfo2.range = sizeof(UboBone);
|
||
|
||
std::array<VkWriteDescriptorSet, 1> descriptorWrites{};
|
||
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[0].dstSet = _descriptorSetsBone[index];
|
||
descriptorWrites[0].dstBinding = 0;
|
||
descriptorWrites[0].dstArrayElement = 0;
|
||
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
descriptorWrites[0].descriptorCount = 1;
|
||
descriptorWrites[0].pBufferInfo = &bufferInfo2;
|
||
|
||
vkUpdateDescriptorSets(_device,
|
||
(uint32_t)descriptorWrites.size(), descriptorWrites.data(),
|
||
0, nullptr);
|
||
}
|
||
}
|
||
}
|
||
|
||
void VK::_create_texture_sampler()
|
||
{
|
||
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;
|
||
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
||
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
||
samplerInfo.anisotropyEnable = VK_TRUE;
|
||
|
||
VkPhysicalDeviceProperties properties{};
|
||
vkGetPhysicalDeviceProperties(_physicalDevice, &properties);
|
||
|
||
if (true)
|
||
{
|
||
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
|
||
}
|
||
else
|
||
{
|
||
samplerInfo.anisotropyEnable = VK_FALSE;
|
||
samplerInfo.maxAnisotropy = 1.0f;
|
||
}
|
||
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;
|
||
samplerInfo.mipLodBias = 0.0f;
|
||
samplerInfo.minLod = 0.0f;
|
||
samplerInfo.maxLod = VK_LOD_CLAMP_NONE;
|
||
|
||
if (vkCreateSampler(_device, &samplerInfo, nullptr, &_textureSampler) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建纹理采样器失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_update_uniform_buffer(uint32_t currentImage)
|
||
{
|
||
UniformBufferObject ubo{};
|
||
|
||
Matrix4 mat_view = _camera->GetMatrixView();
|
||
|
||
Matrix4 mat_proj = Mat::CreatePerspective(
|
||
(Float)Math::PI(1, 4), _extentSwapChain.width / (float)_extentSwapChain.height,
|
||
0.1f, 1000.0f);
|
||
|
||
mat_proj[1][1] *= -1;//翻转Y轴
|
||
|
||
|
||
ubo._viewProj = mat_proj * mat_view;
|
||
|
||
|
||
void* data;
|
||
vkMapMemory(_device, _uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, &data);
|
||
memcpy(data, &ubo, sizeof(ubo));
|
||
vkUnmapMemory(_device, _uniformBuffersMemory[currentImage]);
|
||
}
|
||
|
||
|
||
|
||
VkFormat VK::FindSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
|
||
{
|
||
for (VkFormat format : candidates)
|
||
{
|
||
VkFormatProperties props;
|
||
vkGetPhysicalDeviceFormatProperties(_physicalDevice, format, &props);
|
||
if (tiling == VK_IMAGE_TILING_LINEAR
|
||
&& (props.linearTilingFeatures & features) == features)
|
||
{
|
||
return format;
|
||
}
|
||
else if (tiling == VK_IMAGE_TILING_OPTIMAL
|
||
&& (props.optimalTilingFeatures & features) == features)
|
||
{
|
||
return format;
|
||
}
|
||
}
|
||
log_damage0("查找支持的格式失败!");
|
||
return VK_FORMAT_UNDEFINED;
|
||
}
|
||
|
||
VkFormat VK::FindDepthFormat()
|
||
{
|
||
return FindSupportedFormat(
|
||
{ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
|
||
VK_IMAGE_TILING_OPTIMAL,
|
||
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
|
||
}
|
||
|
||
size_t VK::CreatePrimitive(ModelObjectMaterial& m)
|
||
{
|
||
size_t j = _allPrimitive.size();
|
||
_allPrimitive.push_back({});
|
||
|
||
Primitive& pri = _allPrimitive[j];
|
||
pri._idMaterial = CreateMaterial(m._material);
|
||
pri._idTexDiffuse = CreateTexture(m._pathTexDiffuse);
|
||
pri._idTexNormal = CreateTexture(m._pathTexNormal);
|
||
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
size_t index = j * NUM_MAX_FRAME_IN_FLIGHT + i;
|
||
//ubo
|
||
VkDescriptorBufferInfo bufferInfo{};
|
||
bufferInfo.buffer = _uniformBuffers[i];
|
||
bufferInfo.offset = 0;
|
||
bufferInfo.range = sizeof(UniformBufferObject);
|
||
//ubo material
|
||
VkDescriptorBufferInfo bufferInfo1{};
|
||
bufferInfo1.buffer = _ubMaterial[pri._idMaterial];
|
||
bufferInfo1.offset = 0;
|
||
bufferInfo1.range = sizeof(Material);
|
||
//纹理
|
||
VkDescriptorImageInfo imageInfo{};
|
||
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||
imageInfo.imageView = _allTexture3D[pri._idTexDiffuse]._textureImageView;
|
||
imageInfo.sampler = _textureSampler;
|
||
//纹理1
|
||
VkDescriptorImageInfo imageInfo1{};
|
||
imageInfo1.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||
imageInfo1.imageView = _allTexture3D[pri._idTexNormal]._textureImageView;
|
||
imageInfo1.sampler = _textureSampler;
|
||
|
||
std::array<VkWriteDescriptorSet, 4> descriptorWrites{};
|
||
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[0].dstSet = _descriptorSets[index];
|
||
descriptorWrites[0].dstBinding = 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[index];
|
||
descriptorWrites[1].dstBinding = 1;
|
||
descriptorWrites[1].dstArrayElement = 0;
|
||
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
descriptorWrites[1].descriptorCount = 1;
|
||
descriptorWrites[1].pBufferInfo = &bufferInfo1;
|
||
|
||
descriptorWrites[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[2].dstSet = _descriptorSets[index];
|
||
descriptorWrites[2].dstBinding = 2;
|
||
descriptorWrites[2].dstArrayElement = 0;
|
||
descriptorWrites[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
descriptorWrites[2].descriptorCount = 1;
|
||
descriptorWrites[2].pImageInfo = &imageInfo;
|
||
|
||
descriptorWrites[3].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[3].dstSet = _descriptorSets[index];
|
||
descriptorWrites[3].dstBinding = 3;
|
||
descriptorWrites[3].dstArrayElement = 0;
|
||
descriptorWrites[3].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
descriptorWrites[3].descriptorCount = 1;
|
||
descriptorWrites[3].pImageInfo = &imageInfo1;
|
||
|
||
vkUpdateDescriptorSets(_device,
|
||
(uint32_t)descriptorWrites.size(), descriptorWrites.data(),
|
||
0, nullptr);
|
||
}
|
||
return j;
|
||
}
|
||
|
||
Model* VK::CreateModel(ModelObject* object)
|
||
{
|
||
Model* model = new Model;
|
||
model->_boneData = object->_boneData;
|
||
//顶点缓冲
|
||
if (object->_boneData)
|
||
{
|
||
CreateVertexBufferGPU(
|
||
object->_allVertexBone, model->_vertexBuffer, model->_vertexBufferMemory);
|
||
}
|
||
else
|
||
{
|
||
CreateVertexBufferGPU(
|
||
object->_allVertex, model->_vertexBuffer, model->_vertexBufferMemory);
|
||
}
|
||
|
||
//索引缓冲
|
||
CreateIndexBuffer(
|
||
object->_allIndex, model->_indexBuffer, model->_indexBufferMemory);
|
||
|
||
//生成sub(更新 描述符表,代表一个材质)
|
||
size_t num_sub = object->_allSub.size();
|
||
//size_t num_material = object->_allMaterial.size();
|
||
|
||
model->_allSub.resize(num_sub);
|
||
for (size_t i = 0; i < num_sub; ++i)
|
||
{
|
||
ModelSub& a = model->_allSub[i];
|
||
ModelObjectSub& b = object->_allSub[i];
|
||
a._range = b._range;
|
||
if (b._indexMaterial != -1)
|
||
{//-1为没有材质,不创建
|
||
ModelObjectMaterial& m = object->_allMaterial[b._indexMaterial];
|
||
a._idPrimitive = CreatePrimitive(m);
|
||
}
|
||
}
|
||
return model;
|
||
}
|
||
|
||
void VK::RenderModel(VkCommandBuffer command_buffer, Model* model)
|
||
{
|
||
if (model->_mulNode.empty())
|
||
{
|
||
//debug_info(format("模型尚未使用:{}", (unsigned)model));
|
||
return;
|
||
}
|
||
VkPipeline& pipe = model->_boneData ? _graphicsPipelineBone : _graphicsPipeline;
|
||
VkPipelineLayout& pipe_layout = model->_boneData ? _pipelineLayoutBone : _pipelineLayout;
|
||
|
||
//绑定管线
|
||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
|
||
|
||
//绑定顶点缓冲区
|
||
VkBuffer vertexBuffers[] = { model->_vertexBuffer };
|
||
VkDeviceSize offsets[] = { 0 };
|
||
vkCmdBindVertexBuffers(command_buffer, 0, 1, vertexBuffers, offsets);
|
||
|
||
//绑定索引缓冲
|
||
vkCmdBindIndexBuffer(command_buffer, model->_indexBuffer, 0, VK_INDEX_TYPE_UINT32);
|
||
|
||
//
|
||
for (Model::Node& node : model->_mulNode)
|
||
{
|
||
//推送常量(变换)
|
||
vkCmdPushConstants(command_buffer, pipe_layout, VK_SHADER_STAGE_VERTEX_BIT,
|
||
0, sizeof(PushConstantData), &_allPushConstant[node._idPerObject]);
|
||
//绑定描述符表(ub骨骼)
|
||
if (model->_boneData)
|
||
{
|
||
uint32_t offset = (uint32_t)(node._idBone * NUM_MAX_FRAME_IN_FLIGHT
|
||
+ _currentFrame);
|
||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||
pipe_layout, 1, 1, &_descriptorSetsBone[offset], 0, nullptr);
|
||
}
|
||
for (ModelSub& sub : model->_allSub)
|
||
{
|
||
//绑定描述符表(ubo材质)
|
||
uint32_t offset = (uint32_t)(sub._idPrimitive * NUM_MAX_FRAME_IN_FLIGHT
|
||
+ _currentFrame);
|
||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||
pipe_layout, 0, 1, &_descriptorSets[offset], 0, nullptr);
|
||
|
||
//绘制
|
||
vkCmdDrawIndexed(command_buffer,
|
||
(uint32_t)(sub._range._countTriangle * 3), 1,
|
||
(uint32_t)(sub._range._offsetIndex), 0, 0);
|
||
|
||
int pause = 3;
|
||
}
|
||
}
|
||
//清空
|
||
model->_mulNode.clear();
|
||
}
|
||
|
||
|
||
void VK::_create_2d()
|
||
{
|
||
//------------------------------2d--------------------------------
|
||
//0.描述符布局
|
||
//ubo
|
||
VkDescriptorSetLayoutBinding uboLayoutBinding{};
|
||
uboLayoutBinding.binding = 0;
|
||
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
uboLayoutBinding.descriptorCount = 1;
|
||
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
uboLayoutBinding.pImmutableSamplers = nullptr; // Optional
|
||
//贴图
|
||
VkDescriptorSetLayoutBinding texLayoutBinding0{};
|
||
texLayoutBinding0.binding = 1;
|
||
texLayoutBinding0.descriptorCount = 1;
|
||
texLayoutBinding0.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
texLayoutBinding0.pImmutableSamplers = nullptr;
|
||
texLayoutBinding0.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||
|
||
std::array<VkDescriptorSetLayoutBinding, 2> bindings = {
|
||
uboLayoutBinding, texLayoutBinding0
|
||
};
|
||
|
||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||
layoutInfo.bindingCount = (uint32_t)bindings.size();
|
||
layoutInfo.pBindings = bindings.data();
|
||
|
||
if (vkCreateDescriptorSetLayout(_device, &layoutInfo, nullptr,
|
||
&_2d._descriptorSetLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建描述符集合失败!");
|
||
return;
|
||
}
|
||
//1.管线
|
||
//加载shader文件
|
||
Buffer vertShaderCode = File::GetBuffer("shader/vert_2d.spv");
|
||
Buffer fragShaderCode = File::GetBuffer("shader/frag_2d.spv");
|
||
//创建shader模块
|
||
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 };
|
||
|
||
//顶点输入状态
|
||
auto bindingDescription = Vertex2D::getBindingDescription();
|
||
auto attributeDescriptions = Vertex2D::getAttributeDescriptions();
|
||
|
||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||
vertexInputInfo.vertexBindingDescriptionCount = 1;
|
||
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // Optional
|
||
vertexInputInfo.vertexAttributeDescriptionCount = (uint32_t)attributeDescriptions.size();
|
||
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // Optional
|
||
|
||
//顶点装配状态
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||
inputAssembly.primitiveRestartEnable = VK_FALSE;
|
||
|
||
|
||
//管线动态状态
|
||
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();
|
||
|
||
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_NONE;//不剔除应该更快 //VK_CULL_MODE_BACK_BIT;
|
||
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;//与3d不同
|
||
rasterizer.depthBiasEnable = VK_FALSE;
|
||
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
|
||
rasterizer.depthBiasClamp = 0.0f; // Optional
|
||
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
|
||
|
||
//多重采样状态
|
||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||
multisampling.sampleShadingEnable = VK_FALSE;
|
||
multisampling.rasterizationSamples = _msaaSamples;//必须匹配
|
||
multisampling.minSampleShading = 1.0f; // Optional
|
||
multisampling.pSampleMask = nullptr; // Optional
|
||
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
|
||
multisampling.alphaToOneEnable = VK_FALSE; // Optional
|
||
if (B_OPEN_SAMPLE_SHADING)
|
||
{
|
||
multisampling.sampleShadingEnable = VK_TRUE;
|
||
// min fraction for sample shading; closer to one is smooth
|
||
multisampling.minSampleShading = .2f;
|
||
}
|
||
|
||
//混合模式
|
||
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;
|
||
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
|
||
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
|
||
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA;
|
||
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
|
||
|
||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||
colorBlending.logicOpEnable = VK_FALSE;//启用后会禁用前者
|
||
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
|
||
colorBlending.attachmentCount = 1;
|
||
colorBlending.pAttachments = &colorBlendAttachment;
|
||
colorBlending.blendConstants[0] = 0.0f; // Optional
|
||
colorBlending.blendConstants[1] = 0.0f; // Optional
|
||
colorBlending.blendConstants[2] = 0.0f; // Optional
|
||
colorBlending.blendConstants[3] = 0.0f; // Optional
|
||
|
||
//推送常量区
|
||
VkPushConstantRange pushConstantRange{};
|
||
pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
pushConstantRange.offset = 0;
|
||
pushConstantRange.size = sizeof(VK2D::CBO);
|
||
|
||
//管线布局
|
||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||
pipelineLayoutInfo.setLayoutCount = 1; // Optional
|
||
pipelineLayoutInfo.pSetLayouts = &_2d._descriptorSetLayout; // Optional
|
||
pipelineLayoutInfo.pushConstantRangeCount = 1;
|
||
pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
|
||
|
||
if (vkCreatePipelineLayout(_device, &pipelineLayoutInfo, nullptr, &_2d._pipelineLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建2d管线布局失败!");
|
||
return;
|
||
}
|
||
|
||
//深度模板状态
|
||
VkPipelineDepthStencilStateCreateInfo depthStencil{};
|
||
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
|
||
depthStencil.depthTestEnable = VK_TRUE;
|
||
depthStencil.depthWriteEnable = VK_TRUE;
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
|
||
depthStencil.depthBoundsTestEnable = VK_FALSE;
|
||
depthStencil.minDepthBounds = 0.0f; // Optional
|
||
depthStencil.maxDepthBounds = 1.0f; // Optional
|
||
depthStencil.stencilTestEnable = VK_FALSE;
|
||
depthStencil.front = {}; // Optional
|
||
depthStencil.back = {}; // Optional
|
||
|
||
//图形管线
|
||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||
pipelineInfo.stageCount = 2;
|
||
pipelineInfo.pStages = shaderStages;//引用shader
|
||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||
pipelineInfo.pViewportState = &viewportState;
|
||
pipelineInfo.pRasterizationState = &rasterizer;
|
||
pipelineInfo.pMultisampleState = &multisampling;
|
||
pipelineInfo.pDepthStencilState = &depthStencil;
|
||
pipelineInfo.pColorBlendState = &colorBlending;
|
||
pipelineInfo.pDynamicState = &dynamicState;
|
||
pipelineInfo.layout = _2d._pipelineLayout;//布局
|
||
pipelineInfo.renderPass = _renderPass;//渲染流程
|
||
pipelineInfo.subpass = 0;
|
||
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional
|
||
pipelineInfo.basePipelineIndex = -1; // Optional
|
||
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_2d._graphicsPipeline) != VK_SUCCESS)
|
||
{
|
||
log_damage0("2d图形管线创建失败!");
|
||
return;
|
||
}
|
||
|
||
colorBlendAttachment.blendEnable = VK_TRUE;
|
||
//相等也必须混合,因为背景可能是不透明物体,在DrawCall里,一定是后画的
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
|
||
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_2d._graphicsPipelineTrans) != VK_SUCCESS)
|
||
{
|
||
log_damage0("2d图形管线创建失败!");
|
||
return;
|
||
}
|
||
|
||
//资源释放
|
||
vkDestroyShaderModule(_device, fragShaderModule, nullptr);
|
||
vkDestroyShaderModule(_device, vertShaderModule, nullptr);
|
||
vertShaderCode.clear();
|
||
vertShaderCode.shrink_to_fit();
|
||
fragShaderCode.clear();
|
||
fragShaderCode.shrink_to_fit();
|
||
//3.纹理采样器
|
||
VkSamplerCreateInfo samplerInfo{};
|
||
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
|
||
samplerInfo.magFilter = VK_FILTER_NEAREST;// VK_FILTER_LINEAR;
|
||
samplerInfo.minFilter = VK_FILTER_NEAREST;
|
||
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
||
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
||
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
|
||
samplerInfo.anisotropyEnable = VK_TRUE;
|
||
|
||
VkPhysicalDeviceProperties properties{};
|
||
vkGetPhysicalDeviceProperties(_physicalDevice, &properties);
|
||
|
||
if (true)
|
||
{
|
||
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
|
||
}
|
||
else
|
||
{
|
||
samplerInfo.anisotropyEnable = VK_FALSE;
|
||
samplerInfo.maxAnisotropy = 1.0f;
|
||
}
|
||
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;
|
||
samplerInfo.mipLodBias = 0.0f;
|
||
samplerInfo.minLod = 0.0f;
|
||
samplerInfo.maxLod = 0.0f;
|
||
|
||
if (vkCreateSampler(_device, &samplerInfo, nullptr, &_2d._textureSampler) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建纹理采样器失败!");
|
||
return;
|
||
}
|
||
//3.5 索引缓冲
|
||
std::vector<uint32_t> indices;
|
||
indices.resize(NUM_2D_INDEX);
|
||
|
||
uint32_t n = 0;
|
||
for (uint32_t i = 0; i < NUM_2D_INDEX; i += 6)
|
||
{
|
||
indices[i + 0] = 0 + n;
|
||
indices[i + 1] = 1 + n;
|
||
indices[i + 2] = 2 + n;
|
||
indices[i + 3] = 0 + n;
|
||
indices[i + 4] = 2 + n;
|
||
indices[i + 5] = 3 + n;
|
||
n += 4;
|
||
}
|
||
CreateIndexBuffer(indices, _2d._indexBuffer, _2d._indexBufferMemory);
|
||
|
||
//4.统一缓冲
|
||
VkDeviceSize bufferSize = sizeof(VK2D::UBO);
|
||
|
||
_2d._uniformBuffers.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
_2d._uniformBuffersMemory.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
CreateBuffer(bufferSize,
|
||
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
||
_2d._uniformBuffers[i], _2d._uniformBuffersMemory[i]);
|
||
}
|
||
//5.描述符池
|
||
std::array<VkDescriptorPoolSize, 2> poolSizes{};
|
||
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[0].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL_2D;
|
||
poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
poolSizes[1].descriptorCount = (uint32_t)NUM_MAX_DESCRIPTOR_POOL_2D;
|
||
|
||
VkDescriptorPoolCreateInfo poolInfo{};
|
||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||
poolInfo.poolSizeCount = (uint32_t)poolSizes.size();
|
||
poolInfo.pPoolSizes = poolSizes.data();
|
||
poolInfo.maxSets = (uint32_t)(poolSizes.size() * NUM_MAX_DESCRIPTOR_POOL_2D);
|
||
|
||
if (vkCreateDescriptorPool(_device, &poolInfo, nullptr, &_2d._descriptorPool) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建描述符池失败!");
|
||
return;
|
||
}
|
||
//6.分配描述符
|
||
size_t num = NUM_MAX_DRAW_CALL_2D * NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
std::vector<VkDescriptorSetLayout> layouts(num, _2d._descriptorSetLayout);
|
||
VkDescriptorSetAllocateInfo allocInfo{};
|
||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||
allocInfo.descriptorPool = _2d._descriptorPool;
|
||
allocInfo.descriptorSetCount = (uint32_t)num;
|
||
allocInfo.pSetLayouts = layouts.data();
|
||
|
||
_2d._descriptorSets.resize(num);
|
||
if (vkAllocateDescriptorSets(_device, &allocInfo, _2d._descriptorSets.data()) != VK_SUCCESS)
|
||
{
|
||
log_err0("分配2d描述符集失败!");
|
||
return;
|
||
}
|
||
}
|
||
|
||
void VK::_delete_2d()
|
||
{
|
||
vkDestroySampler(_device, _2d._textureSampler, nullptr);
|
||
for (auto& iter : _2d._allCanvas)
|
||
{
|
||
iter->Delete(_device);
|
||
delete iter;
|
||
}
|
||
//索引缓冲
|
||
vkDestroyBuffer(_device, _2d._indexBuffer, nullptr);
|
||
vkFreeMemory(_device, _2d._indexBufferMemory, nullptr);
|
||
//ub
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
vkDestroyBuffer(_device, _2d._uniformBuffers[i], nullptr);
|
||
vkFreeMemory(_device, _2d._uniformBuffersMemory[i], nullptr);
|
||
}
|
||
vkDestroyDescriptorPool(_device, _2d._descriptorPool, nullptr);
|
||
vkDestroyDescriptorSetLayout(_device, _2d._descriptorSetLayout, nullptr);
|
||
vkDestroyPipeline(_device, _2d._graphicsPipeline, nullptr);
|
||
vkDestroyPipeline(_device, _2d._graphicsPipelineTrans, nullptr);
|
||
vkDestroyPipelineLayout(_device, _2d._pipelineLayout, nullptr);
|
||
}
|
||
|
||
void VK::_create_gfx()
|
||
{
|
||
//------------------------------gfx--------------------------------
|
||
//0.描述符布局
|
||
//ubo
|
||
VkDescriptorSetLayoutBinding uboLayoutBinding{};
|
||
uboLayoutBinding.binding = 0;
|
||
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
uboLayoutBinding.descriptorCount = 1;
|
||
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||
uboLayoutBinding.pImmutableSamplers = nullptr; // Optional
|
||
|
||
std::array<VkDescriptorSetLayoutBinding, 1> bindings = {
|
||
uboLayoutBinding
|
||
};
|
||
|
||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||
layoutInfo.bindingCount = (uint32_t)bindings.size();
|
||
layoutInfo.pBindings = bindings.data();
|
||
|
||
if (vkCreateDescriptorSetLayout(_device, &layoutInfo, nullptr,
|
||
&_gfx._descriptorSetLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建gfx描述符集合失败!");
|
||
return;
|
||
}
|
||
//1.管线
|
||
//加载shader文件
|
||
Buffer vertShaderCode = File::GetBuffer("shader/vert_gfx.spv");
|
||
Buffer fragShaderCode = File::GetBuffer("shader/frag_gfx.spv");
|
||
//创建shader模块
|
||
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 };
|
||
|
||
//顶点输入状态
|
||
auto bindingDescription = VertexGfx::getBindingDescription();
|
||
auto attributeDescriptions = VertexGfx::getAttributeDescriptions();
|
||
|
||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||
vertexInputInfo.vertexBindingDescriptionCount = 1;
|
||
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // Optional
|
||
vertexInputInfo.vertexAttributeDescriptionCount = (uint32_t)attributeDescriptions.size();
|
||
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // Optional
|
||
|
||
//顶点装配状态
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly0{};
|
||
inputAssembly0.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly0.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
|
||
inputAssembly0.primitiveRestartEnable = VK_FALSE;
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly1{};
|
||
inputAssembly1.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly1.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
|
||
inputAssembly1.primitiveRestartEnable = VK_FALSE;
|
||
VkPipelineInputAssemblyStateCreateInfo inputAssembly2{};
|
||
inputAssembly2.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||
inputAssembly2.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||
inputAssembly2.primitiveRestartEnable = VK_FALSE;
|
||
|
||
|
||
//管线动态状态
|
||
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();
|
||
|
||
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_LINE;// VK_POLYGON_MODE_FILL;
|
||
rasterizer.lineWidth = 1.0f;
|
||
rasterizer.cullMode = VK_CULL_MODE_NONE;//不剔除应该更快 //VK_CULL_MODE_BACK_BIT;
|
||
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;//与3d不同
|
||
rasterizer.depthBiasEnable = VK_FALSE;
|
||
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
|
||
rasterizer.depthBiasClamp = 0.0f; // Optional
|
||
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
|
||
|
||
//多重采样状态
|
||
VkPipelineMultisampleStateCreateInfo multisampling{};
|
||
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||
multisampling.sampleShadingEnable = VK_FALSE;
|
||
multisampling.rasterizationSamples = _msaaSamples;//必须匹配
|
||
multisampling.minSampleShading = 1.0f; // Optional
|
||
multisampling.pSampleMask = nullptr; // Optional
|
||
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
|
||
multisampling.alphaToOneEnable = VK_FALSE; // Optional
|
||
if (B_OPEN_SAMPLE_SHADING)
|
||
{
|
||
multisampling.sampleShadingEnable = VK_TRUE;
|
||
// min fraction for sample shading; closer to one is smooth
|
||
multisampling.minSampleShading = .2f;
|
||
}
|
||
|
||
//混合模式
|
||
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;
|
||
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
|
||
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
|
||
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA;
|
||
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
|
||
|
||
VkPipelineColorBlendStateCreateInfo colorBlending{};
|
||
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||
colorBlending.logicOpEnable = VK_FALSE;//启用后会禁用前者
|
||
colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional
|
||
colorBlending.attachmentCount = 1;
|
||
colorBlending.pAttachments = &colorBlendAttachment;
|
||
colorBlending.blendConstants[0] = 0.0f; // Optional
|
||
colorBlending.blendConstants[1] = 0.0f; // Optional
|
||
colorBlending.blendConstants[2] = 0.0f; // Optional
|
||
colorBlending.blendConstants[3] = 0.0f; // Optional
|
||
|
||
//管线布局
|
||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||
pipelineLayoutInfo.setLayoutCount = 1; // Optional
|
||
pipelineLayoutInfo.pSetLayouts = &_gfx._descriptorSetLayout; // Optional
|
||
|
||
if (vkCreatePipelineLayout(_device, &pipelineLayoutInfo, nullptr, &_gfx._pipelineLayout) != VK_SUCCESS)
|
||
{
|
||
log_damage0("创建gfx管线布局失败!");
|
||
return;
|
||
}
|
||
|
||
//深度模板状态
|
||
VkPipelineDepthStencilStateCreateInfo depthStencil{};
|
||
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
|
||
depthStencil.depthTestEnable = VK_TRUE;
|
||
depthStencil.depthWriteEnable = VK_TRUE;
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
|
||
depthStencil.depthBoundsTestEnable = VK_FALSE;
|
||
depthStencil.minDepthBounds = 0.0f; // Optional
|
||
depthStencil.maxDepthBounds = 1.0f; // Optional
|
||
depthStencil.stencilTestEnable = VK_FALSE;
|
||
depthStencil.front = {}; // Optional
|
||
depthStencil.back = {}; // Optional
|
||
|
||
//图形管线
|
||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||
pipelineInfo.stageCount = 2;
|
||
pipelineInfo.pStages = shaderStages;//引用shader
|
||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly0;
|
||
pipelineInfo.pViewportState = &viewportState;
|
||
pipelineInfo.pRasterizationState = &rasterizer;
|
||
pipelineInfo.pMultisampleState = &multisampling;
|
||
pipelineInfo.pDepthStencilState = &depthStencil;
|
||
pipelineInfo.pColorBlendState = &colorBlending;
|
||
pipelineInfo.pDynamicState = &dynamicState;
|
||
pipelineInfo.layout = _gfx._pipelineLayout;//布局
|
||
pipelineInfo.renderPass = _renderPass;//渲染流程
|
||
pipelineInfo.subpass = 0;
|
||
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional
|
||
pipelineInfo.basePipelineIndex = -1; // Optional
|
||
|
||
|
||
// 点图元 顶点着色器需要设置 gl_PointSize
|
||
// https://github.com/KhronosGroup/Vulkan-Samples/issues/539
|
||
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[0]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线0创建失败!");
|
||
return;
|
||
}
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly1;
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[1]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线1创建失败!");
|
||
return;
|
||
}
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly2;
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[2]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线2创建失败!");
|
||
return;
|
||
}
|
||
rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // 修改填充模式
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[3]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线3创建失败!");
|
||
return;
|
||
}
|
||
|
||
colorBlendAttachment.blendEnable = VK_TRUE;
|
||
//相等也必须混合,因为背景可能是不透明物体,在DrawCall里,一定是后画的
|
||
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
|
||
|
||
rasterizer.polygonMode = VK_POLYGON_MODE_LINE; // 修改填充模式
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly0;
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[4]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线4创建失败!");
|
||
return;
|
||
}
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly1;
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[5]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线5创建失败!");
|
||
return;
|
||
}
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly2;
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[6]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线6创建失败!");
|
||
return;
|
||
}
|
||
pipelineInfo.pInputAssemblyState = &inputAssembly2;
|
||
rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // 修改填充模式
|
||
if (vkCreateGraphicsPipelines(_device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr,
|
||
&_gfx._vecGraphicsPipeline[7]) != VK_SUCCESS)
|
||
{
|
||
log_damage0("gfx图形管线7创建失败!");
|
||
return;
|
||
}
|
||
|
||
//资源释放
|
||
vkDestroyShaderModule(_device, fragShaderModule, nullptr);
|
||
vkDestroyShaderModule(_device, vertShaderModule, nullptr);
|
||
vertShaderCode.clear();
|
||
vertShaderCode.shrink_to_fit();
|
||
fragShaderCode.clear();
|
||
fragShaderCode.shrink_to_fit();
|
||
|
||
|
||
//4.统一缓冲
|
||
VkDeviceSize bufferSize = sizeof(VKGfx::UBO);
|
||
|
||
_gfx._uniformBuffers.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
_gfx._uniformBuffersMemory.resize(NUM_MAX_FRAME_IN_FLIGHT);
|
||
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
CreateBuffer(bufferSize,
|
||
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
|
||
_gfx._uniformBuffers[i], _gfx._uniformBuffersMemory[i]);
|
||
}
|
||
//5.描述符池
|
||
std::array<VkDescriptorPoolSize, 1> poolSizes{};
|
||
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
poolSizes[0].descriptorCount = (uint32_t)NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
VkDescriptorPoolCreateInfo poolInfo{};
|
||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||
poolInfo.poolSizeCount = (uint32_t)poolSizes.size();
|
||
poolInfo.pPoolSizes = poolSizes.data();
|
||
poolInfo.maxSets = (uint32_t)(poolSizes.size() * NUM_MAX_FRAME_IN_FLIGHT);
|
||
|
||
if (vkCreateDescriptorPool(_device, &poolInfo, nullptr, &_gfx._descriptorPool) != VK_SUCCESS)
|
||
{
|
||
log_err0("创建描述符池失败!");
|
||
return;
|
||
}
|
||
//6.分配描述符
|
||
size_t num = NUM_MAX_FRAME_IN_FLIGHT;
|
||
|
||
std::vector<VkDescriptorSetLayout> layouts(num, _gfx._descriptorSetLayout);
|
||
VkDescriptorSetAllocateInfo allocInfo{};
|
||
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||
allocInfo.descriptorPool = _gfx._descriptorPool;
|
||
allocInfo.descriptorSetCount = (uint32_t)num;
|
||
allocInfo.pSetLayouts = layouts.data();
|
||
|
||
_gfx._descriptorSets.resize(num);
|
||
if (vkAllocateDescriptorSets(_device, &allocInfo, _gfx._descriptorSets.data()) != VK_SUCCESS)
|
||
{
|
||
log_err0("分配gfx描述符集失败!");
|
||
return;
|
||
}
|
||
|
||
//填充描述符
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
size_t index = 0 * NUM_MAX_FRAME_IN_FLIGHT + i;
|
||
//ubo
|
||
VkDescriptorBufferInfo bufferInfo{};
|
||
bufferInfo.buffer = _gfx._uniformBuffers[i];
|
||
bufferInfo.offset = 0;
|
||
bufferInfo.range = sizeof(VK2D::UBO);
|
||
|
||
std::array<VkWriteDescriptorSet, 1> descriptorWrites{};
|
||
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[0].dstSet = _gfx._descriptorSets[index];
|
||
descriptorWrites[0].dstBinding = 0;
|
||
descriptorWrites[0].dstArrayElement = 0;
|
||
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||
descriptorWrites[0].descriptorCount = 1;
|
||
descriptorWrites[0].pBufferInfo = &bufferInfo;
|
||
|
||
vkUpdateDescriptorSets(_device,
|
||
(uint32_t)descriptorWrites.size(), descriptorWrites.data(),
|
||
0, nullptr);
|
||
}
|
||
|
||
// 顶点缓存
|
||
for (VertexBuffer& vb : _gfx._arrVB)
|
||
{
|
||
vb._num = 10240;
|
||
CreateVertexBufferCPU<VertexGfx>(vb._num,
|
||
vb._vertexBuffer, vb._vertexBufferMemory, vb._vertexBufferSize);
|
||
}
|
||
}
|
||
|
||
void VK::_delete_gfx()
|
||
{
|
||
for (auto& iter : _gfx._arrVB)
|
||
{
|
||
iter.Delete(_device);
|
||
}
|
||
|
||
//ub
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
vkDestroyBuffer(_device, _gfx._uniformBuffers[i], nullptr);
|
||
vkFreeMemory(_device, _gfx._uniformBuffersMemory[i], nullptr);
|
||
}
|
||
vkDestroyDescriptorPool(_device, _gfx._descriptorPool, nullptr);
|
||
vkDestroyDescriptorSetLayout(_device, _gfx._descriptorSetLayout, nullptr);
|
||
for (auto& iter : _gfx._vecGraphicsPipeline)
|
||
{
|
||
vkDestroyPipeline(_device, iter, nullptr);
|
||
}
|
||
vkDestroyPipelineLayout(_device, _gfx._pipelineLayout, nullptr);
|
||
}
|
||
|
||
void VK::GenerateMipmaps(VkImage image, VkFormat imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels)
|
||
{
|
||
//检查线性过滤 可用
|
||
VkFormatProperties formatProperties;
|
||
vkGetPhysicalDeviceFormatProperties(_physicalDevice, imageFormat, &formatProperties);
|
||
if (!(formatProperties.optimalTilingFeatures
|
||
& VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
|
||
{
|
||
log_damage0("不支持当前纹理格式的线性过滤!");
|
||
return;
|
||
}
|
||
|
||
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
|
||
|
||
VkImageMemoryBarrier barrier{};
|
||
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
|
||
barrier.image = image;
|
||
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||
barrier.subresourceRange.baseArrayLayer = 0;
|
||
barrier.subresourceRange.layerCount = 1;
|
||
barrier.subresourceRange.levelCount = 1;
|
||
|
||
int32_t mipWidth = texWidth;
|
||
int32_t mipHeight = texHeight;
|
||
|
||
for (uint32_t i = 1; i < mipLevels; ++i)
|
||
{
|
||
barrier.subresourceRange.baseMipLevel = i - 1;
|
||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
|
||
vkCmdPipelineBarrier(commandBuffer,
|
||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
|
||
0, nullptr,
|
||
0, nullptr,
|
||
1, &barrier);
|
||
|
||
VkImageBlit blit{};
|
||
blit.srcOffsets[0] = { 0, 0, 0 };
|
||
blit.srcOffsets[1] = { mipWidth, mipHeight, 1 };
|
||
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||
blit.srcSubresource.mipLevel = i - 1;
|
||
blit.srcSubresource.baseArrayLayer = 0;
|
||
blit.srcSubresource.layerCount = 1;
|
||
blit.dstOffsets[0] = { 0, 0, 0 };
|
||
blit.dstOffsets[1] = {
|
||
mipWidth > 1 ? mipWidth / 2 : 1,
|
||
mipHeight > 1 ? mipHeight / 2 : 1,
|
||
1 };
|
||
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||
blit.dstSubresource.mipLevel = i;
|
||
blit.dstSubresource.baseArrayLayer = 0;
|
||
blit.dstSubresource.layerCount = 1;
|
||
|
||
vkCmdBlitImage(commandBuffer,
|
||
image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||
image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||
1, &blit,
|
||
VK_FILTER_LINEAR);
|
||
|
||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||
|
||
vkCmdPipelineBarrier(commandBuffer,
|
||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
|
||
0, nullptr,
|
||
0, nullptr,
|
||
1, &barrier);
|
||
if (mipWidth > 1) mipWidth /= 2;
|
||
if (mipHeight > 1) mipHeight /= 2;
|
||
}
|
||
barrier.subresourceRange.baseMipLevel = mipLevels - 1;
|
||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||
|
||
vkCmdPipelineBarrier(commandBuffer,
|
||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
|
||
0, nullptr,
|
||
0, nullptr,
|
||
1, &barrier);
|
||
|
||
EndSingleTimeCommands(commandBuffer);
|
||
}
|
||
|
||
void VK::_create_depth_resources()
|
||
{
|
||
VkFormat depthFormat = FindDepthFormat();
|
||
CreateImage(_extentSwapChain.width, _extentSwapChain.height, 1, _msaaSamples,
|
||
depthFormat, VK_IMAGE_TILING_OPTIMAL,
|
||
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
|
||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, _depthImage, _depthImageMemory);
|
||
_depthImageView = CreateImageView(_depthImage, depthFormat,
|
||
VK_IMAGE_ASPECT_DEPTH_BIT, 1);
|
||
|
||
TransitionImageLayout(_depthImage, depthFormat,
|
||
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||
1);
|
||
}
|
||
|
||
VkSampleCountFlagBits VK::GetMaxUsableSampleCount()
|
||
{
|
||
VkPhysicalDeviceProperties physicalDeviceProperties;
|
||
vkGetPhysicalDeviceProperties(_physicalDevice, &physicalDeviceProperties);
|
||
|
||
VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts
|
||
& physicalDeviceProperties.limits.framebufferDepthSampleCounts;
|
||
if (counts & VK_SAMPLE_COUNT_64_BIT) { return VK_SAMPLE_COUNT_64_BIT; }
|
||
if (counts & VK_SAMPLE_COUNT_32_BIT) { return VK_SAMPLE_COUNT_32_BIT; }
|
||
if (counts & VK_SAMPLE_COUNT_16_BIT) { return VK_SAMPLE_COUNT_16_BIT; }
|
||
if (counts & VK_SAMPLE_COUNT_8_BIT) { return VK_SAMPLE_COUNT_8_BIT; }
|
||
if (counts & VK_SAMPLE_COUNT_4_BIT) { return VK_SAMPLE_COUNT_4_BIT; }
|
||
if (counts & VK_SAMPLE_COUNT_2_BIT) { return VK_SAMPLE_COUNT_2_BIT; }
|
||
|
||
return VK_SAMPLE_COUNT_1_BIT;
|
||
}
|
||
|
||
size_t VK::CreateTexture(std::string_view path_name)
|
||
{
|
||
std::string str = std::string{ path_name };
|
||
auto iter = _mapPath2Texture.find(str);
|
||
if (iter != _mapPath2Texture.end())
|
||
{
|
||
return iter->second;
|
||
}
|
||
|
||
Image* image = createImage(str);
|
||
if (!image)
|
||
return 0;
|
||
size_t ret = CreateTextureReal(image, true);
|
||
if (ret != 0)
|
||
_mapPath2Texture[str] = ret;
|
||
return ret;
|
||
}
|
||
|
||
void VK::CreateCanvas(size_t id, Image* image)
|
||
{
|
||
assert(image);
|
||
assert(id == _2d._allCanvas.size());
|
||
Canvas* canvas = new Canvas;
|
||
canvas->_id = id;
|
||
canvas->_texture = CreateTexture2D(image);
|
||
canvas->_numVertex = NUM_START_2D_VERTEX;
|
||
CreateVertexBufferCPU<Vertex2D>(canvas->_numVertex,
|
||
canvas->_vertexBuffer, canvas->_vertexBufferMemory, canvas->_vertexBufferSize);
|
||
|
||
_2d._allCanvas.push_back(canvas);
|
||
|
||
//填充描述符
|
||
for (size_t i = 0; i < NUM_MAX_FRAME_IN_FLIGHT; i++)
|
||
{
|
||
size_t index = id * NUM_MAX_FRAME_IN_FLIGHT + i;
|
||
//ubo
|
||
VkDescriptorBufferInfo bufferInfo{};
|
||
bufferInfo.buffer = _2d._uniformBuffers[i];
|
||
bufferInfo.offset = 0;
|
||
bufferInfo.range = sizeof(VK2D::UBO);
|
||
//纹理
|
||
VkDescriptorImageInfo imageInfo{};
|
||
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||
imageInfo.imageView = canvas->_texture._textureImageView;
|
||
imageInfo.sampler = _2d._textureSampler;
|
||
|
||
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
|
||
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
descriptorWrites[0].dstSet = _2d._descriptorSets[index];
|
||
descriptorWrites[0].dstBinding = 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 = _2d._descriptorSets[index];
|
||
descriptorWrites[1].dstBinding = 1;
|
||
descriptorWrites[1].dstArrayElement = 0;
|
||
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||
descriptorWrites[1].descriptorCount = 1;
|
||
descriptorWrites[1].pImageInfo = &imageInfo;
|
||
|
||
vkUpdateDescriptorSets(_device,
|
||
(uint32_t)descriptorWrites.size(), descriptorWrites.data(),
|
||
0, nullptr);
|
||
}
|
||
}
|
||
|
||
Texture VK::CreateTexture2D(Image* image)
|
||
{
|
||
assert(image);
|
||
|
||
Texture tex;
|
||
|
||
Size size = image->GetSize();
|
||
//mipmap数(2d暂时不生成mipmap,即使生成也要手动)
|
||
tex._mipLevel = 1;
|
||
|
||
VkDeviceSize imageSize = image->GetSizeByte();
|
||
//复制到暂存缓冲
|
||
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, image->GetBuffer(), static_cast<size_t>(imageSize));
|
||
vkUnmapMemory(_device, stagingBufferMemory);
|
||
|
||
//if (delete_image)
|
||
// delete image;
|
||
//创建显存图像,VK_IMAGE_USAGE_TRANSFER_SRC_BIT用于生成mipmap
|
||
//还用于导出图像
|
||
CreateImage((uint32_t)size[0], (uint32_t)size[1], tex._mipLevel, VK_SAMPLE_COUNT_1_BIT,
|
||
VK_FORMAT_R8G8B8A8_SRGB,
|
||
VK_IMAGE_TILING_OPTIMAL,
|
||
VK_IMAGE_USAGE_TRANSFER_SRC_BIT
|
||
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
|
||
| VK_IMAGE_USAGE_SAMPLED_BIT,
|
||
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
|
||
tex._textureImage, tex._textureImageMemory);
|
||
//转换状态 为 复制目标
|
||
TransitionImageLayout(tex._textureImage, VK_FORMAT_R8G8B8A8_SRGB,
|
||
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||
tex._mipLevel);
|
||
//暂存缓冲 -> 显存缓冲
|
||
CopyBufferToImage(stagingBuffer, tex._textureImage,
|
||
(uint32_t)size[0], (uint32_t)size[1]);
|
||
//转换状态 为 着色器资源
|
||
TransitionImageLayout(tex._textureImage, VK_FORMAT_R8G8B8A8_SRGB,
|
||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 1);
|
||
|
||
|
||
vkDestroyBuffer(_device, stagingBuffer, nullptr);
|
||
vkFreeMemory(_device, stagingBufferMemory, nullptr);
|
||
|
||
tex._textureImageView = CreateImageView(tex._textureImage,
|
||
VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, tex._mipLevel);
|
||
|
||
tex._width = (uint32_t)size[0];
|
||
tex._height = (uint32_t)size[1];
|
||
return tex;
|
||
}
|
||
|
||
void VK::Update(std::vector<DrawCall>& list_dc, std::vector<DrawCall>& list_dc_translucent)
|
||
{
|
||
_2d._renderInfo._numSprite = 0;
|
||
_2d._renderInfo._numSpriteTranslucent = 0;
|
||
|
||
//画布逻辑,更新顶点和cbo
|
||
//半透明需要排序,后面生成dc
|
||
|
||
//生成dc,并按z排序
|
||
std::multimap<float, DrawCall> map_dc_translucent;
|
||
for (Canvas*& canvas : _2d._allCanvas)
|
||
{
|
||
_2d._renderInfo._numSprite += canvas->_allSprite.size();
|
||
_2d._renderInfo._numSpriteTranslucent += canvas->_allSpriteTrans.size();
|
||
//0.顶点缓冲区大小检查
|
||
const size_t NUM_VERTEX_NEED = (canvas->_allSprite.size()
|
||
+ canvas->_allSpriteTrans.size()) * 4;
|
||
|
||
if (NUM_VERTEX_NEED > canvas->_numVertex)
|
||
{
|
||
vkDestroyBuffer(_device, canvas->_vertexBuffer, nullptr);
|
||
vkFreeMemory(_device, canvas->_vertexBufferMemory, nullptr);
|
||
canvas->_numVertex = NUM_VERTEX_NEED * 2;
|
||
CreateVertexBufferCPU<Vertex2D>(
|
||
canvas->_numVertex, canvas->_vertexBuffer,
|
||
canvas->_vertexBufferMemory, canvas->_vertexBufferSize);
|
||
}
|
||
//1.拆分所有精灵到不同drawCall
|
||
//(由于后render的在后面,所以反过来添加,这样同order先Render的就不能通过z测试)
|
||
|
||
std::list<DrawCallList> draw_call;
|
||
for (auto iter = canvas->_allSprite.rbegin(); iter != canvas->_allSprite.rend(); ++iter)
|
||
{
|
||
Sprite* spr = *iter;
|
||
DrawCallList dcl;
|
||
DrawCall& dc = dcl._dc;
|
||
dc._canvas = canvas;
|
||
dc._rootCoor = spr->GetCoor() ? spr->GetCoor()->GetRoot() : nullptr;
|
||
dc._scissorRect = spr->_scissorRect;
|
||
dc._viewport = spr->_viewport;
|
||
dc._sampler = spr->_sampler;
|
||
|
||
auto iter1 = find(draw_call.begin(), draw_call.end(), dcl);
|
||
if (iter1 == draw_call.end())
|
||
{
|
||
dcl._listSpr.push_back(spr);
|
||
draw_call.push_back(dcl);
|
||
}
|
||
else
|
||
{
|
||
iter1->_listSpr.push_back(spr);
|
||
}
|
||
}
|
||
Vertex2D* vertex;//顶点内存
|
||
vkMapMemory(_device, canvas->_vertexBufferMemory, 0,
|
||
canvas->_vertexBufferSize, 0, (void**)&vertex);
|
||
|
||
//2.添加精灵
|
||
size_t j = 0;//写入顶点位置,每个精灵4个
|
||
auto fn_add_spr_vertex = [&](Sprite* spr)
|
||
{
|
||
for (size_t i = 0; i != 4; ++i)
|
||
{
|
||
Position pos = spr->_quad[i];
|
||
//坐标变换
|
||
if (spr->_coor)
|
||
{
|
||
pos = spr->_coor->ThisToRoot(pos);
|
||
}
|
||
|
||
//取整像素
|
||
if (true)
|
||
{
|
||
Every::Round(pos);
|
||
}
|
||
|
||
Vertex2D& v = vertex[j + i];
|
||
|
||
v._pos[0] = (float)pos[0];
|
||
v._pos[1] = (float)pos[1];
|
||
v._pos[2] = spr->_z;
|
||
|
||
v._color = spr->_col[i];
|
||
v._uv = spr->_uv[i];
|
||
}
|
||
j += 4;
|
||
};
|
||
|
||
//3.按DrawCall写入内存,记录顶点位置
|
||
for (auto& iter : draw_call)
|
||
{
|
||
DrawCall dc = iter._dc;//复制一份
|
||
|
||
dc._beg = j;
|
||
for (auto& iter1 : iter._listSpr)
|
||
{
|
||
fn_add_spr_vertex(iter1);
|
||
}
|
||
dc._end = j;
|
||
list_dc.emplace_back(dc);
|
||
}
|
||
//4.生成按z的drawCall(意味着z值不同不能合并,目前为止。只有z值相同,且Dc相同才能合并)
|
||
//半透精灵 z测试是 LESS_EQUAL,所以 后Render的 后添加
|
||
std::vector<DrawCallZ> vec_dc_z;
|
||
for (auto iter = canvas->_allSpriteTrans.begin();
|
||
iter != canvas->_allSpriteTrans.end();
|
||
++iter)
|
||
{
|
||
Sprite* spr = *iter;
|
||
DrawCallZ dcz;
|
||
dcz._z = spr->GetOrder();
|
||
DrawCall& dc = dcz._dcl._dc;
|
||
dc._canvas = canvas;
|
||
dc._rootCoor = spr->GetCoor() ? spr->GetCoor()->GetRoot() : nullptr;
|
||
dc._scissorRect = spr->_scissorRect;
|
||
dc._viewport = spr->_viewport;
|
||
dc._sampler = spr->_sampler;
|
||
|
||
//此处错误的只判断了z值相等,必须使用 std::find。(因为map使用<操作符来查找)
|
||
//map_dc_z[dcz].push_back(spr);
|
||
|
||
auto iter1 = find(vec_dc_z.begin(), vec_dc_z.end(), dcz);
|
||
if (iter1 == vec_dc_z.end())
|
||
{
|
||
dcz._dcl._listSpr.push_back(spr);
|
||
vec_dc_z.push_back(dcz);
|
||
}
|
||
else
|
||
{
|
||
iter1->_dcl._listSpr.push_back(spr);
|
||
}
|
||
}
|
||
//5.写入顶点
|
||
for (auto& iter : vec_dc_z)
|
||
{
|
||
DrawCallZ dcz = iter;//复制一份
|
||
DrawCallList& dcl = dcz._dcl;
|
||
|
||
dcl._dc._beg = j;
|
||
for (auto& iter1 : dcl._listSpr)
|
||
{
|
||
fn_add_spr_vertex(iter1);
|
||
}
|
||
dcl._dc._end = j;
|
||
|
||
map_dc_translucent.insert({ dcz._z, dcl._dc });
|
||
}
|
||
vkUnmapMemory(_device, canvas->_vertexBufferMemory);
|
||
|
||
canvas->_allSprite.clear();
|
||
canvas->_allSpriteTrans.clear();
|
||
}
|
||
|
||
//合并连续 且画布相同的项
|
||
DrawCall* pre = nullptr;
|
||
//由于按z升序,所以反过来添加 ,避免z测试
|
||
for (auto iter = map_dc_translucent.rbegin(); iter != map_dc_translucent.rend(); ++iter)
|
||
{
|
||
auto& dc = iter->second;
|
||
|
||
if (pre
|
||
&& dc == *pre
|
||
&& (dc._beg == pre->_end))
|
||
{//是连续的
|
||
pre->_end = dc._end;
|
||
}
|
||
else
|
||
{
|
||
list_dc_translucent.push_back(dc);
|
||
pre = &list_dc_translucent.back();
|
||
}
|
||
}
|
||
|
||
_2d._renderInfo._numDrawCall = list_dc.size();
|
||
_2d._renderInfo._numDrawCallTranslucent = list_dc_translucent.size();
|
||
|
||
//更新cbo
|
||
for (size_t i = 0; i < NUM_MAX_ROOT_COOR; ++i)
|
||
{
|
||
VK2D::CBO& cbo = _2d._allCBO[i];
|
||
cbo._model.Identity();
|
||
}
|
||
|
||
//更新统一常量ubo
|
||
VK2D::UBO ubo{};
|
||
|
||
|
||
Matrix4 mat_view = Mat::CreateLookTo(
|
||
Position3{ 0.0f, 0.0f, 0.0f },
|
||
Position3{ 0.0f, 0.0f, 1.0f },
|
||
Position3{ 0.0f, -1.0f, 0.0f });
|
||
|
||
Matrix4 mat_proj = Mat::CreateOrthogonal(
|
||
0.0f, 0.0f,
|
||
(Float)_extentSwapChain.width, (Float)_extentSwapChain.height,
|
||
0.0f, 1.0f);
|
||
|
||
ubo._viewProj = mat_proj * mat_view;
|
||
//向下平移h
|
||
Mat::ApplyTranslation(ubo._viewProj,
|
||
Position3{ 0.0f, -(Float)_extentSwapChain.height, 0.0f });
|
||
|
||
|
||
void* data;
|
||
vkMapMemory(_device, _2d._uniformBuffersMemory[_currentFrame], 0, sizeof(ubo), 0, &data);
|
||
memcpy(data, &ubo, sizeof(ubo));
|
||
vkUnmapMemory(_device, _2d._uniformBuffersMemory[_currentFrame]);
|
||
|
||
// 暂时与2d一样
|
||
void* data1;
|
||
vkMapMemory(_device, _gfx._uniformBuffersMemory[_currentFrame], 0, sizeof(ubo), 0, &data1);
|
||
memcpy(data1, &ubo, sizeof(ubo));
|
||
vkUnmapMemory(_device, _gfx._uniformBuffersMemory[_currentFrame]);
|
||
}
|
||
|
||
|
||
}
|
||
|