Gaussian Splatting From Zero · Episode 05
Depth Sorting
Depth Sorting is Episode 05 of Gaussian Splatting From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Triangles have a z-buffer; they never need to be sorted. Transparent Gaussian splats have neither luxury — to blend correctly they must be drawn back-to-front, farthest first, every single frame, re-sorted the instant the camera moves. This is the one chore splatting can't escape, and watching it work is the most satisfying toggle in the series: flip "sort" off and the planet dissolves into milky chaos; flip it on and it snaps into a crisp, correct image. Try it in the demo. Then we'll build the sort.
Why splats need sorting and triangles don't
An opaque triangle can be drawn in any order because the depth buffer arbitrates per
pixel: whoever's nearest wins, the rest are discarded. That works precisely because the
answer is binary — a pixel is either this surface or that one. A transparent splat has no
binary answer; its pixel is a blend of everything behind it, weighted by alpha.
And the "over" operator from Episode 04, src·α + dst·(1−α), only gives the
right blend if you apply the layers in depth order. Paint a far blue splat after a near red
one and the blue wrongly sits on top. Multiply that error by 45,000 overlapping splats and
you get the milky wrongness we ended Episode 04 on.
So before every frame we answer one question for all 45,000 splats — "how far from the camera are you?" — and hand them to the GPU sorted farthest-first.
Sorting by view-space depth
"Distance from camera" for a splat is the z-coordinate of its center in view space
— the camera's own coordinate system. We already build the view matrix every frame; the
depth of splat i is one dot product against its third row:
// view-space depth (more negative = farther, in OpenGL convention)
const e = camera.matrixWorldInverse.elements; // the view matrix
function depthOf(i) {
const x = centers[i*3], y = centers[i*3+1], z = centers[i*3+2];
return e[2]*x + e[6]*y + e[10]*z + e[14]; // (view · center).z
}
A comparison sort (Array.sort) on 45,000 keys is fine, but it's
O(n log n) and allocates. Real renderers use a counting sort
(a radix/bucket sort): it's O(n) and touches each splat a fixed number of
times. We quantize each depth into one of, say, 256·256 buckets, count how many land in
each, turn the counts into start-offsets with a prefix sum, then scatter every splat into
its slot. No comparisons at all.
// counting sort of indices by depth — the technique real splat viewers use
function sortSplats() {
// 1. find the depth range this frame
let dmin = Infinity, dmax = -Infinity;
for (let i = 0; i < N; i++) { const d = depthOf(i); depth[i] = d;
if (d < dmin) dmin = d; if (d > dmax) dmax = d; }
// 2. quantize into B buckets and count
const B = 65536, scale = (B - 1) / (dmax - dmin || 1);
counts.fill(0);
for (let i = 0; i < N; i++) {
const b = ((depth[i] - dmin) * scale) | 0; bucket[i] = b; counts[b]++;
}
// 3. prefix-sum counts → start offsets (ascending = far→near for our sign)
for (let b = 1; b < B; b++) counts[b] += counts[b-1];
// 4. scatter indices into sorted order
for (let i = N - 1; i >= 0; i--) order[--counts[bucket[i]]] = i;
}
That produces order — the splat indices, farthest first. The last step is to
physically reorder the instanced attributes into that order and re-upload, so the GPU draws
instance 0 = farthest, instance N−1 = nearest:
// gather original splat data into draw order, then flag for upload
for (let k = 0; k < N; k++) {
const j = order[k];
outCenter.set(srcCenter.subarray(j*3, j*3+3), k*3);
outColor .set(srcColor .subarray(j*3, j*3+3), k*3);
// ...scale (3), quat (4), opacity (1) the same way...
}
geo.attributes.iCenter.needsUpdate = true; // (and the rest)
Production viewers skip the physical reorder. They keep all splat data in a texture, give each instance just an integer index, and sort only that tiny index array — then upload one small buffer instead of shuffling megabytes. Same algorithm, cheaper plumbing. We reorder the attributes directly because it's the same idea you can actually read. The optimization is an exercise.
Don't sort every frame — throttle it
Sorting 45,000 splats takes a fraction of a millisecond, but doing it 120 times a second is wasteful when the camera is barely moving. Two cheap wins:
- Only re-sort when the view changes meaningfully — track the camera's position/direction and skip the sort if it hasn't moved past a small threshold.
- Cap the sort rate (the demo's "sort rate" slider). Even at 15–30 sorts/second the image looks stable, because the error from a slightly-stale sort is tiny — a few splats momentarily one slot out of place.
Drag the "sort rate" slider to 1/sec and orbit fast: you'll see the planet briefly go milky and then "catch up" each time the sort fires. That's the staleness, and it's why real viewers sort on a worker thread — the sort never blocks the render.
The toggle: ON vs OFF vs REVERSED
The demo's three modes are worth sitting with:
| Mode | Draw order | Result |
|---|---|---|
| ON | Far → near | Correct "over" compositing. Crisp, stable, photographic. |
| OFF | Arbitrary (memory order) | Milky chaos that shifts as you orbit. The Episode 04 problem. |
| REVERSED | Near → far | Subtly but consistently wrong — near splats dimmed, far ones too strong. The seductive bug, because it's almost right. |
REVERSED is the instructive one. Front-to-back compositing isn't garbage — it's a real technique — but it needs a different blend equation that also tracks accumulated transmittance. Plug front-to-back order into the back-to-front "over" operator and you get a consistent, plausible, completely wrong image. Many a splat bug is just a flipped sort comparator.
This is splatting's Achilles' heel
Every hard problem in production splatting traces back to this sort. Animated splats? The sort changes every frame as things move. Millions of splats? The sort is now your bottleneck, so you move it to the GPU (a bitonic or radix sort in a compute shader). Splats mixed with real geometry? You have to interleave the sorted-transparent splats with the z-buffered opaque meshes. We'll meet every one of these later. For now, you've built the thing that makes transparent splats possible at all — and you can feel exactly why it matters by turning it off.
Common pitfalls
- Sorted, but still wrong. Your comparator sign is flipped (front-to-back). Farthest must be drawn first. If toggling REVERSED looks better, your "ON" is actually reversed.
- Stutter when orbiting. You're sorting on the main thread every frame
with
Array.sort. Switch to the counting sort, throttle it, or move it to a Web Worker. - Re-upload kills framerate. Reordering and uploading all attributes every frame is bandwidth-heavy. Throttle the sort, or use the index-texture trick so you only upload N integers.
- Splats "swim" during fast motion. Stale sort. Expected and usually invisible; lower it by raising the sort rate or sorting on view-change.
- Perfect head-on, wrong at the poles. You sorted by distance to the camera point instead of view-space z (distance to the camera plane). For wide scenes the plane distance is the correct key.
Exercises
- Implement the "only sort when the camera moved" optimization: store the last sorted camera position, skip the sort if it moved less than a threshold. Watch the FPS HUD when the planet is still.
- Add a second cloud at a different position and confirm the sort correctly interleaves both — splatting has no concept of "objects," only a global depth order.
- Move the counting sort into a Web Worker. Post the camera matrix in, get the
orderarray back, upload on the main thread. This is how every serious viewer does it. - Switch to the index-texture method (data in a
DataTexture, instance = index). Measure the upload-size difference: N integers vs N×14 floats.
What's next
Episode 06 — Spherical Harmonics & View-Dependent Color. So far each
splat has one fixed color. Real captures store color as a function of viewing direction
— which is why a splatted chrome bumper or a wet street shimmers and shifts as you move,
instead of looking like flat paint. We'll decode the spherical-harmonic coefficients that a
real .ply ships with and watch highlights slide across the surface.