Skip to content

Instantly share code, notes, and snippets.

@sampavlovic
Last active April 1, 2026 20:01
Show Gist options
  • Select an option

  • Save sampavlovic/93fd4b8d8acfa9db5038ad2ed699e27d to your computer and use it in GitHub Desktop.

Select an option

Save sampavlovic/93fd4b8d8acfa9db5038ad2ed699e27d to your computer and use it in GitHub Desktop.
// 64-bit popcount helper
uint CountBits(uint64_t x)
{
return countbits(uint(x)) + countbits(uint(x >> 32));
}
class TreeNode64
{
uint64_t childMask; // 64 bits: one bit per possible child (0-63)
union
{
uint firstChild; // Internal node: index of first child
uint leafData; // Leaf node: your data (material, color, density, etc.)
} data;
bool IsLeaf() { return childMask == 0; }
static uint Traverse(StructuredBuffer<TreeNode64> nodes, uint3 voxelPos, uint rootIndex = 0)
{
uint nodeIdx = rootIndex;
uint3 pos = voxelPos;
[loop]
while (true)
{
uint childIdx = (pos.x & 3) | ((pos.y & 3) << 2) | ((pos.z & 3) << 4);
if ((nodes[nodeIdx].childMask & (1ull << childIdx)) == 0)
return nodeIdx; // Leaf found
uint rank = CountBits(nodes[nodeIdx].childMask & ((1ull << childIdx) - 1));
nodeIdx = nodes[nodeIdx].data.firstChild + rank;
pos >>= 2;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment