Kinru
Kinru

Reputation: 399

Indexing a 3d array into a 1d array - neighbor finding

So I have a 3D array that represents a bounding volume (uniform grid of "cells") that has been flattened into a 1D array so that I can use it in CUDA.

The issue I'm having is that I need to be able to take any given "cell" in my uniform grid and find all of it's neighbors. This is simple when you have a 3D array (it's just 3 for loops looping from -1 to 1 and indexing into the 3D array correctly), but I'm terrible at trying to break this down into a version that works on the 1D array. There should be a simple formula that will calculate this, but I just can't figure it out.

Also, the edges should not loop, meaning the cell in the bottom left-hand corner should not be a "neighbor" to the cell in the bottom right-hand corner.

Any help is appreciated. Thanks.

Upvotes: 0

Views: 484

Answers (1)

jhnnslschnr
jhnnslschnr

Reputation: 404

You can keep the 3 for loops. Just check the bounds in each dimension and calculate the index by nested addition/multiplication.

for (int i1 = -1; i1 <= 1; ++i1) {
    for (int i2 = -1; i2 <= 1; ++i2) {
        for (int i3 = -1; i3 <= 1; ++i3) {
            const int x1 = p1 + i1;
            const int x2 = p2 + i2;
            const int x3 = p3 + i3;
            if (   x1 >= 0 && x1 < n1
                && x2 >= 0 && x2 < n2
                && x3 >= 0 && x3 < n3) {
                neighbour = array[(x1*n2+x2)*n3+x3];
            }
        }
    }
}

Upvotes: 2

Related Questions