GPU Morton Codes & LBVH
Morton Codes (Z-Order Space-Filling Curves): Building hierarchical acceleration trees (BVHs) for hardware ray tracing is traditionally sequential and CPU-bound. Morton codes interleave the binary bits of 3D spatial coordinates $(x, y, z)$, mapping a 3D box onto a 1D fractal Z-order curve. Sorting 1D integer keys via GPU parallel radix sort clusters spatially adjacent 3D geometry into cache-coherent blocks in $O(N)$ time.
Morton Code Bit-Interleaving:
1def expand_bits(v):2 """Expands 10-bit integer to 30-bit integer by inserting 2 zeros between each bit."""3 v = (v * 0x00010001) & 0xFF0000FF4 v = (v * 0x00000101) & 0x0F00F00F5 v = (v * 0x00000011) & 0xC30C30C36 v = (v * 0x00000005) & 0x492492497 return v89def morton_3d(x, y, z):10 """11 Computes 30-bit Morton code (Z-order curve) by interleaving bits of normalized (x, y, z).12 Maps 3D spatial points into a 1D sequence preserving spatial locality.13 Critical for GPU ray tracing BVH construction (Karras 2012).14 """15 xx = expand_bits(int(x * 1023.0))16 yy = expand_bits(int(y * 1023.0))17 zz = expand_bits(int(z * 1023.0))18 return (xx << 2) | (yy << 1) | zz
Linear Bounding Volume Hierarchies (Karras LBVH): Traditional top-down BVH construction requires recursive partitioning that stalls massively parallel GPU compute units. Tero Karras (NVIDIA 2012) revolutionized hardware ray tracing: after sorting primitives by Morton code, each of the $N-1$ internal BVH nodes can be constructed completely independently by a single GPU thread in parallel without locks or recursion, using binary search on bitwise Common Prefix Lengths ($\delta$).
Karras LBVH Parallel Invariant:
1def common_prefix_length(morton_codes, i, j):2 """Counts leading identical bits (clz) between Morton codes i and j."""3 if j < 0 or j >= len(morton_codes):4 return -15 xor_val = morton_codes[i] ^ morton_codes[j]6 if xor_val == 0:7 return 32 + (i ^ j) # Break ties with index8 return 32 - xor_val.bit_length()910def karras_lbvh_split(morton_codes, i):11 """12 Tero Karras (2012) Parallel Radix Tree Split in O(1).13 Each GPU thread i evaluates its range [first, last] and finds binary split position gamma14 using binary search on longest common prefix length delta(i, j).15 Eliminates all synchronization locks and tree recursion on GPU!16 """17 return "Parallel Radix Tree Node (Split Index gamma)"