idx()
Flattening multi-dimensional data into a single array is a common performance and simplicity trick in graphics and simulation code - it avoids the overhead of nested JavaScript arrays and makes swapping whole buffers (like grid and next) trivial.
🔬 This formula packs x, y, and z into one number using N as a base. What do you think would happen if you swapped the order to `z + N * (y + N * x)` - would the simulation still work correctly? (Hint: as long as idx() is used consistently everywhere, the mapping just needs to be unique per coordinate.)
function idx(x, y, z) { return x + N * (y + N * z); }
function idx(x, y, z) { return x + N * (y + N * z); }
Line-by-line explanation (1 lines)
🔧 Subcomponents:
return x + N * (y + N * z);
Converts a 3D coordinate (x,y,z) into a single number so it can be used as an index into the flat grid array
function idx(x, y, z) { return x + N * (y + N * z); }- Instead of a true 3D array (arrays of arrays of arrays), this sketch stores everything in one flat 1D array of length N*N*N. This formula maps any (x,y,z) coordinate to a unique slot in that array - it's the same idea as reading a 3D box row by row, then layer by layer.