《GPU Zen 4: Advanced Rendering Techniques》第 1 章中文译稿。原文作者:Dominik Lazarek、Philip Hammer、Jean Geffroy。
系列导航: 第一篇:从 Forward+ 到 Triangle Visibility Buffer|第二篇:Pixel Command 与 Deferred Lighting|第三篇:Variable-Rate Compute Shaders
译者导读
第一篇介绍了 idTech 8 的 Triangle Visibility Buffer、Deferred Attribute Interpolation,以及以 Merged Quad 配合 Early-Z 调度 Material Shading 的早期实验。本篇接着分析实验为何没有达到预期,并说明最终采用的显式 Pixel List Compute Dispatch,以及 Deferred G-Buffer Update、Deferred Lighting 与 Tile Classification。
1.8 Deferred Texturing(续)
1.8.4 使用显式 Pixel List 的 Compute Dispatch
早期 Quad Dispatch 实验的性能并不理想,团队于是参考 [McLaren 22],实现了一套 Compute-Based Dispatch。它先生成显式的像素坐标列表,也就是 pixel command,再按 Material、Pipeline State(PSO)和 screen-space tile 分组,最后交给 Opaque Lighting Pixel Shader 的 Compute Shader 变体处理。
[McLaren 22] 进一步按 screen-space tile 拆分像素,主要目的是提高逐像素读取 GPU Data 时的 Texture Cache Hit Rate。同一 wave 内的线程仍集中在相近的屏幕区域,pixel coordinate 也可以改用 tile-relative coordinate 表示,从而压缩 Pixel Command Buffer。
Compute Dispatch 避开了 Quad Dispatch 仍然存在的 Rasterization Overhead,但需要预先生成 pixel command 与 Indirect Dispatch Argument,也会占用更多 GPU Memory。图 1.8 展示了从 Visibility Buffer 生成这些 Dispatch Work 的完整过程。

流程从 count pixels Compute Shader 开始,每个 Visibility Buffer pixel 对应一个线程。Shader 读取该像素的 PSO Pipeline Index、dispatchMaterialID 和 screen-space tile index,再通过 atomic add,把这一组合对应的 pipelineTileMaterial 使用次数累加到 GPU Buffer。
计算组合索引时,引擎假定每条 Pipeline 都可能出现在任意 tile 中,而每个 tile 也可能包含所有受支持 Material 的像素。清单 1.1 中,numTiles 表示当前 Internal Render Resolution 下 256 x 256 screen-space tile 的数量,numDispatchMaterials 表示当前启用的可见 Material 数量。
int pipelineTileMaterialIndex =
(pipelineIndex * numTiles * numDispatchMaterials) +
(tileIndex * numDispatchMaterials) +
dispatchMaterialId;
清单 1.1|Material Index 的计算。
如第 1.6 节所述,Visibility Buffer Pipeline 最多支持 MAX_DISPATCH_MATERIALS,即 1,280 个可见 Material。Deferred Texturing 还支持最多 16 个 Pipeline / PSO。这个数字看似不大,但这里运行的都是 Compute Shader,无需为不同 Vertex Layout 或 Render Target Format 创建额外 PSO,Pipeline 主要用于区分 Shader。idTech 也一直严格控制 Shader Permutation 的数量,多数情况下宁可使用 static branch,也不会增加新的 Permutation。
这里采用 256 x 256 tile,而不是 [McLaren 22] 推荐的 128 x 128。测试没有发现更大 tile 会损失性能,tile 数量减少后,GPU Buffer 占用反而更低。tile size 为 256 时,每个轴的 tile-local pixel coordinate 仍可压缩到 8 bit。
大量像素若直接对 GPU Buffer 中同一个 uint32 元素执行 atomic add,会造成严重的 thread contention。清单 1.2 的做法是用串行循环遍历 wave 内不同的 pipelineTileMaterial index,每种 index 只执行一次 atomic add。
uint numToStore = 0;
while (true) {
uint uniformIndex =
subgroupBroadcastFirst(pipelineTileMaterialIndex);
uint total =
subgroupBallotBitCount(
subgroupBallot(uniformIndex == pipelineTileMaterialIndex));
if (subgroupElect()) {
numToStore = total;
}
if (uniformIndex == pipelineTileMaterialIndex) {
break;
}
}
if (numToStore > 0) {
atomicAdd(
numPixelsPerPipelineTileMaterial[pipelineTileMaterialIndex],
numToStore);
}
清单 1.2|通过 scalarization 减少 atomic operation。
完成 pipelineTileMaterial 的像素计数后,一组名为 Generate Offsets 的 Compute Pass 会按 Material 处理像素数量,并自底向上计算 hierarchical prefix sum。它先求出每个 pipelineTile 内各 Material 的 pixel offset / prefix sum,再计算每条 Pipeline 内各 tile 的 offset 与 pixel count,最后汇总出逐 Pipeline 的 offset 和 count。
这些数据决定了属于各 Material 的像素稍后写入 pixelCommands Buffer 的位置。计算 prefix sum 前,pipelineTileMaterial 的 Material pixel count 会先向上对齐到 Hardware Wave Size,确保后续执行 Opaque Pass Compute Shader 时,同一 wave 内的 Material Index 始终一致。
Write Pixel Commands Compute Pass 随后第二次遍历 Visibility Buffer。每个线程此时都能确定对应 pipelineTileMaterial 在全局 pixelCommands Buffer 中的 offset,并把 pixel coordinate 写入相应区间。每个 entry 是一个 16-bit unsigned integer,编码两个 8-bit tile-relative coordinate。
pixelCommands 还配有一份 Padding Bit Buffer,每个 Pixel Command 对应 1 bit,用于标记该条目是否只是为了把 pipelineTileMaterial count 对齐到 wave size 而补入的无效 command。后续 Dispatch 会启动完整 wave,Shader 读取 padding bit 后,让无效条目提前退出。
填充 pixelCommands 后,引擎还要生成 Indirect Dispatch Argument 与辅助数据,针对特定 Pipeline,在已占用的 tile 上启动 Opaque Pass Compute Shader wave。pixel count 与 Pixel Command Buffer 已把 Material 拆成 wave-aligned chunk,后续无需再显式处理 Material,只需以 tile 为单位 Dispatch。
CPU API 端仍需绑定不同的 Pipeline / PSO,因此 Indirect Dispatch Argument 必须按 Pipeline 拆分。不同 tile 也要进入不同 Dispatch,才能让同一 tile 的线程集中执行,充分利用 Data Locality 与 Cache Efficiency。理想情况下,每条 Pipeline 在 CPU 端只调用一次 Dispatch API,再在进入 GPU Command Processor 前展开为每个 tile 一次的多个 Dispatch。
Direct3D 12 可以用 ExecuteIndirect 和自定义 ID3D12CommandSignature 原生表达这种结构:Indirect Argument 先保存 numGroups X/Y/Z,再附带一个 Dispatch Index。Shader 据此识别每次 Dispatch,并读取与之匹配的数据,例如当前 tile 在 Pixel Command Buffer 中的 offset。
Vulkan / PC 没有对应的 Multi-Dispatch-Indirect API;若不依赖 device_generated_commands extension 并重构相关渲染代码,就只能自行绕过这一限制。图 1.9 展示了 Generate Indirect Dispatches Compute Shader 的完整流程。

每个启动的线程代表一个 pipelineTile,负责把 tile 内全部 Material 的像素数量换算成 Opaque Pass 最终需要 Dispatch 的 group 数。随后再按 2 的幂次拆分,把同一 tile 的 group 分到多个较小的 Dispatch Bucket 中。
拆分 bucket 后,gl_GlobalInvocationID.y 可以作为 Dispatch Index,gl_GlobalInvocationID.x 继续表示 Pixel Index。若不拆分,x 维 group 数必须容纳整条 Pipeline 中像素最多的 tile;像素较少的 tile 也会启动大量多余线程,只能依靠 early-out 退出。即使两个 tile 都被 Deferred Texturing pixel 填满,对齐到 wave size 时加入的 padding pixel 数量也可能不同,最终 pixel count 仍未必一致。
const uint numPixelsInPipelineTile =
numPixelsPerPipelineTile[pipelineTileIndex];
if (numPixelsInPipelineTile == 0) {
return;
}
uint numGroups64InPipelineTile =
(numPixelsInPipelineTile + 63) / 64;
uint groupOffset = 0;
for (uint x = numGroups64InPipelineTile; x != 0; x &= x - 1) {
uint bucketIndex = firstBitLow(x);
uint pipelineBucketIndex =
pipelineIndex * MAX_NUM_DISPATCH_BUCKETS + bucketIndex;
uint drawIndexInBucket = 0;
atomicAddOut(
dispatchIndirectCountsRW[pipelineBucketIndex], 1,
drawIndexInBucket);
uint dispatchIndex =
(pipelineIndex * MAX_NUM_DISPATCH_BUCKETS * numTiles) +
(dispatchBucketIndex * numTiles) +
drawIndexInBucket;
uint numGroups64InBucket = 1u << bucketIndex;
dispatchIndirectDispatchIndicesRW[dispatchIndex] =
pipelineTileIndex;
dispatchIndirectDispatchOffsetsRW[dispatchIndex] =
groupOffset * 64;
dispatchIndirectArgsRW[pipelineBucketIndex].x =
numGroups64InBucket;
atomicMax(dispatchIndirectArgsRW[pipelineBucketIndex].y,
drawIndexInBucket + 1);
groupOffset += numGroups64InBucket;
}
清单 1.3|把 Dispatch 拆分到不同 bucket。
**译注:**清单 1.3 定义了
bucketIndex,随后计算dispatchIndex时却使用了未在该代码片段中声明的dispatchBucketIndex。这里保留原书代码,不自行更改变量名。
CPU 端遍历 Deferred Texturing 使用的所有 Pipeline / PSO,并在内层遍历各个 Dispatch Bucket。设置 Indirect Dispatch 时,它会指向 Indirect Argument Buffer 与 Count Buffer 中对应的 Pipeline 和 bucket offset,再通过 vkCmdDispatchIndirect 执行。清单 1.4 展示了 GPU Shader 如何读取逐线程数据,并根据 tile 与 Pixel Command Buffer 重建 pixel coordinate。
uint dispatchStartIndex = pushConstants[0];
uint dispatchIndex = dispatchStartIndex + gl_GlobalInvocationID.y;
uint pipelineTileIndex = dispatchIndirectDispatchIndices[dispatchIndex];
uint dispatchOffset = dispatchIndirectDispatchOffsets[dispatchIndex];
uint pipelineIndex = pipelineTileIndex / numTiles;
uint tileIndex = pipelineTileIndex % numTiles;
uint numPixelsInPipelineTile = numPixelsPerPipelineTile[
pipelineTileIndex];
uint pixelIndexInTile = dispatchOffset + gl_GlobalInvocationID.x;
if (pixelIndexInTile >= numPixelsInPipelineTile) {
return;
}
uint pixelCommandTileStartOffset =
pixelOffsetsPerPipelineTile[pipelineTileIndex];
uint pixelCommandIndex =
pixelCommandTileStartOffset + pixelIndexInTile;
uint paddingMaskIndex = pixelCommandIndex / 32;
uint paddingMaskBit = pixelCommandIndex % 32;
if ((pixelCommandPaddingMask[paddingMaskIndex] & (1u << paddingMaskBit))
!= 0u) {
// Hit one of the padding pixels only there to fill the wave
return;
}
uint16_t pixelCommandData =
pixelCommandBuffer[pixelCommandIndex];
uint2 pixelInTile =
uint2(pixelCommandData & 0xFF, pixelCommandData >> 8);
uint2 tileCoord =
uint2(tileIndex % numTilesX, tileIndex / numTilesY);
// TILE_SIZE = 256
uint2 tileStartPixel = tileCoord * uint2(TILE_SIZE, TILE_SIZE);
uint2 pixel = tileStartPixel + pixelInTile;
// Access visibility buffer at pixel, retrieve interpolated attributes,
// ...
清单 1.4|Compute-Based Dispatch 中用于计算 pixel 的 Shader Header。
**译注:**清单 1.4 使用
tileIndex % numTilesX计算 X,却使用tileIndex / numTilesY计算 Y。按常见的一维行主序索引反解,Y 通常会除以numTilesX;本文无法从当前代码片段确认作者是否采用了特殊布局约定,因此保留原书写法。
1.8.5 Dispatch 策略对比
图 1.10 给出了 Compute-Based Dispatch 的最终渲染结果。图 1.11 则用调试颜色标出按 tile 与 Material Bucket 分组的 pixel command;颜色对应 Material,并在 15 种调试色之间循环。


| 阶段(ms) | idTech 7 | Merged Quad Dispatch | Compute Dispatch |
|---|---|---|---|
| Visibility Depth Buffer | — | 0.03 | — |
| Build Quads/Tiles | — | 0.0007 | — |
| Pixel Commands 与 Dispatch Arguments(Async) | — | — | 0.6 |
| Opaque Render Pass | 14.3 | 13.1 | 9.8 |
| 总计 | 14.3 | 13.13 | 10.4 |
表 1.3|高三角形密度视角下的渲染时间,单位为毫秒。
表 1.3 对比了 Compute-Based Dispatch、常规 Geometry Pass,以及最快的 Quad-Based Dispatch 变体 Merged Quads。作者认为,在这个测试场景中,Compute Dispatch 相对另外两种方案改善了约 25%–30%。
**译注:**若直接按表 1.3 的
Overall数据比较,不同比较对象,以及“耗时降低”与“性能提升”两种计算口径,会得到不同的百分比。
这个视角的三角形密度很高、quad utilization 很低,对常规 Geometry Pass 尤其不利。实际游戏中,Deferred Texturing 相对常规 Geometry Pass 的收益取决于场景和可见三角形的分布。
例如只观察由少量大三角形组成的地面时,差距会显著缩小:
| 阶段(ms) | idTech 7(低三角形密度) | Compute Dispatch(低三角形密度) |
|---|---|---|
| Pixel Commands 与 Dispatch Arguments(Async) | — | 0.2 |
| Opaque Render Pass | 2.75 | 2.45 |
| 总计 | 2.75 | 2.65 |
表 1.4|低三角形密度视角下的渲染时间,单位为毫秒。
即便如此,在《毁灭战士:黑暗时代》首发覆盖的所有平台和 GPU 厂商上,Compute-Based Dispatch 始终带来净性能收益。
1.8.6 进一步利用 Uniform Access Pattern
要在现代 GPU 上获得良好性能,Shader 能否利用 Uniform Access Pattern 十分关键。Bindless 方案尤其如此:所有 Texture 都由 Shader 直接索引,不再随每次 Draw Call 分别绑定到 Pipeline。
如果编译器在 Shader 编译时能够确认资源索引在整个 wave 内是 uniform 的,即使各线程的采样坐标不同,通常也能生成更高效的代码。具体收益因厂商而异,在当前世代主机上可能相当明显,包括降低 Register Usage、提高 occupancy、改善 Cache Utilization,以及省去逐个访问 potentially divergent resource 的 scalarization loop。这一原则既适用于 Texture Sampling,也适用于一般 Memory Operation。
Deferred Texturing 的 Dispatch 策略已经保证同一 wave 内的线程引用相同 Material,因此绝大多数 Texture Access 都是 uniform 的,只有采样坐标随线程变化。不过,Texturing Shader 中仍有一些 Memory Operation 依赖 Per-Instance Data,例如 Texture Tiling / Scrolling Factor、Gradient Mapping Setting、Material Blending Flag,以及 snow、moss 等额外的 world-space projected Environment Texture Layer。同一 Material 用于不同 object 时,这些数据仍可能不同。
朴素的 Deferred 方案会让这些访问产生 divergence,带来额外开销。团队原本愿意接受一定程度的 divergence,以换取更好的 thread occupancy;实际统计却发现,在多数生产场景中,70%–90% 的 wave 具有完全统一的 Resource Indexing:wave 内所有线程不仅使用相同 Material,也来自同一个 mesh 和 mesh instance。这意味着还有进一步优化的空间。
团队因此为每个 Deferred Texturing Shader 创建两个版本:Divergent 版本只假定 Material 统一,允许 mesh 或 instance data 不同;Uniform 版本则假定所有线程引用相同的 Material、mesh 与 instance。每个 Deferred Texturing workload 都会 Dispatch 两个版本。Shader 开始执行时先检查数据是否符合当前版本的假设,不符合便 early-out。
GLSL 的 subgroupAllEqual() 可以直接检查数据是否 uniform。若当前运行的是 Divergent 版本,而数据实际统一,Shader 就立即退出,因为同一 workload 还会交给 Uniform 版本处理。这样,画面的大部分区域都能走假定 wave 内资源统一的 fast path,只有少量 divergent data 进入较慢的路径。
每个 workload 需要 Dispatch 两次,再由不匹配的版本 early-out,因此 GPU 会额外启动少量 wave。不过,画面大部分区域可以执行更高效的 Shader Version,足以覆盖这部分成本。
const bool dataIsUniform =
subgroupAllEqual(meshDataHandle) && subgroupAllEqual(
instanceDataHandle);
#if defined(SHADER_VERSION_UNIFORM_DATA)
if (dataIsUniform == false) {
// Uniform version but data is divergent, early-out
// Pixels will be processed by the divergent version
return;
}
// Data is uniform, use subgroupBroadcastFirst() to let the shader
// compiler know
meshDataHandle =
subgroupBroadcastFirst(meshDataHandle);
instanceDataHandle =
subgroupBroadcastFirst(instanceDataHandle);
#else
if (shaderHasUniformDataVersion && dataIsUniform) {
// Divergent version but data is uniform, early-out
// Pixels will be processed by the uniform version
return;
}
#endif
清单 1.5|为 Deferred Texturing 选择合适的 Uniform 或 Divergent Shader Variant。
1.9 Deferred G-Buffer Update 与 Lighting
Deferred Texturing 生成的 G-Buffer 已经包含不透明物体的数据和混合后的 Material Stack,几乎可以直接用于 Lighting。不过,引擎还允许美术继续修改场景 Material。环境美术和设计师可以放置 Projective Decal 或 Geometry Decal [Geffroy et al. 20],在初次 Material Evaluation 后改变 Material Property;一个 decal 往往会覆盖多个 object 与 Material。Environment Wetness System 和动态生成的 triplanar projected blood 也会在最初的采样与混合完成后修改 Material 及其 channel。
这些修改可以直接内联到 Lighting 之前,但 SSDO、SSR、Global Illumination 等后续 Pass 同样要读取更新后的 Material Data。因此,受 decal 或类似效果影响的像素必须写回相应的 G-Buffer channel。
直接内联虽然简单可行,却会提高 Register Pressure,降低 occupancy,最终损害性能。经过 Profiling 和实验,团队确定了三项优化:
- 把 Deferred Lighting 拆成两个 Pass:G-Buffer Update 与 Lighting。
- 针对不同 screen-space tile 使用 Feature Set 更小的 Shader Permutation。
- 通过 FP16 Register Packing 与常规 micro-optimization 降低 Register Pressure。
整体思路仍是 divide and conquer:把 GPU Work 拆成更简单的步骤,减轻 Shader Compiler 和 GPU 的处理压力。团队保留了 Runtime Switch,用于在不同平台和场景中比较合并与拆分 Pass;所有测试配置中,拆分方案始终更快。
拆分后需要 Dispatch 两倍的 threadgroup,还要额外读取一次 G-Buffer,但更高效的 Shader 足以抵消这些开销。G-Buffer Update Pass 也只覆盖真正需要更新的 screen-space tile:受 decal、blood、rain 或 Environment Wetness 影响的 tile 才会执行,其余全部跳过。下一节介绍 Tile Classification 如何完成这项筛选。
即使完成拆分,Deferred Lighting 的 Register Pressure 仍然很高。传统 Deferred Lighting ubershader 的问题在于,过多渲染特性集中在同一程序中,会推高 Register Usage。Material Modification 虽然已经移入 G-Buffer Update,Lighting Shader 仍需支持 skin、cloth、hair、dual-lobe specular 等高级 BRDF。仅靠 dynamic branch 把这些特性留在同一个 Shader 中,依然会增加 Register Pressure。
实际游戏数据表明,最昂贵的功能往往只覆盖很小的屏幕区域。例如 Skin Lighting 通常只作用于人类皮肤,几乎不会铺满全屏。团队据此设计了一套方法,检测各 Deferred Pass 需要的 Shader Feature,再按分类结果 Dispatch Register-Optimal Workload。
1.9.1 使用 Tile Classification 提高 Compute Workload 效率
最初版本的 Deferred Lighting 在 screen space 中运行一个 Ubershader。CPU 只 Dispatch 一次,启动足够多的 threadgroup,让每个 screen pixel 对应一个线程。这个 Ubershader 必须包含屏幕上可能出现的所有渲染功能;只要有一个像素需要特殊 BRDF、decal 或 contact shadow,相应代码就必须编入 Shader。
大量可能 divergent 的 Code Path 挤在同一个 Shader 中,即使昂贵路径只由少数像素执行,也会造成很高的 Register Pressure。Shader Compiler 对 Register Lifetime 的优化空间有限,代码越复杂越难处理;Microcode 体积过大、branch 过多,还可能引发 Instruction Cache Miss。
Tile Classification 正是为了解决这个问题。它把屏幕划分成 tile,为每个 tile 确定一组 Feature,再 Dispatch 与该 Feature Set 匹配的优化 workload,也就是 Deferred Lighting Ubershader 的不同 Variant。这样可以减少运行昂贵 Shader 的 tile,让更多区域使用成本最低的版本。
Tile Classification 并不依赖 Deferred Lighting,也能用于其他 screen-space Compute Pass。例如,Deferred Composite Pass 会为 100% sky 的 tile Dispatch 专用 Shader。Deferred Lighting 的收益最明显,所以下文以它为例。
idTech 8 的实现步骤如下:
- 把屏幕划分为 32 x 32 pixel 的 tile grid。
- 每个 tile 保存一个 payload,其中包含
uint32Feature Bitmask。 - 定义多组只支持不同 Feature Subset 的 Shader Variant,也就是 workload。
- 每个 workload 执行一次 Indirect Dispatch,只处理与其匹配的 tile。
图 1.12 展示 Sentinel Hangar 的 Deferred Lighting Workload 调试视图,覆盖色表示每个 tile 实际 Dispatch 的 workload。为了便于说明,图中只显示 Deferred Lighting,并把 opaque、cloth、skin、decal 四种示例 Feature 映射到红、绿、蓝三种 workload。游戏实际使用的 Pass、Tile Feature 和 Workload Variant 更多。
红色 tile 使用功能最全、开销最高的 Lighting Shader,本质上就是原始 Ubershader。它的 occupancy 最低、Register Count 最高,性能也最差。即使其中很多像素并不需要昂贵功能,运行速度仍明显慢于绿色和蓝色 workload。
蓝色 tile 只包含基础 Feature Set,对应成本最低的 Lighting Shader。简单 Environment Material 不需要 translucency、skin shading 或 Subsurface Scattering,也就不必承担这些功能的开销。绿色 tile 的 Feature Set 介于两者之间;图中的绿色区域需要为 Sentinel Scientist 的长袍运行 Cloth Shading BRDF。没有覆盖色的 tile 完全不会 Dispatch。

Deferred Lighting 只处理不透明几何体,因此 100% 为 sky pixel 的 tile 可以直接跳过。较差的做法是在 Lighting Shader 内根据很大的 depth 判断 sky pixel,再逐像素 early-out。这样虽然省下一部分计算,GPU Command Processor 仍要启动线程,Shader 仍要读取 Depth Buffer,还会引入 divergent branch。以 tile 为单位彻底不启动 Shader,效率更高。
画面顶部的调试文字统计了各种 workload 的屏幕占比。这个视图也支持 picking:鼠标悬停在 tile 上即可查看其关联的全部 Feature。G-Buffer Update、Deferred Composite、SSS Filtering 等其他 workload 也有对应的显示模式。
图 1.13 用四种示例 Feature 说明基本原理。Feature Bitmask 通过 bitwise OR 合并,目前每个 tile 最多保存 32 个 Feature Bit。

Tile Grid 本质上是一个以 linear 1D GPU Buffer 实现的 uint32 array。引擎提供函数,在二维 screen pixel position 与一维 Buffer Index 之间转换,也允许一帧中的各个阶段通过全局函数修改 Buffer Entry。多个 Shader Thread 可能同时写入同一 Bitmask,因此必须使用 atomic operation:
// The payload offset allows us to store more than just the feature
// bitmask in the payload buffer, e.g., additional tile data. For
// simplicity and for this example, we only use a single uint32
const uint TC_PAYLOAD_FEATURE_BITMASK = 0;
void SET_TC_FEATURE_MASK(uint bufferBaseIdx, uint featureBitmask) {
const uint idx = bufferBaseIdx + TC_PAYLOAD_FEATURE_BITMASK;
atomicOr(constants.tileClassificationPayloadBufferRW[idx],
featureBitmask);
}
清单 1.6|使用 atomic bitwise OR 并发修改 tile data。
最坏情况下,这段代码会为屏幕上的每个像素执行。大量 atomic operation 和密集 Buffer Write 代价很高,而每个 32 x 32 pixel tile 实际只需要一个值。团队把操作 scalarize 到每个 wave 一次。当前最大 wave size 为 64,8 x 8 threadgroup 正好覆盖 tile 的一个子集;修改后,整帧填充 Tile Buffer 的成本几乎可以忽略。
uint tileFeatureBitmask = 0x0;
tileFeatureBitmask |= (hasSkinBRDF)
? (1 << TC_FEATURE_BRDF_SKIN) : 0x0;
tileFeatureBitmask |= (hasClothBRDF)
? (1 << TC_FEATURE_BRDF_CLOTH) : 0x0;
// Add more features to tileFeatureBitmask
// ...
if (subgroupAny(featureBitMask > 0) == true) {
// Compute the payload buffer index based on pixel location
const uint bufferBaseIdx =
computeTileClassificationBufferBaseIndex(pixelLocation);
SET_TILE_CLASSIFICATION_FEATURE_MASK(
bufferBaseIdx, featureBitMask);
}
清单 1.7|以 scalarized 方式设置 Tile Classification Feature。
**译注:**清单 1.7 前文声明的是
tileFeatureBitmask,后续条件与函数调用却使用了featureBitMask。原书如此,本文按原样保留。
每个 32 x 32 tile 都有独立 Bitmask 后,引擎便可据此选择 workload。它使用 Indirect Compute Dispatch,每个 Indirect Argument 对应一个 tile;不同 tile 可以运行不同 Shader,也可以完全跳过 Dispatch。
有些情况下,Shader 内一次简单的条件 early-out 也会产生可测量的开销,条件发生 divergence 时尤其如此。完全不启动 Compute Thread,收益更直接。例如,Skin Shading 需要 screen-space filtering,却只应在皮肤真正可见的区域执行;若启动线程只是为了判断像素是否需要 Skin Filtering,本身就是浪费。Tile Classification 在 Xbox Series X|S 的典型游戏场景中最多可节省 200 μs。
为了准备 Indirect Dispatch,还需运行两个 Compute Pass:
computeTileClassificationGenWork:为 Indirect Dispatch 生成 Work Item。computeTileClassificationGenIndirectDispatchArgs:生成 Indirect Argument Buffer。
第一个 Compute Shader 为每个 tile 启动一个线程,读取 Feature Bitmask,并按图 1.14 的规则映射到 Workload Identifier。这个 Identifier 随后作为 Indirect Dispatch Index,用于区分不同的 Workload Shader。

这部分 Shader 包含引擎自己的 domain-specific logic,例如哪些 Pass 使用 Tile Classification,以及 Feature 如何映射到 Shader Permutation。清单 1.8 只以 Deferred Lighting Workload 为例。tileClassificationTileCountBuffer 保存各 Dispatch Index 对应的 tile count;tileClassificationTileCoordBuffer 为每个 tile 保存一维 tile coordinate,供后续计算 global tile position 与 screen-space pixel position。
**译注:**正文将 Tile Classification 的 tile 描述为 32 × 32 pixel,但清单 1.8、1.9 中的
tileSize均为 16 × 16。本文按原书保留两处数值,不自行判断哪一个代表最终实现。
// Process one tile per invocation
const uint tileCoord1d = uint(compute.globalInvocationID.x);
const uint2 tileSize = uint2(16, 16);
const uint2 numTiles = uint2((uint2(constants.renderViewSize) +
tileSize - 1) / tileSize);
const uint numTilesTotal = numTiles.x * numTiles.y;
const uint2 tileCoord2d = unflatten1DTo2D(tileCoord1d, numTiles.x);
const uint bufferBaseIdx = tileCoord1d * TC_PAYLOAD_COUNT;
const uint tileFeatureBitmask = constants.
tileClassificationPayloadBuffer[bufferBaseIdx +
TC_PAYLOAD_FEATURE_BITMASK];
// Generate deferred lighting workload
if ((tileFeatureBitmask & (1 << TC_FEATURE_OPAQUE)) != 0) {
uint dispatchIndex = 0;
if (((tileFeatureBitmask & (1 << TC_FEATURE_BRDF_SKIN)) != 0) ||
((tileFeatureBitmask & (1 << TC_FEATURE_DECALS)) != 0)) {
dispatchIndex = TC_WORKLOAD_DEFERREDLIGHTING_RED;
} else if ((tileFeatureBitmask & (1 << TC_FEATURE_BRDF_CLOTH)) != 0) {
dispatchIndex = TC_WORKLOAD_DEFERREDLIGHTING_GREEN;
} else {
dispatchIndex = TC_WORKLOAD_DEFERREDLIGHTING_BLUE;
}
if (indirectDispatchIndex > 0) {
uint idx = 0;
atomicAddOut(
constants.tileClassificationTileCountBuffer[dispatchIndex],
1, idx);
constants.tileClassificationTileCoordBuffer[numTilesTotal *
dispatchIndex + idx] = tileCoord1d;
}
}
// Generate other workloads
{
// ...
}
清单 1.8|生成 Work Item 与 Indirect Dispatch 分类数据。
**译注:**清单 1.8 前文定义的是
dispatchIndex,条件判断却使用了indirectDispatchIndex;原书如此,代码按原样保留。
取得各 workload 的 tile count 与 coordinate offset 后,一个简单的单线程 Compute Shader 就能生成 Indirect Dispatch Argument。它遍历所有可用 Dispatch Workload,用 tile count 乘以每个 tile 的 threadgroup 数,得到需要启动的 threadgroup 总数,再写入 Lighting 等 Indirect Dispatch Workload 使用的 Argument Buffer。所有 Tile Classification Workload Shader 必须采用相同的 threadgroup size,这里为 8 x 4。
const uint2 tileSize = uint2(16, 16);
// The localSize of the shaders that support Tile Classification
const uint2 groupSize = uint2(8, 4);
assert(tileSize.x >= groupSize.x && tileSize.y >= groupSize.y);
const uint2 numTiles = (uint2(constants.renderViewSize.xy) + tileSize
- 1) / tileSize;
const uint numTilesTotal = numTiles.x * numTiles.y;
const uint2 groupsPerTile = tileSize / groupSize;
const uint groupsPerTileTotal = groupsPerTile.x * groupsPerTile.y;
// Generate indirect dispatch arguments based on feature selection
// Multiple active features can be combined to one indirect dispatch,
// e.g., split deferred lighting into "simple" and "complex" dispatches
// to minimize Vector General Purpose Registers (VGPRs)
for (int dispatchIndex = 0; dispatchIndex < TC_WORKLOAD_COUNT;
++dispatchIndex) {
const uint tileCount =
constants.tileClassificationTileCountBuffer[dispatchIndex];
const uint groupsToDispatch = tileCount * groupsPerTileTotal;
constants.tileClassificationIndirectDispatchArgs[dispatchIndex].x =
groupsToDispatch;
constants.tileClassificationIndirectDispatchArgs[dispatchIndex].y = 1;
constants.tileClassificationIndirectDispatchArgs[dispatchIndex].z = 1;
}
清单 1.9|生成 Indirect Argument。
图 1.15 展示了 workload 与实际 tile 的对应关系。蓝色 Workload 1 处理 5 个 tile,绿色 Workload 2 处理 7 个,红色 Workload 3 处理 2 个。中间两个空 tile 没有映射到任何 workload,会被直接跳过;在图 1.13 中,它们的 Bitmask 为 0x0。

CPU 端不再执行一次 fullscreen Dispatch,而是调用多个 Indirect Compute Shader:
const idVec2i workgroupSize(8, 4);
const int32 dispatchX = (w + workgroupSize.x - 1) / workgroupSize.x;
const int32 dispatchY = (h + workgroupSize.y - 1) / workgroupSize.y;
const idDeclRenderProg * prog = progComputeDeferredLightingOnly;
if (TileClassification::IsEnabled() == true) {
// Indirect dispatch with selected feature permutations
// No sync necessary between the passes since each dispatch touches
// different tiles/groups
const uint32 dispatchWorkloads[] = {
TC_WORKLOAD_DEFERREDLIGHTING_RED,
TC_WORKLOAD_DEFERREDLIGHTING_GREEN,
TC_WORKLOAD_DEFERREDLIGHTING_BLUE };
const uint32 dispatchWorkloadCount = ID_ARRAY_COUNT(dispatchWorkloads);
for (int idx = 0; idx < dispatchWorkloadCount; ++idx) {
const uint32 dispatchIndex = dispatchWorkloads[idx];
switch (dispatchIndex) {
case TC_WORKLOAD_DEFERREDLIGHTING_RED:
prog = progComputeDeferredLightingRed;
break;
case TC_WORKLOAD_DEFERREDLIGHTING_GREEN:
prog = progComputeDeferredLightingGreen;
break;
case TC_WORKLOAD_DEFERREDLIGHTING_BLUE:
prog = progComputeDeferredLightingBlue;
break;
};
// We let this dispatch know about the workload index
SetRenderConstant(c_DispatchIndex, dispatchIndex);
DispatchComputeIndirectPass(prog,
tileClassificationIndirectDispatchArgs, dispatchIndex * sizeof(
indirectDispatchArgs_t));
}
} else {
// Default single fullscreen dispatch
DispatchComputePass(prog, dispatchX, dispatchY, 1);
}
清单 1.10|比较 Indirect Tile Workload 与单次 Fullscreen Workload 的 Dispatch。
Shader 端同样需要适配 Tile Classification Workload。常规 fullscreen Dispatch 通常只调用一次,以每像素一个线程的方式运行,并直接把 global dispatch thread ID,也就是 HLSL 的 SV_DispatchThreadID,作为 pixel position。Tile Workload 必须显式计算这个位置。每次 Dispatch 会把 Workload Identifier 作为常量传给 GPU,Shader 再从 count 与 coordinate buffer 读取数据,通过 tile offset 得到最终 pixel position。
uint flatten2DTo1D(uint2 coord2d, uint w) {
return coord2d.y * w + coord2d.x;
}
uint2 unflatten1DTo2D(uint coord1d, uint w) {
return uint2(coord1d % w, coord1d / w);
}
int2 computeGlobalScreenPosition(uint groupIdx, uint2 groupSize2d,
uint2 localPosition, uint dispatchIndex) {
const uint2 tileSize2d =
uint2(constants.tileClassificationParms0.xx);
// The 2D number of groups per tile
const uint2 groupsPerTile = tileSize2d / groupSize2d;
// The total number of groups per tile
const uint groupsPerTileTotal = groupsPerTile.x * groupsPerTile.y;
// Group clamped to tile index for the array
const uint groupAsTileIdx = uint(groupIdx / groupsPerTileTotal);
const uint2 numTiles = (uint2(constants.renderViewSize.xy) +
tileSize2d - 1) / tileSize2d;
const uint numTilesTotal = numTiles.x * numTiles.y;
// Find the tile coordinate
const uint dispatchGroupOffset = numTilesTotal * dispatchIndex;
const uint tileCoord1d = constants.tileClassificationTileCoordBuffer[
dispatchGroupOffset + groupAsTileIdx];
// Compute 2D tile coordinate
const uint2 tileCoord2d = unflatten1DTo2D(tileCoord1d, numTiles.x);
// Validate the tile coordinates
assert((tileCoord2d.x < numTiles.x) &&
(tileCoord2d.y < numTiles.y));
// Tile position in pixel coordinates
const uint2 tilePosition = tileCoord2d * tileSize2d;
// The 1D group coordinate relative/local to tileCoord2d
const uint groupLocalToTile = uint(groupIdx % groupsPerTileTotal);
// The 2D group coordinates relative to the tile
const uint2 groupCoord2d =
unflatten1DTo2D(groupLocalToTile, groupsPerTile.x);
// Group pixel position
const uint2 groupPosition = (groupCoord2d * groupSize2d);
// Add up to get the global position
return int2(tilePosition + groupPosition + localPosition);
}
清单 1.11|在 Tiled Workload 中计算 Global Screen Position。
清单 1.12 展示了最终 Shader 如何取得 global pixel position,并在需要时计算 global workgroup ID。这段代码通常用于 Deferred Lighting Shader,以及其他支持 Tile Classification 的 workload。
const uint2 groupSize2d = uint2(8, 4);
// When dispatching workgroups for the full screen, this is the actual
// invocation as usual
int2 globalScreenPos = int2(compute.globalInvocationID.xy);
int2 globalWorkGroupID = int2(compute.workGroupID.xy);
if (constants.tileClassificationEnabled == true) {
// The workgroup group ID is 1D because of how indirect dispatch
// arguments are set up (across all tiles of this indirect dispatch)
globalScreenPos =
computeGlobalScreenPosition(uint(compute.workGroupID.x),
groupSize2d, compute.localInvocationID.xy, constants.dispatchIndex);
globalWorkGroupID = globalScreenPos / int2(groupSize2d);
}
清单 1.12|在最终 Shader 中计算 Screen Position 与 Workgroup ID。
Tile Classification 带来了可观的性能收益。多次 Indirect Dispatch 虽然比单次 fullscreen Dispatch 更复杂,仍可整理成固定模式,并复用于其他 Pass。
第三篇将继续介绍 Variable-Rate Compute Shaders(VRCS),并总结整套 idTech 8 不透明几何渲染管线的性能、内存成本和后续方向。
《《毁灭战士:黑暗时代》的 Visibility Buffer 与 Deferred Rendering|第二篇:Pixel Command 与 Deferred Lighting》有1条评论