Task 2 of 5
Real gravity has no star at the center — every body pulls on every other. For 64 bodies that's 64 × 63 interactions; for a million, half a trillion. On the GPU the shape is beautiful: the outer loop over bodies becomes 64 parallel threads, and each thread keeps a small inner loop over the other 63. O(n²) work, O(n) time per thread, all at once.
One wrinkle: pulls are vectors now, not strengths. The unit direction
from you to body j is (dx / r, dy / r), and the strength is
mass[j] / r² — multiply them and the x-component of each contribution is
mass[j] · dx / r³. This kernel sums just the x-components; skip yourself, or
you'll divide by zero.
mass[j] · dx / r³ over every other body.j over all this.constants.n bodiesj !== this.thread.x guard is already theremass[j] * dx / (r² · r) into axDirection dx / r times strength 1 / r² is
dx / r³. With r2 = dx*dx + dy*dy in hand, that's
r2 * Math.sqrt(r2) — one square root per pair.
const dx = posX[j] - myX;
const dy = posY[j] - myY;
const r2 = dx * dx + dy * dy;
ax += mass[j] * dx / (r2 * Math.sqrt(r2));var<workgroup> and Metal's threadgroup memory exist for the same trick.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.