From f39eb4ebc199b160d05c8deaaa2274c96a24deb1 Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sat, 24 Oct 2026 14:00:34 +0200 Subject: [PATCH 1/9] New sample for using secondary command buffers with dynamic rendering Work-in-progress --- examples/CMakeLists.txt | 1 + .../dynamicrenderingsecondary.cpp | 374 ++++++++++++++++++ 2 files changed, 375 insertions(+) create mode 100644 examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b4ce74eef..4cce0b55f 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -113,6 +113,7 @@ set(EXAMPLES dynamicrendering dynamicrenderinglocalread dynamicrenderingmultisampling + dynamicrenderingsecondary dynamicstate dynamicuniformbuffer fragmentshaderbarycentrics diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp new file mode 100644 index 000000000..a61642241 --- /dev/null +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -0,0 +1,374 @@ +/* + * Vulkan Example - Using secondary command buffers with VK_KHR_dynamic_rendering + * + * Copyright (C) 2026 by Sascha Willems - www.saschawillems.de + * + * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) + */ + +#include "vulkanexamplebase.h" +#include "VulkanglTFModel.h" + + +class VulkanExample : public VulkanExampleBase +{ +public: + PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHR{ VK_NULL_HANDLE }; + PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHR{ VK_NULL_HANDLE }; + + VkPhysicalDeviceDynamicRenderingFeaturesKHR enabledDynamicRenderingFeaturesKHR{}; + + vkglTF::Model model; + VkCommandBuffer secondaryCmdBuf{ VK_NULL_HANDLE }; + VkCommandBuffer secondaryUICmdBuf{ VK_NULL_HANDLE }; + + struct UniformData { + glm::mat4 projection; + glm::mat4 modelView; + glm::vec4 viewPos; + } uniformData; + std::array uniformBuffers; + + VkPipeline pipeline{ VK_NULL_HANDLE }; + VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE }; + VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE }; + std::array descriptorSets{}; + + VulkanExample() : VulkanExampleBase() + { + title = "Dynamic rendering"; + camera.type = Camera::CameraType::lookat; + camera.setPosition(glm::vec3(0.0f, 0.0f, -10.0f)); + camera.setRotation(glm::vec3(-7.5f, 72.0f, 0.0f)); + camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f); + + enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + + // The sample uses the extension (instead of Vulkan 1.2, where dynamic rendering is core) + enabledDeviceExtensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_MULTIVIEW_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME); + + // in addition to the extension, the feature needs to be explicitly enabled too by chaining the extension structure into device creation + enabledDynamicRenderingFeaturesKHR = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, + .dynamicRendering = VK_TRUE + }; + + deviceCreatepNextChain = &enabledDynamicRenderingFeaturesKHR; + } + + ~VulkanExample() + { + if (device) { + vkDestroyPipeline(device, pipeline, nullptr); + vkDestroyPipelineLayout(device, pipelineLayout, nullptr); + vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); + for (auto& buffer : uniformBuffers) { + buffer.destroy(); + } + } + } + + void setupRenderPass() + { + // With VK_KHR_dynamic_rendering we no longer need a render pass, so skip the sample base render pass setup + renderPass = VK_NULL_HANDLE; + } + + void setupFrameBuffer() + { + // With VK_KHR_dynamic_rendering we no longer need a frame buffer, so skip the sample base framebuffer setup + } + + // Enable physical device features required for this example + virtual void getEnabledFeatures() + { + // Enable anisotropic filtering if supported + if (deviceFeatures.samplerAnisotropy) { + enabledFeatures.samplerAnisotropy = VK_TRUE; + }; + } + + void loadAssets() + { + const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; + model.loadFromFile(getAssetPath() + "models/voyager.gltf", vulkanDevice, queue, glTFLoadingFlags); + } + + void setupDescriptors() + { + // Pool + std::vector poolSizes = { + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, maxConcurrentFrames), + }; + VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, maxConcurrentFrames); + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + // Layout + const std::vector setLayoutBindings = { + vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + }; + VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); + // Sets per frame, just like the buffers themselves + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); + for (auto i = 0; i < uniformBuffers.size(); i++) { + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets[i])); + std::vector writeDescriptorSets = { + vks::initializers::writeDescriptorSet(descriptorSets[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers[i].descriptor), + }; + vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); + } + } + + void preparePipelines() + { + // Layout + // Uses set 0 for passing vertex shader ubo and set 1 for fragment shader images (taken from glTF model) + const std::vector setLayouts = { + descriptorSetLayout, + vkglTF::descriptorSetLayoutImage, + }; + VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), 2); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout)); + + // Pipeline + 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_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, 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 dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); + std::array shaderStages{ + loadShader(getShadersPath() + "dynamicrendering/texture.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + loadShader(getShadersPath() + "dynamicrendering/texture.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT) + }; + + // New create info to define color, depth and stencil attachments at pipeline create time + VkPipelineRenderingCreateInfoKHR pipelineRenderingCreateInfo{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR, + .colorAttachmentCount = 1, + .pColorAttachmentFormats = &swapChain.colorFormat, + .depthAttachmentFormat = depthFormat, + .stencilAttachmentFormat = depthFormat + }; + + // We no longer need to set a renderpass for the pipeline create info + VkGraphicsPipelineCreateInfo pipelineCI{ + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + // Dynamic rendering info has to be chainged into the pipeline create info + .pNext = &pipelineRenderingCreateInfo, + .stageCount = static_cast(shaderStages.size()), + .pStages = shaderStages.data(), + .pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({ vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::UV }), + .pInputAssemblyState = &inputAssemblyState, + .pViewportState = &viewportState, + .pRasterizationState = &rasterizationState, + .pMultisampleState = &multisampleState, + .pDepthStencilState = &depthStencilState, + .pColorBlendState = &colorBlendState, + .pDynamicState = &dynamicState, + .layout = pipelineLayout + }; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); + } + + // Prepare and initialize uniform buffer containing shader uniforms + void prepareUniformBuffers() + { + for (auto& buffer : uniformBuffers) { + VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &buffer, sizeof(UniformData), &uniformData)); + VK_CHECK_RESULT(buffer.map()); + } + } + + void updateUniformBuffers() + { + uniformData.projection = camera.matrices.perspective; + uniformData.modelView = camera.matrices.view; + uniformData.viewPos = camera.viewPos; + memcpy(uniformBuffers[currentBuffer].mapped, &uniformData, sizeof(uniformData)); + } + + void prepare() + { + VulkanExampleBase::prepare(); + + // Since we use an extension, we need to expliclity load the function pointers for extension related Vulkan commands + vkCmdBeginRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBeginRenderingKHR")); + vkCmdEndRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR")); + + loadAssets(); + prepareUniformBuffers(); + setupDescriptors(); + preparePipelines(); + prepared = true; + } + + void buildCommandBuffer() + { + // nope + vkQueueWaitIdle(queue); + + // New structures are used to define the attachments used in dynamic rendering + VkRenderingAttachmentInfoKHR colorAttachment{ + .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, + .imageView = swapChain.imageViews[currentImageIndex], + .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .clearValue = {.color = {0.0f,0.0f,0.0f,0.0f} }, + }; + + // A single depth stencil attachment info can be used, but they can also be specified separately. + // When both are specified separately, the only requirement is that the image view is identical. + VkRenderingAttachmentInfoKHR depthStencilAttachment{ + .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, + .imageView = depthStencil.view, + .imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .clearValue = {.depthStencil = {1.0f, 0} } + }; + + // @todo: secondaryCmdBuf + if (!secondaryCmdBuf) { + VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); + VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCmdBuf)); + } + + VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + + { + VkCommandBufferInheritanceRenderingInfoKHR inheritanceRenderingInfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR, + .colorAttachmentCount = 1, + .pColorAttachmentFormats = &swapChain.colorFormat, + .depthAttachmentFormat = depthFormat, + .stencilAttachmentFormat = depthFormat, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT, + }; + + VkCommandBufferInheritanceInfo inheritanceInfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, + .pNext = &inheritanceRenderingInfo + }; + + VkCommandBufferBeginInfo secCmdBufInfo{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, + .pInheritanceInfo = &inheritanceInfo, + }; + VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuf, &secCmdBufInfo)); + + vkCmdSetViewport(secondaryCmdBuf, 0, 1, &viewport); + + vkCmdSetScissor(secondaryCmdBuf, 0, 1, &scissor); + + vkCmdBindDescriptorSets(secondaryCmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(secondaryCmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + model.draw(secondaryCmdBuf, vkglTF::RenderFlags::BindImages, pipelineLayout); + + VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuf)); + + // + + if (!secondaryUICmdBuf) { + VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); + VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryUICmdBuf)); + } + + VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryUICmdBuf, &secCmdBufInfo)); + + vkCmdSetViewport(secondaryUICmdBuf, 0, 1, &viewport); + vkCmdSetScissor(secondaryUICmdBuf, 0, 1, &scissor); + + vkCmdBindDescriptorSets(secondaryUICmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(secondaryUICmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + drawUI(secondaryUICmdBuf); + + VK_CHECK_RESULT(vkEndCommandBuffer(secondaryUICmdBuf)); + } + + VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; + + VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); + VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo)); + + // With dynamic rendering there are no subpass dependencies, so we need to take care of proper layout transitions by using barriers + // This set of barriers prepares the color and depth images for output + vks::tools::insertImageMemoryBarrier( + cmdBuffer, + swapChain.images[currentImageIndex], + 0, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); + vks::tools::insertImageMemoryBarrier( + cmdBuffer, + depthStencil.image, + 0, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VkImageSubresourceRange{ VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1 }); + + VkRenderingInfoKHR renderingInfo{ + .sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR, + .flags = VK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_BIT_KHR, + .renderArea = { 0, 0, width, height }, + .layerCount = 1, + .colorAttachmentCount = 1, + .pColorAttachments = &colorAttachment, + .pDepthAttachment = &depthStencilAttachment, + .pStencilAttachment = &depthStencilAttachment + }; + + vkCmdBeginRenderingKHR(cmdBuffer, &renderingInfo); + + // No draw calls here, all done by executing the secondaries + std::vector cmdBuffers = { secondaryCmdBuf, secondaryUICmdBuf }; + vkCmdExecuteCommands(cmdBuffer, static_cast(cmdBuffers.size()), cmdBuffers.data()); + + vkCmdEndRenderingKHR(cmdBuffer); + + // This set of barriers prepares the color image for presentation, we don't need to care for the depth image + vks::tools::insertImageMemoryBarrier( + cmdBuffer, + swapChain.images[currentImageIndex], + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + 0, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); + + VK_CHECK_RESULT(vkEndCommandBuffer(cmdBuffer)); + } + + virtual void render() + { + if (!prepared) + return; + VulkanExampleBase::prepareFrame(); + updateUniformBuffers(); + buildCommandBuffer(); + VulkanExampleBase::submitFrame(); + } +}; + +VULKAN_EXAMPLE_MAIN() From 9669db174f246364c2a090ea0d565aaab24e3088 Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sat, 24 Oct 2026 14:04:00 +0200 Subject: [PATCH 2/9] Comments --- .../dynamicrenderingsecondary/dynamicrenderingsecondary.cpp | 2 ++ examples/multithreading/multithreading.cpp | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp index a61642241..902a805a7 100644 --- a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -1,6 +1,8 @@ /* * Vulkan Example - Using secondary command buffers with VK_KHR_dynamic_rendering * + * @todo: rebase on multithreading sample + * * Copyright (C) 2026 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) diff --git a/examples/multithreading/multithreading.cpp b/examples/multithreading/multithreading.cpp index 89c7d4e9b..53b7f64a9 100644 --- a/examples/multithreading/multithreading.cpp +++ b/examples/multithreading/multithreading.cpp @@ -1,7 +1,9 @@ /* * Vulkan Example - Multi threaded command buffer generation * -* Copyright (C) 2016-2025 by Sascha Willems - www.saschawillems.de +* Note: See the dynamicrenderingsecondary sample for how to use secondary command buffers with dynamic rendering +* +* Copyright (C) 2016-2026 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ From 70ee7cefbf7fab51b718fea76218d2f7a54b67cc Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sat, 24 Oct 2026 18:59:16 +0200 Subject: [PATCH 3/9] Secondary command buffers per max frames in flight --- .../dynamicrenderingsecondary.cpp | 85 ++++++++++--------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp index 902a805a7..5b853e9ba 100644 --- a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -21,8 +21,7 @@ class VulkanExample : public VulkanExampleBase VkPhysicalDeviceDynamicRenderingFeaturesKHR enabledDynamicRenderingFeaturesKHR{}; vkglTF::Model model; - VkCommandBuffer secondaryCmdBuf{ VK_NULL_HANDLE }; - VkCommandBuffer secondaryUICmdBuf{ VK_NULL_HANDLE }; + std::array secondaryCmdBufs{}; struct UniformData { glm::mat4 projection; @@ -205,6 +204,15 @@ class VulkanExample : public VulkanExampleBase vkCmdBeginRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBeginRenderingKHR")); vkCmdEndRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR")); + // @todo + VkCommandBufferAllocateInfo cmdBufAllocateInfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = cmdPool, + .level = VK_COMMAND_BUFFER_LEVEL_SECONDARY, + .commandBufferCount = maxConcurrentFrames + }; + VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, secondaryCmdBufs.data())); + loadAssets(); prepareUniformBuffers(); setupDescriptors(); @@ -215,34 +223,7 @@ class VulkanExample : public VulkanExampleBase void buildCommandBuffer() { // nope - vkQueueWaitIdle(queue); - - // New structures are used to define the attachments used in dynamic rendering - VkRenderingAttachmentInfoKHR colorAttachment{ - .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, - .imageView = swapChain.imageViews[currentImageIndex], - .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .clearValue = {.color = {0.0f,0.0f,0.0f,0.0f} }, - }; - - // A single depth stencil attachment info can be used, but they can also be specified separately. - // When both are specified separately, the only requirement is that the image view is identical. - VkRenderingAttachmentInfoKHR depthStencilAttachment{ - .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, - .imageView = depthStencil.view, - .imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .clearValue = {.depthStencil = {1.0f, 0} } - }; - - // @todo: secondaryCmdBuf - if (!secondaryCmdBuf) { - VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); - VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCmdBuf)); - } + //vkQueueWaitIdle(queue); VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); @@ -267,26 +248,27 @@ class VulkanExample : public VulkanExampleBase .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, .pInheritanceInfo = &inheritanceInfo, }; - VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuf, &secCmdBufInfo)); + VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBufs[currentBuffer], &secCmdBufInfo)); - vkCmdSetViewport(secondaryCmdBuf, 0, 1, &viewport); + vkCmdSetViewport(secondaryCmdBufs[currentBuffer], 0, 1, &viewport); - vkCmdSetScissor(secondaryCmdBuf, 0, 1, &scissor); + vkCmdSetScissor(secondaryCmdBufs[currentBuffer], 0, 1, &scissor); - vkCmdBindDescriptorSets(secondaryCmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); - vkCmdBindPipeline(secondaryCmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + vkCmdBindDescriptorSets(secondaryCmdBufs[currentBuffer], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(secondaryCmdBufs[currentBuffer], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - model.draw(secondaryCmdBuf, vkglTF::RenderFlags::BindImages, pipelineLayout); + model.draw(secondaryCmdBufs[currentBuffer], vkglTF::RenderFlags::BindImages, pipelineLayout); - VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuf)); + VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBufs[currentBuffer])); // - if (!secondaryUICmdBuf) { - VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); - VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryUICmdBuf)); - } + //if (!secondaryUICmdBuf) { + // VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); + // VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryUICmdBuf)); + //} + /* VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryUICmdBuf, &secCmdBufInfo)); vkCmdSetViewport(secondaryUICmdBuf, 0, 1, &viewport); @@ -298,6 +280,7 @@ class VulkanExample : public VulkanExampleBase drawUI(secondaryUICmdBuf); VK_CHECK_RESULT(vkEndCommandBuffer(secondaryUICmdBuf)); + */ } VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; @@ -328,6 +311,24 @@ class VulkanExample : public VulkanExampleBase VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VkImageSubresourceRange{ VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1 }); + VkRenderingAttachmentInfoKHR colorAttachment{ + .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, + .imageView = swapChain.imageViews[currentImageIndex], + .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .clearValue = {.color = {0.0f,0.0f,0.0f,0.0f} }, + }; + + VkRenderingAttachmentInfoKHR depthStencilAttachment{ + .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, + .imageView = depthStencil.view, + .imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .clearValue = {.depthStencil = {1.0f, 0} } + }; + VkRenderingInfoKHR renderingInfo{ .sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR, .flags = VK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_BIT_KHR, @@ -342,7 +343,7 @@ class VulkanExample : public VulkanExampleBase vkCmdBeginRenderingKHR(cmdBuffer, &renderingInfo); // No draw calls here, all done by executing the secondaries - std::vector cmdBuffers = { secondaryCmdBuf, secondaryUICmdBuf }; + std::vector cmdBuffers = { secondaryCmdBufs[currentBuffer]/*, secondaryUICmdBuf*/}; vkCmdExecuteCommands(cmdBuffer, static_cast(cmdBuffers.size()), cmdBuffers.data()); vkCmdEndRenderingKHR(cmdBuffer); From 9fa50c831e5936ac010888c3ee997e5cc6e24ead Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sun, 25 Oct 2026 10:49:08 +0100 Subject: [PATCH 4/9] Secondary command buffers per max frames in flight --- .../dynamicrenderingsecondary.cpp | 64 ++++++++++--------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp index 5b853e9ba..d89ebfeb4 100644 --- a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -21,7 +21,11 @@ class VulkanExample : public VulkanExampleBase VkPhysicalDeviceDynamicRenderingFeaturesKHR enabledDynamicRenderingFeaturesKHR{}; vkglTF::Model model; - std::array secondaryCmdBufs{}; + struct SecondaryCommandBuffer { + VkCommandBuffer model{ VK_NULL_HANDLE }; + VkCommandBuffer ui{ VK_NULL_HANDLE }; + }; + std::array secondaryCommandBuffers{}; struct UniformData { glm::mat4 projection; @@ -205,13 +209,16 @@ class VulkanExample : public VulkanExampleBase vkCmdEndRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR")); // @todo - VkCommandBufferAllocateInfo cmdBufAllocateInfo = { + const VkCommandBufferAllocateInfo cmdBufAllocateInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = cmdPool, .level = VK_COMMAND_BUFFER_LEVEL_SECONDARY, - .commandBufferCount = maxConcurrentFrames - }; - VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, secondaryCmdBufs.data())); + .commandBufferCount = 1 + }; + for (uint32_t i = 0; i < maxConcurrentFrames; i++) { + VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCommandBuffers[i].model)); + VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCommandBuffers[i].ui)); + } loadAssets(); prepareUniformBuffers(); @@ -222,13 +229,15 @@ class VulkanExample : public VulkanExampleBase void buildCommandBuffer() { - // nope - //vkQueueWaitIdle(queue); - VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); - VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + + SecondaryCommandBuffer secondaryCmdBuffer = secondaryCommandBuffers[currentBuffer]; + + // Just a demonstration, with this simple example, this won't gain performance, but shows how to do { + VkCommandBufferInheritanceRenderingInfoKHR inheritanceRenderingInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR, .colorAttachmentCount = 1, @@ -248,39 +257,32 @@ class VulkanExample : public VulkanExampleBase .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, .pInheritanceInfo = &inheritanceInfo, }; - VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBufs[currentBuffer], &secCmdBufInfo)); + VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuffer.model, &secCmdBufInfo)); - vkCmdSetViewport(secondaryCmdBufs[currentBuffer], 0, 1, &viewport); + vkCmdSetViewport(secondaryCmdBuffer.model, 0, 1, &viewport); - vkCmdSetScissor(secondaryCmdBufs[currentBuffer], 0, 1, &scissor); + vkCmdSetScissor(secondaryCmdBuffer.model, 0, 1, &scissor); - vkCmdBindDescriptorSets(secondaryCmdBufs[currentBuffer], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); - vkCmdBindPipeline(secondaryCmdBufs[currentBuffer], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + vkCmdBindDescriptorSets(secondaryCmdBuffer.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(secondaryCmdBuffer.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - model.draw(secondaryCmdBufs[currentBuffer], vkglTF::RenderFlags::BindImages, pipelineLayout); + model.draw(secondaryCmdBuffer.model, vkglTF::RenderFlags::BindImages, pipelineLayout); - VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBufs[currentBuffer])); + VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuffer.model)); // - //if (!secondaryUICmdBuf) { - // VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(cmdPool, VK_COMMAND_BUFFER_LEVEL_SECONDARY, 1); - // VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryUICmdBuf)); - //} - - /* - VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryUICmdBuf, &secCmdBufInfo)); + VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuffer.ui, &secCmdBufInfo)); - vkCmdSetViewport(secondaryUICmdBuf, 0, 1, &viewport); - vkCmdSetScissor(secondaryUICmdBuf, 0, 1, &scissor); + vkCmdSetViewport(secondaryCmdBuffer.ui, 0, 1, &viewport); + vkCmdSetScissor(secondaryCmdBuffer.ui, 0, 1, &scissor); - vkCmdBindDescriptorSets(secondaryUICmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); - vkCmdBindPipeline(secondaryUICmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + vkCmdBindDescriptorSets(secondaryCmdBuffer.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(secondaryCmdBuffer.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - drawUI(secondaryUICmdBuf); + drawUI(secondaryCmdBuffer.ui); - VK_CHECK_RESULT(vkEndCommandBuffer(secondaryUICmdBuf)); - */ + VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuffer.ui)); } VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; @@ -343,7 +345,7 @@ class VulkanExample : public VulkanExampleBase vkCmdBeginRenderingKHR(cmdBuffer, &renderingInfo); // No draw calls here, all done by executing the secondaries - std::vector cmdBuffers = { secondaryCmdBufs[currentBuffer]/*, secondaryUICmdBuf*/}; + std::vector cmdBuffers = { secondaryCmdBuffer.model, secondaryCmdBuffer .ui }; vkCmdExecuteCommands(cmdBuffer, static_cast(cmdBuffers.size()), cmdBuffers.data()); vkCmdEndRenderingKHR(cmdBuffer); From aa7d22c6ca33b1540f2145983ad1b0e1711d960d Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sun, 25 Oct 2026 11:04:25 +0100 Subject: [PATCH 5/9] Move secondary command buffer creation to separate functions --- .../dynamicrenderingsecondary.cpp | 104 ++++++++++-------- 1 file changed, 57 insertions(+), 47 deletions(-) diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp index d89ebfeb4..eaba82a8f 100644 --- a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -227,63 +227,73 @@ class VulkanExample : public VulkanExampleBase prepared = true; } + void buildSecondaryModelCommandBuffer(SecondaryCommandBuffer cmdBufferSet, VkCommandBufferInheritanceInfo &inheritanceInfo) + { + const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + const VkCommandBufferBeginInfo secCmdBufInfo{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, + .pInheritanceInfo = &inheritanceInfo, + }; + VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBufferSet.model, &secCmdBufInfo)); + vkCmdSetViewport(cmdBufferSet.model, 0, 1, &viewport); + vkCmdSetScissor(cmdBufferSet.model, 0, 1, &scissor); + vkCmdBindDescriptorSets(cmdBufferSet.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(cmdBufferSet.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + model.draw(cmdBufferSet.model, vkglTF::RenderFlags::BindImages, pipelineLayout); + VK_CHECK_RESULT(vkEndCommandBuffer(cmdBufferSet.model)); + } + + void buildSecondaryUICommandBuffer(SecondaryCommandBuffer cmdBufferSet, VkCommandBufferInheritanceInfo& inheritanceInfo) + { + const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + const VkCommandBufferBeginInfo secCmdBufInfo{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, + .pInheritanceInfo = &inheritanceInfo, + }; + VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBufferSet.ui, &secCmdBufInfo)); + vkCmdSetViewport(cmdBufferSet.ui, 0, 1, &viewport); + vkCmdSetScissor(cmdBufferSet.ui, 0, 1, &scissor); + vkCmdBindDescriptorSets(cmdBufferSet.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); + vkCmdBindPipeline(cmdBufferSet.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + drawUI(cmdBufferSet.ui); + VK_CHECK_RESULT(vkEndCommandBuffer(cmdBufferSet.ui)); + } + void buildCommandBuffer() { VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); - SecondaryCommandBuffer secondaryCmdBuffer = secondaryCommandBuffers[currentBuffer]; - // Just a demonstration, with this simple example, this won't gain performance, but shows how to do - { - - VkCommandBufferInheritanceRenderingInfoKHR inheritanceRenderingInfo = { - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR, - .colorAttachmentCount = 1, - .pColorAttachmentFormats = &swapChain.colorFormat, - .depthAttachmentFormat = depthFormat, - .stencilAttachmentFormat = depthFormat, - .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT, - }; - - VkCommandBufferInheritanceInfo inheritanceInfo = { - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, - .pNext = &inheritanceRenderingInfo - }; - - VkCommandBufferBeginInfo secCmdBufInfo{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, - .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, - .pInheritanceInfo = &inheritanceInfo, - }; - VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuffer.model, &secCmdBufInfo)); - - vkCmdSetViewport(secondaryCmdBuffer.model, 0, 1, &viewport); - - vkCmdSetScissor(secondaryCmdBuffer.model, 0, 1, &scissor); - - vkCmdBindDescriptorSets(secondaryCmdBuffer.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); - vkCmdBindPipeline(secondaryCmdBuffer.model, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - - model.draw(secondaryCmdBuffer.model, vkglTF::RenderFlags::BindImages, pipelineLayout); - - VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuffer.model)); - - // - - VK_CHECK_RESULT(vkBeginCommandBuffer(secondaryCmdBuffer.ui, &secCmdBufInfo)); + VkCommandBufferInheritanceRenderingInfoKHR inheritanceRenderingInfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR, + .colorAttachmentCount = 1, + .pColorAttachmentFormats = &swapChain.colorFormat, + .depthAttachmentFormat = depthFormat, + .stencilAttachmentFormat = depthFormat, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT, + }; - vkCmdSetViewport(secondaryCmdBuffer.ui, 0, 1, &viewport); - vkCmdSetScissor(secondaryCmdBuffer.ui, 0, 1, &scissor); + VkCommandBufferInheritanceInfo inheritanceInfo = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, + .pNext = &inheritanceRenderingInfo + }; - vkCmdBindDescriptorSets(secondaryCmdBuffer.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentBuffer], 0, nullptr); - vkCmdBindPipeline(secondaryCmdBuffer.ui, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + VkCommandBufferBeginInfo secCmdBufInfo{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, + .pInheritanceInfo = &inheritanceInfo, + }; - drawUI(secondaryCmdBuffer.ui); + SecondaryCommandBuffer secondaryCmdBufferSet = secondaryCommandBuffers[currentBuffer]; - VK_CHECK_RESULT(vkEndCommandBuffer(secondaryCmdBuffer.ui)); - } + buildSecondaryModelCommandBuffer(secondaryCmdBufferSet, inheritanceInfo); + buildSecondaryUICommandBuffer(secondaryCmdBufferSet, inheritanceInfo); VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; @@ -345,7 +355,7 @@ class VulkanExample : public VulkanExampleBase vkCmdBeginRenderingKHR(cmdBuffer, &renderingInfo); // No draw calls here, all done by executing the secondaries - std::vector cmdBuffers = { secondaryCmdBuffer.model, secondaryCmdBuffer .ui }; + std::vector cmdBuffers = { secondaryCmdBufferSet.model, secondaryCmdBufferSet.ui }; vkCmdExecuteCommands(cmdBuffer, static_cast(cmdBuffers.size()), cmdBuffers.data()); vkCmdEndRenderingKHR(cmdBuffer); From 9941d75b788cb06f6b6303ba17484f254be1dcb4 Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sun, 25 Oct 2026 12:33:52 +0100 Subject: [PATCH 6/9] Multi-thread secondary command buffer generation WIll prob. be slower (than not multi-threading) due to the simplicity of this sample Only there for demonstration purposes --- README.md | 4 ++ .../dynamicrenderingsecondary.cpp | 43 +++++++++++++------ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index e7f97db8e..639db1b67 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,10 @@ Vulkan is an extensible api with lots of functionality added by extensions. Thes Based on the dynamic rendering sample, this sample shows how to do implement multi sampling with dynamic rendering. +- [Dynamic rendering with secondary command bufferss](examples/dynamicrenderingsecondary/) - `VK_KHR_dynamic_rendering` + + Based on the dynamic rendering sample, this sample shows how to implement multi-threaded secondary commmand buffer creation with dynamic rendering. + - [Graphics pipeline library](./examples/graphicspipelinelibrary) - `VK_EXT_graphics_pipeline_library` Uses the graphics pipeline library extensions to improve run-time pipeline creation. Instead of creating the whole pipeline at once, this sample pre builds shared pipeline parts like like vertex input state and fragment output state. These are then used to create full pipelines at runtime, reducing build times and possible hick-ups. diff --git a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp index eaba82a8f..96d0652f0 100644 --- a/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp +++ b/examples/dynamicrenderingsecondary/dynamicrenderingsecondary.cpp @@ -1,8 +1,6 @@ /* * Vulkan Example - Using secondary command buffers with VK_KHR_dynamic_rendering * - * @todo: rebase on multithreading sample - * * Copyright (C) 2026 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) @@ -10,7 +8,7 @@ #include "vulkanexamplebase.h" #include "VulkanglTFModel.h" - +#include class VulkanExample : public VulkanExampleBase { @@ -26,6 +24,8 @@ class VulkanExample : public VulkanExampleBase VkCommandBuffer ui{ VK_NULL_HANDLE }; }; std::array secondaryCommandBuffers{}; + // We'll record secondary command buffers on multiple threads, and command pools need to be per thread + std::array commandPools{}; struct UniformData { glm::mat4 projection; @@ -74,6 +74,9 @@ class VulkanExample : public VulkanExampleBase for (auto& buffer : uniformBuffers) { buffer.destroy(); } + for (auto i = 0; i < commandPools.size(); i++) { + vkDestroyCommandPool(device, commandPools[i], nullptr); + } } } @@ -208,15 +211,26 @@ class VulkanExample : public VulkanExampleBase vkCmdBeginRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBeginRenderingKHR")); vkCmdEndRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR")); - // @todo - const VkCommandBufferAllocateInfo cmdBufAllocateInfo = { + // We'll record secondary command buffers on multiple threads, and command pools need to be per thread + const VkCommandPoolCreateInfo cmdPoolCI = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, + .queueFamilyIndex = vulkanDevice->queueFamilyIndices.graphics + }; + for (auto i = 0; i < commandPools.size(); i++) { + vkCreateCommandPool(device, &cmdPoolCI, nullptr, &commandPools[i]); + } + + // Allocate secondary command buffers + VkCommandBufferAllocateInfo cmdBufAllocateInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, - .commandPool = cmdPool, .level = VK_COMMAND_BUFFER_LEVEL_SECONDARY, .commandBufferCount = 1 }; - for (uint32_t i = 0; i < maxConcurrentFrames; i++) { + for (auto i = 0; i < maxConcurrentFrames; i++) { + cmdBufAllocateInfo.commandPool = commandPools[0]; VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCommandBuffers[i].model)); + cmdBufAllocateInfo.commandPool = commandPools[1]; VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &secondaryCommandBuffers[i].ui)); } @@ -227,8 +241,9 @@ class VulkanExample : public VulkanExampleBase prepared = true; } - void buildSecondaryModelCommandBuffer(SecondaryCommandBuffer cmdBufferSet, VkCommandBufferInheritanceInfo &inheritanceInfo) + void buildSecondaryModelCommandBuffer(SecondaryCommandBuffer& cmdBufferSet, VkCommandBufferInheritanceInfo& inheritanceInfo) { + SecondaryCommandBuffer secondaryCmdBufferSet = secondaryCommandBuffers[currentBuffer]; const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); const VkCommandBufferBeginInfo secCmdBufInfo{ @@ -245,7 +260,7 @@ class VulkanExample : public VulkanExampleBase VK_CHECK_RESULT(vkEndCommandBuffer(cmdBufferSet.model)); } - void buildSecondaryUICommandBuffer(SecondaryCommandBuffer cmdBufferSet, VkCommandBufferInheritanceInfo& inheritanceInfo) + void buildSecondaryUICommandBuffer(SecondaryCommandBuffer& cmdBufferSet, VkCommandBufferInheritanceInfo& inheritanceInfo) { const VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); const VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); @@ -268,8 +283,6 @@ class VulkanExample : public VulkanExampleBase VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); - // Just a demonstration, with this simple example, this won't gain performance, but shows how to do - VkCommandBufferInheritanceRenderingInfoKHR inheritanceRenderingInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR, .colorAttachmentCount = 1, @@ -292,8 +305,12 @@ class VulkanExample : public VulkanExampleBase SecondaryCommandBuffer secondaryCmdBufferSet = secondaryCommandBuffers[currentBuffer]; - buildSecondaryModelCommandBuffer(secondaryCmdBufferSet, inheritanceInfo); - buildSecondaryUICommandBuffer(secondaryCmdBufferSet, inheritanceInfo); + // Record secondary command buffers in parallel + // This is just for demonstration purposes, for such a simple use-case this won't improve performance (and most likel will be slower) + std::thread threadA(&VulkanExample::buildSecondaryModelCommandBuffer, this, std::ref(secondaryCmdBufferSet), std::ref(inheritanceInfo)); + std::thread threadB(&VulkanExample::buildSecondaryUICommandBuffer, this, std::ref(secondaryCmdBufferSet), std::ref(inheritanceInfo)); + threadA.join(); + threadB.join(); VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; From df2ba21b57a7050724e67c130c50a8402f87f32e Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sun, 25 Oct 2026 12:37:17 +0100 Subject: [PATCH 7/9] Add Android build files for dynamic rendering example --- .../dynamicrenderingsecondary/CMakeLists.txt | 35 ++++++++++ .../dynamicrenderingsecondary/build.gradle | 65 +++++++++++++++++++ .../src/main/AndroidManifest.xml | 24 +++++++ .../vulkanSample/VulkanActivity.java | 58 +++++++++++++++++ 4 files changed, 182 insertions(+) create mode 100644 android/examples/dynamicrenderingsecondary/CMakeLists.txt create mode 100644 android/examples/dynamicrenderingsecondary/build.gradle create mode 100644 android/examples/dynamicrenderingsecondary/src/main/AndroidManifest.xml create mode 100644 android/examples/dynamicrenderingsecondary/src/main/java/de/saschawillems/vulkanSample/VulkanActivity.java diff --git a/android/examples/dynamicrenderingsecondary/CMakeLists.txt b/android/examples/dynamicrenderingsecondary/CMakeLists.txt new file mode 100644 index 000000000..e10b8fbc3 --- /dev/null +++ b/android/examples/dynamicrenderingsecondary/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required(VERSION 3.10.0 FATAL_ERROR) + +set(NAME dynamicrenderingsecondary) + +set(SRC_DIR ../../../examples/${NAME}) +set(BASE_DIR ../../../base) +set(EXTERNAL_DIR ../../../external) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -DVK_USE_PLATFORM_ANDROID_KHR -DVK_NO_PROTOTYPES") + +file(GLOB EXAMPLE_SRC "${SRC_DIR}/*.cpp") + +add_library(native-lib SHARED ${EXAMPLE_SRC}) + +add_library(native-app-glue STATIC ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c) + +add_subdirectory(../base ${CMAKE_SOURCE_DIR}/../base) + +set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -u ANativeActivity_onCreate") + +include_directories(${BASE_DIR}) +include_directories(${EXTERNAL_DIR}) +include_directories(${EXTERNAL_DIR}/glm) +include_directories(${EXTERNAL_DIR}/imgui) +include_directories(${EXTERNAL_DIR}/tinygltf) +include_directories(${ANDROID_NDK}/sources/android/native_app_glue) + +target_link_libraries( + native-lib + native-app-glue + libbase + android + log + z +) diff --git a/android/examples/dynamicrenderingsecondary/build.gradle b/android/examples/dynamicrenderingsecondary/build.gradle new file mode 100644 index 000000000..7e869bc7f --- /dev/null +++ b/android/examples/dynamicrenderingsecondary/build.gradle @@ -0,0 +1,65 @@ +apply plugin: 'com.android.application' +apply from: '../gradle/outputfilename.gradle' + +android { + compileSdkVersion rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "de.saschawillems.vulkanDynamicrenderingsecondary" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + ndk { + abiFilters rootProject.ext.abiFilters + } + externalNativeBuild { + cmake { + cppFlags "-std=c++20" + arguments "-DANDROID_STL=c++_shared", '-DANDROID_TOOLCHAIN=clang', '-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON' + } + } + } + sourceSets { + main.assets.srcDirs = ['assets'] + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + externalNativeBuild { + cmake { + path "CMakeLists.txt" + } + } +} + +task copyTask { + copy { + from '../../common/res/drawable' + into "src/main/res/drawable" + include 'icon.png' + } + + copy { + from rootProject.ext.shaderPath + 'glsl/base' + into 'assets/shaders/glsl/base' + include '*.spv' + } + + copy { + from rootProject.ext.shaderPath + 'glsl/dynamicrendering' + into 'assets/shaders/glsl/dynamicrendering' + include '*.*' + } + + copy { + from rootProject.ext.assetPath + 'models' + into 'assets/models' + include 'voyager.gltf' + } + +} + +preBuild.dependsOn copyTask \ No newline at end of file diff --git a/android/examples/dynamicrenderingsecondary/src/main/AndroidManifest.xml b/android/examples/dynamicrenderingsecondary/src/main/AndroidManifest.xml new file mode 100644 index 000000000..8992a48f7 --- /dev/null +++ b/android/examples/dynamicrenderingsecondary/src/main/AndroidManifest.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/android/examples/dynamicrenderingsecondary/src/main/java/de/saschawillems/vulkanSample/VulkanActivity.java b/android/examples/dynamicrenderingsecondary/src/main/java/de/saschawillems/vulkanSample/VulkanActivity.java new file mode 100644 index 000000000..12e14fc6d --- /dev/null +++ b/android/examples/dynamicrenderingsecondary/src/main/java/de/saschawillems/vulkanSample/VulkanActivity.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2018 by Sascha Willems - www.saschawillems.de + * + * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) + */ +package de.saschawillems.vulkanSample; + +import android.app.AlertDialog; +import android.app.NativeActivity; +import android.content.DialogInterface; +import android.content.pm.ApplicationInfo; +import android.os.Bundle; + +import java.util.concurrent.Semaphore; + +public class VulkanActivity extends NativeActivity { + + static { + // Load native library + System.loadLibrary("native-lib"); + } + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + // Use a semaphore to create a modal dialog + + private final Semaphore semaphore = new Semaphore(0, true); + + public void showAlert(final String message) + { + final VulkanActivity activity = this; + + ApplicationInfo applicationInfo = activity.getApplicationInfo(); + final String applicationName = applicationInfo.nonLocalizedLabel.toString(); + + this.runOnUiThread(new Runnable() { + public void run() { + AlertDialog.Builder builder = new AlertDialog.Builder(activity, android.R.style.Theme_Material_Dialog_Alert); + builder.setTitle(applicationName); + builder.setMessage(message); + builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + semaphore.release(); + } + }); + builder.setCancelable(false); + AlertDialog dialog = builder.create(); + dialog.show(); + } + }); + try { + semaphore.acquire(); + } + catch (InterruptedException e) { } + } +} From cd9b9e1e7b6fa0b0f6199c73abddc4924766c7fa Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sat, 7 Nov 2026 15:19:48 +0100 Subject: [PATCH 8/9] Start work on sample for VK_KHR_device_address_commands --- base/VulkanBuffer.h | 4 +- examples/CMakeLists.txt | 1 + .../deviceaddresscommands.cpp | 494 ++++++++++++++++++ shaders/glsl/deviceaddresscommands/cube.frag | 18 + shaders/glsl/deviceaddresscommands/cube.vert | 36 ++ 5 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 examples/deviceaddresscommands/deviceaddresscommands.cpp create mode 100644 shaders/glsl/deviceaddresscommands/cube.frag create mode 100644 shaders/glsl/deviceaddresscommands/cube.vert diff --git a/base/VulkanBuffer.h b/base/VulkanBuffer.h index 770213515..1a8bc8a95 100644 --- a/base/VulkanBuffer.h +++ b/base/VulkanBuffer.h @@ -3,7 +3,7 @@ * * Encapsulates a Vulkan buffer * -* Copyright (C) 2016-2025 by Sascha Willems - www.saschawillems.de +* Copyright (C) 2016-2026 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ @@ -34,7 +34,7 @@ namespace vks VkBufferUsageFlags usageFlags; /** @brief Memory property flags to be filled by external source at buffer creation (to query at some later point) */ VkMemoryPropertyFlags memoryPropertyFlags; - uint64_t deviceAddress; + uint64_t deviceAddress{}; VkResult map(VkDeviceSize size = VK_WHOLE_SIZE, VkDeviceSize offset = 0); void unmap(); VkResult bind(VkDeviceSize offset = 0); diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 4cce0b55f..744f3a924 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -108,6 +108,7 @@ set(EXAMPLES descriptorheapuntyped descriptorindexing descriptorsets + deviceaddresscommands displacement distancefieldfonts dynamicrendering diff --git a/examples/deviceaddresscommands/deviceaddresscommands.cpp b/examples/deviceaddresscommands/deviceaddresscommands.cpp new file mode 100644 index 000000000..500568d26 --- /dev/null +++ b/examples/deviceaddresscommands/deviceaddresscommands.cpp @@ -0,0 +1,494 @@ +/* +* Vulkan Example - Device address commands (VK_KHR_device_address_commands) +* +* todo +* +* Copyright (C) 2026 by Sascha Willems - www.saschawillems.de +* +*/ + +#include "vulkanexamplebase.h" +#include "VulkanglTFModel.h" + +class VulkanExample : public VulkanExampleBase +{ +public: + bool animate = true; + + struct Cube { + glm::mat4 modelMatrix; + glm::vec3 rotation{ }; + std::array buffers{}; + std::array bufferDeviceAddresses{}; + }; + std::array cubes{}; + + vks::Texture2D texture; + vkglTF::Model model; + + // Global matrices + struct Scene { + glm::mat4 mvp; + std::array buffers; + std::array bufferDeviceAddresses{}; + } scene; + + VkPipeline pipeline{ VK_NULL_HANDLE }; + VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE }; + VkDescriptorSet descriptorSet{ VK_NULL_HANDLE }; + VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE }; + + PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR{ VK_NULL_HANDLE }; + VkPhysicalDeviceBufferDeviceAddressFeatures enabledBufferDeviceAddresFeatures{}; + + PFN_vkCmdFillMemoryKHR vkCmdFillMemoryKHR{ VK_NULL_HANDLE }; + PFN_vkCmdBindVertexBuffers3KHR vkCmdBindVertexBuffers3KHR{ VK_NULL_HANDLE }; + PFN_vkCmdBindIndexBuffer3KHR vkCmdBindIndexBuffer3KHR{ VK_NULL_HANDLE }; + PFN_vkCmdDrawIndexedIndirect2KHR vkCmdDrawIndexedIndirect2KHR{ VK_NULL_HANDLE }; + VkPhysicalDeviceDeviceAddressCommandsFeaturesKHR enabledDeviceDeviceAddressCommandsFeaturesKHR{}; + + // This sample passes the buffer references ("pointer") using push constants, the shader then reads data from that buffer address + struct PushConstantBlock { + // Reference to the global matrices + VkDeviceAddress sceneReference; + // Reference to the per model matrices + VkDeviceAddress modelReference; + }; + + struct Vertex { + float position[3]; + float color[3]; + }; + + vks::Buffer vertexBuffer; + vks::Buffer indexBuffer; + uint32_t indexCount{ 0 }; + + vks::Buffer indirectDrawBuffer; + + VulkanExample() : VulkanExampleBase() + { + title = "Device address commands"; + camera.type = Camera::CameraType::lookat; + camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 512.0f); + camera.setRotation(glm::vec3(0.0f, -180.0f, 0.0f)); + camera.setTranslation(glm::vec3(0.0f, 0.0f, -2.5f)); + + enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + enabledInstanceExtensions.push_back(VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_DEVICE_GROUP_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME); + enabledDeviceExtensions.push_back(VK_KHR_DEVICE_ADDRESS_COMMANDS_EXTENSION_NAME); + + enabledBufferDeviceAddresFeatures = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, + .bufferDeviceAddress = VK_TRUE + }; + + enabledDeviceDeviceAddressCommandsFeaturesKHR = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEVICE_ADDRESS_COMMANDS_FEATURES_KHR, + .pNext = &enabledBufferDeviceAddresFeatures, + .deviceAddressCommands = VK_TRUE + }; + + deviceCreatepNextChain = &enabledDeviceDeviceAddressCommandsFeaturesKHR; + } + + ~VulkanExample() + { + if (device) { + vkDestroyPipeline(device, pipeline, nullptr); + vkDestroyPipelineLayout(device, pipelineLayout, nullptr); + vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); + texture.destroy(); + for (auto& cube : cubes) { + for (auto& buffer : cube.buffers) { + buffer.destroy(); + } + } + for (auto& buffer : scene.buffers) { + buffer.destroy(); + } + } + } + + virtual void getEnabledFeatures() + { + if (deviceFeatures.samplerAnisotropy) { + enabledFeatures.samplerAnisotropy = VK_TRUE; + }; + } + + uint64_t getBufferDeviceAddress(VkBuffer buffer) + { + VkBufferDeviceAddressInfoKHR bufferDeviceAI{ .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = buffer}; + return vkGetBufferDeviceAddressKHR(vulkanDevice->logicalDevice, &bufferDeviceAI); + } + + void loadAssets() + { + const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; + model.loadFromFile(getAssetPath() + "models/cube.gltf", vulkanDevice, queue, glTFLoadingFlags); + texture.loadFromFile(getAssetPath() + "textures/crate01_color_height_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue); + // @todo + createVertexBuffer(); + } + + // Rename... + void createVertexBuffer() + { + // @todo: create multiple triangles, maybe with texture mapping or at least different color + // @todo: then switch BDA (triangle) in shader based on draw index? + // @todo: combine vtx and idx buffer into single buffer + + std::vector vertices = { + { { 1.0f, 1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, + { { -1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, + { { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } } + }; + uint32_t vertexBufferSize = static_cast(vertices.size()) * sizeof(Vertex); + std::vector indices = { 0, 1, 2 }; + indexCount = static_cast(indices.size()); + uint32_t indexBufferSize = indexCount * sizeof(uint32_t); + + struct StagingBuffers { + vks::Buffer vertexBuffer; + vks::Buffer indexBuffer; + } stagingBuffers; + + // Host visible source buffers (staging) + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + &stagingBuffers.vertexBuffer, + vertexBufferSize, + vertices.data())); + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + &stagingBuffers.indexBuffer, + indexBufferSize, + indices.data())); + + // Device local destination buffers + // @todo: check if vtx/idx buf flags are still required + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + &vertexBuffer, + vertexBufferSize)); + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + &indexBuffer, + indexBufferSize)); + + // Copy from host do device + vulkanDevice->copyBuffer(&stagingBuffers.vertexBuffer, &vertexBuffer, queue); + vulkanDevice->copyBuffer(&stagingBuffers.indexBuffer, &indexBuffer, queue); + + // Clean up + stagingBuffers.vertexBuffer.destroy(); + stagingBuffers.indexBuffer.destroy(); + + // Indirect draw buffer + // @todo + uint32_t indirectDrawBufferSize = sizeof(VkDrawIndexedIndirectCommand); + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + &indirectDrawBuffer, + vertexBufferSize)); + + vertexBuffer.deviceAddress = getBufferDeviceAddress(vertexBuffer.buffer); + indexBuffer.deviceAddress = getBufferDeviceAddress(indexBuffer.buffer); + indirectDrawBuffer.deviceAddress = getBufferDeviceAddress(indirectDrawBuffer.buffer); + } + + void setupDescriptors() + { + // Pool + std::vector descriptorPoolSizes = { + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) + }; + VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(descriptorPoolSizes, 2); + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + // Layout + std::vector setLayoutBindings = { + vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0) + }; + VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); + // Set + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); + std::vector writeDescriptorSets = { + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &texture.descriptor) + }; + vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); + } + + void preparePipelines() + { + // The buffer addresses will be passed to the shader using push constants + // That way it's very easy to do a draw call, change the reference to another buffer (or part of that buffer) and do the next draw call using different data + VkPushConstantRange pushConstantRange{ + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, + .offset = 0, + .size = sizeof(PushConstantBlock) + }; + + VkPipelineLayoutCreateInfo pipelineLayoutCI{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = 1, + .pSetLayouts = &descriptorSetLayout, + .pushConstantRangeCount = 1, + .pPushConstantRanges = &pushConstantRange + }; + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayout)); + + const std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + + VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCI = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineRasterizationStateCreateInfo rasterizationStateCI = 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); + VkPipelineColorBlendStateCreateInfo colorBlendStateCI = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); + VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); + VkPipelineViewportStateCreateInfo viewportStateCI = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); + VkPipelineMultisampleStateCreateInfo multisampleStateCI = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineDynamicStateCreateInfo dynamicStateCI = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), static_cast(dynamicStateEnables.size()), 0); + std::array shaderStages = { + loadShader(getShadersPath() + "deviceaddresscommands/cube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + loadShader(getShadersPath() + "deviceaddresscommands/cube.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT) + }; + + // Vertex bindings and attributes + std::vector vertexInputBindings{ + vks::initializers::vertexInputBindingDescription(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), + }; + std::vector vertexInputAttributes{ + vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, position)), + vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, color)), + }; + VkPipelineVertexInputStateCreateInfo vertexInputState{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, + .vertexBindingDescriptionCount = static_cast(vertexInputBindings.size()), + .pVertexBindingDescriptions = vertexInputBindings.data(), + .vertexAttributeDescriptionCount = static_cast(vertexInputAttributes.size()), + .pVertexAttributeDescriptions = vertexInputAttributes.data() + }; + + VkGraphicsPipelineCreateInfo pipelineCI{ + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .stageCount = static_cast(shaderStages.size()), + .pStages = shaderStages.data(), + .pVertexInputState = &vertexInputState, + .pInputAssemblyState = &inputAssemblyStateCI, + .pViewportState = &viewportStateCI, + .pRasterizationState = &rasterizationStateCI, + .pMultisampleState = &multisampleStateCI, + .pDepthStencilState = &depthStencilStateCI, + .pColorBlendState = &colorBlendStateCI, + .pDynamicState = &dynamicStateCI, + .layout = pipelineLayout, + .renderPass = renderPass + }; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); + } + + void prepareUniformBuffers() + { + for (uint32_t i = 0; i < maxConcurrentFrames; i++) { + // Note that we don't use this buffer for uniforms but rather pass it's address as a reference to the shader, so isntead of the uniform buffer usage we use a different flag + VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &scene.buffers[i], sizeof(glm::mat4))); + VK_CHECK_RESULT(scene.buffers[i].map()); + + // Get the device of this buffer that is later on passed to the shader (aka "reference") + VkBufferDeviceAddressInfo bufferDeviceAdressInfo{ + .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, + .buffer = scene.buffers[i].buffer + }; + scene.bufferDeviceAddresses[i] = vkGetBufferDeviceAddressKHR(device, &bufferDeviceAdressInfo); + + for (auto& cube : cubes) { + // Note that we don't use this buffer for uniforms but rather pass it's address as a reference to the shader, so isntead of the uniform buffer usage we use a different flag + VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &cube.buffers[i], sizeof(glm::mat4))); + VK_CHECK_RESULT(cube.buffers[i].map()); + + // Get the device of this buffer that is later on passed to the shader (aka "reference") + bufferDeviceAdressInfo.buffer = cube.buffers[i].buffer; + cube.bufferDeviceAddresses[i] = vkGetBufferDeviceAddressKHR(device, &bufferDeviceAdressInfo); + } + } + } + + void updateUniformBuffers() + { + scene.mvp = camera.matrices.perspective * camera.matrices.view; + memcpy(scene.buffers[currentBuffer].mapped, &scene, sizeof(glm::mat4)); + + cubes[0].modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); + cubes[1].modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(1.5f, 0.5f, 0.0f)); + + for (auto& cube : cubes) { + //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(cube.rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); + //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); + //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(cube.rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); + //cube.modelMatrix = glm::scale(cube.modelMatrix, glm::vec3(0.25f)); + memcpy(cube.buffers[currentBuffer].mapped, &cube.modelMatrix, sizeof(glm::mat4)); + } + } + + void prepare() + { + VulkanExampleBase::prepare(); + + vkGetBufferDeviceAddressKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkGetBufferDeviceAddressKHR")); + vkCmdFillMemoryKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdFillMemoryKHR")); + vkCmdBindVertexBuffers3KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBindVertexBuffers3KHR")); + vkCmdBindIndexBuffer3KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBindIndexBuffer3KHR")); + vkCmdDrawIndexedIndirect2KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdDrawIndexedIndirect2KHR")); + + loadAssets(); + prepareUniformBuffers(); + setupDescriptors(); + preparePipelines(); + prepared = true; + } + + void buildCommandBuffer() + { + VkCommandBuffer cmdBuffer = drawCmdBuffers[currentBuffer]; + + VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); + + VkClearValue clearValues[2]{}; + clearValues[0].color = defaultClearColor; + clearValues[1].depthStencil = { 1.0f, 0 }; + + VkRenderPassBeginInfo renderPassBeginInfo{ + .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, + .renderPass = renderPass, + .framebuffer = frameBuffers[currentImageIndex], + .renderArea = {.offset = {.x = 0, .y = 0 }, .extent = {.width = width, .height = height } }, + .clearValueCount = 2, + .pClearValues = clearValues, + }; + + VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo)); + + vkCmdBeginRenderPass(cmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + vkCmdSetViewport(cmdBuffer, 0, 1, &viewport); + + VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + vkCmdSetScissor(cmdBuffer, 0, 1, &scissor); + + vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); + + // @todo + VkBindVertexBuffer3InfoKHR vertexBindingInfo = { + .sType = VK_STRUCTURE_TYPE_BIND_VERTEX_BUFFER_3_INFO_KHR, + .addressRange = {vertexBuffer.deviceAddress, vertexBuffer.size}, + .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, + }; + + VkBindIndexBuffer3InfoKHR indexBindingInfo = { + .sType = VK_STRUCTURE_TYPE_BIND_INDEX_BUFFER_3_INFO_KHR, + .addressRange = {indexBuffer.deviceAddress, indexBuffer.size}, + .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, + .indexType = VK_INDEX_TYPE_UINT32, + }; + + VkDrawIndirect2InfoKHR indirectInfo = { + .sType = VK_STRUCTURE_TYPE_DRAW_INDIRECT_2_INFO_KHR, + .addressRange = {indirectDrawBuffer.deviceAddress, indirectDrawBuffer.size, sizeof(VkDrawIndexedIndirectCommand)}, + .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, + .drawCount = 1 + }; + + VkDeviceAddressRangeKHR range = { + .address = indirectDrawBuffer.deviceAddress, + .size = sizeof(uint32_t) + //.size = indirectDrawBuffer.size + }; + + VkDrawIndexedIndirectCommand idc = { + .indexCount = 6, + .instanceCount = 1, + .firstIndex = 0 + }; + vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.indexCount); + range.address += sizeof(uint32_t); + vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.instanceCount); + range.address += sizeof(uint32_t); + vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.firstIndex); + + vkCmdBindVertexBuffers3KHR(cmdBuffer, 0, 1, &vertexBindingInfo); + vkCmdBindIndexBuffer3KHR(cmdBuffer, &indexBindingInfo); + + //model.bindBuffers(cmdBuffer); + + // Instead of using descriptors to pass global and per-model matrices to the shader, we can now simply pass buffer references via push constants + // The shader then simply reads data from the address of that reference + PushConstantBlock references{}; + // Pass pointer to the global matrix via a buffer device address + references.sceneReference = scene.bufferDeviceAddresses[currentBuffer]; + references.modelReference = cubes[0].bufferDeviceAddresses[currentBuffer]; + vkCmdPushConstants(cmdBuffer, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(PushConstantBlock), &references); + + vkCmdDrawIndexedIndirect2KHR(cmdBuffer, &indirectInfo); + + /* + for (auto& cube : cubes) { + // Pass pointer to this cube's data buffer via a buffer device address + // So instead of having to bind different descriptors, we only pass a different device address + // This doesn't have to be an address from a different buffer, but could very well be just another address in the same buffer + references.modelReference = cube.bufferDeviceAddresses[currentBuffer]; + vkCmdPushConstants(cmdBuffer, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(PushConstantBlock), &references); + + model.draw(cmdBuffer); + } + */ + + //drawUI(cmdBuffer); + + vkCmdEndRenderPass(cmdBuffer); + + VK_CHECK_RESULT(vkEndCommandBuffer(cmdBuffer)); + } + + virtual void render() + { + if (!prepared) + return; + VulkanExampleBase::prepareFrame(); + /* + if (animate && !paused) { + cubes[0].rotation.x += 2.5f * frameTimer; + if (cubes[0].rotation.x > 360.0f) + cubes[0].rotation.x -= 360.0f; + cubes[1].rotation.y += 2.0f * frameTimer; + if (cubes[1].rotation.x > 360.0f) + cubes[1].rotation.x -= 360.0f; + } + */ + updateUniformBuffers(); + buildCommandBuffer(); + VulkanExampleBase::submitFrame(); + } + + virtual void OnUpdateUIOverlay(vks::UIOverlay* overlay) + { + if (overlay->header("Settings")) { + overlay->checkBox("Animate", &animate); + } + } +}; + +VULKAN_EXAMPLE_MAIN() diff --git a/shaders/glsl/deviceaddresscommands/cube.frag b/shaders/glsl/deviceaddresscommands/cube.frag new file mode 100644 index 000000000..72bcee6f4 --- /dev/null +++ b/shaders/glsl/deviceaddresscommands/cube.frag @@ -0,0 +1,18 @@ +/* Copyright (c) 2026, Sascha Willems + * + * SPDX-License-Identifier: MIT + * + */ + +#version 450 + +layout (set = 0, binding = 0) uniform sampler2D samplerColorMap; + +layout (location = 0) in vec3 inColor; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + outFragColor = vec4(inColor, 1.0); +} \ No newline at end of file diff --git a/shaders/glsl/deviceaddresscommands/cube.vert b/shaders/glsl/deviceaddresscommands/cube.vert new file mode 100644 index 000000000..fed3f7d94 --- /dev/null +++ b/shaders/glsl/deviceaddresscommands/cube.vert @@ -0,0 +1,36 @@ +/* Copyright (c) 2026, Sascha Willems + * + * SPDX-License-Identifier: MIT + * + */ + +#version 450 + +#extension GL_EXT_scalar_block_layout: require +#extension GL_EXT_buffer_reference : require + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inColor; + +layout (buffer_reference, scalar) readonly buffer MatrixReference { + mat4 matrix; +}; + +layout (push_constant) uniform PushConstants +{ + // Pointer to the buffer with the scene's MVP matrix + MatrixReference sceneDataReference; + // Pointer to the buffer for the data for each model + MatrixReference modelDataReference; +} pushConstants; + +layout (location = 0) out vec3 outColor; + +void main() +{ + MatrixReference sceneData = pushConstants.sceneDataReference; + MatrixReference modelData = pushConstants.modelDataReference; + + outColor = inColor; + gl_Position = sceneData.matrix * modelData.matrix * vec4(inPos.xyz, 1.0); +} \ No newline at end of file From d8041c83a760fd0b1ce28c450539c6e12e1a2c4e Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sun, 8 Nov 2026 12:48:13 +0100 Subject: [PATCH 9/9] Polish new VK_KHR_device_address_commands sample --- README.md | 9 + .../deviceaddresscommands.cpp | 302 +++++------------- shaders/glsl/deviceaddresscommands/cube.frag | 2 - .../glsl/deviceaddresscommands/cube.frag.spv | Bin 0 -> 500 bytes shaders/glsl/deviceaddresscommands/cube.vert | 8 +- .../glsl/deviceaddresscommands/cube.vert.spv | Bin 0 -> 1988 bytes 6 files changed, 90 insertions(+), 231 deletions(-) create mode 100644 shaders/glsl/deviceaddresscommands/cube.frag.spv create mode 100644 shaders/glsl/deviceaddresscommands/cube.vert.spv diff --git a/README.md b/README.md index 639db1b67..b86549bae 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ + + # Vulkan C++ examples and demos A comprehensive collection of open source C++ examples for [VulkanĀ®](https://www.vulkan.org), the low-level graphics and compute API from Khronos. @@ -503,6 +508,10 @@ Vulkan is an extensible api with lots of functionality added by extensions. Thes Demonstrates how to access barycentric coordinates in a fragment shader to create a wireframe visual effect. +- [Device address commands](./examples/deviceaddresscommands/) - `VK_KHR_device_address_commands` + + Builds upon buffer device address and demonstrates how to use device addresses for additional buffer types like vertex, index and indirect draw commands. + ### Effects Assorted samples showing graphical effects not special to Vulkan. diff --git a/examples/deviceaddresscommands/deviceaddresscommands.cpp b/examples/deviceaddresscommands/deviceaddresscommands.cpp index 500568d26..2de2e7632 100644 --- a/examples/deviceaddresscommands/deviceaddresscommands.cpp +++ b/examples/deviceaddresscommands/deviceaddresscommands.cpp @@ -1,68 +1,48 @@ /* -* Vulkan Example - Device address commands (VK_KHR_device_address_commands) +* Vulkan Example - Device address commands +* +* This sample shows how to use buffer device addresses for additional functionality via the VK_KHR_device_address_commands extension. +* The extension builts upon VK_KHR_buffer_device_address and lets you use handles instead of buffer objects for functionality +* like vertex, index and indirect draw buffers * -* todo -* * Copyright (C) 2026 by Sascha Willems - www.saschawillems.de * */ #include "vulkanexamplebase.h" -#include "VulkanglTFModel.h" class VulkanExample : public VulkanExampleBase { public: - bool animate = true; - - struct Cube { - glm::mat4 modelMatrix; - glm::vec3 rotation{ }; - std::array buffers{}; - std::array bufferDeviceAddresses{}; - }; - std::array cubes{}; - - vks::Texture2D texture; - vkglTF::Model model; - - // Global matrices struct Scene { - glm::mat4 mvp; + struct Matrices { + glm::mat4 camera; + glm::mat4 model[2]; + } matrices; std::array buffers; - std::array bufferDeviceAddresses{}; } scene; VkPipeline pipeline{ VK_NULL_HANDLE }; VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE }; - VkDescriptorSet descriptorSet{ VK_NULL_HANDLE }; - VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE }; PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR{ VK_NULL_HANDLE }; VkPhysicalDeviceBufferDeviceAddressFeatures enabledBufferDeviceAddresFeatures{}; - PFN_vkCmdFillMemoryKHR vkCmdFillMemoryKHR{ VK_NULL_HANDLE }; + PFN_vkCmdUpdateMemoryKHR vkCmdUpdateMemoryKHR{ VK_NULL_HANDLE }; PFN_vkCmdBindVertexBuffers3KHR vkCmdBindVertexBuffers3KHR{ VK_NULL_HANDLE }; PFN_vkCmdBindIndexBuffer3KHR vkCmdBindIndexBuffer3KHR{ VK_NULL_HANDLE }; PFN_vkCmdDrawIndexedIndirect2KHR vkCmdDrawIndexedIndirect2KHR{ VK_NULL_HANDLE }; VkPhysicalDeviceDeviceAddressCommandsFeaturesKHR enabledDeviceDeviceAddressCommandsFeaturesKHR{}; - // This sample passes the buffer references ("pointer") using push constants, the shader then reads data from that buffer address - struct PushConstantBlock { - // Reference to the global matrices - VkDeviceAddress sceneReference; - // Reference to the per model matrices - VkDeviceAddress modelReference; - }; - struct Vertex { float position[3]; float color[3]; }; vks::Buffer vertexBuffer; - vks::Buffer indexBuffer; - uint32_t indexCount{ 0 }; + uint32_t vertexBufferSize{ 0 }; + uint32_t indexBufferSize{ 0 }; + uint32_t indirectDrawBufferSize{ 0 }; vks::Buffer indirectDrawBuffer; @@ -71,7 +51,7 @@ class VulkanExample : public VulkanExampleBase title = "Device address commands"; camera.type = Camera::CameraType::lookat; camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 512.0f); - camera.setRotation(glm::vec3(0.0f, -180.0f, 0.0f)); + camera.setRotation(glm::vec3(0.0f, 0.0f, 0.0f)); camera.setTranslation(glm::vec3(0.0f, 0.0f, -2.5f)); enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); @@ -82,6 +62,8 @@ class VulkanExample : public VulkanExampleBase enabledDeviceExtensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME); enabledDeviceExtensions.push_back(VK_KHR_DEVICE_ADDRESS_COMMANDS_EXTENSION_NAME); + enabledFeatures.multiDrawIndirect = VK_TRUE; + enabledBufferDeviceAddresFeatures = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, .bufferDeviceAddress = VK_TRUE @@ -94,6 +76,7 @@ class VulkanExample : public VulkanExampleBase }; deviceCreatepNextChain = &enabledDeviceDeviceAddressCommandsFeaturesKHR; + } ~VulkanExample() @@ -101,16 +84,11 @@ class VulkanExample : public VulkanExampleBase if (device) { vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); - vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); - texture.destroy(); - for (auto& cube : cubes) { - for (auto& buffer : cube.buffers) { - buffer.destroy(); - } - } for (auto& buffer : scene.buffers) { buffer.destroy(); } + indirectDrawBuffer.destroy(); + vertexBuffer.destroy(); } } @@ -127,123 +105,68 @@ class VulkanExample : public VulkanExampleBase return vkGetBufferDeviceAddressKHR(vulkanDevice->logicalDevice, &bufferDeviceAI); } - void loadAssets() + void createBuffers() { - const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; - model.loadFromFile(getAssetPath() + "models/cube.gltf", vulkanDevice, queue, glTFLoadingFlags); - texture.loadFromFile(getAssetPath() + "textures/crate01_color_height_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue); - // @todo - createVertexBuffer(); - } - - // Rename... - void createVertexBuffer() - { - // @todo: create multiple triangles, maybe with texture mapping or at least different color - // @todo: then switch BDA (triangle) in shader based on draw index? - // @todo: combine vtx and idx buffer into single buffer - std::vector vertices = { + // First triangle { { 1.0f, 1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, { { -1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, - { { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } } + { { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, + // Second triangle + { { 1.0f, -1.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, + { { -1.0f, -1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, + { { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } } }; - uint32_t vertexBufferSize = static_cast(vertices.size()) * sizeof(Vertex); - std::vector indices = { 0, 1, 2 }; - indexCount = static_cast(indices.size()); - uint32_t indexBufferSize = indexCount * sizeof(uint32_t); + std::vector indices = { 2, 1, 0, 5, 4, 3 }; + vertexBufferSize = static_cast(vertices.size()) * sizeof(Vertex); + indexBufferSize = static_cast(indices.size()) * sizeof(uint32_t); - struct StagingBuffers { - vks::Buffer vertexBuffer; - vks::Buffer indexBuffer; - } stagingBuffers; + vks::Buffer stagingBuffer; // Host visible source buffers (staging) VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &stagingBuffers.vertexBuffer, - vertexBufferSize, - vertices.data())); - VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &stagingBuffers.indexBuffer, - indexBufferSize, - indices.data())); + &stagingBuffer, + vertexBufferSize + indexBufferSize)); + stagingBuffer.map(); + // Vertex and index buffer are combined into one buffer (vertices first, then indices) + memcpy(stagingBuffer.mapped, vertices.data(), vertexBufferSize); + memcpy((char*)stagingBuffer.mapped + vertexBufferSize, indices.data(), indexBufferSize); - // Device local destination buffers - // @todo: check if vtx/idx buf flags are still required VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &vertexBuffer, - vertexBufferSize)); - VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - &indexBuffer, - indexBufferSize)); - - // Copy from host do device - vulkanDevice->copyBuffer(&stagingBuffers.vertexBuffer, &vertexBuffer, queue); - vulkanDevice->copyBuffer(&stagingBuffers.indexBuffer, &indexBuffer, queue); + vertexBufferSize + indexBufferSize)); - // Clean up - stagingBuffers.vertexBuffer.destroy(); - stagingBuffers.indexBuffer.destroy(); + vulkanDevice->copyBuffer(&stagingBuffer, &vertexBuffer, queue); + stagingBuffer.destroy(); - // Indirect draw buffer - // @todo - uint32_t indirectDrawBufferSize = sizeof(VkDrawIndexedIndirectCommand); + // Indirect draw buffer for two draw calls (one per triangle) + indirectDrawBufferSize = 2 * sizeof(VkDrawIndexedIndirectCommand); VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &indirectDrawBuffer, vertexBufferSize)); + // With VK_KHR_device_address_commands we can access vertex/index and indirect draw buffers by their device address vertexBuffer.deviceAddress = getBufferDeviceAddress(vertexBuffer.buffer); - indexBuffer.deviceAddress = getBufferDeviceAddress(indexBuffer.buffer); indirectDrawBuffer.deviceAddress = getBufferDeviceAddress(indirectDrawBuffer.buffer); } - void setupDescriptors() - { - // Pool - std::vector descriptorPoolSizes = { - vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) - }; - VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(descriptorPoolSizes, 2); - VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); - // Layout - std::vector setLayoutBindings = { - vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0) - }; - VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); - VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); - // Set - VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); - std::vector writeDescriptorSets = { - vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &texture.descriptor) - }; - vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); - } - void preparePipelines() { // The buffer addresses will be passed to the shader using push constants - // That way it's very easy to do a draw call, change the reference to another buffer (or part of that buffer) and do the next draw call using different data VkPushConstantRange pushConstantRange{ .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, - .size = sizeof(PushConstantBlock) + .size = sizeof(VkDeviceAddress) }; VkPipelineLayoutCreateInfo pipelineLayoutCI{ .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .setLayoutCount = 1, - .pSetLayouts = &descriptorSetLayout, .pushConstantRangeCount = 1, .pPushConstantRanges = &pushConstantRange }; @@ -252,7 +175,7 @@ class VulkanExample : public VulkanExampleBase const std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCI = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendStateCI = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); @@ -304,41 +227,16 @@ class VulkanExample : public VulkanExampleBase // Note that we don't use this buffer for uniforms but rather pass it's address as a reference to the shader, so isntead of the uniform buffer usage we use a different flag VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &scene.buffers[i], sizeof(glm::mat4))); VK_CHECK_RESULT(scene.buffers[i].map()); - - // Get the device of this buffer that is later on passed to the shader (aka "reference") - VkBufferDeviceAddressInfo bufferDeviceAdressInfo{ - .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, - .buffer = scene.buffers[i].buffer - }; - scene.bufferDeviceAddresses[i] = vkGetBufferDeviceAddressKHR(device, &bufferDeviceAdressInfo); - - for (auto& cube : cubes) { - // Note that we don't use this buffer for uniforms but rather pass it's address as a reference to the shader, so isntead of the uniform buffer usage we use a different flag - VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &cube.buffers[i], sizeof(glm::mat4))); - VK_CHECK_RESULT(cube.buffers[i].map()); - - // Get the device of this buffer that is later on passed to the shader (aka "reference") - bufferDeviceAdressInfo.buffer = cube.buffers[i].buffer; - cube.bufferDeviceAddresses[i] = vkGetBufferDeviceAddressKHR(device, &bufferDeviceAdressInfo); - } + scene.buffers[i].deviceAddress = getBufferDeviceAddress(scene.buffers[i].buffer); } } void updateUniformBuffers() { - scene.mvp = camera.matrices.perspective * camera.matrices.view; - memcpy(scene.buffers[currentBuffer].mapped, &scene, sizeof(glm::mat4)); - - cubes[0].modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); - cubes[1].modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(1.5f, 0.5f, 0.0f)); - - for (auto& cube : cubes) { - //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(cube.rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); - //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); - //cube.modelMatrix = glm::rotate(cube.modelMatrix, glm::radians(cube.rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); - //cube.modelMatrix = glm::scale(cube.modelMatrix, glm::vec3(0.25f)); - memcpy(cube.buffers[currentBuffer].mapped, &cube.modelMatrix, sizeof(glm::mat4)); - } + scene.matrices.camera = camera.matrices.perspective * camera.matrices.view; + scene.matrices.model[0] = glm::translate(glm::mat4(1.0f), glm::vec3(-1.0f, 0.0f, 0.0f)); + scene.matrices.model[1] = glm::translate(glm::mat4(1.0f), glm::vec3( 1.0f, 0.0f, 0.0f)); + memcpy(scene.buffers[currentBuffer].mapped, &scene.matrices, sizeof(scene.matrices)); } void prepare() @@ -346,14 +244,13 @@ class VulkanExample : public VulkanExampleBase VulkanExampleBase::prepare(); vkGetBufferDeviceAddressKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkGetBufferDeviceAddressKHR")); - vkCmdFillMemoryKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdFillMemoryKHR")); + vkCmdUpdateMemoryKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdUpdateMemoryKHR")); vkCmdBindVertexBuffers3KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBindVertexBuffers3KHR")); vkCmdBindIndexBuffer3KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBindIndexBuffer3KHR")); vkCmdDrawIndexedIndirect2KHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdDrawIndexedIndirect2KHR")); - loadAssets(); + createBuffers(); prepareUniformBuffers(); - setupDescriptors(); preparePipelines(); prepared = true; } @@ -389,74 +286,49 @@ class VulkanExample : public VulkanExampleBase VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(cmdBuffer, 0, 1, &scissor); - vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); - - // @todo - VkBindVertexBuffer3InfoKHR vertexBindingInfo = { - .sType = VK_STRUCTURE_TYPE_BIND_VERTEX_BUFFER_3_INFO_KHR, - .addressRange = {vertexBuffer.deviceAddress, vertexBuffer.size}, + // Update indirect draw commands + // Note that this is an artificial example, as the draw calls never actually change + VkDrawIndirect2InfoKHR indirectInfo{ + .sType = VK_STRUCTURE_TYPE_DRAW_INDIRECT_2_INFO_KHR, + .addressRange = {indirectDrawBuffer.deviceAddress, indirectDrawBuffer.size, sizeof(VkDrawIndexedIndirectCommand)}, .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, + .drawCount = 2 }; - VkBindIndexBuffer3InfoKHR indexBindingInfo = { - .sType = VK_STRUCTURE_TYPE_BIND_INDEX_BUFFER_3_INFO_KHR, - .addressRange = {indexBuffer.deviceAddress, indexBuffer.size}, - .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, - .indexType = VK_INDEX_TYPE_UINT32, + VkDeviceAddressRangeKHR indirectRange{ + .address = indirectDrawBuffer.deviceAddress, + .size = indirectDrawBuffer.size }; - VkDrawIndirect2InfoKHR indirectInfo = { - .sType = VK_STRUCTURE_TYPE_DRAW_INDIRECT_2_INFO_KHR, - .addressRange = {indirectDrawBuffer.deviceAddress, indirectDrawBuffer.size, sizeof(VkDrawIndexedIndirectCommand)}, - .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, - .drawCount = 1 + std::array indirectDrawCommands{ + VkDrawIndexedIndirectCommand{.indexCount = 3, .instanceCount = 1}, + VkDrawIndexedIndirectCommand{.indexCount = 3, .instanceCount = 1, .vertexOffset = 3, .firstInstance = 1 }, }; - VkDeviceAddressRangeKHR range = { - .address = indirectDrawBuffer.deviceAddress, - .size = sizeof(uint32_t) - //.size = indirectDrawBuffer.size + vkCmdUpdateMemoryKHR(cmdBuffer, &indirectRange, 0, indirectDrawBufferSize, indirectDrawCommands.data()); + + // Vertex and index buffers can now be bound via their buffer device address instead + VkBindVertexBuffer3InfoKHR vertexBindingInfo{ + .sType = VK_STRUCTURE_TYPE_BIND_VERTEX_BUFFER_3_INFO_KHR, + .addressRange = {vertexBuffer.deviceAddress, vertexBuffer.size}, + .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, }; - VkDrawIndexedIndirectCommand idc = { - .indexCount = 6, - .instanceCount = 1, - .firstIndex = 0 + VkBindIndexBuffer3InfoKHR indexBindingInfo{ + .sType = VK_STRUCTURE_TYPE_BIND_INDEX_BUFFER_3_INFO_KHR, + .addressRange = {vertexBuffer.deviceAddress + vertexBufferSize, indexBufferSize}, + .addressFlags = VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, + .indexType = VK_INDEX_TYPE_UINT32, }; - vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.indexCount); - range.address += sizeof(uint32_t); - vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.instanceCount); - range.address += sizeof(uint32_t); - vkCmdFillMemoryKHR(cmdBuffer, &range, VK_ADDRESS_COMMAND_FULLY_BOUND_BIT_KHR, idc.firstIndex); vkCmdBindVertexBuffers3KHR(cmdBuffer, 0, 1, &vertexBindingInfo); vkCmdBindIndexBuffer3KHR(cmdBuffer, &indexBindingInfo); - - //model.bindBuffers(cmdBuffer); - // Instead of using descriptors to pass global and per-model matrices to the shader, we can now simply pass buffer references via push constants - // The shader then simply reads data from the address of that reference - PushConstantBlock references{}; - // Pass pointer to the global matrix via a buffer device address - references.sceneReference = scene.bufferDeviceAddresses[currentBuffer]; - references.modelReference = cubes[0].bufferDeviceAddresses[currentBuffer]; - vkCmdPushConstants(cmdBuffer, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(PushConstantBlock), &references); + vkCmdPushConstants(cmdBuffer, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VkDeviceAddress), &scene.buffers[currentBuffer].deviceAddress); vkCmdDrawIndexedIndirect2KHR(cmdBuffer, &indirectInfo); - /* - for (auto& cube : cubes) { - // Pass pointer to this cube's data buffer via a buffer device address - // So instead of having to bind different descriptors, we only pass a different device address - // This doesn't have to be an address from a different buffer, but could very well be just another address in the same buffer - references.modelReference = cube.bufferDeviceAddresses[currentBuffer]; - vkCmdPushConstants(cmdBuffer, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(PushConstantBlock), &references); - - model.draw(cmdBuffer); - } - */ - - //drawUI(cmdBuffer); + drawUI(cmdBuffer); vkCmdEndRenderPass(cmdBuffer); @@ -468,27 +340,11 @@ class VulkanExample : public VulkanExampleBase if (!prepared) return; VulkanExampleBase::prepareFrame(); - /* - if (animate && !paused) { - cubes[0].rotation.x += 2.5f * frameTimer; - if (cubes[0].rotation.x > 360.0f) - cubes[0].rotation.x -= 360.0f; - cubes[1].rotation.y += 2.0f * frameTimer; - if (cubes[1].rotation.x > 360.0f) - cubes[1].rotation.x -= 360.0f; - } - */ + updateUniformBuffers(); buildCommandBuffer(); VulkanExampleBase::submitFrame(); } - - virtual void OnUpdateUIOverlay(vks::UIOverlay* overlay) - { - if (overlay->header("Settings")) { - overlay->checkBox("Animate", &animate); - } - } }; VULKAN_EXAMPLE_MAIN() diff --git a/shaders/glsl/deviceaddresscommands/cube.frag b/shaders/glsl/deviceaddresscommands/cube.frag index 72bcee6f4..25c22e166 100644 --- a/shaders/glsl/deviceaddresscommands/cube.frag +++ b/shaders/glsl/deviceaddresscommands/cube.frag @@ -6,8 +6,6 @@ #version 450 -layout (set = 0, binding = 0) uniform sampler2D samplerColorMap; - layout (location = 0) in vec3 inColor; layout (location = 0) out vec4 outFragColor; diff --git a/shaders/glsl/deviceaddresscommands/cube.frag.spv b/shaders/glsl/deviceaddresscommands/cube.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..ad4159133580a498844f3a27c1ca0813d2f65262 GIT binary patch literal 500 zcmYk1PfJ2k5XC27Pc8F5)GmycfwZUyqFMyHaZ&UMgdl|Sf!W^A=BH{S^!r_((S>v8 z&Y3fF=4O@iTEt#7q8|O&o^DiN0 za0EK&JiBbL+djkAog( z$t}|Rn0FO!08Y@mi@E*-?mE%m$lsN@9&+jriR#VOH;8;8@#@XpLGFTFZ3{%K9&h-8 z`{?Cy#t%$RyoYsm6WIR(Yj3;c2!C9sfQpI&Dj>$75HJG~lMxK@t|>!-#?q2$CjqZ~1$`u6 zMZNO@yfN|r+U{Y(CX2oPe;xN)okHhCw=o^2&-9p=COiG6Q;ad(Kd&2e!StH#+K%&X zeaksMJdORj8#r+iHQWQw*=_Fcdkw{x(wOSz_U3e)>`l+j&ywx3DVSf%LB1=>#Oab8 zxqgU#Q!*+UmpqcpNDBJv)cr$2U8dVqH=VbiKIWC2hNpU7SodV>v9?$(xeaGGi0Yr6 zz&(wci7`cawAU)C$4kol-c1_*$yO^*NuKbWqts^PnfcQ9QMBg;S&%%7dWSJ_-3z@n zH*uwt_p0t%Gd^66!Z>lmBo;2IKX^{d|Ez2pcTKkAb8*yQE_%dj6hsZ;c?)y$!;GS4 zMff0aYF=ZtY;zyy_?$n?6q`V&{+x{01KWk&=vaJUG@tV&o>R!uM z$ZgFaXxWO|6MN$nm7o17ej}Yg-P;KFvYzOjz51cr(Onh3sJkRtPH`cfKlRsTv%4s! z_-r@&P}6y~`;46PnGoh!AKu%Z2YfycTzeicd6p$ry^($Y(Kn3FKC?cHt=-z1yoCB}f8CI?y-C%N$=zp(nIPjqU^GmKsI8!;MHhD*d*)K70Wnp#-hOY?Q zy71u3x~T_WRxivM9b3O{V&PupnBNT?y$tBCNIE3+0@jn#L;RpLe96b#*fq771NIxa z4o`kCd$jgj(#dV@VD@V3F$=q6-hM}z{BUJet?0J%#D-9JOm|izs|y})ab4!Fbaq4U z_FWI8cSwkTnCrZkzQKG0*unJ4HvlG{o}NmK`TBU&XAqjh6)=Toq=9}@al>z_Z+{Wx~OPCur<_orQ6VmY~H}AeDfy;82(iz;( zdHUpAu(6ZUi3KwYzJKPhqK?S*Sb`6;!?q-znLd$Vv-!TOHvF`NTG+`+@3WE_$p`r` zgJ(IXtHnLfIp%Hs=5mf2HAOP(c?t3OV`nGdlsDT$Rv#Z`!HyOs;}T}U?7$0>f7