我正在尝试编写一个读取存储在存储缓冲区中的八叉树的 WGSL 着色器。问题是,编译器不喜欢我为访问存储缓冲区中的叶子而计算的动态索引。wgpu 产生以下验证错误:
thread 'main' panicked at 'wgpu error: Validation Error
Caused by:
In Device::create_shader_module
Function [1] 'get_voxel' is invalid
Expression [68] is invalid
The expression [67] may only be indexed by a constant
八叉树的结构使得我可以在 GPU 上遍历它。该结构在这篇 NVIDIA 论文中进行了概述:https ://developer.nvidia.com/gpugems/gpugems2/part-v-image-orientation-computing/chapter-37-octree-textures-gpu
从本质上讲,八叉树是一个IndirectionGrid
s 数组,每个在内存IndirectionGrid
中正好有 8个 s。GridCell
网格单元可以表示指向另一个的指针IndirectionGrid
或一些数据。
让我们说八叉树的最深处代表一个 16x16x16 的网格。我想GridCell
在 7,7,7 得到。我们知道 7,7,7 在根的单元格 0 中,IndirectionGrid
因为坐标的每个分量都小于中点。如果我们将坐标分量相加,我们可以得到当前 的GridCell
索引IndirectionGrid
。因为我正在遍历一棵树,所以我在每个级别都这样做。下面是演示这一点的不完整代码。
导致问题的行是let cell = grid.cells[grid_index].data;
所以最终我的问题是,动态索引是否允许?有什么我可以改变的东西可以神奇地让它发挥作用吗?或者我需要了解更多关于 WebGPU 权衡的背景信息吗?
struct GridCell {
data: u32;
};
struct IndirectionGrid {
cells: array<GridCell, 8>;
};
[[block]]
struct VoxelVolume {
resolution: vec3<f32>;
size: vec3<f32>;
palette: array<u32, 256>;
indirection_pool: array<IndirectionGrid>;
};
[[group(2), binding(0)]]
var<storage, read> voxel_volume: VoxelVolume;
let COLOR_RED_MASK = 0xFF000000u;
let COLOR_GREEN_MASK = 0x00FF0000u;
let COLOR_BLUE_MASK = 0x0000FF00u;
let COLOR_ALPHA_MASK = 0x000000FFu;
let CELL_TYPE_MASK: u32 = 0xFF000000u;
let CELL_DATA_MASK: u32 = 0x00FFFFFFu;
fn get_voxel(pos: vec3<f32>) -> vec4<f32> {
let max_depth: i32 = 12;
let color = vec4<f32>(0.0, 0.0, 0.0, 0.0);
var pool_index = 0u;
var grid_size = max(max(voxel_volume.size.x, voxel_volume.size.y), voxel_volume.size.z);
for (var i: i32 = 0; i < max_depth; i = i + 1) {
let grid = voxel_volume.indirection_pool[pool_index];
let grid_coord_x = select(1u, 0u, pos.x / grid_size < 0.5);
let grid_coord_y = select(1u, 0u, pos.y / grid_size < 0.5);
let grid_coord_z = select(1u, 0u, pos.z / grid_size < 0.5);
let grid_index = grid_coord_x + grid_coord_y * 2u + grid_coord_z * 2u * 2u;
let cell = grid.cells[grid_index].data;
let cell_type = cell & CELL_TYPE_MASK >> 16u;
switch (cell_type) {
case 1u: {
pool_index = cell & CELL_DATA_MASK >> 8u;
}
case 2u: {
let palette_index = cell & CELL_DATA_MASK >> 8u;
let palette_color = voxel_volume.palette[palette_index];
return vec4<f32>(
f32(palette_color & COLOR_RED_MASK >> 24u) / 255.0,
f32(palette_color & COLOR_GREEN_MASK >> 16u) / 255.0,
f32(palette_color & COLOR_BLUE_MASK >> 8u) / 255.0,
f32(palette_color & COLOR_ALPHA_MASK) / 255.0
);
}
default: {
// discard;
return vec4<f32>(pos.x / 16.0, pos.y / 16.0, pos.z / 16.0, 1.0);
}
}
}
discard;
}