PushConstant
本篇内容主要介绍了VulkanSceneGraph使用PushConstants实现类似OpenGL中uniform的方法。在vsgExamples中仅有使用descriptorset相关的传递uniform变量的方法,希望本篇能为大家在VSG中使用PushContants一点小小的帮助。
全部代码示例看这里
debuglayer
在进入主题之前,先说VSG提供的调试功能。
VSG集成了Vulkan的debugLayer,这对于在写程序时查找错误有着重要的作用。
在vsgExamples官方仓库中,大多示例均有下面的代码。可以在程序的命令行中加入相应的参数开启该功能。
windowTraits->debugLayer = arguments.read({ "--debug", "-d" });
VSG内部直接就集成了深度测试的相关模块,因此在构建管线时应当添加对应部分,否则debuglayer会有对应的提示信息。
vsg::GraphicsPipelineStates pipelineStates{
vsg::VertexInputState::create(vertexBindingsDescriptions, vertexAttributeDescriptions),
vsg::InputAssemblyState::create(),
vsg::RasterizationState::create(),
vsg::MultisampleState::create(),
vsg::ColorBlendState::create(),
vsg::DepthStencilState::create()
};
pushConstant的使用
VSG中对于场景的MVP矩阵的传递使用了vulkan的PushConstant方式,当我们想用该方式传递自己的uniform变量时,需要考虑到这个因素。
VSG内部保障了我们不使用任何(包含其内置的MVP相关矩阵)PushConstants可以保证程序不会有任何的错误信息,但想要传递自己的uniform时,VSG会自动把MVP矩阵传递,因此,需要将暂时没用到的MVP相关的设置做好。
vertexShader中
要添加对应的定义
layout(push_constant) uniform PushConstants {
mat4 projection;
mat4 modelView;
} pc;
fragmentShader中
添加我自己的uniform,这里我传入了一个颜色值。注意这里的layout,这个offset数值为vertexShader中PushConstants 的大小(即为两个mat4)。offset设置正确是正确使用pushConstants的关键
layout(push_constant) uniform PushColor {
layout(offset = 128)vec4 color;
} uColor;
场景图节点
要在场景图节点中加入对应的节点,相当于可以在渲染过程中加入了对应的vulkan command
auto colorData = vsg::vec4Array::create({ {1.0, 0.0, 0.0, 1.0} });
auto pushConstant = vsg::PushConstants::create(VK_SHADER_STAGE_FRAGMENT_BIT,128, colorData);
// setup geometry
auto drawCommands = vsg::Commands::create();
drawCommands->addChild(pushConstant);
颜色值修改
这里只需要修改节点中的数据即可,传递过程还是相对简单的。
while (viewer->advanceToNextFrame())
{
viewer->handleEvents();
float time = std::chrono::duration<float, std::chrono::seconds::period>(viewer->getFrameStamp()->time - viewer->start_point()).count();
colorData->at(0).r = 0.5f * sin(time) + 0.5f;
viewer->update();
viewer->recordAndSubmit();
viewer->present();
}
} ;
小结
VSG在根本上还是Vulkan,各种功能的使用方式还是需要参考Vulkan的使用。在实现本篇内容的过程中,在Vulkan的文档中读了又读还是不太明白,最后还是在官方例子查找了类似的实现。
希望我能够时常有为使用VSG的朋友提供一些简明的教程,但愿这些教程在未来也能够在工作等方面对我自己有所反馈吧。