WGSL for the GPU depth sort, one shader module per pass.
The passes, in dispatch order (see gpu-depth-sorter.ts):
computeDepth — each element's view-space z from its element-texture
center, plus the min/max over in-front elements (z < 0), reduced per
workgroup and merged with atomics on an order-preserving u32 encoding.
computeKeys — the 16-bit back-to-front key, written over the depth.
histogram — per block, the count of each 4-bit digit at a shift.
scanBlocks / addTotals — the multi-level exclusive scan of the
digit-major histogram, giving each block its write offset per digit.
scatterFirst / scatterMiddle / scatterLast — the STABLE scatter of
one pass (see scatter below). Steps 3-5 repeat for each of the four
4-bit digits, least significant first: the first pass reads the keys and
the implicit element index, the last writes the final element indices.
The key arithmetic is the CPU kernel's (wasm/typescript/depth-sort.ts):
view z = m2·x + m6·y + m10·z + m14; zMin/zMax over z < 0; a degenerate range
(!(zMax > zMin)) keys everything 0, which the stable sort turns into the
identity order, like the CPU's identity fallback; otherwise
key = min(trunc((z − zMin) · (1 / (zMax − zMin)) · 65535), 65535) for an
element in front of the camera and 0 behind it. WGSL may contract a
multiply-add into an FMA and its division is accurate to 2.5 ULP (refined
here by one Newton step), so a key near a bucket edge can land one bucket
from the CPU's. The sort of the GPU's own keys is exact and stable.
WGSL for the GPU depth sort, one shader module per pass.
The passes, in dispatch order (see
gpu-depth-sorter.ts):computeDepth— each element's view-space z from its element-texture center, plus the min/max over in-front elements (z < 0), reduced per workgroup and merged with atomics on an order-preserving u32 encoding.computeKeys— the 16-bit back-to-front key, written over the depth.histogram— per block, the count of each 4-bit digit at a shift.scanBlocks/addTotals— the multi-level exclusive scan of the digit-major histogram, giving each block its write offset per digit.scatterFirst/scatterMiddle/scatterLast— the STABLE scatter of one pass (seescatterbelow). Steps 3-5 repeat for each of the four 4-bit digits, least significant first: the first pass reads the keys and the implicit element index, the last writes the final element indices.The key arithmetic is the CPU kernel's (
wasm/typescript/depth-sort.ts): view z = m2·x + m6·y + m10·z + m14; zMin/zMax over z < 0; a degenerate range (!(zMax > zMin)) keys everything 0, which the stable sort turns into the identity order, like the CPU's identity fallback; otherwisekey = min(trunc((z − zMin) · (1 / (zMax − zMin)) · 65535), 65535)for an element in front of the camera and 0 behind it. WGSL may contract a multiply-add into an FMA and its division is accurate to 2.5 ULP (refined here by one Newton step), so a key near a bucket edge can land one bucket from the CPU's. The sort of the GPU's own keys is exact and stable.