Josh Taylor

Projects · 03 of 08

Galaxy simulation

A galaxy that runs in a browser tab. Gravity, gas, new stars, and the drawing all stay on the graphics card.

The galaxy simulation: a disc of blue and white stars seen at a tilt, with a warm red core.
Year
2026
Built with
JavaScript, WebGPU, WGSL

At McMaster I simulated a galaxy in Fortran 90 and watched a star cluster form its own spiral arms. This is the same idea again, in a browser tab, where you can turn it over with a mouse.

It starts with 25,000 stars and the panel takes it as high as 500,000. Every star pulls on every other, and the graphics card does that work through WebGPU, so the page needs a browser that has it (Chrome 113 or later, Safari 26 or later). About 30% of the disc is gas that cools, settles thin, and turns into new stars where it gets dense, and the heaviest stars end as supernovae and hand their matter back to the gas. Click a star and keep zooming, and the view crosses into that star’s own solar system, with the galaxy still turning behind it.

The hard part

Pulling every star toward every other one is too much work once there are many stars. The usual answer is a Barnes-Hut tree, which sorts the stars into nested boxes and treats a far box as one heavy point. The tree is built off the graphics card, in the background, while the stars keep moving, so the tree that steers them is always a little out of date. Each time a fresh tree took over from a stale one the forces jumped, and the galaxy gained about half a percent of its kinetic energy on every swap. Energy that comes from nowhere is the one thing a physics simulation cannot be allowed to have.

How I solved it

I split the tree in two. Its shape, which is to say which stars share a box, changes slowly, so a Web Worker rebuilds it in the background from a copy of the positions. Its contents, the mass and the centre of each box, are summed again on the graphics card before every step, from where the stars are at that moment. The force on a star now follows the live positions smoothly, and a new tree changes only how the sum is grouped. The swaps stopped adding energy.

The readout in the corner of the demo shows how far the total energy has drifted. What is left is mostly the gas, which is meant to lose energy as it cools.