1

I have the following structure that represents a 3D VoxelGrid:

var<storage, read> chunks: array<Chunk>;
struct Chunk {
    position: vec3<i32>,
    metadata: u32,
    data: array<vec4<u32>, CHUNK_DATA_SIZE>,
};

I had to use a vector inside the array, because it must be 16 bit aligned and because of that I created the following function to get two indices, the first one for the array and the second one for the vector.

const CHUNK_SIZE: u32 = 32u;
const CHUNK_VEC_SIZE: u32 = 4u;
const CHUNK_X_SIZE: u32 = 8u;

fn get_chunk_index(index: vec3<u32>) -> vec2<u32> {
    let vec_index = vec3<u32>(index[0] / CHUNK_VEC_SIZE, index[1], index[2]);
    let inner_x_index = index[0] % CHUNK_VEC_SIZE;

    let flat_vec_index =
        vec_index[0] +
        (vec_index[1] * CHUNK_X_SIZE) + 
        (vec_index[2] * CHUNK_X_SIZE * CHUNK_SIZE);

    return vec2<u32>(flat_vec_index, inner_x_index);
}

and to get the actual data out of the chunk I have this function:

fn index_chunk(chunk: Chunk, index: vec3<u32>) -> u32 {
    let chunk_index = get_chunk_index(index);
    let data = chunk.data[chunk_index.x][chunk_index.y];
    return data;
}

but naga complains that this array can only be indexed by constant values

Shader validation error: 
    ┌─ pathtrace shader:221:1
    │  
221 │ ╭ fn index_chunk(chunk: Chunk, index: vec3<u32>) -> u32 {
222 │ │     let chunk_index = get_chunk_index(index);
223 │ │     let data = chunk.data[chunk_index.x][chunk_index.y];
    │ │                ^^^^^^^^^^^^^^^^^^^^^^^^^ naga::Expression [6]
224 │ │     return data;
    │ ╰────────────────^ naga::Function [8]

    Function [8] 'index_chunk' is invalid
    Expression [6] is invalid
    The expression [4] may only be indexed by a constant

How can I get around this problem. Dynamic indexing should be okay as the Chunk struct is stored as storage.

BrunoWallner
  • 417
  • 3
  • 10

0 Answers0