Code cleanup

This commit is contained in:
Sascha Willems 2024-01-03 18:31:23 +01:00
parent 8f1a5e38f2
commit d8a3379e0b
5 changed files with 308 additions and 487 deletions

View file

@ -1,7 +1,7 @@
/* /*
* Vulkan Example - Dynamic uniform buffers * Vulkan Example - Dynamic uniform buffers
* *
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * Copyright (C) 2016-2023 by Sascha Willems - www.saschawillems.de
* *
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
* *
@ -54,15 +54,9 @@ void alignedFree(void* data)
class VulkanExample : public VulkanExampleBase class VulkanExample : public VulkanExampleBase
{ {
public: public:
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
vks::Buffer vertexBuffer; vks::Buffer vertexBuffer;
vks::Buffer indexBuffer; vks::Buffer indexBuffer;
uint32_t indexCount; uint32_t indexCount{ 0 };
struct { struct {
vks::Buffer view; vks::Buffer view;
@ -81,17 +75,17 @@ public:
// One big uniform buffer that contains all matrices // One big uniform buffer that contains all matrices
// Note that we need to manually allocate the data to cope for GPU-specific uniform buffer offset alignments // Note that we need to manually allocate the data to cope for GPU-specific uniform buffer offset alignments
struct UboDataDynamic { struct UboDataDynamic {
glm::mat4 *model = nullptr; glm::mat4* model{ nullptr };
} uboDataDynamic; } uboDataDynamic;
VkPipeline pipeline; VkPipeline pipeline{ VK_NULL_HANDLE };
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE };
VkDescriptorSet descriptorSet; VkDescriptorSet descriptorSet{ VK_NULL_HANDLE };
VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE };
float animationTimer = 0.0f; float animationTimer{ 0.0f };
size_t dynamicAlignment; size_t dynamicAlignment{ 0 };
VulkanExample() : VulkanExampleBase() VulkanExample() : VulkanExampleBase()
{ {
@ -104,23 +98,19 @@ public:
~VulkanExample() ~VulkanExample()
{ {
if (device) {
if (uboDataDynamic.model) { if (uboDataDynamic.model) {
alignedFree(uboDataDynamic.model); alignedFree(uboDataDynamic.model);
} }
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
vertexBuffer.destroy(); vertexBuffer.destroy();
indexBuffer.destroy(); indexBuffer.destroy();
uniformBuffers.view.destroy(); uniformBuffers.view.destroy();
uniformBuffers.dynamic.destroy(); uniformBuffers.dynamic.destroy();
} }
}
void buildCommandBuffers() void buildCommandBuffers()
{ {
@ -178,20 +168,6 @@ public:
} }
} }
void draw()
{
VulkanExampleBase::prepareFrame();
// Command buffer to be submitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void generateCube() void generateCube()
{ {
// Setup vertices indices for a colored cube // Setup vertices indices for a colored cube
@ -229,150 +205,78 @@ public:
indices.size() * sizeof(uint32_t), indices.size() * sizeof(uint32_t),
indices.data())); indices.data()));
} }
void setupDescriptors()
void setupVertexDescriptions()
{
// Binding description
vertices.bindingDescriptions = {
vks::initializers::vertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX),
};
// Attribute descriptions
vertices.attributeDescriptions = {
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, pos)), // Location 0 : Position
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, color)), // Location 1 : Color
};
vertices.inputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertices.bindingDescriptions.size());
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertices.attributeDescriptions.size());
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void setupDescriptorPool()
{
// Example uses one ubo and one image sampler
std::vector<VkDescriptorPoolSize> poolSizes =
{ {
// Pool
std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1),
// Dynamic uniform buffer
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1) vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1)
}; };
VkDescriptorPoolCreateInfo descriptorPoolInfo = VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()),
poolSizes.data(),
2);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout() // Layout
{ std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings =
{
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0),
// Dynamic uniform buffer
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_VERTEX_BIT, 1) vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_VERTEX_BIT, 1)
}; };
VkDescriptorSetLayoutCreateInfo descriptorLayout = VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
vks::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = // Set
vks::initializers::pipelineLayoutCreateInfo( VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets = { std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
// Binding 0 : Projection/View matrix uniform buffer // Binding 0 : Projection/View matrix as uniform buffer
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.view.descriptor), vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.view.descriptor),
// Binding 1 : Instance matrix as dynamic uniform buffer // Binding 1 : Instance matrix as dynamic uniform buffer
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, &uniformBuffers.dynamic.descriptor), vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, &uniformBuffers.dynamic.descriptor),
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
} }
void preparePipelines() void preparePipelines()
{ {
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = // Layout
vks::initializers::pipelineInputAssemblyStateCreateInfo( VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1);
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout));
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = // Pipeline
vks::initializers::pipelineRasterizationStateCreateInfo( VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VK_POLYGON_MODE_FILL, VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
VK_CULL_MODE_NONE, VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VK_FRONT_FACE_COUNTER_CLOCKWISE, VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
0); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState = VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0);
vks::initializers::pipelineColorBlendAttachmentState( std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
0xf, VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables);
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vks::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vks::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vks::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()),
0);
// Load shaders
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
// Vertex bindings and attributes
VkVertexInputBindingDescription vertexInputBinding = {
vks::initializers::vertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX)
};
std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = {
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, pos)), // Location 0 : Position
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, color)), // Location 1 : Color
};
VkPipelineVertexInputStateCreateInfo vertexInputStateCI = vks::initializers::pipelineVertexInputStateCreateInfo();
vertexInputStateCI.vertexBindingDescriptionCount = 1;
vertexInputStateCI.pVertexBindingDescriptions = &vertexInputBinding;
vertexInputStateCI.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size());
vertexInputStateCI.pVertexAttributeDescriptions = vertexInputAttributes.data();
shaderStages[0] = loadShader(getShadersPath() + "dynamicuniformbuffer/base.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[0] = loadShader(getShadersPath() + "dynamicuniformbuffer/base.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getShadersPath() + "dynamicuniformbuffer/base.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); shaderStages[1] = loadShader(getShadersPath() + "dynamicuniformbuffer/base.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo = VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0);
vks::initializers::pipelineCreateInfo( pipelineCreateInfo.pVertexInputState = &vertexInputStateCI;
pipelineLayout,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pColorBlendState = &colorBlendState;
@ -382,7 +286,6 @@ public:
pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pStages = shaderStages.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline)); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline));
} }
@ -439,7 +342,7 @@ public:
} }
updateUniformBuffers(); updateUniformBuffers();
updateDynamicUniformBuffer(true); updateDynamicUniformBuffer();
} }
void updateUniformBuffers() void updateUniformBuffers()
@ -451,11 +354,11 @@ public:
memcpy(uniformBuffers.view.mapped, &uboVS, sizeof(uboVS)); memcpy(uniformBuffers.view.mapped, &uboVS, sizeof(uboVS));
} }
void updateDynamicUniformBuffer(bool force = false) void updateDynamicUniformBuffer()
{ {
// Update at max. 60 fps // Update at max. 60 fps
animationTimer += frameTimer; animationTimer += frameTimer;
if ((animationTimer <= 1.0f / 60.0f) && (!force)) { if (animationTimer <= 1.0f / 60.0f) {
return; return;
} }
@ -501,28 +404,29 @@ public:
{ {
VulkanExampleBase::prepare(); VulkanExampleBase::prepare();
generateCube(); generateCube();
setupVertexDescriptions();
prepareUniformBuffers(); prepareUniformBuffers();
setupDescriptorSetLayout(); setupDescriptors();
preparePipelines(); preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers(); buildCommandBuffers();
prepared = true; prepared = true;
} }
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
return; return;
draw();
if (!paused)
updateDynamicUniformBuffer();
}
virtual void viewChanged()
{
updateUniformBuffers(); updateUniformBuffers();
updateDynamicUniformBuffer();
draw();
} }
}; };

View file

@ -36,36 +36,36 @@ public:
} uniformBuffers; } uniformBuffers;
struct { struct {
VkPipeline attachmentWrite; VkPipeline attachmentWrite{ VK_NULL_HANDLE };
VkPipeline attachmentRead; VkPipeline attachmentRead{ VK_NULL_HANDLE };
} pipelines; } pipelines;
struct { struct {
VkPipelineLayout attachmentWrite; VkPipelineLayout attachmentWrite{ VK_NULL_HANDLE };
VkPipelineLayout attachmentRead; VkPipelineLayout attachmentRead{ VK_NULL_HANDLE };
} pipelineLayouts; } pipelineLayouts;
struct { struct {
VkDescriptorSet attachmentWrite; VkDescriptorSet attachmentWrite{ VK_NULL_HANDLE };
std::vector<VkDescriptorSet> attachmentRead; std::vector<VkDescriptorSet> attachmentRead{ VK_NULL_HANDLE };
} descriptorSets; } descriptorSets;
struct { struct {
VkDescriptorSetLayout attachmentWrite; VkDescriptorSetLayout attachmentWrite{ VK_NULL_HANDLE };
VkDescriptorSetLayout attachmentRead; VkDescriptorSetLayout attachmentRead{ VK_NULL_HANDLE };
} descriptorSetLayouts; } descriptorSetLayouts;
struct FrameBufferAttachment { struct FrameBufferAttachment {
VkImage image = VK_NULL_HANDLE; VkImage image{ VK_NULL_HANDLE };
VkDeviceMemory memory = VK_NULL_HANDLE; VkDeviceMemory memory{ VK_NULL_HANDLE };
VkImageView view = VK_NULL_HANDLE; VkImageView view{ VK_NULL_HANDLE };
VkFormat format; VkFormat format;
}; };
struct Attachments { struct Attachments {
FrameBufferAttachment color, depth; FrameBufferAttachment color, depth;
}; };
std::vector<Attachments> attachments; std::vector<Attachments> attachments;
VkExtent2D attachmentSize; VkExtent2D attachmentSize{};
const VkFormat colorFormat = VK_FORMAT_R8G8B8A8_UNORM; const VkFormat colorFormat = VK_FORMAT_R8G8B8A8_UNORM;
@ -82,9 +82,7 @@ public:
~VulkanExample() ~VulkanExample()
{ {
// Clean up used Vulkan resources if (device) {
// Note : Inherited destructor cleans up resources stored in base class
for (uint32_t i = 0; i < attachments.size(); i++) { for (uint32_t i = 0; i < attachments.size(); i++) {
vkDestroyImageView(device, attachments[i].color.view, nullptr); vkDestroyImageView(device, attachments[i].color.view, nullptr);
vkDestroyImage(device, attachments[i].color.image, nullptr); vkDestroyImage(device, attachments[i].color.image, nullptr);
@ -106,6 +104,7 @@ public:
uniformBuffers.matrices.destroy(); uniformBuffers.matrices.destroy();
uniformBuffers.params.destroy(); uniformBuffers.params.destroy();
} }
}
void clearAttachment(FrameBufferAttachment* attachment) void clearAttachment(FrameBufferAttachment* attachment)
{ {
@ -596,15 +595,8 @@ public:
{ {
if (!prepared) if (!prepared)
return; return;
updateUniformBuffers();
draw(); draw();
if (camera.updated) {
updateUniformBuffers();
}
}
virtual void viewChanged()
{
updateUniformBuffers();
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)

View file

@ -24,51 +24,48 @@ public:
struct { struct {
vks::Texture2DArray rocks; vks::Texture2DArray rocks;
vks::Texture2D planet; vks::Texture2D planet;
} textures; } textures{};
struct { struct {
vkglTF::Model rock; vkglTF::Model rock;
vkglTF::Model planet; vkglTF::Model planet;
} models; } models{};
// Per-instance data block // We provide position, rotation and scale per mesh instance
struct InstanceData { struct InstanceData {
glm::vec3 pos; glm::vec3 pos;
glm::vec3 rot; glm::vec3 rot;
float scale; float scale{ 0.0f };
uint32_t texIndex; uint32_t texIndex{ 0 };
}; };
// Contains the instanced data // Contains the instanced data
struct InstanceBuffer { struct InstanceBuffer {
VkBuffer buffer = VK_NULL_HANDLE; VkBuffer buffer{ VK_NULL_HANDLE };
VkDeviceMemory memory = VK_NULL_HANDLE; VkDeviceMemory memory{ VK_NULL_HANDLE };
size_t size = 0; size_t size = 0;
VkDescriptorBufferInfo descriptor; VkDescriptorBufferInfo descriptor{ VK_NULL_HANDLE };
} instanceBuffer; } instanceBuffer;
struct UBOVS { struct UniformData {
glm::mat4 projection; glm::mat4 projection;
glm::mat4 view; glm::mat4 view;
glm::vec4 lightPos = glm::vec4(0.0f, -5.0f, 0.0f, 1.0f); glm::vec4 lightPos = glm::vec4(0.0f, -5.0f, 0.0f, 1.0f);
float locSpeed = 0.0f; float locSpeed = 0.0f;
float globSpeed = 0.0f; float globSpeed = 0.0f;
} uboVS; } uniformData;
vks::Buffer uniformBuffer;
VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE };
struct { struct {
vks::Buffer scene; VkPipeline instancedRocks{ VK_NULL_HANDLE };
} uniformBuffers; VkPipeline planet{ VK_NULL_HANDLE };
VkPipeline starfield{ VK_NULL_HANDLE };
VkPipelineLayout pipelineLayout;
struct {
VkPipeline instancedRocks;
VkPipeline planet;
VkPipeline starfield;
} pipelines; } pipelines;
VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE };
struct { struct {
VkDescriptorSet instancedRocks; VkDescriptorSet instancedRocks{ VK_NULL_HANDLE };
VkDescriptorSet planet; VkDescriptorSet planet{ VK_NULL_HANDLE };
} descriptorSets; } descriptorSets;
VulkanExample() : VulkanExampleBase() VulkanExample() : VulkanExampleBase()
@ -82,6 +79,7 @@ public:
~VulkanExample() ~VulkanExample()
{ {
if (device) {
vkDestroyPipeline(device, pipelines.instancedRocks, nullptr); vkDestroyPipeline(device, pipelines.instancedRocks, nullptr);
vkDestroyPipeline(device, pipelines.planet, nullptr); vkDestroyPipeline(device, pipelines.planet, nullptr);
vkDestroyPipeline(device, pipelines.starfield, nullptr); vkDestroyPipeline(device, pipelines.starfield, nullptr);
@ -91,7 +89,8 @@ public:
vkFreeMemory(device, instanceBuffer.memory, nullptr); vkFreeMemory(device, instanceBuffer.memory, nullptr);
textures.rocks.destroy(); textures.rocks.destroy();
textures.planet.destroy(); textures.planet.destroy();
uniformBuffers.scene.destroy(); uniformBuffer.destroy();
}
} }
// Enable physical device features required for this example // Enable physical device features required for this example
@ -176,62 +175,60 @@ public:
textures.rocks.loadFromFile(getAssetPath() + "textures/texturearray_rocks_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue); textures.rocks.loadFromFile(getAssetPath() + "textures/texturearray_rocks_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue);
} }
void setupDescriptorPool() void setupDescriptors()
{
// Example uses one ubo
std::vector<VkDescriptorPoolSize> poolSizes =
{ {
// Pool
std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2),
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2),
}; };
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout() // Layout
{
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
// Binding 0 : Vertex shader uniform buffer // Binding 0 : Vertex shader uniform buffer
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0),
// Binding 1 : Fragment shader combined sampler // Binding 1 : Fragment shader combined sampler
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1),
}; };
VkDescriptorSetLayoutCreateInfo descriptorLayout = VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); // Sets
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo descripotrSetAllocInfo; VkDescriptorSetAllocateInfo descripotrSetAllocInfo;
std::vector<VkWriteDescriptorSet> writeDescriptorSets; std::vector<VkWriteDescriptorSet> writeDescriptorSets;
descripotrSetAllocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);; descripotrSetAllocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
// Instanced rocks // Instanced rocks
// Binding 0 : Vertex shader uniform buffer
// Binding 1 : Color map
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &descripotrSetAllocInfo, &descriptorSets.instancedRocks)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &descripotrSetAllocInfo, &descriptorSets.instancedRocks));
writeDescriptorSets = { writeDescriptorSets = {
vks::initializers::writeDescriptorSet(descriptorSets.instancedRocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.scene.descriptor), // Binding 0 : Vertex shader uniform buffer vks::initializers::writeDescriptorSet(descriptorSets.instancedRocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor),
vks::initializers::writeDescriptorSet(descriptorSets.instancedRocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.rocks.descriptor) // Binding 1 : Color map vks::initializers::writeDescriptorSet(descriptorSets.instancedRocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.rocks.descriptor)
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
// Planet // Planet
// Binding 0 : Vertex shader uniform buffer
// Binding 1 : Color map
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &descripotrSetAllocInfo, &descriptorSets.planet)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &descripotrSetAllocInfo, &descriptorSets.planet));
writeDescriptorSets = { writeDescriptorSets = {
vks::initializers::writeDescriptorSet(descriptorSets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.scene.descriptor), // Binding 0 : Vertex shader uniform buffer vks::initializers::writeDescriptorSet(descriptorSets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor),
vks::initializers::writeDescriptorSet(descriptorSets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.planet.descriptor) // Binding 1 : Color map vks::initializers::writeDescriptorSet(descriptorSets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.planet.descriptor)
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
} }
void preparePipelines() void preparePipelines()
{ {
// Layout
VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayout));
// Pipelines
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineRasterizationStateCreateInfo rasterizationState =vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
@ -282,7 +279,7 @@ public:
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6), // Location 2: Texture coordinates vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6), // Location 2: Texture coordinates
vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 3: Color vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 3: Color
// Per-Instance attributes // Per-Instance attributes
// These are fetched for each instance rendered // These are advanced for each instance rendered
vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 4, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 4: Position vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 4, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 4: Position
vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 5, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 5: Rotation vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 5, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 5: Rotation
vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 6, VK_FORMAT_R32_SFLOAT,sizeof(float) * 6), // Location 6: Scale vks::initializers::vertexInputAttributeDescription(INSTANCE_BUFFER_BIND_ID, 6, VK_FORMAT_R32_SFLOAT,sizeof(float) * 6), // Location 6: Scale
@ -320,6 +317,7 @@ public:
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.starfield)); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.starfield));
} }
// Create a buffer with per-instance data that is sourced in the shaders
void prepareInstanceData() void prepareInstanceData()
{ {
std::vector<InstanceData> instanceData; std::vector<InstanceData> instanceData;
@ -406,47 +404,23 @@ public:
void prepareUniformBuffers() void prepareUniformBuffers()
{ {
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(UniformData)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_CHECK_RESULT(uniformBuffer.map());
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.scene,
sizeof(uboVS)));
// Map persistent updateUniformBuffer();
VK_CHECK_RESULT(uniformBuffers.scene.map());
updateUniformBuffer(true);
} }
void updateUniformBuffer(bool viewChanged) void updateUniformBuffer()
{ {
if (viewChanged) uniformData.projection = camera.matrices.perspective;
{ uniformData.view = camera.matrices.view;
uboVS.projection = camera.matrices.perspective;
uboVS.view = camera.matrices.view; if (!paused) {
uniformData.locSpeed += frameTimer * 0.35f;
uniformData.globSpeed += frameTimer * 0.01f;
} }
if (!paused) memcpy(uniformBuffer.mapped, &uniformData, sizeof(uniformData));
{
uboVS.locSpeed += frameTimer * 0.35f;
uboVS.globSpeed += frameTimer * 0.01f;
}
memcpy(uniformBuffers.scene.mapped, &uboVS, sizeof(uboVS));
}
void draw()
{
VulkanExampleBase::prepareFrame();
// Command buffer to be sumitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
} }
void prepare() void prepare()
@ -455,30 +429,29 @@ public:
loadAssets(); loadAssets();
prepareInstanceData(); prepareInstanceData();
prepareUniformBuffers(); prepareUniformBuffers();
setupDescriptorSetLayout(); setupDescriptors();
preparePipelines(); preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers(); buildCommandBuffers();
prepared = true; prepared = true;
} }
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
{ {
return; return;
} }
updateUniformBuffer();
draw(); draw();
if ((!paused) || (camera.updated))
{
updateUniformBuffer(camera.updated);
}
}
virtual void viewChanged()
{
updateUniformBuffer(true);
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)

View file

@ -16,36 +16,35 @@ class VulkanExample : public VulkanExampleBase
public: public:
struct MultiviewPass { struct MultiviewPass {
struct FrameBufferAttachment { struct FrameBufferAttachment {
VkImage image; VkImage image{ VK_NULL_HANDLE };
VkDeviceMemory memory; VkDeviceMemory memory{ VK_NULL_HANDLE };
VkImageView view; VkImageView view{ VK_NULL_HANDLE };
} color, depth; } color, depth;
VkFramebuffer frameBuffer; VkFramebuffer frameBuffer{ VK_NULL_HANDLE };
VkRenderPass renderPass; VkRenderPass renderPass{ VK_NULL_HANDLE };
VkDescriptorImageInfo descriptor; VkDescriptorImageInfo descriptor{ VK_NULL_HANDLE };
VkSampler sampler; VkSampler sampler{ VK_NULL_HANDLE };
VkSemaphore semaphore; VkSemaphore semaphore{ VK_NULL_HANDLE };
std::vector<VkCommandBuffer> commandBuffers; std::vector<VkCommandBuffer> commandBuffers{};
std::vector<VkFence> waitFences; std::vector<VkFence> waitFences{};
} multiviewPass; } multiviewPass;
vkglTF::Model scene; vkglTF::Model scene;
struct UBO { struct UniformData {
glm::mat4 projection[2]; glm::mat4 projection[2];
glm::mat4 modelview[2]; glm::mat4 modelview[2];
glm::vec4 lightPos = glm::vec4(-2.5f, -3.5f, 0.0f, 1.0f); glm::vec4 lightPos = glm::vec4(-2.5f, -3.5f, 0.0f, 1.0f);
float distortionAlpha = 0.2f; float distortionAlpha = 0.2f;
} ubo; } uniformData;
vks::Buffer uniformBuffer; vks::Buffer uniformBuffer;
VkPipeline pipeline; VkPipeline pipeline{ VK_NULL_HANDLE };
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE };
VkDescriptorSet descriptorSet; VkDescriptorSet descriptorSet{ VK_NULL_HANDLE };
VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE };
VkPipeline viewDisplayPipelines[2]; VkPipeline viewDisplayPipelines[2]{};
VkPhysicalDeviceMultiviewFeaturesKHR physicalDeviceMultiviewFeatures{}; VkPhysicalDeviceMultiviewFeaturesKHR physicalDeviceMultiviewFeatures{};
@ -78,36 +77,30 @@ public:
~VulkanExample() ~VulkanExample()
{ {
if (device) {
vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
// Multiview pass
vkDestroyImageView(device, multiviewPass.color.view, nullptr); vkDestroyImageView(device, multiviewPass.color.view, nullptr);
vkDestroyImage(device, multiviewPass.color.image, nullptr); vkDestroyImage(device, multiviewPass.color.image, nullptr);
vkFreeMemory(device, multiviewPass.color.memory, nullptr); vkFreeMemory(device, multiviewPass.color.memory, nullptr);
vkDestroyImageView(device, multiviewPass.depth.view, nullptr); vkDestroyImageView(device, multiviewPass.depth.view, nullptr);
vkDestroyImage(device, multiviewPass.depth.image, nullptr); vkDestroyImage(device, multiviewPass.depth.image, nullptr);
vkFreeMemory(device, multiviewPass.depth.memory, nullptr); vkFreeMemory(device, multiviewPass.depth.memory, nullptr);
vkDestroyRenderPass(device, multiviewPass.renderPass, nullptr); vkDestroyRenderPass(device, multiviewPass.renderPass, nullptr);
vkDestroySampler(device, multiviewPass.sampler, nullptr); vkDestroySampler(device, multiviewPass.sampler, nullptr);
vkDestroyFramebuffer(device, multiviewPass.frameBuffer, nullptr); vkDestroyFramebuffer(device, multiviewPass.frameBuffer, nullptr);
vkFreeCommandBuffers(device, cmdPool, static_cast<uint32_t>(multiviewPass.commandBuffers.size()), multiviewPass.commandBuffers.data()); vkFreeCommandBuffers(device, cmdPool, static_cast<uint32_t>(multiviewPass.commandBuffers.size()), multiviewPass.commandBuffers.data());
vkDestroySemaphore(device, multiviewPass.semaphore, nullptr); vkDestroySemaphore(device, multiviewPass.semaphore, nullptr);
for (auto& fence : multiviewPass.waitFences) { for (auto& fence : multiviewPass.waitFences) {
vkDestroyFence(device, fence, nullptr); vkDestroyFence(device, fence, nullptr);
} }
for (auto& pipeline : viewDisplayPipelines) { for (auto& pipeline : viewDisplayPipelines) {
vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipeline(device, pipeline, nullptr);
} }
uniformBuffer.destroy(); uniformBuffer.destroy();
} }
}
/* /*
Prepares all resources required for the multiview attachment Prepares all resources required for the multiview attachment
@ -150,8 +143,9 @@ public:
depthStencilView.flags = 0; depthStencilView.flags = 0;
depthStencilView.subresourceRange = {}; depthStencilView.subresourceRange = {};
depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
if (depthFormat >= VK_FORMAT_D16_UNORM_S8_UINT) if (depthFormat >= VK_FORMAT_D16_UNORM_S8_UINT) {
depthStencilView.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; depthStencilView.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
depthStencilView.subresourceRange.baseMipLevel = 0; depthStencilView.subresourceRange.baseMipLevel = 0;
depthStencilView.subresourceRange.levelCount = 1; depthStencilView.subresourceRange.levelCount = 1;
depthStencilView.subresourceRange.baseArrayLayer = 0; depthStencilView.subresourceRange.baseArrayLayer = 0;
@ -583,13 +577,8 @@ public:
// Prepare and initialize uniform buffer containing shader uniforms // Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers() void prepareUniformBuffers()
{ {
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(UniformData)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffer,
sizeof(ubo)));
VK_CHECK_RESULT(uniformBuffer.map()); VK_CHECK_RESULT(uniformBuffer.map());
updateUniformBuffers();
} }
void updateUniformBuffers() void updateUniformBuffers()
@ -625,8 +614,8 @@ public:
transM = glm::translate(glm::mat4(1.0f), camera.position - camRight * (eyeSeparation / 2.0f)); transM = glm::translate(glm::mat4(1.0f), camera.position - camRight * (eyeSeparation / 2.0f));
ubo.projection[0] = glm::frustum(left, right, bottom, top, zNear, zFar); uniformData.projection[0] = glm::frustum(left, right, bottom, top, zNear, zFar);
ubo.modelview[0] = rotM * transM; uniformData.modelview[0] = rotM * transM;
// Right eye // Right eye
left = -aspectRatio * wd2 + 0.5f * eyeSeparation * ndfl; left = -aspectRatio * wd2 + 0.5f * eyeSeparation * ndfl;
@ -634,35 +623,10 @@ public:
transM = glm::translate(glm::mat4(1.0f), camera.position + camRight * (eyeSeparation / 2.0f)); transM = glm::translate(glm::mat4(1.0f), camera.position + camRight * (eyeSeparation / 2.0f));
ubo.projection[1] = glm::frustum(left, right, bottom, top, zNear, zFar); uniformData.projection[1] = glm::frustum(left, right, bottom, top, zNear, zFar);
ubo.modelview[1] = rotM * transM; uniformData.modelview[1] = rotM * transM;
memcpy(uniformBuffer.mapped, &ubo, sizeof(ubo)); memcpy(uniformBuffer.mapped, &uniformData, sizeof(UniformData));
}
void draw()
{
VulkanExampleBase::prepareFrame();
// Multiview offscreen render
VK_CHECK_RESULT(vkWaitForFences(device, 1, &multiviewPass.waitFences[currentBuffer], VK_TRUE, UINT64_MAX));
VK_CHECK_RESULT(vkResetFences(device, 1, &multiviewPass.waitFences[currentBuffer]));
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
submitInfo.pSignalSemaphores = &multiviewPass.semaphore;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &multiviewPass.commandBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, multiviewPass.waitFences[currentBuffer]));
// View display
VK_CHECK_RESULT(vkWaitForFences(device, 1, &waitFences[currentBuffer], VK_TRUE, UINT64_MAX));
VK_CHECK_RESULT(vkResetFences(device, 1, &waitFences[currentBuffer]));
submitInfo.pWaitSemaphores = &multiviewPass.semaphore;
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, waitFences[currentBuffer]));
VulkanExampleBase::submitFrame();
} }
void prepare() void prepare()
@ -728,19 +692,37 @@ public:
} }
} }
void draw()
{
VulkanExampleBase::prepareFrame();
// Multiview offscreen render
VK_CHECK_RESULT(vkWaitForFences(device, 1, &multiviewPass.waitFences[currentBuffer], VK_TRUE, UINT64_MAX));
VK_CHECK_RESULT(vkResetFences(device, 1, &multiviewPass.waitFences[currentBuffer]));
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
submitInfo.pSignalSemaphores = &multiviewPass.semaphore;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &multiviewPass.commandBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, multiviewPass.waitFences[currentBuffer]));
// View display
VK_CHECK_RESULT(vkWaitForFences(device, 1, &waitFences[currentBuffer], VK_TRUE, UINT64_MAX));
VK_CHECK_RESULT(vkResetFences(device, 1, &waitFences[currentBuffer]));
submitInfo.pWaitSemaphores = &multiviewPass.semaphore;
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, waitFences[currentBuffer]));
VulkanExampleBase::submitFrame();
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
return; return;
updateUniformBuffers();
draw(); draw();
if (camera.updated) {
updateUniformBuffers();
}
}
virtual void viewChanged()
{
updateUniformBuffers();
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)
@ -749,7 +731,7 @@ public:
if (overlay->sliderFloat("Eye separation", &eyeSeparation, -1.0f, 1.0f)) { if (overlay->sliderFloat("Eye separation", &eyeSeparation, -1.0f, 1.0f)) {
updateUniformBuffers(); updateUniformBuffers();
} }
if (overlay->sliderFloat("Barrel distortion", &ubo.distortionAlpha, -0.6f, 0.6f)) { if (overlay->sliderFloat("Barrel distortion", &uniformData.distortionAlpha, -0.6f, 0.6f)) {
updateUniformBuffers(); updateUniformBuffers();
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* Vulkan Example - Viewport array with single pass rendering using geometry shaders * Vulkan Example - Viewport array with single pass rendering using geometry shaders
* *
* Copyright (C) 2017 by Sascha Willems - www.saschawillems.de * Copyright (C) 2017-2023 by Sascha Willems - www.saschawillems.de
* *
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/ */
@ -14,18 +14,17 @@ class VulkanExample : public VulkanExampleBase
public: public:
vkglTF::Model scene; vkglTF::Model scene;
struct UBOGS { struct UniformDataGS {
glm::mat4 projection[2]; glm::mat4 projection[2];
glm::mat4 modelview[2]; glm::mat4 modelview[2];
glm::vec4 lightPos = glm::vec4(-2.5f, -3.5f, 0.0f, 1.0f); glm::vec4 lightPos = glm::vec4(-2.5f, -3.5f, 0.0f, 1.0f);
} uboGS; } uniformDataGS;
vks::Buffer uniformBufferGS; vks::Buffer uniformBufferGS;
VkPipeline pipeline; VkPipeline pipeline{ VK_NULL_HANDLE };
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE };
VkDescriptorSet descriptorSet; VkDescriptorSet descriptorSet{ VK_NULL_HANDLE };
VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE };
// Camera and view properties // Camera and view properties
float eyeSeparation = 0.08f; float eyeSeparation = 0.08f;
@ -45,13 +44,13 @@ public:
~VulkanExample() ~VulkanExample()
{ {
if (device) {
vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
uniformBufferGS.destroy(); uniformBufferGS.destroy();
} }
}
// Enable physical device features required for this example // Enable physical device features required for this example
virtual void getEnabledFeatures() virtual void getEnabledFeatures()
@ -98,12 +97,12 @@ public:
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewports[2]; // We render to two viewports simultaneously, so we need to viewports and two scissor rectangles
// Right // 0 = right, 1 = left
viewports[0] = { (float)width / 2.0f, 0, (float)width / 2.0f, (float)height, 0.0, 1.0f }; VkViewport viewports[2] = {
// Left { (float)width / 2.0f, 0, (float)width / 2.0f, (float)height, 0.0, 1.0f },
viewports[1] = { 0, 0, (float)width / 2.0f, (float)height, 0.0, 1.0f }; { 0, 0, (float)width / 2.0f, (float)height, 0.0, 1.0f },
};
vkCmdSetViewport(drawCmdBuffers[i], 0, 2, viewports); vkCmdSetViewport(drawCmdBuffers[i], 0, 2, viewports);
VkRect2D scissorRects[2] = { VkRect2D scissorRects[2] = {
@ -131,55 +130,39 @@ public:
scene.loadFromFile(getAssetPath() + "models/sampleroom.gltf", vulkanDevice, queue, vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY); scene.loadFromFile(getAssetPath() + "models/sampleroom.gltf", vulkanDevice, queue, vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY);
} }
void setupDescriptorPool() void setupDescriptors()
{ {
// Example uses two ubos // Pool
std::vector<VkDescriptorPoolSize> poolSizes = { std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1),
}; };
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(static_cast<uint32_t>(poolSizes.size()), poolSizes.data(), 1);
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(static_cast<uint32_t>(poolSizes.size()), poolSizes.data(), 1);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout() // Layout
{
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_GEOMETRY_BIT, 0) // Binding 1: Geometry shader ubo vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_GEOMETRY_BIT, 0) // Binding 1: Geometry shader ubo
}; };
VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = // Set
vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets = { std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBufferGS.descriptor), // Binding 0 :Geometry shader ubo vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBufferGS.descriptor), // Binding 0 :Geometry shader ubo
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
} }
void preparePipelines() void preparePipelines()
{ {
// Layout
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout));
// Pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
@ -217,16 +200,9 @@ public:
void prepareUniformBuffers() void prepareUniformBuffers()
{ {
// Geometry shader uniform buffer block // Geometry shader uniform buffer block
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBufferGS, sizeof(UniformDataGS)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBufferGS,
sizeof(uboGS)));
// Map persistent // Map persistent
VK_CHECK_RESULT(uniformBufferGS.map()); VK_CHECK_RESULT(uniformBufferGS.map());
updateUniformBuffers();
} }
void updateUniformBuffers() void updateUniformBuffers()
@ -262,8 +238,8 @@ public:
transM = glm::translate(glm::mat4(1.0f), camera.position - camRight * (eyeSeparation / 2.0f)); transM = glm::translate(glm::mat4(1.0f), camera.position - camRight * (eyeSeparation / 2.0f));
uboGS.projection[0] = glm::frustum(left, right, bottom, top, zNear, zFar); uniformDataGS.projection[0] = glm::frustum(left, right, bottom, top, zNear, zFar);
uboGS.modelview[0] = rotM * transM; uniformDataGS.modelview[0] = rotM * transM;
// Right eye // Right eye
left = -aspectRatio * wd2 - 0.5f * eyeSeparation * ndfl; left = -aspectRatio * wd2 - 0.5f * eyeSeparation * ndfl;
@ -271,10 +247,21 @@ public:
transM = glm::translate(glm::mat4(1.0f), camera.position + camRight * (eyeSeparation / 2.0f)); transM = glm::translate(glm::mat4(1.0f), camera.position + camRight * (eyeSeparation / 2.0f));
uboGS.projection[1] = glm::frustum(left, right, bottom, top, zNear, zFar); uniformDataGS.projection[1] = glm::frustum(left, right, bottom, top, zNear, zFar);
uboGS.modelview[1] = rotM * transM; uniformDataGS.modelview[1] = rotM * transM;
memcpy(uniformBufferGS.mapped, &uboGS, sizeof(uboGS)); memcpy(uniformBufferGS.mapped, &uniformDataGS, sizeof(uniformDataGS));
}
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
prepareUniformBuffers();
setupDescriptors();
preparePipelines();
buildCommandBuffers();
prepared = true;
} }
void draw() void draw()
@ -286,29 +273,12 @@ public:
VulkanExampleBase::submitFrame(); VulkanExampleBase::submitFrame();
} }
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
return; return;
draw();
}
virtual void viewChanged()
{
updateUniformBuffers(); updateUniformBuffers();
draw();
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)