Astro
A real-time GPU N-body gravitational simulation in Swift and Metal, scaling to 500k+ particles via a Barnes-Hut octree and a custom Morton-keyed radix sort.
Screenshots
Astro

Astro old

How it works
- Morton encoding (
MortonCode.metal) — each frame, every particle's position is mapped to a 63-bit Morton code (21 bits per axis), giving fine spatial resolution while preserving z-order locality for the rest of the pipeline. - Custom radix sort (
RadixSort.metal,RadixSort.swift) — particles are sorted by Morton key with a 64-pass split-based radix sort over ping-pong buffers. Multi-pass prefix sums in auxiliary buffers handle large inputs. The sort runs entirely in Metal compute kernels with 64-thread workgroups tuned for Apple Silicon occupancy. Done from scratch rather than via Metal Performance Shaders so the bit-pass count and key layout match the Barnes-Hut tree exactly. - Octree construction (
Octree.metal) — the sorted Morton stream lets every level of the octree be built in a single pass. Layers are stored sequentially leaves-to-root in one contiguous buffer; each layer's offset and size are derived analytically from the maximum particle count, so children find their parents by arithmetic rather than pointer chasing. Empirically 7 levels (21 Morton bits) is the sweet spot — most particles end up at their own leaf while the upper levels stay coarse enough to skip in force evaluation. - Barnes-Hut force evaluation (
BarnesHut.metal) — each particle walks the tree with a stack-based depth-first traversal, accepting an internal node as a single mass when its angular size satisfies the multipole criterion θ < 0.7. Includes softening for close encounters and per-step clamping against numerical blow-up.
The current build targets 500k particles at 120 FPS on M-series GPUs, with all data structures laid out for coalesced GPU access via a single bridging header shared with Swift.
Versions
The repository keeps two recordings:
Astro new.mov— current build, tuned for scale (post-processing off).Astro old.mov— earlier build with gravitational lensing, redshift, bloom, and chromatic aberration inPostProcess.metal/Spheres.metal. Kept as reference; the current build deliberately drops them to spend the budget on the Barnes-Hut pipeline.
Astro old demo
Stack
- Swift / Metal — host code and compute kernels
- Apple Silicon GPU target
License
MIT — see LICENSE.