Skip to content

Instantly share code, notes, and snippets.

@SalatielSauer
Last active January 11, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SalatielSauer/abe02d095bbce56696dc42ab0c1f5398 to your computer and use it in GitHub Desktop.
Save SalatielSauer/abe02d095bbce56696dc42ab0c1f5398 to your computer and use it in GitHub Desktop.
JavaScript functions to get the position or index of a cube following the Sauerbraten octree structure
// example: getCubeIndex(256, 256, 512, 8) // returns: 35
function getCubeIndex(x, y, z, gridpower) {
let index = 0;
let size = 1<<gridpower;
index += parseInt((x / size).toString(2), 8);
index += parseInt((y / size).toString(2), 8) * 2;
index += parseInt((z / size).toString(2), 8) * 4;
return index;
}
// example: getCubePos(35, 8) // returns: [256, 256, 512]
function getCubePos(index, gridpower) {
let octal = index.toString(8);
let size = 1<<gridpower;
let position = [0, 0, 0];
for (i = 0; i < octal.length; i++) {
let digit = parseInt(octal[octal.length - i - 1], 8);
position[0] += (Math.floor(digit / 1) % 2) * (2 ** i) * size;
position[1] += (Math.floor(digit / 2) % 2) * (2 ** i) * size;
position[2] += (Math.floor(digit / 4) % 2) * (2 ** i) * size;
}
return position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment