Add sample Template; some generalization in utils; some minor improvements in some samples. (#349)

* Add samples SecondaryCommandBuffer and SeparateImageSampler.

+ made some helper functions more explicit.

* Add sample Template, some generalizations in utils, some minor improvements in various samples.
This commit is contained in:
Andreas Süßenbach
2019-06-25 09:47:27 +02:00
committed by Markus Tavenrath
parent 89a56017a8
commit d811c3a7e2
37 changed files with 964 additions and 672 deletions

View File

@@ -65,12 +65,13 @@ namespace vk
return device->createDescriptorPoolUnique(descriptorPoolCreateInfo);
}
vk::UniqueDescriptorSetLayout createDescriptorSetLayout(vk::UniqueDevice &device, std::vector<std::pair<vk::DescriptorType, vk::ShaderStageFlags>> const& bindingData, vk::DescriptorSetLayoutCreateFlags flags)
vk::UniqueDescriptorSetLayout createDescriptorSetLayout(vk::UniqueDevice const& device, std::vector<std::tuple<vk::DescriptorType, uint32_t, vk::ShaderStageFlags>> const& bindingData,
vk::DescriptorSetLayoutCreateFlags flags)
{
std::vector<vk::DescriptorSetLayoutBinding> bindings(bindingData.size());
for (size_t i = 0; i < bindingData.size(); i++)
{
bindings[i] = vk::DescriptorSetLayoutBinding(checked_cast<uint32_t>(i), bindingData[i].first, 1, bindingData[i].second);
bindings[i] = vk::DescriptorSetLayoutBinding(checked_cast<uint32_t>(i), std::get<0>(bindingData[i]), std::get<1>(bindingData[i]), std::get<2>(bindingData[i]));
}
return device->createDescriptorSetLayoutUnique(vk::DescriptorSetLayoutCreateInfo(flags, checked_cast<uint32_t>(bindings.size()), bindings.data()));
}
@@ -98,60 +99,72 @@ namespace vk
vk::ImageView attachments[2];
attachments[1] = depthImageView.get();
vk::FramebufferCreateInfo framebufferCreateInfo(vk::FramebufferCreateFlags(), *renderPass, depthImageView ? 2 : 1, attachments, extent.width, extent.height, 1);
std::vector<vk::UniqueFramebuffer> framebuffers;
framebuffers.reserve(imageViews.size());
for (auto const& view : imageViews)
{
attachments[0] = view.get();
framebuffers.push_back(device->createFramebufferUnique(vk::FramebufferCreateInfo(vk::FramebufferCreateFlags(), renderPass.get(), depthImageView ? 2 : 1, attachments, extent.width, extent.height, 1)));
framebuffers.push_back(device->createFramebufferUnique(framebufferCreateInfo));
}
return framebuffers;
}
vk::UniquePipeline createGraphicsPipeline(vk::UniqueDevice &device, vk::UniquePipelineCache &pipelineCache, vk::UniqueShaderModule &vertexShaderModule,
vk::UniqueShaderModule &fragmentShaderModule, uint32_t vertexStride, bool depthBuffered, bool textured, vk::UniquePipelineLayout &pipelineLayout, vk::UniqueRenderPass &renderPass)
vk::UniquePipeline createGraphicsPipeline(vk::UniqueDevice const& device, vk::UniquePipelineCache const& pipelineCache,
std::pair<vk::ShaderModule, vk::SpecializationInfo const*> const& vertexShaderData,
std::pair<vk::ShaderModule, vk::SpecializationInfo const*> const& fragmentShaderData, uint32_t vertexStride,
std::vector<std::pair<vk::Format, uint32_t>> const& vertexInputAttributeFormatOffset, vk::FrontFace frontFace, bool depthBuffered
, vk::UniquePipelineLayout const& pipelineLayout, vk::UniqueRenderPass const& renderPass)
{
vk::PipelineShaderStageCreateInfo pipelineShaderStageCreateInfos[2] =
{
vk::PipelineShaderStageCreateInfo(vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eVertex, vertexShaderModule.get(), "main"),
vk::PipelineShaderStageCreateInfo(vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eFragment, fragmentShaderModule.get(), "main")
vk::PipelineShaderStageCreateInfo(vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eVertex, vertexShaderData.first, "main", vertexShaderData.second),
vk::PipelineShaderStageCreateInfo(vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eFragment, fragmentShaderData.first, "main", fragmentShaderData.second)
};
std::vector<vk::VertexInputAttributeDescription> vertexInputAttributeDescriptions;
vk::PipelineVertexInputStateCreateInfo pipelineVertexInputStateCreateInfo;
if (0 < vertexStride)
{
vk::VertexInputBindingDescription vertexInputBindingDescription(0, vertexStride);
vk::VertexInputAttributeDescription vertexInputAttributeDescriptions[2] =
vertexInputAttributeDescriptions.reserve(vertexInputAttributeFormatOffset.size());
for (uint32_t i=0 ; i<vertexInputAttributeFormatOffset.size() ; i++)
{
vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32A32Sfloat, 0),
vk::VertexInputAttributeDescription(1, 0, textured ? vk::Format::eR32G32Sfloat : vk::Format::eR32G32B32A32Sfloat, 16)
};
vertexInputAttributeDescriptions.push_back(vk::VertexInputAttributeDescription(i, 0, vertexInputAttributeFormatOffset[i].first, vertexInputAttributeFormatOffset[i].second));
}
pipelineVertexInputStateCreateInfo.vertexBindingDescriptionCount = 1;
pipelineVertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexInputBindingDescription;
pipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = 2;
pipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions;
pipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = vk::su::checked_cast<uint32_t>(vertexInputAttributeDescriptions.size());
pipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions.data();
}
vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo(vk::PipelineInputAssemblyStateCreateFlags(), vk::PrimitiveTopology::eTriangleList);
vk::PipelineViewportStateCreateInfo pipelineViewportStateCreateInfo(vk::PipelineViewportStateCreateFlags(), 1, nullptr, 1, nullptr);
vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo(vk::PipelineRasterizationStateCreateFlags(), false, false, vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise, false, 0.0f, 0.0f, 0.0f, 1.0f);
vk::PipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo(vk::PipelineRasterizationStateCreateFlags(), false, false, vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack,
frontFace, false, 0.0f, 0.0f, 0.0f, 1.0f);
vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo;
vk::StencilOpState stencilOpState(vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::StencilOp::eKeep, vk::CompareOp::eAlways);
vk::PipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo(vk::PipelineDepthStencilStateCreateFlags(), depthBuffered, depthBuffered, vk::CompareOp::eLessOrEqual, false, false, stencilOpState, stencilOpState);
vk::PipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo(vk::PipelineDepthStencilStateCreateFlags(), depthBuffered, depthBuffered, vk::CompareOp::eLessOrEqual, false,
false, stencilOpState, stencilOpState);
vk::ColorComponentFlags colorComponentFlags(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
vk::PipelineColorBlendAttachmentState pipelineColorBlendAttachmentState(false, vk::BlendFactor::eZero, vk::BlendFactor::eZero, vk::BlendOp::eAdd, vk::BlendFactor::eZero, vk::BlendFactor::eZero, vk::BlendOp::eAdd, colorComponentFlags);
vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(vk::PipelineColorBlendStateCreateFlags(), false, vk::LogicOp::eNoOp, 1, &pipelineColorBlendAttachmentState, { { (1.0f, 1.0f, 1.0f, 1.0f) } });
vk::PipelineColorBlendAttachmentState pipelineColorBlendAttachmentState(false, vk::BlendFactor::eZero, vk::BlendFactor::eZero, vk::BlendOp::eAdd, vk::BlendFactor::eZero,
vk::BlendFactor::eZero, vk::BlendOp::eAdd, colorComponentFlags);
vk::PipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(vk::PipelineColorBlendStateCreateFlags(), false, vk::LogicOp::eNoOp, 1, &pipelineColorBlendAttachmentState,
{ { (1.0f, 1.0f, 1.0f, 1.0f) } });
vk::DynamicState dynamicStates[2] = { vk::DynamicState::eViewport, vk::DynamicState::eScissor };
vk::PipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo(vk::PipelineDynamicStateCreateFlags(), 2, dynamicStates);
vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo(vk::PipelineCreateFlags(), 2, pipelineShaderStageCreateInfos, &pipelineVertexInputStateCreateInfo, &pipelineInputAssemblyStateCreateInfo, nullptr, &pipelineViewportStateCreateInfo, &pipelineRasterizationStateCreateInfo, &pipelineMultisampleStateCreateInfo, &pipelineDepthStencilStateCreateInfo, &pipelineColorBlendStateCreateInfo, &pipelineDynamicStateCreateInfo, pipelineLayout.get(), renderPass.get());
vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo(vk::PipelineCreateFlags(), 2, pipelineShaderStageCreateInfos, &pipelineVertexInputStateCreateInfo,
&pipelineInputAssemblyStateCreateInfo, nullptr, &pipelineViewportStateCreateInfo, &pipelineRasterizationStateCreateInfo,
&pipelineMultisampleStateCreateInfo, &pipelineDepthStencilStateCreateInfo, &pipelineColorBlendStateCreateInfo,
&pipelineDynamicStateCreateInfo, pipelineLayout.get(), renderPass.get());
return device->createGraphicsPipelineUnique(pipelineCache.get(), graphicsPipelineCreateInfo);
}
@@ -180,7 +193,7 @@ namespace vk
// create a UniqueInstance
vk::ApplicationInfo applicationInfo(appName.c_str(), 1, engineName.c_str(), 1, apiVersion);
vk::UniqueInstance instance = vk::createInstanceUnique(vk::InstanceCreateInfo({}, &applicationInfo, checked_cast<uint32_t>(enabledLayers.size()), enabledLayers.data(),
checked_cast<uint32_t>(enabledExtensions.size()), enabledExtensions.data()));
checked_cast<uint32_t>(enabledExtensions.size()), enabledExtensions.data()));
#if !defined(NDEBUG)
static bool initialized = false;
@@ -201,16 +214,19 @@ namespace vk
std::vector<vk::AttachmentDescription> attachmentDescriptions;
assert(colorFormat != vk::Format::eUndefined);
attachmentDescriptions.push_back(vk::AttachmentDescription(vk::AttachmentDescriptionFlags(), colorFormat, vk::SampleCountFlagBits::e1, loadOp, vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined, colorFinalLayout));
vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined, colorFinalLayout));
if (depthFormat != vk::Format::eUndefined)
{
attachmentDescriptions.push_back(vk::AttachmentDescription(vk::AttachmentDescriptionFlags(), depthFormat, vk::SampleCountFlagBits::e1, loadOp, vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eStore, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal));
attachmentDescriptions.push_back(vk::AttachmentDescription(vk::AttachmentDescriptionFlags(), depthFormat, vk::SampleCountFlagBits::e1, loadOp, vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal));
}
vk::AttachmentReference colorAttachment(0, vk::ImageLayout::eColorAttachmentOptimal);
vk::AttachmentReference depthAttachment(1, vk::ImageLayout::eDepthStencilAttachmentOptimal);
vk::SubpassDescription subpassDescription(vk::SubpassDescriptionFlags(), vk::PipelineBindPoint::eGraphics, 0, nullptr, 1, &colorAttachment, nullptr, (depthFormat != vk::Format::eUndefined) ? &depthAttachment : nullptr);
return device->createRenderPassUnique(vk::RenderPassCreateInfo(vk::RenderPassCreateFlags(), static_cast<uint32_t>(attachmentDescriptions.size()), attachmentDescriptions.data(), 1, &subpassDescription));
vk::SubpassDescription subpassDescription(vk::SubpassDescriptionFlags(), vk::PipelineBindPoint::eGraphics, 0, nullptr, 1, &colorAttachment, nullptr,
(depthFormat != vk::Format::eUndefined) ? &depthAttachment : nullptr);
return device->createRenderPassUnique(vk::RenderPassCreateInfo(vk::RenderPassCreateFlags(), static_cast<uint32_t>(attachmentDescriptions.size()), attachmentDescriptions.data(), 1,
&subpassDescription));
}
VkBool32 debugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT /*objectType*/, uint64_t /*object*/, size_t /*location*/, int32_t /*messageCode*/, const char* /*pLayerPrefix*/, const char* pMessage, void* /*pUserData*/)
@@ -244,7 +260,7 @@ namespace vk
{
// get the first index into queueFamiliyProperties which supports graphics
size_t graphicsQueueFamilyIndex = std::distance(queueFamilyProperties.begin(), std::find_if(queueFamilyProperties.begin(), queueFamilyProperties.end(),
[](vk::QueueFamilyProperties const& qfp) { return qfp.queueFlags & vk::QueueFlagBits::eGraphics; }));
[](vk::QueueFamilyProperties const& qfp) { return qfp.queueFlags & vk::QueueFlagBits::eGraphics; }));
assert(graphicsQueueFamilyIndex < queueFamilyProperties.size());
return checked_cast<uint32_t>(graphicsQueueFamilyIndex);
@@ -331,9 +347,24 @@ namespace vk
return extensions;
}
vk::Format pickDepthFormat(vk::PhysicalDevice const& physicalDevice)
{
std::vector<vk::Format> candidates = {vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint};
for (vk::Format format : candidates)
{
vk::FormatProperties props = physicalDevice.getFormatProperties(format);
if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment)
{
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
vk::PresentModeKHR pickPresentMode(std::vector<vk::PresentModeKHR> const& presentModes)
{
vk::PresentModeKHR pickedMode = vk::PresentModeKHR::eFifo;;
vk::PresentModeKHR pickedMode = vk::PresentModeKHR::eFifo;
for(const auto& presentMode : presentModes)
{
if(presentMode == vk::PresentModeKHR::eMailbox)
@@ -382,7 +413,7 @@ namespace vk
return pickedFormat;
}
void setImageLayout(vk::UniqueCommandBuffer &commandBuffer, vk::Image image, vk::Format format, vk::ImageLayout oldImageLayout, vk::ImageLayout newImageLayout)
void setImageLayout(vk::UniqueCommandBuffer const& commandBuffer, vk::Image image, vk::Format format, vk::ImageLayout oldImageLayout, vk::ImageLayout newImageLayout)
{
vk::AccessFlags sourceAccessMask;
switch (oldImageLayout)
@@ -450,6 +481,9 @@ namespace vk
case vk::ImageLayout::eColorAttachmentOptimal:
destinationStage = vk::PipelineStageFlagBits::eColorAttachmentOutput;
break;
case vk::ImageLayout::eDepthStencilAttachmentOptimal:
destinationStage = vk::PipelineStageFlagBits::eEarlyFragmentTests;
break;
case vk::ImageLayout::eGeneral:
destinationStage = vk::PipelineStageFlagBits::eHost;
break;
@@ -466,7 +500,7 @@ namespace vk
}
vk::ImageAspectFlags aspectMask;
if (newImageLayout == vk::ImageLayout::eDepthAttachmentStencilReadOnlyOptimal)
if (newImageLayout == vk::ImageLayout::eDepthStencilAttachmentOptimal)
{
aspectMask = vk::ImageAspectFlagBits::eDepth;
if (format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD24UnormS8Uint)
@@ -493,18 +527,63 @@ namespace vk
;
}
void updateDescriptorSets(vk::UniqueDevice &device, vk::UniqueDescriptorSet &descriptorSet, vk::DescriptorType descriptorType, vk::DescriptorBufferInfo const* descriptorBufferInfo, vk::DescriptorImageInfo const* descriptorImageInfo)
void updateDescriptorSets(vk::UniqueDevice const& device, vk::UniqueDescriptorSet const& descriptorSet, std::map<vk::DescriptorType, vk::UniqueBuffer const&> const& bufferData,
vk::su::TextureData const& textureData)
{
std::vector<vk::DescriptorBufferInfo> bufferInfos;
bufferInfos.reserve(bufferData.size());
std::vector<vk::WriteDescriptorSet> writeDescriptorSets;
writeDescriptorSets.push_back(vk::WriteDescriptorSet(descriptorSet.get(), 0, 0, 1, descriptorType, nullptr, descriptorBufferInfo, nullptr));
if (descriptorImageInfo)
writeDescriptorSets.reserve(bufferData.size() + 1);
uint32_t dstBinding = 0;
for (auto const& bd : bufferData)
{
writeDescriptorSets.push_back(vk::WriteDescriptorSet(descriptorSet.get(), 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, descriptorImageInfo, nullptr, nullptr));
bufferInfos.push_back(vk::DescriptorBufferInfo(*bd.second, 0, VK_WHOLE_SIZE));
writeDescriptorSets.push_back(vk::WriteDescriptorSet(*descriptorSet, dstBinding++, 0, 1, bd.first, nullptr, &bufferInfos.back()));
}
vk::DescriptorImageInfo imageInfo(*textureData.textureSampler, *textureData.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal);
writeDescriptorSets.push_back(vk::WriteDescriptorSet(*descriptorSet, dstBinding, 0, 1, vk::DescriptorType::eCombinedImageSampler, &imageInfo, nullptr, nullptr));
device->updateDescriptorSets(writeDescriptorSets, nullptr);
}
void updateDescriptorSets(vk::UniqueDevice const& device, vk::UniqueDescriptorSet const& descriptorSet, std::map<vk::DescriptorType, vk::UniqueBuffer const&> const& bufferData,
std::vector<vk::su::TextureData> const& textureData)
{
std::vector<vk::DescriptorBufferInfo> bufferInfos;
bufferInfos.reserve(bufferData.size());
std::vector<vk::WriteDescriptorSet> writeDescriptorSets;
writeDescriptorSets.reserve(bufferData.size() + textureData.empty() ? 0 : 1);
uint32_t dstBinding = 0;
for (auto const& bd : bufferData)
{
bufferInfos.push_back(vk::DescriptorBufferInfo(*bd.second, 0, VK_WHOLE_SIZE));
writeDescriptorSets.push_back(vk::WriteDescriptorSet(*descriptorSet, dstBinding++, 0, 1, bd.first, nullptr, &bufferInfos.back()));
}
std::vector<vk::DescriptorImageInfo> imageInfos;
if (!textureData.empty())
{
imageInfos.reserve(textureData.size());
for (auto const& td : textureData)
{
imageInfos.push_back(vk::DescriptorImageInfo(*td.textureSampler, *td.imageData->imageView, vk::ImageLayout::eShaderReadOnlyOptimal));
}
writeDescriptorSets.push_back(vk::WriteDescriptorSet(*descriptorSet, dstBinding, 0, checked_cast<uint32_t>(imageInfos.size()), vk::DescriptorType::eCombinedImageSampler, imageInfos.data(),
nullptr, nullptr));
}
device->updateDescriptorSets(writeDescriptorSets, nullptr);
}
BufferData::BufferData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::DeviceSize size, vk::BufferUsageFlags usage, vk::MemoryPropertyFlags propertyFlags)
#if !defined(NDEBUG)
: m_size(size)
, m_usage(usage)
, m_propertyFlags(propertyFlags)
#endif
{
buffer = device->createBufferUnique(vk::BufferCreateInfo(vk::BufferCreateFlags(), size, usage));
deviceMemory = vk::su::allocateMemory(device, physicalDevice.getMemoryProperties(), device->getBufferMemoryRequirements(buffer.get()), propertyFlags);
@@ -512,13 +591,17 @@ namespace vk
}
DepthBufferData::DepthBufferData(vk::PhysicalDevice &physicalDevice, vk::UniqueDevice & device, vk::Format format, vk::Extent2D const& extent)
: ImageData(physicalDevice, device, format, extent, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::ImageLayout::eUndefined, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageAspectFlagBits::eDepth)
{}
: ImageData(physicalDevice, device, format, extent, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::ImageLayout::eUndefined,
vk::MemoryPropertyFlagBits::eDeviceLocal, vk::ImageAspectFlagBits::eDepth)
{
}
ImageData::ImageData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::Format format_, vk::Extent2D const& extent, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::ImageLayout initialLayout, vk::MemoryPropertyFlags memoryProperties, vk::ImageAspectFlags aspectMask)
ImageData::ImageData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::Format format_, vk::Extent2D const& extent, vk::ImageTiling tiling,
vk::ImageUsageFlags usage, vk::ImageLayout initialLayout, vk::MemoryPropertyFlags memoryProperties, vk::ImageAspectFlags aspectMask)
: format(format_)
{
vk::ImageCreateInfo imageCreateInfo(vk::ImageCreateFlags(), vk::ImageType::e2D, format, vk::Extent3D(extent, 1), 1, 1, vk::SampleCountFlagBits::e1, tiling, usage | vk::ImageUsageFlagBits::eSampled, vk::SharingMode::eExclusive, 0, nullptr, initialLayout);
vk::ImageCreateInfo imageCreateInfo(vk::ImageCreateFlags(), vk::ImageType::e2D, format, vk::Extent3D(extent, 1), 1, 1,
vk::SampleCountFlagBits::e1, tiling, usage | vk::ImageUsageFlagBits::eSampled, vk::SharingMode::eExclusive, 0, nullptr, initialLayout);
image = device->createImageUnique(imageCreateInfo);
deviceMemory = vk::su::allocateMemory(device, physicalDevice.getMemoryProperties(), device->getImageMemoryRequirements(image.get()), memoryProperties);
@@ -541,11 +624,13 @@ namespace vk
#endif
}
SwapChainData::SwapChainData(vk::PhysicalDevice &physicalDevice, vk::UniqueDevice &device, vk::UniqueSurfaceKHR &surface, vk::Extent2D const& extent, vk::ImageUsageFlags usage, uint32_t graphicsQueueFamilyIndex, uint32_t presentQueueFamilyIndex)
SwapChainData::SwapChainData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::SurfaceKHR const& surface, vk::Extent2D const& extent, vk::ImageUsageFlags usage,
vk::UniqueSwapchainKHR const& oldSwapChain, uint32_t graphicsQueueFamilyIndex, uint32_t presentQueueFamilyIndex)
{
colorFormat = vk::su::pickSurfaceFormat(physicalDevice.getSurfaceFormatsKHR(surface.get())).format;
vk::SurfaceFormatKHR surfaceFormat = vk::su::pickSurfaceFormat(physicalDevice.getSurfaceFormatsKHR(surface));
colorFormat = surfaceFormat.format;
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get());
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface);
VkExtent2D swapchainExtent;
if (surfaceCapabilities.currentExtent.width == std::numeric_limits<uint32_t>::max())
{
@@ -563,12 +648,12 @@ namespace vk
(surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied) ? vk::CompositeAlphaFlagBitsKHR::ePreMultiplied :
(surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::ePostMultiplied) ? vk::CompositeAlphaFlagBitsKHR::ePostMultiplied :
(surfaceCapabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::eInherit) ? vk::CompositeAlphaFlagBitsKHR::eInherit : vk::CompositeAlphaFlagBitsKHR::eOpaque;
vk::PresentModeKHR presentMode = vk::su::pickPresentMode(physicalDevice.getSurfacePresentModesKHR(*surface));
vk::SwapchainCreateInfoKHR swapChainCreateInfo({}, surface.get(), surfaceCapabilities.minImageCount, colorFormat, vk::ColorSpaceKHR::eSrgbNonlinear, swapchainExtent, 1, usage,
vk::SharingMode::eExclusive, 0, nullptr, preTransform, compositeAlpha, presentMode, true, nullptr);
uint32_t queueFamilyIndices[2] = { graphicsQueueFamilyIndex, presentQueueFamilyIndex };
vk::PresentModeKHR presentMode = vk::su::pickPresentMode(physicalDevice.getSurfacePresentModesKHR(surface));
vk::SwapchainCreateInfoKHR swapChainCreateInfo({}, surface, surfaceCapabilities.minImageCount, colorFormat, surfaceFormat.colorSpace, swapchainExtent, 1, usage, vk::SharingMode::eExclusive,
0, nullptr, preTransform, compositeAlpha, presentMode, true, *oldSwapChain);
if (graphicsQueueFamilyIndex != presentQueueFamilyIndex)
{
uint32_t queueFamilyIndices[2] = { graphicsQueueFamilyIndex, presentQueueFamilyIndex };
// If the graphics and present queues are from different queue families, we either have to explicitly transfer ownership of images between
// the queues, or we have to create the swapchain with imageSharingMode as vk::SharingMode::eConcurrent
swapChainCreateInfo.imageSharingMode = vk::SharingMode::eConcurrent;
@@ -589,7 +674,7 @@ namespace vk
}
}
void CheckerboardTextureCreator::operator()(void* data, vk::Extent2D &extent) const
void CheckerboardImageGenerator::operator()(void* data, vk::Extent2D &extent) const
{
// Checkerboard of 16x16 pixel squares
unsigned char *pImageMemory = static_cast<unsigned char*>(data);
@@ -607,11 +692,11 @@ namespace vk
}
}
MonochromeTextureGenerator::MonochromeTextureGenerator(std::array<unsigned char, 3> const& rgb_)
: rgb(rgb_)
MonochromeImageGenerator::MonochromeImageGenerator(std::array<unsigned char, 3> const& rgb)
: m_rgb(rgb)
{}
void MonochromeTextureGenerator::operator()(void* data, vk::Extent2D &extent) const
void MonochromeImageGenerator::operator()(void* data, vk::Extent2D &extent) const
{
// fill in with the monochrome color
unsigned char *pImageMemory = static_cast<unsigned char*>(data);
@@ -619,16 +704,31 @@ namespace vk
{
for (uint32_t col = 0; col < extent.width; col++)
{
pImageMemory[0] = rgb[0];
pImageMemory[1] = rgb[1];
pImageMemory[2] = rgb[2];
pImageMemory[0] = m_rgb[0];
pImageMemory[1] = m_rgb[1];
pImageMemory[2] = m_rgb[2];
pImageMemory[3] = 255;
pImageMemory += 4;
}
}
}
TextureData::TextureData(vk::PhysicalDevice &physicalDevice, vk::UniqueDevice &device, vk::Extent2D const& extent_, vk::ImageUsageFlags usageFlags, vk::FormatFeatureFlags formatFeatureFlags)
PixelsImageGenerator::PixelsImageGenerator(vk::Extent2D const& extent, size_t channels, unsigned char const* pixels)
: m_extent(extent)
, m_channels(channels)
, m_pixels(pixels)
{
assert(m_channels == 4);
}
void PixelsImageGenerator::operator()(void* data, vk::Extent2D & extent) const
{
assert(extent == m_extent);
memcpy(data, m_pixels, m_extent.width * m_extent.height * m_channels);
}
TextureData::TextureData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::Extent2D const& extent_, vk::ImageUsageFlags usageFlags,
vk::FormatFeatureFlags formatFeatureFlags, bool anisotropyEnable, bool forceStaging)
: format(vk::Format::eR8G8B8A8Unorm)
, extent(extent_)
{
@@ -636,7 +736,7 @@ namespace vk
vk::FormatProperties formatProperties = physicalDevice.getFormatProperties(format);
formatFeatureFlags |= vk::FormatFeatureFlagBits::eSampledImage;
needsStaging = (formatProperties.linearTilingFeatures & formatFeatureFlags) != formatFeatureFlags;
needsStaging = forceStaging || ((formatProperties.linearTilingFeatures & formatFeatureFlags) != formatFeatureFlags);
vk::ImageTiling imageTiling;
vk::ImageLayout initialLayout;
vk::MemoryPropertyFlags requirements;
@@ -654,11 +754,12 @@ namespace vk
initialLayout = vk::ImageLayout::ePreinitialized;
requirements = vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostVisible;
}
imageData = std::make_unique<ImageData>(physicalDevice, device, format, extent, imageTiling, usageFlags | vk::ImageUsageFlagBits::eSampled, initialLayout, requirements, vk::ImageAspectFlagBits::eColor);
imageData = std::make_unique<ImageData>(physicalDevice, device, format, extent, imageTiling, usageFlags | vk::ImageUsageFlagBits::eSampled, initialLayout, requirements,
vk::ImageAspectFlagBits::eColor);
textureSampler = device->createSamplerUnique(vk::SamplerCreateInfo(vk::SamplerCreateFlags(), vk::Filter::eNearest, vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest,
vk::SamplerAddressMode::eClampToEdge, vk::SamplerAddressMode::eClampToEdge, vk::SamplerAddressMode::eClampToEdge, 0.0f, false, 1.0f, false, vk::CompareOp::eNever, 0.0f, 0.0f
, vk::BorderColor::eFloatOpaqueWhite));
textureSampler = device->createSamplerUnique(vk::SamplerCreateInfo(vk::SamplerCreateFlags(), vk::Filter::eLinear, vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear,
vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat, 0.0f, anisotropyEnable,
16.0f, false, vk::CompareOp::eNever, 0.0f, 0.0f, vk::BorderColor::eFloatOpaqueBlack));
}
UUID::UUID(uint8_t data[VK_UUID_SIZE])
@@ -671,11 +772,11 @@ namespace vk
{
switch (uMsg)
{
case WM_CLOSE:
PostQuitMessage(0);
break;
default:
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
default:
break;
}
return (DefWindowProc(hWnd, uMsg, wParam, lParam));
}
@@ -705,7 +806,7 @@ namespace vk
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);
HWND window = CreateWindowEx(0, className.c_str(), windowName.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_SYSMENU, 100, 100, windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top, nullptr, nullptr, instance, nullptr);
windowRect.bottom - windowRect.top, nullptr, nullptr, instance, nullptr);
if (!window)
{
throw std::runtime_error("Failed to create window -> terminating");
@@ -732,4 +833,4 @@ std::ostream& operator<<(std::ostream& os, vk::su::UUID const& uuid)
}
os << std::setfill(' ');
return os;
}
}

View File

@@ -1,3 +1,5 @@
#pragma once
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,6 +17,7 @@
#include "vulkan/vulkan.hpp"
#include <iostream>
#include <map>
namespace vk
{
@@ -27,14 +30,62 @@ namespace vk
BufferData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::DeviceSize size, vk::BufferUsageFlags usage,
vk::MemoryPropertyFlags propertyFlags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
template <typename DataType>
void upload(vk::UniqueDevice const& device, DataType const& data) const
{
assert((m_propertyFlags & vk::MemoryPropertyFlagBits::eHostCoherent) && (m_propertyFlags & vk::MemoryPropertyFlagBits::eHostVisible));
assert(sizeof(DataType) <= m_size);
void* dataPtr = device->mapMemory(*this->deviceMemory, 0, sizeof(DataType));
memcpy(dataPtr, &data, sizeof(DataType));
device->unmapMemory(*this->deviceMemory);
}
template <typename DataType>
void upload(vk::UniqueDevice const& device, std::vector<DataType> const& data) const
{
assert((m_propertyFlags & vk::MemoryPropertyFlagBits::eHostCoherent) && (m_propertyFlags & vk::MemoryPropertyFlagBits::eHostVisible));
size_t dataSize = data.size() * sizeof(DataType);
assert(dataSize <= m_size);
void* dataPtr = device->mapMemory(*this->deviceMemory, 0, dataSize);
memcpy(dataPtr, data.data(), dataSize);
device->unmapMemory(*this->deviceMemory);
}
template <typename DataType>
void upload(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::UniqueCommandPool const& commandPool, vk::Queue queue, std::vector<DataType> const& data) const
{
assert(m_usage & vk::BufferUsageFlagBits::eTransferDst);
assert(m_propertyFlags & vk::MemoryPropertyFlagBits::eDeviceLocal);
size_t dataSize = data.size() * sizeof(DataType);
assert(dataSize <= m_size);
vk::su::BufferData stagingBuffer(physicalDevice, device, dataSize, vk::BufferUsageFlagBits::eTransferSrc);
void* dataPtr = device->mapMemory(*stagingBuffer.deviceMemory, 0, dataSize);
memcpy(dataPtr, data.data(), dataSize);
device->unmapMemory(*stagingBuffer.deviceMemory);
vk::UniqueCommandBuffer commandBuffer = std::move(device->allocateCommandBuffersUnique(vk::CommandBufferAllocateInfo(*commandPool, vk::CommandBufferLevel::ePrimary, 1)).front());
vk::su::oneTimeSubmit(commandBuffer, queue, [&]() { commandBuffer->copyBuffer(*stagingBuffer.buffer, *this->buffer, vk::BufferCopy(0, 0, dataSize)); });
}
vk::UniqueBuffer buffer;
vk::UniqueDeviceMemory deviceMemory;
#if !defined(NDEBUG)
private:
vk::DeviceSize m_size;
vk::BufferUsageFlags m_usage;
vk::MemoryPropertyFlags m_propertyFlags;
#endif)
};
struct ImageData
{
ImageData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::Format format, vk::Extent2D const& extent, vk::ImageTiling tiling, vk::ImageUsageFlags usage
, vk::ImageLayout initialLayout, vk::MemoryPropertyFlags memoryProperties, vk::ImageAspectFlags aspectMask);
, vk::ImageLayout initialLayout, vk::MemoryPropertyFlags memoryProperties, vk::ImageAspectFlags aspectMask);
vk::Format format;
vk::UniqueImage image;
@@ -58,7 +109,8 @@ namespace vk
struct SwapChainData
{
SwapChainData(vk::PhysicalDevice &physicalDevice, vk::UniqueDevice &device, vk::UniqueSurfaceKHR &surface, vk::Extent2D const& extent, vk::ImageUsageFlags usage, uint32_t graphicsFamilyIndex, uint32_t presentFamilyIndex);
SwapChainData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::SurfaceKHR const& surface, vk::Extent2D const& extent, vk::ImageUsageFlags usage,
vk::UniqueSwapchainKHR const& oldSwapChain, uint32_t graphicsFamilyIndex, uint32_t presentFamilyIndex);
vk::Format colorFormat;
vk::UniqueSwapchainKHR swapChain;
@@ -66,36 +118,49 @@ namespace vk
std::vector<vk::UniqueImageView> imageViews;
};
class CheckerboardTextureCreator
class CheckerboardImageGenerator
{
public:
public:
void operator()(void* data, vk::Extent2D &extent) const;
};
class MonochromeTextureGenerator
class MonochromeImageGenerator
{
public:
MonochromeTextureGenerator(std::array<unsigned char, 3> const& rgb_);
public:
MonochromeImageGenerator(std::array<unsigned char, 3> const& rgb);
void operator()(void* data, vk::Extent2D &extent) const;
private:
std::array<unsigned char, 3> const& rgb;
private:
std::array<unsigned char, 3> const& m_rgb;
};
class PixelsImageGenerator
{
public:
PixelsImageGenerator(vk::Extent2D const& extent, size_t channels, unsigned char const* pixels);
void operator()(void* data, vk::Extent2D & extent) const;
private:
vk::Extent2D m_extent;
size_t m_channels;
unsigned char const* m_pixels;
};
struct TextureData
{
TextureData(vk::PhysicalDevice &physicalDevice, vk::UniqueDevice &device, vk::Extent2D const& extent_ = {256, 256}, vk::ImageUsageFlags usageFlags = {},
vk::FormatFeatureFlags formatFeatureFlags = {});
TextureData(vk::PhysicalDevice const& physicalDevice, vk::UniqueDevice const& device, vk::Extent2D const& extent_ = {256, 256}, vk::ImageUsageFlags usageFlags = {},
vk::FormatFeatureFlags formatFeatureFlags = {}, bool anisotropyEnable = false, bool forceStaging = false);
template <typename TextureCreator>
void setTexture(vk::UniqueDevice &device, vk::UniqueCommandBuffer &commandBuffer, TextureCreator const& textureCreator)
template <typename ImageGenerator>
void setImage(vk::UniqueDevice const& device, vk::UniqueCommandBuffer const& commandBuffer, ImageGenerator const& imageGenerator)
{
void* data = needsStaging
? device->mapMemory(stagingBufferData->deviceMemory.get(), 0, device->getBufferMemoryRequirements(stagingBufferData->buffer.get()).size)
: device->mapMemory(imageData->deviceMemory.get(), 0, device->getImageMemoryRequirements(imageData->image.get()).size);
textureCreator(data, extent);
imageGenerator(data, extent);
device->unmapMemory(needsStaging ? stagingBufferData->deviceMemory.get() : imageData->deviceMemory.get());
if (needsStaging)
@@ -124,7 +189,7 @@ namespace vk
struct UUID
{
public:
public:
UUID(uint8_t data[VK_UUID_SIZE]);
uint8_t m_data[VK_UUID_SIZE];
@@ -173,16 +238,30 @@ namespace vk
return v < lo ? lo : hi < v ? hi : v;
}
template <typename Func, typename... Args>
void oneTimeSubmit(vk::UniqueCommandBuffer const& commandBuffer, vk::Queue const& queue, Func const& func, Args... args)
{
commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
func(args...);
commandBuffer->end();
queue.submit(vk::SubmitInfo(0, nullptr, nullptr, 1, &(*commandBuffer)), nullptr);
queue.waitIdle();
}
vk::UniqueDeviceMemory allocateMemory(vk::UniqueDevice const& device, vk::PhysicalDeviceMemoryProperties const& memoryProperties, vk::MemoryRequirements const& memoryRequirements,
vk::MemoryPropertyFlags memoryPropertyFlags);
vk::UniqueCommandPool createCommandPool(vk::UniqueDevice &device, uint32_t queueFamilyIndex);
vk::UniqueDebugReportCallbackEXT createDebugReportCallback(vk::UniqueInstance &instance);
vk::UniqueDescriptorPool createDescriptorPool(vk::UniqueDevice &device, std::vector<vk::DescriptorPoolSize> const& poolSizes);
vk::UniqueDescriptorSetLayout createDescriptorSetLayout(vk::UniqueDevice &device, std::vector<std::pair<vk::DescriptorType, vk::ShaderStageFlags>> const& bindingData, vk::DescriptorSetLayoutCreateFlags flags = {});
vk::UniqueDescriptorSetLayout createDescriptorSetLayout(vk::UniqueDevice const& device, std::vector<std::tuple<vk::DescriptorType, uint32_t, vk::ShaderStageFlags>> const& bindingData,
vk::DescriptorSetLayoutCreateFlags flags = {});
vk::UniqueDevice createDevice(vk::PhysicalDevice physicalDevice, uint32_t queueFamilyIndex, std::vector<std::string> const& extensions = {}, vk::PhysicalDeviceFeatures const* physicalDeviceFeatures = nullptr, void const* pNext = nullptr);
std::vector<vk::UniqueFramebuffer> createFramebuffers(vk::UniqueDevice &device, vk::UniqueRenderPass &renderPass, std::vector<vk::UniqueImageView> const& imageViews, vk::UniqueImageView const& depthImageView, vk::Extent2D const& extent);
vk::UniquePipeline createGraphicsPipeline(vk::UniqueDevice &device, vk::UniquePipelineCache &pipelineCache, vk::UniqueShaderModule &vertexShaderModule,
vk::UniqueShaderModule &fragmentShaderModule, uint32_t vertexStride, bool depthBuffered, bool textured, vk::UniquePipelineLayout &pipelineLayout, vk::UniqueRenderPass &renderPass);
vk::UniquePipeline createGraphicsPipeline(vk::UniqueDevice const& device, vk::UniquePipelineCache const& pipelineCache,
std::pair<vk::ShaderModule, vk::SpecializationInfo const*> const& vertexShaderData,
std::pair<vk::ShaderModule, vk::SpecializationInfo const*> const& fragmentShaderData, uint32_t vertexStride,
std::vector<std::pair<vk::Format, uint32_t>> const& vertexInputAttributeFormatOffset, vk::FrontFace frontFace, bool depthBuffered,
vk::UniquePipelineLayout const& pipelineLayout, vk::UniqueRenderPass const& renderPass);
vk::UniqueInstance createInstance(std::string const& appName, std::string const& engineName, std::vector<std::string> const& extensions = {}, uint32_t apiVersion = VK_API_VERSION_1_0);
vk::UniqueRenderPass createRenderPass(vk::UniqueDevice &device, vk::Format colorFormat, vk::Format depthFormat, vk::AttachmentLoadOp loadOp = vk::AttachmentLoadOp::eClear, vk::ImageLayout colorFinalLayout = vk::ImageLayout::ePresentSrcKHR);
VkBool32 debugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData);
@@ -191,11 +270,15 @@ namespace vk
uint32_t findMemoryType(vk::PhysicalDeviceMemoryProperties const& memoryProperties, uint32_t typeBits, vk::MemoryPropertyFlags requirementsMask);
std::vector<std::string> getDeviceExtensions();
std::vector<std::string> getInstanceExtensions();
vk::Format pickDepthFormat(vk::PhysicalDevice const& physicalDevice);
vk::PresentModeKHR pickPresentMode(std::vector<vk::PresentModeKHR> const& presentModes);
vk::SurfaceFormatKHR pickSurfaceFormat(std::vector<vk::SurfaceFormatKHR> const& formats);
void setImageLayout(vk::UniqueCommandBuffer &commandBuffer, vk::Image image, vk::Format format, vk::ImageLayout oldImageLayout, vk::ImageLayout newImageLayout);
void setImageLayout(vk::UniqueCommandBuffer const& commandBuffer, vk::Image image, vk::Format format, vk::ImageLayout oldImageLayout, vk::ImageLayout newImageLayout);
void submitAndWait(vk::UniqueDevice &device, vk::Queue queue, vk::UniqueCommandBuffer &commandBuffer);
void updateDescriptorSets(vk::UniqueDevice &device, vk::UniqueDescriptorSet &descriptorSet, vk::DescriptorType descriptorType, vk::DescriptorBufferInfo const* descriptorBufferInfo, vk::DescriptorImageInfo const* descriptorImageInfo = nullptr);
void updateDescriptorSets(vk::UniqueDevice const& device, vk::UniqueDescriptorSet const& descriptorSet, std::map<vk::DescriptorType, vk::UniqueBuffer const&> const& bufferData,
vk::su::TextureData const& textureData);
void updateDescriptorSets(vk::UniqueDevice const& device, vk::UniqueDescriptorSet const& descriptorSet, std::map<vk::DescriptorType, vk::UniqueBuffer const&> const& bufferData,
std::vector<vk::su::TextureData> const& textureData);
#if defined(VK_USE_PLATFORM_WIN32_KHR)
HWND initializeWindow(std::string const& className, std::string const& windowName, LONG width, LONG height);
@@ -205,4 +288,4 @@ namespace vk
}
}
std::ostream& operator<<(std::ostream& os, vk::su::UUID const& uuid);
std::ostream& operator<<(std::ostream& os, vk::su::UUID const& uuid);