光线排序优化
光线排序是一种 GPU 优化技术,通过减少 warp 分歧提升渲染性能。
Warp 分歧问题
在 GPU 上,同一 warp 内的 32 个线程执行相同指令。当光线命中不同物体时,会产生分支:
cpp
// 导致 warp 分歧的代码
if (ray hits sphere A) {
shade_sphere_A();
} else if (ray hits sphere B) {
shade_sphere_B();
} else {
// ...
}排序策略
按命中物体 ID 对光线排序,使相邻光线命中相同物体:
cpp
// 按 object_id 排序光线
thrust::sort_by_key(
thrust::device,
object_ids, // keys: 物体 ID
object_ids + num_rays,
ray_indices // values: 光线索引
);性能收益
| 场景 | 未排序 (ms) | 已排序 (ms) | 提升 |
|---|---|---|---|
| Demo | 45 | 36 | 20% |
| Random | 120 | 72 | 40% |
| Complex | 350 | 210 | 40% |
实现代码
cpp
void ray_sort(
int* object_ids,
int* ray_indices,
int num_rays,
cudaStream_t stream
) {
// 初始化光线索引
thrust::sequence(
thrust::cuda::par.on(stream),
ray_indices,
ray_indices + num_rays
);
// 按物体 ID 排序
thrust::sort_by_key(
thrust::cuda::par.on(stream),
object_ids,
object_ids + num_rays,
ray_indices
);
}适用场景
- 适用: Phong 着色 + 单采样
- 不适用: 路径追踪(光线方向随机变化)
参考资料
- [Hoberock 2010] "Thrust: A Parallel Algorithms Library"