《VulkanSceneGraph 1.1.16 源码深度解析》第九章 管线对象:GraphicsPipeline / ComputePipeline

2 阅读1小时+

《VulkanSceneGraph 1.1.16 源码深度解析》第九章 管线对象:GraphicsPipeline / ComputePipeline / PipelineLayout

9.0 先把规模和答案摆出来

第八章结束时留下的问题是:被压进 slot 0 的那个 BindGraphicsPipeline,里面的 VkPipeline 到底是怎么来的?这一章把它从头到尾拆开。

先给可复核的规模。include/vsg/state/ 有 36 个头文件、3,002 行,src/vsg/state/ 有 35 个实现文件、7,076 行,合计 10,078 行。本章正面处理的 13 个文件共 2,619 行:

文件行数本章角色
include/vsg/state/GraphicsPipeline.h135图形管线、GraphicsPipelineState 基类、BindGraphicsPipeline
src/vsg/state/GraphicsPipeline.cpp326三层状态合并、compile、Implementation 构造
include/vsg/state/PipelineLayout.h74VkPipelineLayout 封装、vk_buffer 索引
src/vsg/state/PipelineLayout.cpp171布局创建、computeCompatibility
include/vsg/state/ComputePipeline.h87计算管线、BindComputePipeline
src/vsg/state/ComputePipeline.cpp167计算路径的 compile 与 Implementation
include/vsg/state/ShaderStage.h67VkPipelineShaderStageCreateInfo 描述
src/vsg/state/ShaderStage.cpp219apply、特化常量打包、compile
include/vsg/state/ShaderModule.h127SPIR-V 容器、VkShaderModule
src/vsg/state/ShaderModule.cpp326vkCreateShaderModule、源码编译设置
src/vsg/app/CompileTraversal.cpp479renderPass / 三层状态的注入者
src/vsg/app/WindowResizeHandler.cpp211两条重建路径、release(viewID)
src/vsg/app/RenderGraph.cpp230动态/静态视口分派、resized()

九个 GraphicsPipelineState 子类头文件加实现共 1,466 行;真正决定结论的不到 400 行:GraphicsPipeline.cpp:159 的 compile(取 viewID)、GraphicsPipeline.cpp:226 的 Implementation(写 renderPass)、PipelineLayout.cpp:48 的 computeCompatibility、ShaderStage.cpp:170 的 apply(打包 specializationConstants)、CompileTraversal.cpp:343 的上下文切换。

9.0.1 本章的问题清单

两条索引轴为何并存(9.2);状态的三层来源与优先级(9.6);GraphicsPipelineState 的空 record() 意味着什么(9.5);DynamicState 为何单独取并集(9.6.2);compile() 复用判据漏了哪些输入(9.7.2、9.10);ScratchMemory 为何能在 vkCreateGraphicsPipelines 后立即 release()(9.8.3);零处 VkPipelineCache 的代价(9.9);两条 resize 重建路径的差别(9.12);memcmp 比较在哪些布局下成立(9.5.4、9.11)。

9.0.2 答案骨架

先把结论列在这里,后面逐条用源码展开,读者可以带着结论去核对:

#结论主要证据
1图形管线按 viewID 分实现,是因为 RenderPass、ViewportState、MultisampleState 都由编译时的视图上下文注入,不是管线对象自己的字段GraphicsPipeline.h:105、GraphicsPipeline.cpp:161/233、CompileTraversal.cpp:87/117/164
2状态是"三层合并":Context 默认层 → 管线自身层 → Context 覆盖层,同类型后者替换前者,DynamicState 取并集GraphicsPipeline.cpp:169–173、GraphicsPipeline.cpp:56–96
3GraphicsPipeline.h:36 把 mask 默认为 MASK_ALL;九个子类只有 ViewportState 的 record()(ViewportState.cpp:142)真发 vkCmdSetViewport,其余八个空操作GraphicsPipeline.h:39、ViewportState.cpp:142–146
4compile() 的复用判据只比 _pipelineStates,不比 renderPass、mask、stages、subpass,缓存键不完整GraphicsPipeline.cpp:175–182
5CompileTraversal 在 RenderGraph / SecondaryCommandGraph 下临时替换 context->renderPass 却不改 viewID,与第 4 条叠加会绑错 renderPassCompileTraversal.cpp:354–379、390–411
6全库零处 vkCreatePipelineCache,两次 vkCreate*Pipelines 都传 VK_NULL_HANDLE,只有对象内按 viewID 的浅层复用GraphicsPipeline.cpp:260、ComputePipeline.cpp:110
7validated_vk() 与 computeCompatibility() 全库零调用,是写好但没接上的 APIgrep 全库,仅定义处出现
8ShaderStage::compare(ShaderStage.cpp:76)比 stage/module/entryPointName 却漏 mask,read/write 则序列化 mask;flags 从未进 stageInfo,在 shaderStageCreateInfo 里被写死为 0(GraphicsPipeline.cpp:245)ShaderStage.cpp:76/127–168/170–211、GraphicsPipeline.cpp:245
9fatal() 在 ThreadLogger 下只打印不抛异常,未编译 GLSLang 时着色器编译失败会继续走到 codeSize = 0 的 vkCreateShaderModuleLogger.cpp:315–319、ShaderModule.cpp:193–203、GraphicsPipeline.cpp:206
10DepthStencilState::compare / RasterizationState::compare 用 memcmp 横跨成员区间,当前布局恰好无 padding 因而正确,但任何成员增删都会静默改变比较语义compare.h:52–61、DepthStencilState.h:29–38

第 4、5、8、9 条是硬缺陷,第 1、2、6 条是设计取舍,第 3、7、10 条是易误读的接口边界。下面按对象层次自底向上展开。

9.0.3 阅读路线

PipelineLayout → ShaderModule → ShaderStage → GraphicsPipelineState → 三层合并 → GraphicsPipeline::compile → Implementation → BindGraphicsPipeline::record → ComputePipeline → resize 与释放 → 与第八章状态栈的接合。

顺序即 compile() 的依赖顺序:GraphicsPipeline.cpp:211 先 layout->compile,再逐个 shaderStage->compile,最后创建 VkPipeline。反过来读会误以为 VkPipeline 是这些对象的容器,实际是它们编译结果的快照。


9.1 五层对象与四个 Vulkan 句柄

把第八章的 StateGroup 展开,图形管线这一支的对象链是:

StateGroup::stateCommands[0]
  └─ BindGraphicsPipeline            (StateCommand, slot = 0)
       └─ GraphicsPipeline           (Object, 不是 StateCommand)
            ├─ PipelineLayout        (Object)
            │    └─ DescriptorSetLayout[]  (第十一章)
            ├─ ShaderStages[]        (Object)
            │    └─ ShaderModule     (Object) → VkShaderModule
            └─ GraphicsPipelineStates[]      (StateCommand 子类,但 record 多为空)
                 └─ 九个具体状态      → Vk*StateCreateInfo

  编译产物(不在场景图里):
       VkPipelineLayout     ← PipelineLayout::Implementation
       VkShaderModule       ← ShaderModule::Implementation
       VkPipeline           ← GraphicsPipeline::Implementation[viewID]

四个 Vulkan 句柄是 VkDescriptorSetLayout(下一章)、VkPipelineLayout、VkShaderModule、VkPipeline。前三个按 deviceID 索引,最后一个按 viewID 索引。这个分叉是理解整章的钥匙。

9.1.1 Object 与 StateCommand 的边界

GraphicsPipeline 是 Inherit<Object, GraphicsPipeline>(GraphicsPipeline.h:56),不是 Command/StateCommand,不进状态栈。进 stateCommands 的是 BindGraphicsPipeline(GraphicsPipeline.h:110),它 Inherit<StateCommand, BindGraphicsPipeline> 并显式 Inherit(0)(GraphicsPipeline.cpp:279–283)。

VkPipeline 不可变且创建昂贵,"绑定哪个管线"才随遍历变化。StateStack 用 stack[0] 去重,同一管线连续 push 只在栈顶变化时录制;若 GraphicsPipeline 本身是 StateCommand,每个节点都要压一次大对象。分开后栈里只存一个小指针。

GraphicsPipeline::compare(GraphicsPipeline.cpp:126–137)是深度比较,递归遍历 stages/pipelineStates/layout。放进 std::set<..., DereferenceLess> 时每次插入都是 O(状态数 × 字段数) 的递归比较;DereferenceLess(compare.h:105–113)正是用 compare() 做序关系。

9.1.2 三个 compile 入口的调用关系

BindGraphicsPipeline::compile(Context&) 只有一行有效代码(GraphicsPipeline.cpp:318–321):

void BindGraphicsPipeline::compile(Context& context)
{
    if (pipeline) pipeline->compile(context);
}

CompileTraversal 遍历到 BindGraphicsPipeline 时调用它,进而触发 GraphicsPipeline::compile。注意判空:pipeline 为空时静默返回,不报错。但 BindGraphicsPipeline::record 不判空(GraphicsPipeline.cpp:312–316):

void BindGraphicsPipeline::record(CommandBuffer& commandBuffer) const
{
    vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->vk(commandBuffer.viewID));
    commandBuffer.setCurrentPipelineLayout(pipeline->layout);
}

所以构造一个默认 BindGraphicsPipeline()(GraphicsPipeline.h:113 的默认参数就是空 ref_ptr)并放进 StateGroup,编译期不会报任何错,帧期第一次录制直接空指针解引用。这是"编译宽容、录制崩溃"的一处典型。

9.1.3 setCurrentPipelineLayout 的完整调用面

第八章留下过一个隐患:全库只有三处 setCurrentPipelineLayout 调用,都在 Bind*Pipeline::record 里。本章把第三处补齐:

位置绑定点传入的布局
GraphicsPipeline.cpp:315VK_PIPELINE_BIND_POINT_GRAPHICSpipeline->layout
ComputePipeline.cpp:161VK_PIPELINE_BIND_POINT_COMPUTEpipeline->layout
RayTracingPipeline.cpp:257VK_PIPELINE_BIND_POINT_RAY_TRACING_KHRpipeline->layout

CommandBuffer::_currentPipelineLayout 只在这三处被赋值,随后被 BindDescriptorSet、PushConstants 用于校验或取 VkPipelineLayout。StateSwitch::record 绕过 StateStack 直接调子命令 record(),会执行 setCurrentPipelineLayout 却不更新 stack[0],于是命令缓冲里的管线与 _currentPipelineLayout 可能来自不同绑定点。


9.2 两条索引轴:viewID 与 deviceID

这是第九章标题里"按 viewID 的多实现"的来源。四个类的实现容器声明如下:

// GraphicsPipeline.h:105
std::vector<ref_ptr<Implementation>> _implementation;

// PipelineLayout.h:70
vk_buffer<ref_ptr<Implementation>> _implementation;

// ComputePipeline.h:59
vk_buffer<ref_ptr<Implementation>> _implementation;

// ShaderModule.h:120
vk_buffer<ref_ptr<Implementation>> _implementation;

对应的取值函数:

// GraphicsPipeline.h:64
VkPipeline vk(uint32_t viewID) const { return _implementation[viewID]->_pipeline; }

// PipelineLayout.h:39
VkPipelineLayout vk(uint32_t deviceID) const { return _implementation[deviceID]->_pipelineLayout; }

// ComputePipeline.h:45
VkPipeline vk(uint32_t deviceID) const { return _implementation[deviceID]->_pipeline; }

// ShaderModule.h:91
VkShaderModule vk(uint32_t deviceID) const { return _implementation[deviceID]->_shaderModule; }

四个 vk() 全都没有判空、没有边界检查。GraphicsPipeline.h:67 另给了一个 validated_vk():

VkPipeline validated_vk(uint32_t viewID) const
{
    return (viewID < _implementation.size())
               ? (_implementation[viewID] ? _implementation[viewID]->_pipeline : 0)
               : 0;
}

它检查了 viewID 越界与槽位为空两种情况,返回 0 而不是崩溃。全库 grep validated_vk 只有这一处定义,没有任何调用点。也就是说,库里所有实际录制路径走的都是不检查的 vk()。这不是"有备用安全版本"的设计,而是一个没接上的安全版本。

9.2.1 vk_buffer 的三个编译分支

include/vsg/vk/vk_buffer.h 按 VSG_MAX_DEVICES 展开成三套完全不同的实现:

#if VSG_MAX_DEVICES <= 1
    template<class T>
    struct vk_buffer
    {
        T value;
        T& operator[](uint32_t) { return value; }              // 索引被完全忽略
        const T& operator[](uint32_t) const { return value; }
        constexpr static uint32_t size() { return 1; }
        void clear() { value = {}; }
        auto begin() { return &value; }
        auto end() { return &value + 1; }
        ...
    };
#elif VSG_MAX_DEVICES <= 4
    ... std::array<T, VSG_MAX_DEVICES> buffer; ...
#else
    ... std::vector<T> buffer; T& operator[](uint32_t id) { if (id >= buffer.size()) buffer.resize(id + 1); return buffer[id]; } ...
#endif

在默认 VSG_MAX_DEVICES = 1 下(第六章 6.x 讲过这个宏的进程级约束),operator[] 连参数都不看,vk(7) 与 vk(0) 返回同一个 value。这意味着 PipelineLayout::compile 里的 _implementation[context.deviceID] 永远指向唯一槽位,无论 context.deviceID 是多少。

而 Context::deviceID 本身是常量:

// Context.h:78 — 与可变的 viewID / MASK_ALL 不同,deviceID 是 const
const uint32_t deviceID = 0;

deviceID 是 const 成员,拷贝构造(Context.cpp:142)仍是 deviceID(context.deviceID),从 0 拷到 0,同时把 renderPass 与 defaultPipelineStates 从 context 拷来。Device 侧虽有 s_ActiveDevices,Context 却把索引焊死在 0 上:多设备路径在 Context 层是死的,vk_buffer 的 >4 分支收不到非 0 的 deviceID。

因此 PipelineLayout / ComputePipeline / ShaderModule 选择 vk_buffer 的理由不是"它们与设备一一对应且需要多设备支持",而是"它们与设备相关,而设备数被硬限制为 1,用定长容器省一次间接寻址"。这是性能优化,不是架构抽象。

9.2.2 为什么图形管线不能用 vk_buffer

GraphicsPipeline::compile 的第一段就是答案(GraphicsPipeline.cpp:159–167):

void GraphicsPipeline::compile(Context& context)
{
    uint32_t viewID = context.viewID;
    if (static_cast<uint32_t>(_implementation.size()) < (viewID + 1))
    {
        _implementation.resize(viewID + 1);
    }

    if (!_implementation[viewID])
    {
        ...
    }
}

viewID 来自 Context::viewID(Context.h:83,默认 0),由 CompileTraversal::apply(View&) 赋值(CompileTraversal.cpp:436:context->viewID = view.viewID;)。视图数无编译期上限,CompileTraversal 为每个 View 建独立 Context(CompileTraversal.cpp:135),所以图形管线的实现数必须是可变长 std::vector。

但"可变长"只是形式原因,语义原因是 VkGraphicsPipelineCreateInfo 里有三个字段不归管线对象所有:

字段赋值处来源
renderPassGraphicsPipeline.cpp:233 pipelineInfo.renderPass = *renderPass;context.renderPass,由 CompileTraversal 按窗口/帧缓冲/RenderGraph 注入
layoutGraphicsPipeline.cpp:232 pipelineLayout->vk(device->deviceID)管线对象自己的 layout,但句柄按设备索引
pViewportState 等九个状态指针九个 apply()combined_pipelineStates,其中含 context.defaultPipelineStates 与 context.overridePipelineStates

其中 defaultPipelineStates 与 overridePipelineStates 明确写着注释(Context.h:100–110):

// pipeline states that are usually not set in a scene, e.g.,
// the viewport state, but might be set for some uses
GraphicsPipelineStates defaultPipelineStates;

// pipeline states that must be set to avoid Vulkan errors
// e.g., MultisampleState.
// XXX MultisampleState is complicated because the sample
// number needs to agree with the renderpass attachment, but
// other parts of the state, like alpha to coverage, belong to
// the scene graph .
GraphicsPipelineStates overridePipelineStates;

第二条注释里那个 XXX 是源码自带的未完成标记,它解释了为什么需要"覆盖层":rasterizationSamples 必须与 renderPass 的附件采样数一致,这是渲染目标的属性,不是场景作者能随便写的。所以 CompileTraversal 在 add() 里强行注入:

// CompileTraversal.cpp:97
if (renderPass->maxSamples != VK_SAMPLE_COUNT_1_BIT)
    context->overridePipelineStates.emplace_back(MultisampleState::create(renderPass->maxSamples));

于是同一个 GraphicsPipeline 对象,在 MSAA=1 的窗口和 MSAA=4 的窗口下编译,会得到两个不同的 VkPipeline。按 viewID 分槽是让这两份产物共存的唯一办法。

9.2.3 计算管线为什么回到 deviceID

ComputePipeline::compile(ComputePipeline.cpp:66–90)没有 renderPass,没有状态合并,没有 subpass:

void ComputePipeline::compile(Context& context)
{
    if (!_implementation[context.deviceID])
    {
        bool requiresShaderCompiler = stage && stage->module &&
                                      stage->module->code.empty() &&
                                      !(stage->module->source.empty());
        ...
        layout->compile(context);
        stage->compile(context);
        _implementation[context.deviceID] = ComputePipeline::Implementation::create(
            context, context.device, layout, stage);
    }
}

VkComputePipelineCreateInfo 只有 layout 与 stage,两者都只依赖设备。所以计算管线用 vk_buffer 按 deviceID 索引是自洽的。录制端也对齐:

// ComputePipeline.cpp:158–162
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE,
                  pipeline->vk(commandBuffer.deviceID));

两个 Bind*Pipeline 都占 slot 0(GraphicsPipeline.cpp:280、ComputePipeline.cpp:126 的 Inherit(0)),取键却不同:Vulkan 分别维护各绑定点状态,VSG 用单一槽位表达两者,隐含假设不在同一作用域共存。

GraphicsPipeline 的 stages/pipelineStates/layout/subpass 是可序列化、可 compare 的纯数据,Implementation 里的 VkPipeline 则绑定具体 renderPass、layout、设备与采样数。配方没变的判断不能只看配方的一部分,compile() 的复用循环正犯了这个错,9.10 节逐行拆。


9.3 PipelineLayout:最小、最先编译、问题最多

PipelineLayout.h 只有 74 行,却是整条链上第一个必须成功的节点。它持有三类数据:

// PipelineLayout.h:23, 34–36
using PushConstantRanges = std::vector<VkPushConstantRange>;

VkPipelineLayoutCreateFlags flags = 0;
DescriptorSetLayouts setLayouts;
PushConstantRanges pushConstantRanges;

DescriptorSetLayouts 是 std::vector<ref_ptr<DescriptorSetLayout>>,PushConstantRanges 直接是 Vulkan 结构体的 std::vector。注意这里没有 Inherit<Command, ...>:PipelineLayout 是纯描述对象,和 GraphicsPipeline 一样不进场景图遍历。

9.3.1 三个构造与一个拷贝陷阱

// PipelineLayout.h:29–31
PipelineLayout();
PipelineLayout(const PipelineLayout& rhs, const CopyOp& copyop = {});
PipelineLayout(const DescriptorSetLayouts& in_setLayouts,
               const PushConstantRanges& in_pushConstantRanges,
               VkPipelineLayoutCreateFlags in_flags = 0);

拷贝构造(PipelineLayout.cpp:29–35)复制 setLayouts 与 pushConstantRanges,却不复制 _implementation:句柄属于设备,不能随对象拷贝共享裸句柄,新对象下次 compile() 自建 VkPipelineLayout。这与 Object::clone()(PipelineLayout.h:50)一致,走重新编译路线。

ref_ptr<Object> clone(const CopyOp& copyop = {}) const override
{
    return PipelineLayout::create(*this, copyop);
}

深拷贝带 SharedObjects 共享的场景图时,若 CopyOp 未把同一 PipelineLayout 解析回同一指针,每个副本各建一个 VkPipelineLayout。GraphicsPipelineConfigurator::copyTo(GraphicsPipelineConfigurator.cpp:831–836)显式 share(layout->setLayouts)、share(layout) 来避免。

9.3.2 compile 与 VkPipelineLayout 的创建

// PipelineLayout.cpp:122–132
void PipelineLayout::compile(Context& context)
{
    if (!_implementation[context.deviceID])
    {
        for (auto dsl : setLayouts)
        {
            if (dsl) dsl->compile(context);
        }
        _implementation[context.deviceID] =
            PipelineLayout::Implementation::create(
                context.device, setLayouts, pushConstantRanges, flags);
    }
}

三点值得注意:

  1. 先编译依赖。DescriptorSetLayout::compile 必须在 vkCreatePipelineLayout 前完成,Implementation 取 dsl->vk(device->deviceID);Vulkan 要求 pSetLayouts 句柄有效。
  2. 判空但不判长度。for (auto dsl : setLayouts) if (dsl) 允许容器里有空项,后面 Implementation 会把它转成 0。
  3. 缓存判据只是"槽位非空"。某设备槽位建过后,对 flags/setLayouts/pushConstantRanges 的修改都不反映到 VkPipelineLayout。这与 9.10 同类:创建后描述对象仍是可写公开字段,但库没有失效机制。

Implementation 构造(第 138–163 行):

// PipelineLayout.cpp:141
std::vector<VkDescriptorSetLayout> layouts;
for (auto& dsl : descriptorSetLayouts)
{
    if (dsl)
        layouts.push_back(dsl->vk(device->deviceID));
    else
        layouts.push_back(0);          // ← 见 9.3.3
}

VkPipelineLayoutCreateInfo pipelineLayoutInfo;
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.flags = flags;
pipelineLayoutInfo.setLayoutCount = static_cast<uint32_t>(layouts.size());
pipelineLayoutInfo.pSetLayouts = layouts.data();
pipelineLayoutInfo.pushConstantRangeCount = static_cast<uint32_t>(pushConstantRanges.size());
pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges.data();
pipelineLayoutInfo.pNext = nullptr;

if (VkResult result = vkCreatePipelineLayout(*device, &pipelineLayoutInfo,
        _device->getAllocationCallbacks(), &_pipelineLayout); result != VK_SUCCESS)
{
    throw Exception{"Error: Failed to create PipelineLayout.", result};
}

VkPipelineLayoutCreateInfo pipelineLayoutInfo; 未值初始化;对比 GraphicsPipeline.cpp:230 的 VkGraphicsPipelineCreateInfo pipelineInfo = {};,后者把 sType/layout/renderPass/subpass 全清零才稳妥。前者靠逐字段赋值凑齐七个字段,复制漏一行就读到未初始化栈内存。

9.3.3 空 setLayout 被转成 0

layouts.push_back(0) 只应出现在启用 VK_EXT_graphics_pipeline_library 且带 VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT 时——该扩展允许 pSetLayouts 元素为 VK_NULL_HANDLE,由后续 library 片段补齐。否则规范要求每个元素有效。

VSG 这里没有判断 flags、没有判断扩展是否启用,无条件写 0。它之所以在常规场景不炸,是因为常规场景根本不会往 setLayouts 里放空项——GraphicsPipelineConfigurator 从 ShaderSet 生成的布局是连续的,第十一章会看到 DescriptorSetLayout 的分配逻辑。但 computeCompatibility() 里有一段专门处理空项的注释,说明作者确实预期空项会出现:

// PipelineLayout.cpp:59–61
// if this is a partial layout for a graphics pipeline library, it may be made compatible later
if (!setLayouts[result.second] || !other.setLayouts[result.second])
    continue;

于是形成一个不对称:compile() 把空项直接交给 Vulkan,computeCompatibility() 却把它当"暂未确定、跳过"。前者是潜在违规,后者是宽松判定,两条路径对同一个数据的假设不一致。

9.3.4 computeCompatibility():一个没接上、且返回值错误的 API

全库 grep computeCompatibility 只有两处:PipelineLayout.h:47 的声明与 PipelineLayout.cpp:48 的定义。没有调用者。它返回 std::pair<bool, uint32_t>,注释写的是:

// PipelineLayout.h:46
// returns whether the layouts are push-constant-compatible and the lowest N
// for which the layouts are not compatible for descriptor set N

实现拆成三段:

// PipelineLayout.cpp:48–66(原文)
std::pair<bool, uint32_t> vsg::PipelineLayout::computeCompatibility(const PipelineLayout& other)
{
    auto result = std::make_pair<bool, uint32_t>(
        compare_value_container(pushConstantRanges, other.pushConstantRanges) == 0, 0);
    if (!result.first)
        return result;
#ifdef VK_EXT_graphics_pipeline_library
    if ((flags & VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT) !=
        (other.flags & VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT))
        return result;                                  // ← 这里
#endif
    for (result.second = 0;
         result.second < std::min(setLayouts.size(), other.setLayouts.size());
         ++result.second)
    {
        if (!setLayouts[result.second] || !other.setLayouts[result.second])
            continue;
        if (compare_value_container(setLayouts[result.second]->bindings,
                                    other.setLayouts[result.second]->bindings) != 0)
            break;
    }
    return result;
}

三个问题:

第一,flags 不兼容时返回的却是"兼容"。 PipelineLayout.cpp:54 发现 VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT 位不一致直接 return result,此时 result.first 仍是上一步算出的 true(推送常量范围相同);正确做法应先置 false。规范要求推送常量范围、创建标志、前 N 个集合布局都一致才兼容,标志不一致会改变绑定有效性。当前返回 {true, 0}——first=true 与 second=0 自相矛盾。

第二,长度不等时 second 语义失真。 循环上界是 std::min(a.size(), b.size())。较短者全兼容时循环结束,second == min(...),含义变成"第一个不存在的集合编号";注释说的却是"第一个不兼容的集合"。调用者据此决定重绑定起点会多绑或少绑。

第三,continue 让部分布局被当作通配。 只要任一侧某个集合是空指针就跳过该集合,于是 A = [nullptr, X] 与 B = [nullptr, Y](X != Y)会返回 second = 2(被判为全部兼容)。结合 9.3.3,空项在 compile() 里又不能合法传给 Vulkan,这段代码描述的是一种在当前实现下无法实际存在的布局。

加上前面"零调用"的事实,结论是:这是一个为 graphics pipeline library 预留、尚未完成、也尚未验证的接口。文档里不应把它当作可用的兼容性判断工具。

9.3.5 compare 与序列化

// PipelineLayout.cpp:68–78
int PipelineLayout::compare(const Object& rhs_object) const
{
    int result = Object::compare(rhs_object);
    if (result != 0) return result;

    const auto& rhs = static_cast<decltype(*this)>(rhs_object);

    if ((result = compare_value(flags, rhs.flags))) return result;
    if ((result = compare_pointer_container(setLayouts, rhs.setLayouts))) return result;
    return compare_value_container(pushConstantRanges, rhs.pushConstantRanges);
}

Object::compare(Object.cpp:112–122)先比 this == &rhs,再比 typeid(*this),最后比 _auxiliary。所以不同子类一定不相等;同类型才进入字段比较。compare_pointer_container(compare.h:63–77)先比容器长度,再逐元素调 compare_pointer;同文件的 compare_region 用 memcmp 按字节比(依赖 <cstring>):

// compare.h:22
template<class T, class R>
int compare_pointer(const ref_ptr<T>& lhs, const ref_ptr<R>& rhs)
{
    if (lhs == rhs) return 0;                     // 同一指针,短路
    return lhs ? (rhs ? lhs->compare(*rhs) : 1) : (rhs ? -1 : 0);
}

同一指针直接返回 0,不递归;不同指针则深比较。这让 SharedObjects 去重既能快速命中共享对象,也能把"内容相同但指针不同"的两个布局合并。pushConstantRanges 走的是 compare_value_container → compare_region → memcmp(见 9.11),这是字节级比较,不是逐字段比较。

序列化侧(PipelineLayout.cpp:80–120)手写字段而非用通用反射:

output.writeValue<uint32_t>("flags", flags);
output.writeValue<uint32_t>("setLayouts", setLayouts.size());
for (const auto& descriptorLayout : setLayouts)
    output.writeObject("descriptorLayout", descriptorLayout);
output.writeValue<uint32_t>("pushConstantRanges", pushConstantRanges.size());
for (const auto& pushConstantRange : pushConstantRanges)
{
    output.writeValue<uint32_t>("stageFlags", pushConstantRange.stageFlags);
    output.write("offset", pushConstantRange.offset);
    output.write("size", pushConstantRange.size);
}

flags 是 uint32_t 的 typedef,显式写成 uint32_t 没问题;stageFlags 同理。字段顺序即格式,加字段必须同时改 read 与 write,且没有版本守卫——对比 GraphicsPipelineState::read/write 里的 input.version_greater_equal(1, 0, 9) 版本守卫,PipelineLayout 完全没有版本判断,字段布局从 1.0 早期就固定了。


9.4 ShaderModule 与 ShaderStage:SPIR-V 的三个入口

9.4.1 ShaderModule 的数据面

// ShaderModule.h:76–91
using SPIRV = std::vector<uint32_t>;

std::string source;
ref_ptr<ShaderCompileSettings> hints;
SPIRV code;

VkShaderModule vk(uint32_t deviceID) const
{
    return _implementation[deviceID]->_shaderModule;
}

三个字段构成一条降级链:有 code 就直接用 SPIR-V;没有 code 但有 source,交给 ShaderCompiler 现场编译并把结果写回 code;两者都没有,就是一个空壳。source 与 code 允许同时存在(ShaderModule(const std::string& source, const SPIRV& in_code),ShaderModule.h:82),这样序列化后的对象既保留可读源码也保留可直接上载的字节码。

ShaderCompileSettings(ShaderModule.h:27–68)是给 glslang 的参数包:

九个字段的默认值:vulkanVersion = VK_API_VERSION_1_0、clientInputVersion = 100、language = GLSL、defaultVersion = 450、target = SPIRV_1_0、forwardCompatible / generateDebugInfo / optimize 均为 false、defines 为空 std::set<std::string>。

SpirvTarget 枚举用位拼装版本号(ShaderModule.h:41–46):SPIRV_1_0 = 1<<16、SPIRV_1_1 = (1<<16)|(1<<8)、SPIRV_1_2 = (1<<16)|(2<<8)……直到 SPIRV_1_5 = (1<<16)|(5<<8)。也就是主版本恒为 1,次版本放在第 8 位。这是 glslang 的 EShTargetLanguageVersion 编码约定,不是 VSG 自定义协议。

defines 用 std::set 而非 std::map,只能表达"定义了宏"、不能表达"宏等于某值"。ShaderCompileSettings::compare_except_defines(ShaderModule.h:63)提供忽略 defines 的比较,供 ShaderCompiler 判断变体能否共用编译结果——第十章讲变体分发时用到。

9.4.2 vkCreateShaderModule 与 codeSize

// ShaderModule.cpp:190–204
ShaderModule::Implementation::Implementation(Device* device, ShaderModule* shaderModule) :
    _device(device)
{
    VkShaderModuleCreateInfo createInfo = {};
    createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
    createInfo.pNext = nullptr;
    createInfo.flags = 0;
    createInfo.codeSize = shaderModule->code.size() * sizeof(ShaderModule::SPIRV::value_type);
    createInfo.pCode = shaderModule->code.data();

    if (VkResult result = vkCreateShaderModule(*device, &createInfo,
            _device->getAllocationCallbacks(), &_shaderModule); result != VK_SUCCESS)
    {
        throw Exception{"Error: vsg::ShaderModule::create(...) failed to create shader module.", result};
    }
}

codeSize 用 sizeof(SPIRV::value_type) 而非硬编码 4,正确;pCode 指向 vector 内部缓冲,Vulkan 在返回前复制数据,所以 code 之后可释放。但 Vulkan 要求 codeSize 是 4 的倍数且大于 0、pCode 非空——VSG 都没检查。code.empty() 时 codeSize = 0、pCode 可能为 nullptr,驱动行为未定义。

// ShaderModule.cpp:185–188
void ShaderModule::compile(Context& context)
{
    if (!_implementation[context.deviceID])
        _implementation[context.deviceID] = Implementation::create(context.device, this);
}

编译 GLSL 不在 compile():它只把 code 变成 VkShaderModule。GLSL→SPIR-V 在上层 GraphicsPipeline::compile/ComputePipeline::compile 里由 context.getOrCreateShaderCompiler() 完成。ShaderModule 因而可单独创建和序列化、不链接 glslang,只有管线发现“有 source 无 code”时才触发编译器。

9.4.3 编译触发条件的精确形式

图形路径(GraphicsPipeline.cpp:184,判断 requiresShaderCompiler):

// GraphicsPipeline.cpp:185
bool requiresShaderCompiler = false;
for (const auto& shaderStage : stages)
{
    if (shaderStage->module)
    {
        if (shaderStage->module->code.empty() && !(shaderStage->module->source.empty()))
        {
            requiresShaderCompiler = true;
        }
    }
}

if (requiresShaderCompiler)
{
    auto shaderCompiler = context.getOrCreateShaderCompiler();
    if (shaderCompiler)
    {
        shaderCompiler->compile(stages);
    }
    else
    {
        fatal("VulkanSceneGraph not compiled with GLSLang, unable to compile shaders.");
    }
}

计算路径(ComputePipeline.cpp:70–84)用同样的逻辑,只是压成单个表达式:

bool requiresShaderCompiler = stage && stage->module &&
                              stage->module->code.empty() &&
                              !(stage->module->source.empty());

共同漏洞:module 为空时 requiresShaderCompiler 为假,不报错。shaderStage->compile 的 if (module) 也静默跳过(ShaderStage.cpp:213),直到 ShaderStage::apply 第 174 行 module->vk(context.deviceID) 才空指针解引用。"忘记设 module"在编译期无声,创建 VkPipeline 时以段错误出现。

第二个漏洞是 fatal() 的行为分叉。include/vsg/io/Logger.h:163–170 把 fatal 转发到 fatal_implementation,而三个 Logger 实现不一样:

Loggerfatal_implementation效果
StdLogger(Logger.cpp:248–252)fprintf(stderr, ...) + throw vsg::Exception打印并抛异常
ThreadLogger(Logger.cpp:315–319)只 fprintf(stderr, ...)打印后继续返回
NullLogger(Logger.cpp:342–345)throw Exception静默抛异常

ThreadLogger 下缺少 GLSLang,fatal(...) 返回后 compile 继续走 layout->compile、shaderStage->compile,以 codeSize = 0 调 vkCreateShaderModule。多线程 Viewer 常用 ThreadLogger,未开 VSG_SUPPORTS_ShaderCompiler 时 getOrCreateShaderCompiler() 返回空——错误路径依赖全局 Logger 类型,是控制流藏在日志后端里。

另外,fatal() 的模板版本(Logger.h:172)还带一个短路:if (level > LOGGER_FATAL) return;。如果用户把日志级别调到高于 FATAL,StdLogger 的那个 throw 也不会发生,同样会继续执行。所以"抛不抛异常"取决于两个全局状态:Logger 类型与日志级别。

9.4.4 ShaderStage 的五个构造与两个死字段

// ShaderStage.h:26–31
ShaderStage();
ShaderStage(const ShaderStage& rhs, const CopyOp& copyop = {});
ShaderStage(VkShaderStageFlagBits stage, const std::string& entryPointName, ref_ptr<ShaderModule> shaderModule);
ShaderStage(VkShaderStageFlagBits stage, const std::string& entryPointName, const std::string& source, ref_ptr<ShaderCompileSettings> hints = {});
ShaderStage(VkShaderStageFlagBits stage, const std::string& entryPointName, const ShaderModule::SPIRV& spirv);
ShaderStage(VkShaderStageFlagBits stage, const std::string& entryPointName, const std::string& source, const ShaderModule::SPIRV& spirv);

实际是六个声明(含默认与拷贝),对应四种数据来源:现成 ShaderModule、GLSL 源码、裸 SPIR-V、源码+SPIR-V 双份。数据面:

// ShaderStage.h:33–43
using SpecializationConstants = std::map<uint32_t, vsg::ref_ptr<vsg::Data>>;

Mask mask = MASK_ALL;
VkPipelineShaderStageCreateFlags flags = 0;
VkShaderStageFlagBits stage = {};
ref_ptr<ShaderModule> module;
std::string entryPointName;
SpecializationConstants specializationConstants;

flags 是死字段。 使用点仅三处:ShaderStage.h:39 声明、ShaderStage.cpp:27 拷贝初始化、ShaderStage.cpp:74 比较;read/write(ShaderStage.cpp:127–168)不序列化它,apply(ShaderStage.cpp:170–211)不写进 stageInfo。GraphicsPipeline.cpp:245 把 shaderStageCreateInfo[i].flags 写死为 0,ComputePipeline.cpp:99 靠 = {} 零初始化。用户设任何值,编译出的管线都一样,但 compare() 据此判出"假差异"。

mask 是漏比较字段。 mask(ShaderStage.h:36,注释 apply ShaderStage when (mask & view.mask) is non zero)在 read/write 里有版本守卫(ShaderStage.cpp:131–134、153–156,要求 ≥ 1.0.9),在 GraphicsPipeline::Implementation 里被用来过滤 stage(GraphicsPipeline.cpp:243):

if ((context.mask & shaderStage->mask) != 0)
{
    shaderStageCreateInfo[i].flags = 0;
    shaderStageCreateInfo[i].pNext = nullptr;
    shaderStage->apply(context, shaderStageCreateInfo[i]);
    ++i;
}

ShaderStage::compare(ShaderStage.cpp:76)比 flags/stage/module/entryPointName/specializationConstants,漏 mask。仅 mask 不同的 stage 被判等、管线被 SharedObjects 合并,按掩码过滤阶段的功能在共享场景下失效——ShaderSet 变体机制(第十章)正靠 mask 与 defines 区分阶段。

对比 GraphicsPipelineState::compare(GraphicsPipeline.h:36 的 MASK_ALL 加 Object::compare),两类互补各漏一半:一个算 mask 不算子字段,一个算子字段漏 mask。子类 compare 会调 GraphicsPipelineState::compare 补上 mask,状态这一支完整;ShaderStage 无子类,漏了就是漏了。

9.4.5 apply():特化常量的手工打包

// ShaderStage.cpp:170–211(关键段)
void ShaderStage::apply(Context& context, VkPipelineShaderStageCreateInfo& stageInfo) const
{
    stageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    stageInfo.stage = stage;
    stageInfo.module = module->vk(context.deviceID);
    stageInfo.pName = entryPointName.c_str();

    if (specializationConstants.empty())
    {
        stageInfo.pSpecializationInfo = nullptr;
    }
    else
    {
        uint32_t packedDataSize = 0;
        for (auto& id_data : specializationConstants)
            packedDataSize += static_cast<uint32_t>(id_data.second->dataSize());

        auto mapEntries = context.scratchMemory->allocate<VkSpecializationMapEntry>(specializationConstants.size());
        auto packedData = context.scratchMemory->allocate<uint8_t>(packedDataSize);
        uint32_t offset = 0;
        uint32_t i = 0;
        for (auto& [id, data] : specializationConstants)
        {
            mapEntries[i++] = VkSpecializationMapEntry{id, offset, data->dataSize()};
            std::memcpy(packedData + offset,
                        static_cast<uint8_t*>(data->dataPointer()),
                        data->dataSize());
            offset += static_cast<uint32_t>(data->dataSize());
        }

        auto specializationInfo = context.scratchMemory->allocate<VkSpecializationInfo>(1);
        stageInfo.pSpecializationInfo = specializationInfo;
        specializationInfo->mapEntryCount = static_cast<uint32_t>(specializationConstants.size());
        specializationInfo->pMapEntries = mapEntries;
        specializationInfo->dataSize = packedDataSize;
        specializationInfo->pData = packedData;
    }
}

逐项拆:

  • pName 指向 std::string 缓冲;Implementation 只存 _pipelineStates(GraphicsPipeline.cpp:227),但 GraphicsPipeline 持有 stages(GraphicsPipeline.h:70)经场景图存活,vkCreateGraphicsPipelines 同步复制 pName:隐式生命周期契约成立,依赖场景图不提前释放。
  • pSpecializationInfo 为 nullptr 时表示无特化常量,正确。
  • packedDataSize 是各 Data::dataSize() 之和,无对齐填充;Vulkan 允许 VkSpecializationMapEntry::offset 任意指定,紧打包合法。但 dataSize() 返回"数据区字节数",若 stride > sizeof(T)(交错顶点数据)会连填充塞进特化常量区,着色器读到错位值。
  • 三段 scratch 分配(mapEntries、packedData、specializationInfo)都来自 context.scratchMemory,由 GraphicsPipeline::Implementation 构造末尾的 context.scratchMemory->release()(GraphicsPipeline.cpp:262)统一归还。顺序正确:vkCreateGraphicsPipelines 在 release() 之前。
  • mapEntries[i++] = VkSpecializationMapEntry{id, offset, data->dataSize()} 的 size 是 size_t、dataSize() 返回 size_t/VkDeviceSize,收窄没问题;但 offset 与 packedDataSize 都是 uint32_t,超 4 GiB 静默回绕——实际不可能,却暴露"没考虑边界"的习惯。
  • specializationConstants 是 std::map<uint32_t, ...>,constantID 天然唯一有序无需去重;Vulkan 要求 mapEntryCount > 0 时 pMapEntries 非空且 offset + size <= dataSize,构造保证成立。

ScratchMemory::allocate(ScratchMemory.h:53–72)的对齐方式值得在此确认,因为 VkSpecializationInfo 含三个指针:

static uint8_t* align(uint8_t* p)
{
    auto alignment = sizeof(p);                 // 指针大小,64 位下为 8
    uint8_t* new_p = reinterpret_cast<uint8_t*>(
        ((reinterpret_cast<size_t>(p) + alignment - 1) / alignment) * alignment);
    return new_p;
}

template<typename T>
T* allocate(size_t num = 1)
{
    if (num == 0) return nullptr;
    size_t allocate_size = sizeof(T) * num;
    if ((ptr + allocate_size) <= (buffer + size))
    {
        T* allocated_ptr = reinterpret_cast<T*>(ptr);
        ptr = align(ptr + allocate_size);       // 只对齐下一次的起点
        return allocated_ptr;
    }
    if (!next) next = ScratchMemory::create(std::max(size, allocate_size));
    return next->allocate<T>(num);
}

align() 固定按 sizeof(void*) 对齐,与 alignof(T) 无关。本章 T 最大对齐恰为 8,等于 sizeof(p),路径成立——但这是"恰好"而非"保证":alignas(16) 类型会拿到未对齐指针。

release() 把 ptr 拨回 buffer 并递归重置 next,不释放块。Implementation 构造末尾调用它,等于把整个 Context 的 scratch 栈一次性清空,要求 compile() 期间无人持有跨调用的 scratch 指针;ShaderStage::apply 与九个 apply 都只在创建管线前使用,满足契约,但无注释、无断言,是维护风险。


9.5 九个 GraphicsPipelineState:名义上的状态命令

GraphicsPipeline.h:25–49 给出基类:

/// Base class for setting up the various pipeline states with the VkGraphicsPipelineCreateInfo
/// Subclasses are ColorBlendState, DepthStencilState, DynamicState, InputAssemblyState,
/// MultisampleState, RasterizationState, TessellationState, VertexInputState and ViewportState.
class VSG_DECLSPEC GraphicsPipelineState : public Inherit<StateCommand, GraphicsPipelineState>
{
public:
    GraphicsPipelineState() {}
    GraphicsPipelineState(const GraphicsPipelineState& gp) :
        Inherit(), mask(gp.mask) {}

    /// apply GraphicsPipelineState when (mask & view.mask) is non zero
    Mask mask = MASK_ALL;

    virtual void apply(Context& context, VkGraphicsPipelineCreateInfo& pipelineInfo) const = 0;
    void record(CommandBuffer&) const override {};

public:
    int compare(const Object& rhs) const override;
    void read(Input& input) override;
    void write(Output& output) const override;
    ...
};

注释里列出的九个子类,与 grep "Inherit<GraphicsPipelineState" 的结果完全一致(ColorBlendState.h、DepthStencilState.h、DynamicState.h、InputAssemblyState.h、MultisampleState.h、RasterizationState.h、TessellationState.h、VertexInputState.h、ViewportState.h)。第八章曾把这个数字核到 9,这里再次确认。

9.5.1 record() 是空的,为什么还要继承 StateCommand

因为需要的是 StateCommand 带来的两样东西,而不是它的 record():

  1. slot(StateCommand.h:uint32_t slot = 0;),让状态对象能进 StateStack;
  2. ref_ptr<StateCommand> 的类型身份,让它们能塞进 GraphicsPipelineStates = std::vector<ref_ptr<GraphicsPipelineState>> 并被 Visitor 遍历、被 compare_pointer_container 深比较、被 Input/Output 序列化。

StateGroup::traverse(Visitor&) 遍历 stateCommands + children,而 traverse(RecordTraversal&) 只遍历 children。GraphicsPipelineState 作为 StateCommand 放进 StateGroup 时 ConstVisitor 会看到它——WindowResizeHandler::ContainsViewport 就靠这点工作(WindowResizeHandler.cpp:116–128):

struct ContainsViewport : public ConstVisitor
{
    bool foundViewport = false;
    void apply(const ViewportState&) override { foundViewport = true; }
    bool operator()(const GraphicsPipeline& gp)
    {
        for (auto& pipelineState : gp.pipelineStates)
            pipelineState->accept(*this);
        return foundViewport;
    }
} containsViewport;

这里 pipelineState->accept(*this) 触发 ConstVisitor 分派,apply(const ViewportState&) 被命中。如果 GraphicsPipelineState 只是普通 Object,这套遍历就不成立。所以继承 StateCommand 是为了复用对象模型,不是为了复用录制语义。

代价是概念噪音:一个 StateCommand 的 record() 什么都不做,意味着把它直接放进 StateGroup::stateCommands 不会产生任何 GPU 命令。九个类里只有一个例外。

9.5.2 唯一的例外:ViewportState::record

// ViewportState.cpp:19–22
ViewportState::ViewportState()
{
    slot = 8;
}
// ViewportState.cpp:142–146
void ViewportState::record(CommandBuffer& commandBuffer) const
{
    vkCmdSetScissor(commandBuffer, 0, static_cast<uint32_t>(scissors.size()), scissors.data());
    vkCmdSetViewport(commandBuffer, 0, static_cast<uint32_t>(viewports.size()), viewports.data());
}

第八章指出:slot = 8 是全库唯一在构造之后给 slot 赋值的位置(其余都是 Inherit(n))。ViewportState 因此同时扮演两个角色:

角色触发时机入口产物
管线静态状态编译期apply(Context&, VkGraphicsPipelineCreateInfo&)pipelineInfo.pViewportState
帧期状态命令录制期record(CommandBuffer&)vkCmdSetViewport / vkCmdSetScissor

两个角色是否同时生效,由 RenderGraph::viewportStateHint 决定(RenderGraph.h:71 默认 DYNAMIC_VIEWPORTSTATE,ResourceHints.h:29–33 定义 STATIC_VIEWPORTSTATE = 1<<0、DYNAMIC_VIEWPORTSTATE = 1<<1):

// RenderGraph.cpp:147–167
recordTraversal.getState()->viewportStateHint = viewportStateHint;
vkCmdBeginRenderPass(vk_commandBuffer, &renderPassInfo, contents);

// sync the viewportState and push
viewportState->set(renderArea.offset.x, renderArea.offset.y,
                   renderArea.extent.width, renderArea.extent.height);

if ((viewportStateHint & DYNAMIC_VIEWPORTSTATE))
{
    recordTraversal.getState()->pushView(viewportState);
    traverse(recordTraversal);
    recordTraversal.getState()->popView(viewportState);
}
else
{
    traverse(recordTraversal);
}

State::pushView / popView(State.cpp:68/74)同样受这个 hint 约束:

if ((viewportStateHint & DYNAMIC_VIEWPORTSTATE) && view.camera && view.camera->viewportState)
    pushView(view.camera->viewportState);

而 Context 构造函数(Context.cpp:134–137)也读同一个 hint:

if ((resourceRequirements.viewportStateHint & DYNAMIC_VIEWPORTSTATE))
{
    defaultPipelineStates.push_back(
        DynamicState::create(VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR));
}

三处一致,闭环成立:动态模式下管线声明 VK_DYNAMIC_STATE_VIEWPORT/SCISSOR,每帧由 pushView 压入 ViewportState 发出 vkCmdSetViewport;静态模式下烘死 viewport,帧期不发命令。viewportStateHint 由 ResourceHints 传入(ResourceRequirements.cpp:90),形成"提示 → 需求 → 提示"闭环。

ViewportState::record() 无条件发命令,自己不检查 hint。若把 ViewportState 放进 stateCommands 却把 hint 设为 STATIC_VIEWPORTSTATE,RenderGraph 不 pushView,但 StateGroup 里那个仍会被 StateStack 录制(slot 8),对一个未声明动态视口的管线调用 vkCmdSetViewport——验证层会报 VUID-vkCmdSetViewport-pipelines-bound-...。约束放在 RenderGraph 的 hint 上而非 ViewportState 身上,是跨对象的隐式契约。

9.5.3 九个 apply 的统一形状

九个实现(src/vsg/state/*State.cpp)长度从 11 行到 17 行不等,形状完全一致,以 ColorBlendState 为例(ColorBlendState.cpp:145–163):

void ColorBlendState::apply(Context& context, VkGraphicsPipelineCreateInfo& pipelineInfo) const
{
    auto colorBlendState = context.scratchMemory->allocate<VkPipelineColorBlendStateCreateInfo>();

    colorBlendState->sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    colorBlendState->pNext = nullptr;
    colorBlendState->flags = 0;

    colorBlendState->logicOpEnable = logicOpEnable;
    colorBlendState->logicOp = logicOp;
    colorBlendState->attachmentCount = static_cast<uint32_t>(attachments.size());
    colorBlendState->pAttachments = attachments.data();
    colorBlendState->blendConstants[0] = blendConstants[0];
    ...
    pipelineInfo.pColorBlendState = colorBlendState;
}

九个类各自负责的 pipelineInfo 字段与数据来源:

类设置的字段内层数组指针来自
ColorBlendState(ColorBlendState.cpp:147)pColorBlendState(ColorBlendState.cpp:162)attachments.data()
DepthStencilState(DepthStencilState.cpp:112)pDepthStencilState(DepthStencilState.cpp:128)无数组,逐字段赋值(默认 VK_COMPARE_OP_GREATER,第四章 reverse-Z)
DynamicState(DynamicState.cpp:66)pDynamicState(DynamicState.cpp:74)dynamicStates.data()
InputAssemblyState(InputAssemblyState.cpp:68)pInputAssemblyState(InputAssemblyState.cpp:76)无数组
MultisampleState(MultisampleState.cpp:100)pMultisampleState(MultisampleState.cpp:113)sampleMasks.data()(空则 nullptr)
RasterizationState(RasterizationState.cpp:95)pRasterizationState(RasterizationState.cpp:112)无数组
TessellationState(TessellationState.cpp:60)pTessellationState(TessellationState.cpp:67)无数组
VertexInputState(VertexInputState.cpp:97)pVertexInputState(VertexInputState.cpp:107)vertexBindingDescriptions.data() / vertexAttributeDescriptions.data()
ViewportState(ViewportState.cpp:128)pViewportState(ViewportState.cpp:139)viewports.data() / scissors.data()

内存布局分两层:外层 Vk*StateCreateInfo 结构体分配在 ScratchMemory 上,内层数组指向状态对象自身的 std::vector。这个区别很关键:Implementation 构造函数末尾 release() 会把外层结构体一并归还,但 VkPipeline 在 vkCreateGraphicsPipelines 返回时已经复制了所有内容,所以外层失效无害;内层数组则因为 Implementation::_pipelineStates(GraphicsPipeline.h:99)持有 ref_ptr<GraphicsPipelineState> 而继续存活,虽然同样不再被 Vulkan 需要。

Implementation::_pipelineStates 的存在理由是复用比较(9.10),不是维持 Vulkan 指针有效;它存状态对象的引用,用于 compare_pointer_container(...)。

9.5.4 九个 compare 的两种写法

九个类都先调 GraphicsPipelineState::compare(rhs_object)(把 mask、类型、_auxiliary 比掉),然后分两派:

逐字段派(ColorBlendState、DynamicState、InputAssemblyState、MultisampleState、TessellationState、VertexInputState、ViewportState):用 compare_value 或 compare_value_container。例如 ViewportState(ViewportState.cpp:47)的 compare:

// ViewportState.cpp:54
if ((result = compare_value_container(viewports, rhs.viewports))) return result;
return compare_value_container(scissors, rhs.scissors);

区间 memcmp 派(DepthStencilState.cpp:46 比较 depthTestEnable 至 maxDepthBounds,RasterizationState.cpp:47 比较 depthClampEnable 至 lineWidth):

// DepthStencilState.cpp:41–46
return compare_region(depthTestEnable, maxDepthBounds, rhs.depthTestEnable);
// RasterizationState.cpp:42–47
return compare_region(depthClampEnable, lineWidth, rhs.depthClampEnable);

compare_region(compare.h:52、compare.h:60)里 std::memcmp 的实现是:

template<typename S, typename E>
int compare_region(const S& start, const E& end, const S& rhs)
{
    const char* lhs_ptr = reinterpret_cast<const char*>(&start);
    const char* rhs_ptr = reinterpret_cast<const char*>(&rhs);
    size_t size = size_t(reinterpret_cast<const char*>(&end) - lhs_ptr) + sizeof(E);
    return std::memcmp(lhs_ptr, rhs_ptr, size);
}

它把"从第一个成员到最后一个成员"的整段对象内存按字节比较,包括所有中间成员与成员之间的 padding。以 DepthStencilState.h:29 起、到 maxDepthBounds(DepthStencilState.h:36)的实际声明为例:

VkBool32 depthTestEnable;          // 4
VkBool32 depthWriteEnable;         // 4
VkCompareOp depthCompareOp;        // 4
VkBool32 depthBoundsTestEnable;    // 4
VkBool32 stencilTestEnable;        // 4
VkStencilOpState front;            // 28(7 个 32 位字段,Vulkan 规范)
VkStencilOpState back;             // 28
float minDepthBounds;              // 4
float maxDepthBounds;              // 4

9 个成员全部是 4 字节对齐、无 padding,compare_region 覆盖的恰好是这 9 个成员,没有夹带别的成员,memcmp 结果正确(VkStencilOpState 按 Vulkan 规范含 7 个 32 位字段,实际字节数以本机 Vulkan SDK 为准)。RasterizationState.h:29 起的 rasterizerDiscardEnable / polygonMode / cullMode 直到 lineWidth 共 10 个成员同样全是 4 字节标量,也正确。

但"正确"来自布局巧合,不是来自类型系统:

  • front/back 间插入 std::string,memcmp 比较其对象表示(指针/SSO)而非内容,且读未初始化字节;
  • 字段改成 double/uint64_t 会引入 padding,memcmp 读到未初始化字节,逻辑相等的对象可能被判不等;
  • VkBool32、VkCompareOp 都是 32 位,但 float 的 +0.0 与 -0.0 位模式不同,NaN 的位模式也不唯一,memcmp 会把它们当成不同值,而逐字段 compare_value 用 < 比较时 +0.0 == -0.0 成立。minDepthBounds/maxDepthBounds 恰是 float。

第 9.11 节会把这个风险放回整个 compare 体系里评估。这里先记住:九个 compare 里有两个是字节级比较,其余七个是字段级比较,两套语义并存。

9.5.5 九个 apply 都不检查的 Vulkan 约束

GraphicsPipeline::Implementation 在调用九个 apply 之前只设了 6 个字段(GraphicsPipeline.cpp:230、GraphicsPipeline.cpp:236):sType、layout、renderPass、subpass、basePipelineHandle、pNext。其余 p*State 指针全部由 apply 设置,没有默认值。

Vulkan 规定 pVertexInputState、pInputAssemblyState、pRasterizationState、pColorBlendState(有 color attachment 时)、pViewportState(除非 rasterizerDiscardEnable)、pMultisampleState 等必须在 VkGraphicsPipelineCreateInfo 中非空。VSG 靠"三层合并一定会凑齐"来保证:

  • defaultPipelineStates 至少有 ViewportState(CompileTraversal.cpp:93、CompileTraversal.cpp:127)与动态下的 DynamicState(Context.cpp:134、Context.cpp:135);
  • overridePipelineStates 在 MSAA 时补 MultisampleState(CompileTraversal.cpp:97、CompileTraversal.cpp:122、CompileTraversal.cpp:165);
  • 场景侧的 GraphicsPipelineConfigurator 会补 VertexInputState、InputAssemblyState、RasterizationState、ColorBlendState、DepthStencilState。

凑齐九个状态的责任分散在三个互不知情的模块里。`mergeGraphicsPipelineStates` 按类型去重但不查"是否齐了":手工构造只给两个状态时编译不报错,直到 `vkCreateGraphicsPipelines` 触发未定义行为或验证层错误——"声明式配置 + 无校验"的代价。

另一个具体坑:ColorBlendState::apply 里 pAttachments = attachments.data()(ColorBlendState.cpp:155)、attachmentCount = attachments.size()。若 attachments 为空而 renderPass 有一个 color attachment,attachmentCount = 0 与附件数不匹配,Vulkan 要求两者相等(除非启用 VK_DYNAMIC_STATE_COLOR_BLEND_* 系列扩展)。VSG 的动态状态默认只有 VIEWPORT/SCISSOR,所以这条约束仍由调用方手工保证。


9.6 mergeGraphicsPipelineStates:三层合并与唯一例外

GraphicsPipeline.cpp:56–104 是本章最"设计味"的一段。它把三个来源的状态合并成一份 GraphicsPipelineStates。

9.6.1 单元素合并的逐行逻辑

void vsg::mergeGraphicsPipelineStates(
    Mask mask,
    GraphicsPipelineStates& dest_PipelineStates,
    ref_ptr<GraphicsPipelineState> src_PipelineState)
{
    if (!src_PipelineState || (mask & src_PipelineState->mask) == 0) return;

    auto* src_DynamicState = src_PipelineState->cast<DynamicState>();

    // replace any entries in the dest_PipelineStates that have the same type as src_PipelineState
    for (auto& original_pipelineState : dest_PipelineStates)
    {
        if (original_pipelineState->type_info() == src_PipelineState->type_info())
        {
            if (src_DynamicState)
            {
                auto original_DynamicState = original_pipelineState->cast<DynamicState>();
                if (original_DynamicState->dynamicStates.empty())
                {
                    original_pipelineState = src_PipelineState;
                }
                else if (original_DynamicState->dynamicStates != src_DynamicState->dynamicStates)
                {
                    auto new_DynamicState = DynamicState::create(original_DynamicState->dynamicStates);
                    for (auto state : src_DynamicState->dynamicStates)
                    {
                        if (std::find(new_DynamicState->dynamicStates.begin(),
                                      new_DynamicState->dynamicStates.end(),
                                      state) == new_DynamicState->dynamicStates.end())
                        {
                            new_DynamicState->dynamicStates.push_back(state);
                        }
                    }
                    original_pipelineState = new_DynamicState;
                }
            }
            else
            {
                original_pipelineState = src_PipelineState;
            }
            return;
        }
    }
    dest_PipelineStates.push_back(src_PipelineState);
}

三条规则:

  1. 过滤:(mask & src->mask) == 0 时丢弃。Mask 是 uint64_t(Mask.h:20),MASK_ALL = ~MASK_OFF(Mask.h:22);context.mask 在 apply(View&) 第 437 行设为 view.mask,即按视图掩码选状态。
  2. 同类型替换:type_info() 相等即同类,后者覆盖前者(RTTI 身份而非 compare() 值相等),影响 compare_pointer_container 的短路优化但不影响语义。
  3. DynamicState 取并集:唯一不允许简单覆盖的类。因为 dynamicStates 是一个列表,多个来源各自声明一部分动态状态,覆盖会丢掉前面声明的。

9.6.2 DynamicState 分支里三个不显眼的细节

第一,cast<DynamicState>() 的返回值没判空就用。 第 69 行 original_DynamicState->dynamicStates.empty() 直接解引用。它成立的前提是:type_info() 相等 ⇒ 两个对象的动态类型相同 ⇒ 若 src 是 DynamicState,original 也一定是。这个推理正确,但代码里没有断言,只靠行数相隔 5 行的隐式不变量。若将来有人把 type_info() 判断改成 compare() 或允许子类,cast 会返回空指针。

第二,"空则替换、非空则并集"有空集陷阱。 original 空而 src 非空 → 直接替换(正确);original 非空而 src 空 → 进 else if 比较后新建 DynamicState(original.dynamicStates),遍历空的 src,结果等价但分配新对象并替换指针。Implementation::_pipelineStates 存的引用与 combined_pipelineStates 里的变成新对象,破坏指针短路。代价小,属无谓分配。

第三,并集不排序。 new_DynamicState 保留 original 顺序再追加 src 新元素,合并结果依赖三层调用顺序。DynamicState::compare(DynamicState.cpp:33–40)用 compare_value_container 做顺序敏感的 memcmp。三层顺序在 compile 里固定(第 171–173 行)所以稳定;但应用若通过 View::overridePipelineStates 以不同顺序给两个 DynamicState,语义相同的管线会被判不同,多建 VkPipeline。

compare_value_container(compare.h:79–87)对 std::vector<VkDynamicState> 走 compare_region(lhs.front(), lhs.back(), rhs.front())。VkDynamicState 是 4 字节枚举,无 padding,memcmp 覆盖整个数组且顺序敏感——这一点与"集合语义"直接冲突。

9.6.3 容器版本与三层调用

void vsg::mergeGraphicsPipelineStates(
    Mask mask,
    GraphicsPipelineStates& dest_PipelineStates,
    const GraphicsPipelineStates& src_PipelineStates)
{
    for (const auto& src_PipelineState : src_PipelineStates)
    {
        mergeGraphicsPipelineStates(mask, dest_PipelineStates, src_PipelineState);
    }
}

GraphicsPipeline::compile(第 169–173 行):

GraphicsPipelineStates combined_pipelineStates;
combined_pipelineStates.reserve(
    context.defaultPipelineStates.size() +
    pipelineStates.size() +
    context.overridePipelineStates.size());
mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, context.defaultPipelineStates);
mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, pipelineStates);
mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, context.overridePipelineStates);

优先级明确:override > 场景 > default。这与 Context.h:100–110 的注释一致——"必须设置以避免 Vulkan 错误"的 MultisampleState 放 override,"通常场景里不设置"的 ViewportState 放 default,场景作者写在中间,既可以覆盖 default,也挡不住 override。

reserve() 取三层长度之和一次分配。过滤在 CompileTraversal 注入与 compile 合并各做一次,都用 context.mask;场景自带 pipelineStates 只在第二阶段过滤。

9.6.4 谁往三层里塞东西:七个注入点

把 grep overridePipelineStates|defaultPipelineStates 的结果按用途归类:

位置层塞入内容条件
Context.cpp:136defaultDynamicState(VIEWPORT, SCISSOR)viewportStateHint & DYNAMIC_VIEWPORTSTATE
CompileTraversal.cpp:93/95default外部传入的 ViewportState 或 ViewportState::create(window.extent2D())add(Window&, ...)
CompileTraversal.cpp:97/122/165overrideMultisampleState(renderPass->maxSamples)maxSamples != VK_SAMPLE_COUNT_1_BIT
CompileTraversal.cpp:124/166overrideview->overridePipelineStates 整段追加无条件
CompileTraversal.cpp:127/129/169/171defaultview.camera->viewportState 或按 extent 新建add(..., View&, ...)
CompileTraversal.cpp:362/366/371default / override二级命令图按自身 window/framebuffer extent 新建 ViewportState、按自身 renderPass 补 MultisampleStateapply(SecondaryCommandGraph&)
CompileTraversal.cpp:397/403default / overriderenderGraph.viewportState、MultisampleState(context->renderPass->maxSamples)apply(RenderGraph&)
CompileTraversal.cpp:443/444default / overrideview.camera->viewportState、view.overridePipelineStatesapply(View&)
WindowResizeHandler.cpp:57/195defaultview.camera->viewportStateresize 时
RenderGraph.cpp:204overrideMultisampleState(activeRenderPass->maxSamples)resized() 的 STATIC 分支

注意 CompileTraversal.cpp:443:

mergeGraphicsPipelineStates(context->mask, context->defaultPipelineStates, view.camera->viewportState);

这行没判 view.camera 为空。同文件 add(..., View&, ...) 在第 126/168 行都判了,WindowResizeHandler.cpp:159 也先判 if (!view.camera) 才动 projectionMatrix->changeExtent(...)。所以 apply(View&) 是唯一不判空的:无相机视图(纯计算或未初始化)会在 view.camera->viewportState 处解引用空 ref_ptr 段错误;mergeGraphicsPipelineStates 的 if (!src_PipelineState) 挡不住 camera 为空。

RenderGraph.cpp:204 在 resized() 里 emplace_back(MultisampleState::create(...)) 却不清空 overridePipelineStates。每次 MSAA resize 都多一个元素;按类型去重让最终管线不受影响,但 reserve() 的容量估算与合并循环次数线性增长。对比 CompileTraversal::apply(RenderGraph&) 用 previousOverridePipelineStates 保存/恢复(第 391–410 行),resize 路径漏了清理。


9.7 GraphicsPipeline::compile 逐行

把 GraphicsPipeline.cpp:159–220 完整摊开,按执行阶段编号:

void GraphicsPipeline::compile(Context& context)
{
    // (1) 取键、扩容
    uint32_t viewID = context.viewID;
    if (static_cast<uint32_t>(_implementation.size()) < (viewID + 1))
    {
        _implementation.resize(viewID + 1);
    }

    if (!_implementation[viewID])
    {
        // (2) 三层合并
        GraphicsPipelineStates combined_pipelineStates;
        combined_pipelineStates.reserve(context.defaultPipelineStates.size() +
                                       pipelineStates.size() +
                                       context.overridePipelineStates.size());
        mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, context.defaultPipelineStates);
        mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, pipelineStates);
        mergeGraphicsPipelineStates(context.mask, combined_pipelineStates, context.overridePipelineStates);

        // (3) 跨 viewID 复用
        for (const auto& imp : _implementation)
        {
            if (imp && vsg::compare_pointer_container(imp->_pipelineStates, combined_pipelineStates) == 0)
            {
                _implementation[viewID] = imp;
                return;
            }
        }

        // (4) 需要 GLSL 编译?
        bool requiresShaderCompiler = false;
        for (const auto& shaderStage : stages)
        {
            if (shaderStage->module)
            {
                if (shaderStage->module->code.empty() && !(shaderStage->module->source.empty()))
                    requiresShaderCompiler = true;
            }
        }
        if (requiresShaderCompiler)
        {
            auto shaderCompiler = context.getOrCreateShaderCompiler();
            if (shaderCompiler)
                shaderCompiler->compile(stages);
            else
                fatal("VulkanSceneGraph not compiled with GLSLang, unable to compile shaders.");
        }

        // (5) 编译依赖
        layout->compile(context);
        for (auto& shaderStage : stages) shaderStage->compile(context);

        // (6) 创建实现
        _implementation[viewID] = GraphicsPipeline::Implementation::create(
            context, context.device, context.renderPass, layout,
            stages, combined_pipelineStates, subpass);
    }
}

9.7.1 阶段 (1):扩容但不收缩

_implementation.resize(viewID + 1) 只在容量不足时执行。viewID 若稀疏(如应用创建 viewID = 1000 的 View),会分配 1001 个 ref_ptr<Implementation> 其中 999 个为空。validated_vk() 处理这种稀疏情况却没有调用者;viewID 由 View 分配、通常从 0 连续递增,所以实践中不稀疏。

release()(GraphicsPipeline.h:88)会 _implementation.clear(),把 vector 缩到 0;release(viewID)(第 84–87 行)只把指定槽位赋空,保留其它槽位。两者都不销毁其它 Context 对该对象的引用——ref_ptr 保证 Implementation 在最后一个引用消失时才析构并调用 vkDestroyPipeline(GraphicsPipeline.cpp:270–273)。

9.7.2 阶段 (3):本章最重要的一段

for (const auto& imp : _implementation)
{
    if (imp && compare_pointer_container(imp->_pipelineStates, combined_pipelineStates) == 0)
    {
        _implementation[viewID] = imp;
        return;
    }
}

意图很清楚:同一个 GraphicsPipeline 对象被多个 View 编译时,如果合并后的状态完全相同,就没必要再调一次 vkCreateGraphicsPipelines,直接共用已有的 VkPipeline。这是一个 O(view 数) 的线性扫描,命中后直接 return,跳过阶段 (4)(5)(6)。

但它比较的只有 imp->_pipelineStates 与 combined_pipelineStates。而 VkPipeline 的实际内容由以下因素共同决定:

因素是否进入复用判据实际来源
九个 Vk*StateCreateInfo是combined_pipelineStates
VkRenderPass否context.renderPass
VkPipelineLayout否(间接)layout->vk(deviceID)
shaderStages(含按 mask 过滤后的 stageCount)否stages + context.mask
subpass否对象字段
Device否context.device
特化常量否stages[i].specializationConstants

其中 layout、subpass、stages 是 GraphicsPipeline 对象自己的字段,同一个对象内所有 view 共享,所以"不比较"在这个对象内部是安全的——但前提是这些字段在两次 compile 之间没被改过。它们全是 public 且可写(GraphicsPipeline.h:70–73),库没有禁止编译后修改。真正跨 view 变化的、且完全没进判据的是 context.renderPass 与 context.mask:

  • context.mask 决定 GraphicsPipeline.cpp:243 的 (context.mask & shaderStage->mask) != 0,进而决定 stageCount。两视图掩码不同会过滤出不同阶段集合,但 pipelineStates 可能完全相同,于是复用 stageCount 不同的旧管线。
  • context.renderPass 决定 pipelineInfo.renderPass。Vulkan 要求 VkPipeline 与录制时 vkCmdBeginRenderPass 使用的 renderPass 兼容(同种格式/采样数/附件布局,或显式启用 VK_PIPELINE_CREATE_RENDER_PASS_... 一类的兼容标志)。VSG 创建管线时 flags 由零初始化(GraphicsPipeline.cpp:230 的 = {}),未设置任何兼容标志。

CompileTraversal 提供确凿证据:apply(RenderGraph&) 与 apply(SecondaryCommandGraph&) 临时替换 context->renderPass(第 358、399 行)并在遍历后恢复(第 379、411 行),全程不改 viewID。同一 viewID 下 compile 可能在两个 renderPass 上下文被调用;第二次连 if (!_implementation[viewID]) 都进不去,是完全没有判据。

即便假设 viewID 不同(比如两个 View 各自有 Context),跨 view 的复用循环仍会因 pipelineStates 相同而把绑定到 renderPass A 的 VkPipeline 交给 renderPass B 使用。

9.7.3 阶段 (4)(5):编译的副作用

shaderCompiler->compile(stages)(第 202 行)会就地修改 stages 里的 ShaderModule::code,所以 GraphicsPipeline::compile 不是纯函数。第十二章的 CompileManager 多线程编译时,这个可写性会成为竞态关键:两个线程同时 compile 同一管线,一个写 code,另一个读。

阶段 (5) 的 layout->compile(context) 没有判空。默认构造的 GraphicsPipeline()(GraphicsPipeline.cpp:110–112)里 layout 是空 ref_ptr,若直接 compile 就在这里崩。GraphicsPipelineConfigurator 会设置它,但手工构造路径 unprotected。

9.7.4 Implementation::create 的参数传递

_implementation[viewID] = GraphicsPipeline::Implementation::create(
    context, context.device, context.renderPass, layout,
    stages, combined_pipelineStates, subpass);

Implementation 构造签名(GraphicsPipeline.h:95):

Implementation(Context& context, Device* device, const RenderPass* renderPass,
               const PipelineLayout* pipelineLayout, const ShaderStages& shaderStages,
               const GraphicsPipelineStates& pipelineStates, uint32_t subpass);

shaderStages 与 pipelineStates 都是 const 引用;shaderStages 在构造里遍历调 shaderStage->apply(const 方法,OK),pipelineStates 被拷进 _pipelineStates(GraphicsPipeline.cpp:227)持有到析构。

context 参数在 Implementation 里被用于两件事:context.scratchMemory(第 238、262 行)与 context.mask(第 243 行)。device 单独传一份,同时又能通过 context.device 拿到——重复传参,但让 Implementation 不必依赖 Context 的完整定义。

ComputePipeline::Implementation(ComputePipeline.cpp:96)也接了 Context& context,但它的构造函数体里根本没用到 context(第 99–113 行只用了 device、pipelineLayout、shaderStage)。shaderStage->apply(context, stageInfo) 里用到 context.deviceID 与 context.scratchMemory,所以参数不是完全冗余,只是用得很浅。


9.8 Implementation:一次 vkCreateGraphicsPipelines 的全部细节

GraphicsPipeline.cpp:226–268:

GraphicsPipeline::Implementation::Implementation(
    Context& context, Device* device, const RenderPass* renderPass,
    const PipelineLayout* pipelineLayout, const ShaderStages& shaderStages,
    const GraphicsPipelineStates& pipelineStates, uint32_t subpass) :
    _pipelineStates(pipelineStates),
    _device(device)
{
    VkGraphicsPipelineCreateInfo pipelineInfo = {};
    pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineInfo.layout = pipelineLayout->vk(device->deviceID);
    pipelineInfo.renderPass = *renderPass;
    pipelineInfo.subpass = subpass;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
    pipelineInfo.pNext = nullptr;

    auto shaderStageCreateInfo =
        context.scratchMemory->allocate<VkPipelineShaderStageCreateInfo>(shaderStages.size());
    uint32_t i = 0;
    for (auto& shaderStage : shaderStages)
    {
        if ((context.mask & shaderStage->mask) != 0)
        {
            shaderStageCreateInfo[i].flags = 0;
            shaderStageCreateInfo[i].pNext = nullptr;
            shaderStage->apply(context, shaderStageCreateInfo[i]);
            ++i;
        }
    }

    pipelineInfo.stageCount = i;
    pipelineInfo.pStages = shaderStageCreateInfo;

    for (auto pipelineState : pipelineStates)
    {
        pipelineState->apply(context, pipelineInfo);
    }

    VkResult result = vkCreateGraphicsPipelines(
        *device, VK_NULL_HANDLE, 1, &pipelineInfo,
        _device->getAllocationCallbacks(), &_pipeline);

    context.scratchMemory->release();

    if (result != VK_SUCCESS)
    {
        throw Exception{"Error: vsg::GraphicsPipeline failed to create VkPipeline.", result};
    }
}

9.8.1 结构体字段清点

VkGraphicsPipelineCreateInfo 的字段分三处填充:Implementation 显式设 sType、layout、renderPass、subpass、basePipelineHandle、pNext(6 个)与 stageCount/pStages(2 个),九个 apply 设 p*State 指针,flags 与 basePipelineIndex 由 = {} 零初始化:

  • flags = 0:不启用 VK_PIPELINE_CREATE_DERIVATIVE_BIT / ALLOW_DERIVATIVE_BIT,也不启用 renderPass 兼容标志。
  • basePipelineHandle = VK_NULL_HANDLE 配合 basePipelineIndex = 0:flags 不含 DERIVATIVE_BIT 时二者被忽略,合法。
  • pNext = nullptr:没有接 VkPipelineRenderingCreateInfo(dynamic rendering)、VkGraphicsPipelineLibraryCreateInfoEXT 等扩展结构。

于是 9.7.2 里"renderPass 不兼容"的结论更硬了:VSG 走的是传统 renderPass 路径,且没有设置任何允许跨 renderPass 复用的标志。VkPipeline 与创建时的 VkRenderPass 是强绑定的。

9.8.2 stageCount = i 的三种边界

i 只在 (context.mask & shaderStage->mask) != 0 时递增,但 scratch 分配用的是 shaderStages.size()。所以 stageCount <= size,不会越界。三种情况:

  1. 全部通过:i == shaderStages.size()。
  2. 部分被过滤:i < size,pStages 前 i 个已填充、后面是未初始化 scratch,但 stageCount = i 让驱动只读前 i 个,安全。flags = 0 与 pNext = nullptr 是显式写的——apply() 只设 sType/stage/module/pName/pSpecializationInfo,不写就会让 scratch 泄漏进结构体,故非冗余。
  3. 全部被过滤:i == 0,stageCount = 0。Vulkan 规范允许 stageCount = 0 的前提是启用了 graphics pipeline library 的部分管线;对完整图形管线,stageCount 必须至少包含 vertex stage(除非 mesh shader)。VSG 没有检查,直接交给驱动。

情况 2 是 mask 机制的实际用途:ShaderStage::mask 与 context.mask(即 view.mask)位与为零时,该阶段不进管线。这就是"同一份 GLSL 在不同视图里编译成不同阶段组合"的实现。但如 9.4.4 所述,ShaderStage::compare 漏了 mask,所以两个 mask 不同的 stage 会被 SharedObjects 合并,机制在共享场景下失效。

9.8.3 release() 紧跟 vkCreateGraphicsPipelines

VkResult result = vkCreateGraphicsPipelines(...);
context.scratchMemory->release();
if (result != VK_SUCCESS) throw ...;

顺序是"创建 → 归还 scratch → 检查结果"。Vulkan 规范保证 vkCreateGraphicsPipelines 在返回前消费完所有 pCreateInfo 指向的数据(包括 pStages、p*State 以及更内层的数组),所以归还后驱动不再访问。这一点和规范一致,不是 bug。

ScratchMemory::release 是整个 Context::scratchMemory 的全局重置(ScratchMemory.h:74–78,链尾 ScratchMemory::create 续接新块):构造期间 Context 上其它有效 scratch 指针都会失效。目前 CompileTraversal 没有跨调用持有 scratch 数据,所以安全;但这是没文档化的全局副作用。更稳妥的是 Implementation 自带局部 scratch,或 Context 提供 ScopedScratch 栈帧。

ComputePipeline::Implementation(ComputePipeline.cpp:96)也调 shaderStage->apply,特化常量在 context.scratchMemory 分配,但末尾没有 release(),留给后续某次归还。两条路径归还策略不同,进一步说明契约是隐式的。

9.8.4 错误路径与析构

// GraphicsPipeline.cpp:270–273
GraphicsPipeline::Implementation::~Implementation()
{
    vkDestroyPipeline(*_device, _pipeline, _device->getAllocationCallbacks());
}

析构没判 _pipeline 为空。正常路径成功即有效;但创建失败时 throw Exception 让 Implementation::create 构造的对象回滚析构,此时 _pipeline 是未初始化的裸句柄——VkPipeline _pipeline;(GraphicsPipeline.h:100)没有初始化器。失败路径用未初始化句柄调用 vkDestroyPipeline。

对比 PipelineLayout::Implementation::~Implementation(PipelineLayout.cpp:165–171)就判了:

// PipelineLayout.cpp:167
if (_pipelineLayout)
{
    vkDestroyPipelineLayout(*_device, _pipelineLayout, _device->getAllocationCallbacks());
}

而 ComputePipeline::Implementation::~Implementation(ComputePipeline.cpp:116–119)与 ShaderModule::Implementation::~Implementation 也没判空。四个实现里只有一个做了防御。这是"正常路径写对了、错误路径没测"的常见形态。

返回值由 result 接住并在 release() 后检查——release() 不会抛异常,这不是问题。真正问题:Exception 抛出时 ShaderModule::compile、PipelineLayout::compile 已创建 VkShaderModule/VkPipelineLayout,挂在各自 Object 的 _implementation 上随对象存活,不泄漏,只是白白创建。

9.8.5 VkPipeline 与 Implementation 的所有权

GraphicsPipeline  ──ref_ptr──> Implementation[viewID]  ──ref_ptr──> Device
                                      │
                                      └── VkPipeline(裸句柄,析构里销毁)

Implementation 继承 Object(GraphicsPipeline.h:93),所以能被 ref_ptr 管理。_device 保证 VkDevice 在 vkDestroyPipeline 时仍存活——这是必要的,因为 GraphicsPipeline 可能在 Device 引用计数归零之后才被释放(例如场景图比 Viewer 活得久)。同理 PipelineLayout::Implementation、ShaderModule::Implementation、ComputePipeline::Implementation 都持有 ref_ptr<Device> _device。

代价是 VkPipeline 的销毁时机完全由引用计数决定,可能在帧中间发生;RenderGraph::resized() 里的 vkDeviceWaitIdle(*device)(RenderGraph.cpp:206)正是为了规避:重建前确保 GPU 不再使用旧管线。


9.9 没有 VkPipelineCache:复用的三个层级

全库搜索结果:

$ grep -rn "vkCreatePipelineCache\|VkPipelineCache" include src
include/vsg/vk/vulkan.h:885: typedef VkResult(VKAPI_PTR* PFN_vkCreateRayTracingPipelinesKHR)(... VkPipelineCache pipelineCache ...);
src/vsg/state/ComputePipeline.cpp:110: vkCreateComputePipelines(*device, VK_NULL_HANDLE, 1, ...)
src/vsg/state/GraphicsPipeline.cpp:260: vkCreateGraphicsPipelines(*device, VK_NULL_HANDLE, 1, ...)

VkPipelineCache 只在函数指针 typedef 里作为一个参数类型出现过,没有任何 vkCreatePipelineCache 调用,没有任何缓存对象的成员字段。两处创建都把第二个参数写成 VK_NULL_HANDLE。

9.9.1 三级复用

VSG 实际的复用发生在三个不同层级,范围依次收窄:

层级机制生效范围证据
L1 对象共享SharedObjects::share(graphicsPipeline)跨场景图、跨 ViewGraphicsPipelineConfigurator.cpp:838
L2 实现复用compile() 的 compare_pointer_container 循环单个 GraphicsPipeline 对象内、跨 viewIDGraphicsPipeline.cpp:175–182
L3 驱动缓存VkPipelineCache跨对象、跨帧、可持久化到磁盘不存在

L1 是 CPU 侧去重:GraphicsPipelineConfigurator.cpp:829 的 pipelineUnique 用 compare_pointer 扫 inheritedState,依赖 compare() 深比较与 SharedObjects 互斥锁。L2 是 9.7.2 的 compile() 复用循环,只在 _implementation[viewID] 为空时触发且判据不完整。L3 缺席:两个内容相同但未被共享的管线各调一次 vkCreateGraphicsPipelines,没有跨对象复用机会。

9.9.2 这对启动时间的实际含义

vkCreateGraphicsPipelines 是 Vulkan 里最贵的单次调用之一:驱动要编译/链接着色器、做状态特化、生成硬件命令。VSG 对每个 VkPipeline 单独调用一次,第二个参数是 VK_NULL_HANDLE,createInfoCount = 1:

vkCreateGraphicsPipelines(*device, VK_NULL_HANDLE, 1, &pipelineInfo, ...);

VkPipelineCache 取舍有理由:生命周期绑 Device,序列化要处理驱动版本与设备 UUID 校验,跨设备复用静默失效。第十二章 CompileManager 用多线程并行编译补偿——那是 CPU 侧并发,不是驱动侧缓存。代价明确:冷启动时同一 shader 变体被多少份未共享管线引用,就付多少次完整编译。

9.9.3 validated_vk() 与"没人用的安全版本"

9.2 提过 validated_vk 零调用。把它和 vk() 放一起看,GraphicsPipeline.h:63–67 的注释写得很直白:

/// return the Vulkan Pipeline for specified viewID.
VkPipeline vk(uint32_t viewID) const { return _implementation[viewID]->_pipeline; }

/// variant of vk(viewID) method that is slower but adds validation of the viewID parameter
VkPipeline validated_vk(uint32_t viewID) const { ... }

作者知道 vk() 不校验、也写了更慢的安全版本,却没在任何录制路径启用。推测录制是热路径不愿付分支代价。这把"viewID 必须已在编译期建好实现"变成无检查的全局契约:出错就是段错误而非可读信息。

具体场景:动态新增 View 但没跑 CompileTraversal,录制时 vk(newViewID) 对 _implementation 越界下标;std::vector::operator[] 不检查边界,越界内存被当 ref_ptr<Implementation> 用,随后 _pipeline 解引用——比"返回 0"糟得多。


9.10 缓存键不完整的四种可观测后果

把 9.7.2 的表格转成可推演的场景。四种后果按触发难度排列:

9.10.1 同一 viewID、不同 renderPass(最容易触发)

CompileTraversal::apply(RenderGraph&)(CompileTraversal.cpp:382–412)与 apply(SecondaryCommandGraph&)(343–379)都在遍历前保存 context->renderPass、替换为图自己的 renderPass,遍历后恢复;前者还补 MultisampleState。两段都没改 context->viewID。

若 RenderGraph 的 renderPass 与 Context 初始的不同,且某个管线已被同一 viewID 编译过,GraphicsPipeline::compile 看到 _implementation[viewID] 非空就直接返回,仍绑定旧 renderPass。SecondaryCommandGraph 分支甚至按自身 extent 新建 ViewportState(第 362/366 行)——作者预期上下文会不同,却没纳入缓存键。

9.10.2 不同 viewID、不同 renderPass

两个 View 落在两个不同窗口(各自 getOrCreateRenderPass()),或一屏一离屏。CompileTraversal.cpp:83/113/164 会给两个 Context 不同的 renderPass。因为 View::viewID 不同,_implementation 是两个槽位。若两处合并出的 pipelineStates 恰好相同(很常见:同样的场景状态、同样的窗口尺寸、同样的 MSAA 设置),9.7.2 的复用循环会命中,第二个 view 直接拿第一个的 VkPipeline。

Vulkan 规范下,VkPipeline 与被绑定的 VkRenderPass 必须"兼容"(fragment output 与 attachment 格式、sample count、subpass 布局一致)。若两个窗口只是格式不同,验证层会报错;若驱动不做检查,画面可能正常也可能异常——这属于"看驱动心情"的未定义行为。

9.10.3 mask 改变导致 stageCount 不同

ShaderStage::mask 与 GraphicsPipelineState::mask 都参与 context.mask 的位与过滤,但过滤结果没有进缓存键。构造一个场景:两个 View 的 view.mask 不同,某个 ShaderStage 的 mask 只匹配其中一个;pipelineStates 里所有状态都是 MASK_ALL,合并结果相同。此时 view B 复用 view A 的管线,多带或少带一个着色器阶段。

这条比前两条更难触发,因为 mask 的实际使用点不多(全库主要是 StateSwitch、View::mask、RenderGraph),但它揭示的是同一个结构问题:缓存键只覆盖了 VkGraphicsPipelineCreateInfo 的九个 p*State 字段,剩下九个字段全部没覆盖。

9.10.4 编译后修改描述字段

GraphicsPipeline.h:70–73 全是 public:

ShaderStages stages;
GraphicsPipelineStates pipelineStates;
ref_ptr<PipelineLayout> layout;
uint32_t subpass;

compile() 之后改 pipelineStates,下一次 compile() 仍会因 _implementation[viewID] 非空而整体跳过(连复用循环都不进)。只有显式 release(viewID) 才会触发重建。库没有提供"标记脏"的 API,也没有把字段设为 protected/private 并提供 setter 来自动失效。

VSG 的整体风格是"配置在编译前写好,编译后不再改",文档里却没有把这条禁令写进任何注释。

9.10.5 一个更根本的观察:_pipelineStates 保存的是引用,不是快照

Implementation 构造函数里 _pipelineStates(pipelineStates) 拷贝的是 ref_ptr 容器,而不是状态对象的值。因此:

  • View A 编译时 _implementation[0]->_pipelineStates 存着指向 viewA.camera->viewportState 的引用;
  • resize 时 RenderGraph::record(RenderGraph.cpp:151)就地 viewportState->set(...) 修改它;
  • 下次 compile 的 combined_pipelineStates 放的是同一 ref_ptr(WindowResizeHandler.cpp:57 push 的正是 view.camera->viewportState);
  • compare_pointer_container 先比容器长度,再逐元素调 compare_pointer;同一指针在 compare_pointer 里直接返回 0。

即使 ViewportState 内容变了,复用比较也因"两边是同一对象"判等。这正是 WindowResizeHandler::apply(BindGraphicsPipeline&) 必须先 release(context->viewID) 再 compile(*context)(WindowResizeHandler.cpp:133)的原因:不清空槽位,compile() 连 if (!_implementation[viewID]) 都进不去;即使进了也会命中自己。

这条把 9.7、9.10、9.12 串起来:release(viewID) 不是"释放资源",而是绕过一层本来无法感知内容变化的缓存的唯一手段。第八章 8.7.5 更正过 Bin 状态快照与 viewport 的关系:Bin::add 快照的也是 stateStack.top() 这个 ref_ptr,同样不复制值,两处是同一种"引用即快照"的假设。


9.11 compare 体系总账:深比较、memcmp 与失效边界

本章涉及的所有"相等"判断最终都落到 include/vsg/core/compare.h。把这些调用点列全,才能看清哪些判据可信:

调用者函数比较对象含 mask
GraphicsPipeline::comparecompare_pointer_container ×3stages/pipelineStates/layout/subpass间接
GraphicsPipelineState::compare + 九个子类compare_value/compare_regionmask + 各自字段是
ShaderStage::comparecompare_value/compare_pointerflags/stage/module/entryPointName/特化常量否
PipelineLayout::compare三种混合flags/setLayouts/pushConstantRanges—
ComputePipeline、Bind*Pipelinecompare_pointerlayout/stage/pipeline—
compile() 复用判据compare_pointer_container_pipelineStates vs 合并结果是

三条结构性结论:

第一,所有容器比较都是顺序敏感的。 compare_pointer_container 用两个迭代器并行走,第 i 个对第 i 个;compare_value_container 用 memcmp 比整段。但 VkDynamicState、VkDescriptorSetLayoutBinding、ShaderStages 在 Vulkan 语义里很多是集合或集合的有序化表示。第九章的 mergeGraphicsPipelineStates 靠固定的三层调用顺序保证稳定,第十一章的 descriptor binding 靠 std::map 排序保证稳定——两处都是靠上游约定,不是靠比较函数本身。

第二,深比较成本随对象图增长。 GraphicsPipeline::compare 递归进每个 ShaderStage(比较整份 source 与 code)和每个状态对象;SharedObjects::share() 在 std::set 里用 DereferenceLess 查找,一次插入是 O(log N) 次比较,每次可能扫过几万字节 SPIR-V。大型场景的装配 CPU 时间主要花在这里,而非 vkCreateGraphicsPipelines。

第三,memcmp 与逐字段比较并存,语义不一致。 具体差异有三类:

差异compare_value(< 比较)memcmp(字节比较)
+0.0 / -0.0相等不等
NaN比较结果为 0(两者都不小于对方)位模式不同即不等
结构体 padding不涉及会读到未初始化字节
指针/间接成员不比较比较指针值本身

这些 float 默认值下没有 NaN 或负零,所以运行时不触发;但用户若把 depthBiasSlopeFactor 设成 -0.0f,两个语义相等的状态会被判为不同,多创建一个 VkPipeline。

compare_value_container 还有一个更隐蔽的前提(compare.h:79–87):

// compare.h:82
if (lhs.size() < rhs.size()) return -1;
if (lhs.size() > rhs.size()) return 1;
if (lhs.empty()) return 0;
return compare_region(lhs.front(), lhs.back(), rhs.front());

compare_region 用 &lhs.front() 到 &lhs.back() 的地址差加 sizeof(E) 作长度,假设容器元素连续且无间隙:std::vector<T> 成立,std::deque<T> 会跨段读越界。当前所有使用点都是 std::vector,模板签名却对任意容器开放,没有 static_assert 约束——VSG 把类型约束放在约定里而不是类型系统里。

compare_region 的另一种用法(DepthStencilState.cpp:45、RasterizationState.cpp:46)传的是对象成员而非容器元素,长度由成员地址差算出。9.5.4 已经核对过当前布局恰好无 padding,但这里的"恰好"依赖编译器不重排 public 成员(C++ 标准保证同一 access control 段内按声明顺序递增地址),也依赖所有成员是 4 字节对齐的标量。加一个 bool 成员就会引入 padding 并让 memcmp 读到未初始化字节。


9.12 生命周期:release、窗口变化与两条重建路径

9.12.1 三个 release 的粒度

类重载边界检查
GraphicsPipelinerelease(viewID) / release()release(viewID) 有:if (viewID < size());release() 无(clear 全清)
PipelineLayoutrelease(deviceID) / release()release(deviceID) 无:_implementation[deviceID] = {};
ComputePipelinerelease(deviceID) / release()release(deviceID) 无
ShaderModulerelease(deviceID) / release()release(deviceID) 无

GraphicsPipeline::release(viewID)(GraphicsPipeline.h:84–87)是唯一带边界检查的:

void release(uint32_t viewID)
{
    if (viewID < static_cast<uint32_t>(_implementation.size()))
        _implementation[viewID] = {};
}

其余三个在 vk_buffer 的 VSG_MAX_DEVICES <= 1 分支下 operator[] 忽略索引,所以不会越界;但在 >4 分支下 const 版本 operator[] 直接 buffer[deviceID] 无检查,传错 deviceID 会越界。默认构建下不成问题。

更重要的是释放不级联:GraphicsPipeline::release() 只清自己的 _implementation,不会去释放 layout、stages 里的 VkPipelineLayout/VkShaderModule。这是正确的——那些句柄与设备绑定,与 renderPass/viewport 无关,窗口尺寸变化不需要重建它们。BindGraphicsPipeline::release()(GraphicsPipeline.cpp:323–326)只是转发到 pipeline->release()。

9.12.2 UpdateGraphicsPipelines:无条件重建

WindowResizeHandler.cpp:22–62:

UpdateGraphicsPipelines::UpdateGraphicsPipelines()
{
    overrideMask = MASK_ALL;
}

bool UpdateGraphicsPipelines::visit(const Object* object, uint32_t index)
{
    decltype(visited)::value_type objectIndex(object, index);
    if (visited.count(objectIndex) != 0) return false;
    visited.insert(objectIndex);
    return true;
}

void UpdateGraphicsPipelines::apply(vsg::BindGraphicsPipeline& bindPipeline)
{
    if (!visit(&bindPipeline, context->viewID)) return;

    auto pipeline = bindPipeline.pipeline;
    if (pipeline)
    {
        pipeline->release(context->viewID);
        pipeline->compile(*context);
    }
}

void UpdateGraphicsPipelines::apply(vsg::View& view)
{
    if (!visit(&view, view.viewID)) return;

    context->viewID = view.viewID;
    context->defaultPipelineStates.emplace_back(view.camera->viewportState);

    view.traverse(*this);

    context->defaultPipelineStates.pop_back();
}

四个问题:

  1. visit 键是 &bindPipeline 而非 pipeline。 两个 BindGraphicsPipeline 指向同一管线时第二次用不同指针通过检查,release+compile 又跑一遍,一次遍历对同一管线做 2 次创建 + 1 次销毁;WindowResizeHandler.cpp:109 以管线对象为键才正确去重。
  2. 不恢复 context->viewID。 WindowResizeHandler.cpp:193 保存并恢复 previous_viewID,这里只赋值不恢复,多 View 后停在最后一个。
  3. 不判 view.camera。 emplace_back(view.camera->viewportState) 在 camera 为空时解引用,与 9.6.4 同类。
  4. 无条件 release+compile。 不做 ContainsViewport 判断,每次都重建,语义上就是"强制刷新"。

9.12.3 WindowResizeHandler:条件重建

WindowResizeHandler.cpp:103–137:

void WindowResizeHandler::apply(vsg::BindGraphicsPipeline& bindPipeline)
{
    if (!context) return;

    GraphicsPipeline* graphicsPipeline = bindPipeline.pipeline;
    if (!visit(graphicsPipeline, context->viewID)) return;

    if (graphicsPipeline)
    {
        struct ContainsViewport : public ConstVisitor { ... } containsViewport;

        bool needToRegenerateGraphicsPipeline = !containsViewport(*graphicsPipeline);
        if (needToRegenerateGraphicsPipeline)
        {
            graphicsPipeline->release(context->viewID);
            graphicsPipeline->compile(*context);
        }
    }
}

ContainsViewport 只看 graphicsPipeline->pipelineStates 里有没有 ViewportState(第 122–126 行)。判断逻辑要放到 9.6 的三层合并里才读得通:

  • 若场景自带 ViewportState,它会在"场景层"覆盖 default 层注入的 view.camera->viewportState,于是管线的 viewport 不随 View 变化,窗口 resize 不需要重建 → needToRegenerate = false,正确。
  • 若场景不带,合并结果里用的是 default 层的 view.camera->viewportState(或 ViewportState::create(extent)),窗口 resize 改了它,需要重建 → needToRegenerate = true,正确。

但这个判断只看场景层,不看 overridePipelineStates。若 renderPass 的 maxSamples 在 resize 时变化(例如重建 swapchain 时改了 MSAA 档位),MultisampleState 会变,管线应该重建,而 ContainsViewport 完全看不到它。同样,若 View::overridePipelineStates 里有随窗口尺寸变化的状态,也会被漏掉。

ContainsViewport 用 pipelineState->accept(*this) 遍历,apply(const ViewportState&) 是唯一命中项。自定义 GraphicsPipelineState 子类若内部聚合 ViewportState 并 override 了 traverse,ConstVisitor 可能走进去命中;没 override 就看不到。这是 accept/traverse 分离留下的常见陷阱。

9.12.4 RenderGraph::resized() 只在静态视口模式下建 Context

RenderGraph.cpp:174–208:

// RenderGraph.cpp:173
void RenderGraph::resized()
{
    if (!windowResizeHandler) return;
    if (!window && !framebuffer) return;

    auto activeRenderPass = getRenderPass();
    if (!activeRenderPass) return;
    auto device = activeRenderPass->device;
    auto extent = getExtent();

    windowResizeHandler->renderArea = renderArea;
    windowResizeHandler->previous_extent = previous_extent;
    windowResizeHandler->new_extent = extent;
    windowResizeHandler->visited.clear();

    if ((viewportStateHint & STATIC_VIEWPORTSTATE))
    {
        if (!windowResizeHandler->context)
        {
            ResourceRequirements resourceRequirements;
            resourceRequirements.viewportStateHint = viewportStateHint;
            windowResizeHandler->context = vsg::Context::create(device, resourceRequirements);
        }

        windowResizeHandler->context->commandPool = nullptr;
        windowResizeHandler->context->renderPass = activeRenderPass;

        if (activeRenderPass->maxSamples != VK_SAMPLE_COUNT_1_BIT)
        {
            windowResizeHandler->context->overridePipelineStates.emplace_back(
                vsg::MultisampleState::create(activeRenderPass->maxSamples));
        }

        // make sure the device is idle before we recreate any Vulkan objects
        vkDeviceWaitIdle(*(device));
    }
    ...
}

三点:

  • DYNAMIC_VIEWPORTSTATE 下 resize 不建 Context、不重建管线,viewport 由 vkCmdSetViewport 每帧下发,与 9.5.2 闭环一致。
  • vkDeviceWaitIdle 是全设备同步,静态视口下每次 resize 都付一次;这是必要的,旧 VkPipeline 可能在飞行命令缓冲里被引用,VSG 别处用更细粒度延迟删除。
  • overridePipelineStates.emplace_back(...) 没有先 clear(),9.6.4 已指出会随 resize 次数累积。windowResizeHandler->visited.clear() 清了访问集合,却没清状态容器。

9.12.5 两条路径的对照表

维度UpdateGraphicsPipelinesWindowResizeHandler
触发者 / 去重键显式调用 / (&bindPipeline, viewID)RenderGraph::resized() / (graphicsPipeline, viewID)
重建条件一律重建仅当场景层无 ViewportState
恢复 viewID / default 状态否 / 是(pop_back)是 / 是(pop_back)
考虑 MSAA 变化隐含(重建时重新合并)否

第八章末尾预告问"bin 录制时 viewport 是否会被重新 push":动态视口下 RenderGraph::record 每帧 viewportState->set(renderArea...) 后 pushView,State::pushView 把 ViewportState 压进 slot 8,dirty 时 State::record() 调 record() 发 vkCmdSetViewport;静态视口走 resized() 重建管线。两条路互斥,由 viewportStateHint 分派,该 hint 同时被 Context、RenderGraph、State 读取。


9.13 ComputePipeline:把图形路径砍掉一半后的样子

ComputePipeline.cpp 只有 167 行,是理解图形管线复杂度的良好对照。把它与 GraphicsPipeline 逐项并排:

维度GraphicsPipelineComputePipeline
描述字段stages / pipelineStates / layout / subpassstage / layout
实现索引std::vector,viewIDvk_buffer,deviceID
状态与 renderPass三层合并,必需 renderPass无
ScratchMemory分配 stage 数组 + 九个结构体,末尾 release()仅 apply 可能分配,不 release()
阶段过滤 / 跨槽复用context.mask 过滤 / compare_pointer_container 循环无 / 无
release / 析构判空有边界检查 / 无无边界检查 / 无

ComputePipeline::Implementation(第 96–114 行):

VkPipelineShaderStageCreateInfo stageInfo = {};
stageInfo.pNext = nullptr;
shaderStage->apply(context, stageInfo);

VkComputePipelineCreateInfo pipelineInfo = {};
pipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
pipelineInfo.layout = pipelineLayout->vk(device->deviceID);
pipelineInfo.stage = stageInfo;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
pipelineInfo.pNext = nullptr;

if (VkResult result = vkCreateComputePipelines(
        *device, VK_NULL_HANDLE, 1, &pipelineInfo,
        _device->getAllocationCallbacks(), &_pipeline); result != VK_SUCCESS)
{
    throw Exception{"Error: vsg::ComputePipeline failed to create VkPipeline.", result};
}

VkComputePipelineCreateInfo 只有 6 个字段,这里全部显式赋值或用 = {} 覆盖,比图形路径清爽得多。stageInfo 是栈上局部,不是 scratch;ShaderStage::apply 里若有特化常量,会把 pSpecializationInfo 指向 context.scratchMemory,而 vkCreateComputePipelines 是同步调用,所以栈与 scratch 在返回前都有效。

ComputePipeline::compile(第 66–90 行)的坑与图形路径共享:

  • stage / layout 都不判空,直接 layout->compile(context)、stage->compile(context);
  • requiresShaderCompiler 的三条件判断里 stage && stage->module 若为空就静默跳过,最终 shaderStage->apply 里 module->vk(...) 崩溃;
  • fatal() 的 Logger 依赖问题同样存在;
  • _implementation[context.deviceID] 一旦非空就整体跳过,编译后修改 stage/layout 不生效。

一个图形路径没有的细节:ComputePipeline::compile 里 shaderCompiler->compile(stage)(第 78 行)传的是单个 ShaderStage,而 GraphicsPipeline::compile 传的是 stages 容器。ShaderCompiler 有两个重载,这说明 GLSL 编译在图形路径是"按管线批量编译",在计算路径是"单阶段编译"。第十章会看到批量编译带来的好处:一次初始化 glslang 环境、共享 #include 解析结果。

绑定点:BindComputePipeline::record(第 158–162 行)用 VK_PIPELINE_BIND_POINT_COMPUTE 与 commandBuffer.deviceID,BindGraphicsPipeline::record 用 GRAPHICS 与 viewID,两者都 Inherit(0) 占 slot 0。第八章 8.2 列过 slot 的五种语义,这里补第六条:slot 0 上可并存两种绑定点的命令,但 StateStack 只维护一个栈顶,故 VSG 隐含假设"计算与图形管线不在同一 StateGroup 作用域交替绑定"。这不是 Vulkan 限制(其分别维护 graphics/compute/raytracing 绑定点),是单槽位建模的限制。


9.14 回到第八章:从 ShaderSet 到 slot 0 的完整链

把本章与第八章、第十章接起来,一条典型的管线从配置到录制经过十步:

1. ShaderSet 定义 GLSL、顶点属性约定、描述符绑定、特化常量   (第十章)
2. GraphicsPipelineConfigurator 依据 shaderHints 选变体
3. DescriptorConfigurator 生成 DescriptorSetLayout / setLayouts (第十一章)
4. GraphicsPipelineConfigurator::copyTo(StateCommands&) 装配:
      stateCommands.push_back(bindGraphicsPipeline)          // slot 0
      ... bindDescriptorSet(s)                              // slot 1 + firstSet
      ... 自定义 StateCommand
5. copyTo(StateGroup) 另设 stateGroup->prototypeArrayState
6. CompileTraversal 遍历 StateGroup,遇 BindGraphicsPipeline
      → BindGraphicsPipeline::compile(context)
      → GraphicsPipeline::compile(context)
      → 三层状态合并 → 复用检查 → layout/stages compile
      → vkCreateGraphicsPipelines
7. RenderGraph::record 设 viewportStateHint、pushView(viewportState)  // slot 8
8. StateStack::push(stateCommands) 把 slot 0/1/... 压栈
9. State::record() 在 dirty 时对 0..activeMaxStateSlot 逐槽 record()
      → vkCmdBindPipeline + setCurrentPipelineLayout
      → vkCmdBindDescriptorSets
      → vkCmdSetViewport(若 slot 8 有 ViewportState)
10. vkCmdDraw* 使用当前绑定的 VkPipeline

GraphicsPipelineConfigurator.cpp:820 先用 compare_pointer(sc, bindGraphicsPipeline) 扫 inheritedState 得 pipelineUnique;为真时在 sharedObjects->mutex 下依次 share(layout->setLayouts)、share(layout)、share(graphicsPipeline)、share(bindGraphicsPipeline),置 graphicsPipeline->layout = layout,最后 stateCommands.push_back(bindGraphicsPipeline)。

三处与本章呼应:

  • pipelineUnique 用 compare_pointer 遍历 inheritedState,避免父 StateGroup 已绑同一管线时重复压栈;这是第八章 StateStack 去重之前装配期的第一层去重。
  • sharedObjects->share(graphicsPipeline) 是 9.9.1 的 L1 复用,发生在 copyTo 而非 compile;手工构造 StateGroup 而不用 SharedObjects 时 L1 失效,只剩 L2。
  • graphicsPipeline->layout = layout; 是编译前修改 public 字段的合法例子。它发生在任何 compile() 之前,所以 9.10.4 的缓存失效问题不适用;但也说明库把"编译前可写、编译后不可写"当作纯约定。

第 5 步(copyTo(ref_ptr<StateGroup>),GraphicsPipelineConfigurator.cpp:1000)设置 prototypeArrayState,与本章并行:一条管 GPU 侧顶点输入解释,一条管 CPU 侧 ComputeBounds/Intersector 重建顶点。两者必须一致,却由 ShaderSet 的 vertexAttributes 与 getSuitableArrayState(shaderHints->defines) 两套独立配置生成,无交叉校验。

第 8、9 步回到 StateStack。BindGraphicsPipeline 在 slot 0,GraphicsPipelineState 子类默认也是 0(StateCommand 默认 slot = 0),只有 ViewportState(ViewportState.cpp:21)设成 8。若把八个空 record 状态误放进 StateGroup::stateCommands,它们挤进 slot 0 争栈顶;State::record() 只调栈顶的 record(),若栈顶是空实现状态,vkCmdBindPipeline 这一帧就没发——这是 9.5.1 最实际的危害。


9.15 数字表与源码索引

9.15.1 本章核过的数字

数字值来源
include/vsg/state/ 头文件数 / 行数36 / 3,002ls、wc -l
src/vsg/state/ 实现文件数 / 行数35 / 7,076同上
本章正面处理的 13 个文件总行数2,619wc -l
九个状态类的 .h+.cpp 行数1,466wc -l
GraphicsPipelineState 子类数9grep Inherit<GraphicsPipelineState
apply(Context&, VkGraphicsPipelineCreateInfo&) 实现数9 + 1 纯虚grep
mergeGraphicsPipelineStates 层数 / 优先级3 / override > 场景 > defaultGraphicsPipeline.cpp:171–173
GraphicsPipeline::compile 阶段数6GraphicsPipeline.cpp:159–220
全库 vkCreate*Pipelines 调用点2GraphicsPipeline.cpp:260、ComputePipeline.cpp:110
全库 vkCreatePipelineCache 调用点0grep -rn
全库 validated_vk / computeCompatibility 调用点0 / 0grep -rn
全库 setCurrentPipelineLayout 调用点3GraphicsPipeline.cpp:315、ComputePipeline.cpp:161、RayTracingPipeline.cpp:257
Mask 宽度 / MASK_ALL64 位 / ~MASK_OFFMask.h:20,22
ViewportState 的 slot8ViewportState.cpp:21
ScratchMemory::align 对齐粒度sizeof(void*) = 8ScratchMemory.h:45–49
DepthStencilState::compare 的 memcmp 区间9 个成员,字节数随本机 Vulkan SDK 而定DepthStencilState.h:29–38
Context::deviceIDconst uint32_t = 0Context.h:78
VSG_MAX_DEVICES <= 1 时 vk_buffer::size()1vk_buffer.h:24(#if 分支)

9.15.2 源码索引(按文件分组)

  • GraphicsPipeline.h/.cpp:h:25–49/56–106/110–133(基类/管线/绑定);cpp:56–104/159–220/226–268/279–326(合并/编译/实现/绑定)。
  • PipelineLayout.h/.cpp:h:23–47;cpp:48–66(54 flags 错误)、68–78(compare)、80–120(序列化)、122–132(compile)、138–171(实现)。
  • ComputePipeline/ShaderStage/ShaderModule:前者 cpp:66–90/96–119/125–167;中者 compare 67–91(漏 mask)、序列化 127–168(无 flags)、apply 170–211、compile 213–219;后者 185–204。
  • CompileTraversal.cpp:add() 80–180;SecondaryCommandGraph 343–379、RenderGraph 382–412、View 421–455(443 未判 camera)。
  • WindowResizeHandler.cpp/RenderGraph.cpp:前者 22–62/103–137/155–211;后者 140–170/174–208。
  • compare.h/vk_buffer.h/ScratchMemory.h:比较函数 22–87、DereferenceLess 105–113;vk_buffer 三分支 24–99;ScratchMemory 45–78。

9.16 可复现验证

以下命令都在仓库根目录执行,不依赖构建产物。

验证 1:确认没有任何管线缓存,且安全版本没被调用

grep -rn "vkCreatePipelineCache" include src            # 期望:0 行
grep -rn "vkCreateGraphicsPipelines\|vkCreateComputePipelines" src/vsg
# 期望:仅 GraphicsPipeline.cpp:260 与 ComputePipeline.cpp:110,且都传 VK_NULL_HANDLE
grep -rn "validated_vk\|computeCompatibility" include src
# 期望:各 2 行(声明 + 定义),无调用点

验证 2:确认九个状态子类与九个 apply

grep -rln "Inherit<GraphicsPipelineState" include/vsg/state | wc -l        # 9
grep -rn "::apply(Context& context, VkGraphicsPipelineCreateInfo" src/vsg/state | wc -l  # 9
grep -rn "void record(CommandBuffer&) const override {}" include/vsg/state/GraphicsPipeline.h  # 1
grep -rn "vkCmdSetViewport\|vkCmdSetScissor" src/vsg/state/ViewportState.cpp  # 2

验证 3:确认复用判据只覆盖 pipelineStates

sed -n '159,220p' src/vsg/state/GraphicsPipeline.cpp
# 观察:第 177 行比较 imp->_pipelineStates 与 combined_pipelineStates;
#       第 232–234 行却把 layout / renderPass / subpass 写进 pipelineInfo;
#       第 243 行用 context.mask 过滤 stage。四者都不在比较式中。

验证 4:确认 renderPass 会在同一 viewID 下被替换

grep -n "previousRenderPass\|context->renderPass =\|viewID" src/vsg/app/CompileTraversal.cpp | sed -n '1,40p'
# 期望:354/358/379、390/399/411 出现 renderPass 的保存-替换-恢复;
#       343–412 区间内没有对 context->viewID 的赋值(只有 436 行 apply(View&) 里有)。

验证 5:确认 ShaderStage::compare 漏 mask、flags 是死字段

sed -n '67,91p' src/vsg/state/ShaderStage.cpp | grep -n "mask\|flags"   # 只有 flags,无 mask
grep -n "flags" src/vsg/state/ShaderStage.cpp                            # 只有 27、74 两行
grep -n "shaderStageCreateInfo\[i\].flags" src/vsg/state/GraphicsPipeline.cpp  # 245 行固定为 0

验证 6:确认 fatal() 在不同 Logger 下行为不同

grep -n -A 5 "::fatal_implementation" src/vsg/io/Logger.cpp
# 期望:StdLogger 有 throw、ThreadLogger 只有 fprintf、NullLogger 有 throw
sed -n '197,208p' src/vsg/state/GraphicsPipeline.cpp
# 观察:fatal() 之后没有 return / throw,控制流继续到 layout->compile

验证 7(需要编译):compare_region 的区间长度

#include <cstddef>
#include <cstdio>
// 把 DepthStencilState.h 的九个成员按原顺序写一个 POD 结构,打印区间长度
struct S {
    uint32_t a,b,c,d,e;      // 5 个 VkBool32 / VkCompareOp
    struct { uint32_t v[7]; } front, back;
    float lo, hi;
};
int main() {
    S s{};
    auto start = reinterpret_cast<const char*>(&s.a);
    auto end   = reinterpret_cast<const char*>(&s.hi);
    std::printf("region=%zu sizeof(S)=%zu\n", size_t(end - start) + sizeof(float), sizeof(S));
}
// 期望:region == sizeof(S),即当前布局无 padding;数值随 Vulkan SDK 而定。
// 然后把 struct 中任一成员改成 double,region 与语义都会变,而代码不会报错。

验证 8:vk_buffer 在默认构建下忽略索引

grep -n -A 12 "#if VSG_MAX_DEVICES <= 1" include/vsg/vk/vk_buffer.h
# 期望:operator[](uint32_t) 的参数未使用,返回同一个 value(第 32–33 行)
grep -n "deviceID" include/vsg/vk/Context.h
# 期望:78 行是 const uint32_t deviceID = 0;

验证 9:ShaderStage::flags 是死字段,read/write/apply 都不碰它

grep -n "flags" src/vsg/state/ShaderStage.cpp
# 期望:只有 27 行拷贝构造初始化、74 行 compare 两处
grep -n "stageInfo\..*flags" src/vsg/state/GraphicsPipeline.cpp src/vsg/state/ComputePipeline.cpp
# 期望:GraphicsPipeline.cpp:245 一处且固定为 0;计算路径靠 = {} 零初始化
sed -n '127,168p' src/vsg/state/ShaderStage.cpp | grep -n "flags"
# 期望:0 行(序列化不含 flags)

验证 10:ViewportState 是唯一设 slot = 8 且唯一发视口命令的状态

grep -rn "slot = 8" src/vsg/state
# 期望:仅 ViewportState.cpp:21
grep -rn "vkCmdSetViewport\|vkCmdSetScissor" src/vsg/state
# 期望:仅 ViewportState.cpp:144–145 两行
grep -rn "void record(CommandBuffer&) const override {}" include/vsg/state/GraphicsPipeline.h
# 期望:1 行(基类空 record)

9.17 陷阱表与批判性结论

#陷阱触发条件后果规避
1vk(viewID) 无边界检查新增 View 未跑编译遍历越界 vector[] + 野指针解引用用 validated_vk() 自行包装,或保证每个 viewID 都编译
2复用判据漏 renderPass多窗口 / 二级命令图 / 离屏 renderPass管线绑错 renderPass,验证层报错或未定义行为按 (viewID, renderPass) 重建或用 release(viewID) 强制刷新
3复用判据漏 mask不同 view.mask 过滤出不同 stageCount复用错误阶段集合同上
4编译后改 public 字段运行时改 stages/layout/subpass静默不生效先 release()
5ShaderStage::compare 漏 mask用 SharedObjects 合并仅 mask 不同的 stage变体机制失效手工保证 mask 不同的 stage 不进同一个共享池
6ShaderStage::flags 未使用设置了非 0 值假差异 + 实际被写成 0不用这个字段
7fatal() 在 ThreadLogger 下不抛未链接 GLSLang 且有源码无 SPIR-VcodeSize=0 调 vkCreateShaderModule构建期确保 SPIR-V 已生成,或自建 Logger 抛异常
8module 为空一路静默忘记给 stage 设 moduleapply 里空指针解引用构造后自检
9compare_region 读 padding给状态类加成员 / 改类型相等误判,多余管线创建改成逐字段 compare_value
10空 setLayout 写成 0无 INDEPENDENT_SETS_BIT_EXT 时用了空布局Vulkan 规范违规别往 setLayouts 放空项
11computeCompatibility flags 分支两个布局的 independent-sets 位不同返回 {true, 0} 误报兼容不要用这个 API
12overridePipelineStates 累积静态视口 + MSAA + 频繁 resizevector 线性增长resize 前 clear()
13UpdateGraphicsPipelines 用 bind 对象去重多个 bind 指向同一管线重复创建/销毁管线以 GraphicsPipeline* 为键
14ViewportState::record 不看 hint静态视口模式下仍把 ViewportState 放进 stateCommands对未声明动态视口的管线发 vkCmdSetViewport两者二选一
15八个空 record 状态挤进 slot 0误把 GraphicsPipelineState 放进 StateGroup::stateCommands吞掉 vkCmdBindPipeline只放进 GraphicsPipeline::pipelineStates
16UpdateGraphicsPipelines 不恢复 viewID遍历多个 View 后复用同一 Contextcontext->viewID 停在最后 View,后续编译写错槽位仿 WindowResizeHandler.cpp:193 保存并恢复 previous_viewID
17CompileTraversal::apply(View&) 不判 camera无相机视图(纯计算/未初始化)view.camera->viewportState 空解引用崩溃仿同文件 126 行先判 view.camera
18computeCompatibility 长度不等时 second 失真两布局 setLayouts 长度不同把 min(size) 当成不兼容起点,多绑或少绑描述符集不依赖该 API 做重绑定决策
19空 code 仍创建 VkShaderModule有 source 无 SPIR-V 且 fatal 不抛codeSize=0、pCode 可能为空,驱动未定义构建期确保 SPIR-V 已生成
20稀疏 viewID 扩容不收缩应用分配大 viewID分配 1001 个槽位其中 999 为空viewID 从 0 连续分配
21PipelineLayout::compile 只判槽位非空编译后改 flags/setLayouts修改静默不生效先 release(deviceID) 再重编译

9.17.1 三条批判性结论

第一,"不可变"是约定,不是类型保证。 整个管线体系建立在"描述对象在编译前写好、编译后不改"的前提上,但描述字段全是 public、可写、无 setter、无脏标记;编译产物用 _implementation 槽位是否为空做唯一失效判据。第八章的 ArrayState 原型模式、第五章的 Data 与 GPU 缓冲不同步,都是同一个设计哲学的不同表现。它换来的是极简的对象模型和零运行时校验开销,代价是所有约束都落在文档与使用者自律上——而这一章的十几处陷阱说明,库自己的内部调用点(WindowResizeHandler、CompileTraversal、RenderGraph)都没有完全遵守这些约束。

第二,缓存键应当等于"所有进入 VkGraphicsPipelineCreateInfo 的输入"。 compile() 里那句 compare_pointer_container(imp->_pipelineStates, combined_pipelineStates) 只覆盖了九个 p*State 指针,而 layout、renderPass、subpass、stageCount、pStages、flags 六个字段同样进入 createInfo。一个最小正确的修法是把 Implementation 扩展成持有 ref_ptr<RenderPass> _renderPass、Mask _mask、uint32_t _subpass,并在复用循环里逐项比较;或者更省事地按 (viewID, renderPass.get()) 做二级键。当前实现之所以在多数 demo 里不炸,是因为单窗口单 RenderPass 让 renderPass 恒定、所有 View 的 mask 都是 MASK_ALL——正确性依赖部署拓扑,而非代码保证。

第三,三层状态合并是本章最值得肯定的设计。 把"渲染目标强制要求的"(MultisampleState)、"视图默认的"(ViewportState / DynamicState)、"场景作者表达的"(ColorBlend/DepthStencil/...)分成三层,后者覆盖前者但挡不住 override,再用 type_info() 去重、DynamicState 取并集,是一个干净且可扩展的方案。它让 GraphicsPipelineConfigurator 不必知道窗口的 MSAA 设置,也让 View 不必知道场景用了什么混合模式。问题不在于分层,而在于合并结果既没被完整缓存,也没被校验完整性:凑齐九个 p*State 的责任分散在三处,缺一个就到驱动层才暴露。

9.17.2 可由源码直接复验的五个硬结论

第一,computeCompatibility() 的返回值错误是可静态确认的,不是性能取舍。 computeCompatibility(PipelineLayout.cpp:54)在 INDEPENDENT_SETS_BIT_EXT 位不一致时执行 return result,而此时 result.first 仍保留上一步对 pushConstantRanges 比较得出的 true。这段包在 #ifdef VK_EXT_graphics_pipeline_library 里,说明作者预期处理 pipeline library 的独立集标志,却漏了把布尔位置假。对调用者而言,它会在标志不兼容时返回 {true, 0}:first = true 宣称完全兼容,second = 0 又宣称从第 0 个集合起不兼容,两者自相矛盾。而全库对它的引用只有 PipelineLayout.h:47 的声明与 PipelineLayout.cpp:48 的定义,没有任何调用点。结论不是"这个函数需要重构",而是更基本的:它从未被验证过,任何依赖它做描述符集重绑定决策的上层代码都会拿到错误答案,当前唯一安全的做法是不要用它。

第二,stageCount 的输入没进任何比较式,而它恰好是跨 view 唯一会变的管线输入。 GraphicsPipeline.cpp:243 用 (context.mask & shaderStage->mask) != 0 决定是否递增 i,随后 stageCount = i 被写进 createInfo;但 compile() 的复用循环只比 _pipelineStates。ShaderStage::compare(ShaderStage.cpp:76)逐项比 flags、stage、module、entryPointName、specializationConstants,唯独不比 mask。于是两个只在 mask 上不同的 ShaderStage 被判等,SharedObjects 把它们合并,跨 view 的复用循环又把合并后的管线交出去——按视图掩码过滤着色器阶段的机制在共享场景下失效两次。这不是两个独立缺陷,而是一条从比较函数一直断到缓存键的连续链:比较函数漏字段,缓存键漏输入,两者叠加让"同一配方"的判断在最关键处失真。

第三,两处 apply(View&) 对 view.camera 的处理不对称,而不对称的方向恰好是崩溃方向。 CompileTraversal.cpp:443 把 view.camera->viewportState 直接交给 mergeGraphicsPipelineStates,同一文件的 add(..., View&, ...) 在第 126 行却写成 if (view->camera && view->camera->viewportState);WindowResizeHandler.cpp:159 也先判 if (!view.camera),并在 camera 存在时继续 projectionMatrix->changeExtent(...)。mergeGraphicsPipelineStates 的 if (!src_PipelineState) 只能挡住传进来的状态为空,挡不住取成员前的空指针。无相机视图走进 apply(View&) 会在取 viewportState 的那一刻段错误。三处调用点里两处做了防御,唯一漏掉的偏偏在编译遍历上,而编译遍历是启动必经之路:这意味着缺陷不是边角场景,而是"只要应用创建纯计算 View 就会触发"。

第四,scratch 内存的归还方式暴露了一条没有写进接口的全局副作用。 GraphicsPipeline.cpp:262 在 vkCreateGraphicsPipelines 返回之后调用 context.scratchMemory->release(),而 release 把整条 scratch 栈复位。Vulkan 在创建返回前已消费完 createInfo,归还本身正确;问题在于这是 Context 级而非本次分配级的重置。任何在 compile() 前后跨调用持有 scratch 指针的对象都会拿到悬垂指针。对照 ComputePipeline.cpp:96 的 Implementation,它同样在 apply 里借用 context.scratchMemory(当存在特化常量时由 stageInfo 指过去),却不在构造末尾 release():两条路径对同一资源给出不同承诺。源码既没有断言也没有注释描述这个契约,调用方无法从 compile() 的签名看出它会清空整个 scratch 栈。更稳妥的是让 Implementation 自带局部 scratch,或让 Context 暴露栈帧式的 ScopedScratch。

第五,空壳对象的错误在编译期完全无声,到创建 Vulkan 句柄时才以段错误暴露。 ShaderStage::apply(ShaderStage.cpp:174)直接执行 stageInfo.module = module->vk(context.deviceID),没有判 module;而 GraphicsPipeline::compile 里的 requiresShaderCompiler 判断和 ShaderStage::compile 里的 if (module) 都在 module 为空时静默跳过。一个忘记设置 module 的 ShaderStage 因此能通过整条编译遍历,直到 vkCreateGraphicsPipelines 才崩。这和 9.4.3 记录的 fatal() 日志后端依赖属于同一类:错误路径既不由类型系统表达,也不由断言捕获,而是散落在运行时的多个分支里;任何一个分支的沉默都把故障推向更远的调用栈,使现场与根因相隔甚远。把这两类问题放在一起看,本章反复出现的不是"代码写错",而是"约束只存在于作者头脑中,没有进入类型、断言或文档"。


9.18 下章预告

管线对象结束。下一个问题:这些 ShaderStage 里的 GLSL 与 SPIR-V,以及 VertexInputState 里的顶点属性描述,是谁按什么约定生成的?

本章多次把问题推给第十章:ShaderCompileSettings::defines 如何支撑变体分发;批量编译里 #include 如何解析(ShaderModule.h:125 的 insertIncludes);ShaderStage::mask 漏比较为何在 ShaderSet 场景下才致命;ShaderSet 如何把 vertexAttributes 变成 VkVertexInputAttributeDescription。

第十章 着色器与 ShaderSet:从 GLSL 到 SPIR-V 的约定 要回答:ShaderSet 的配置字段分别控制什么;ShaderCompiler 如何把 defines 映射到 glslang;vsg::read 加载 .glsl/.spv 时 ShaderStage::read 的两种降级逻辑;以及为什么"同一个 ShaderSet + 不同 shaderHints"会生成内容不同但 compare() 相等的 ShaderStage。