How the spatial-hash collision force works on the GPU
mainThe collision force uses a spatial-hash grid to avoid $O(n^2)$ complexity, allowing it to scale to hundreds of thousands of points. The GPU pipeline operates in two phases per tick, repeated over 4 half-cell offsets to handle collisions straddling cell boundaries:
- Build Phase: For each offset, a point-list draw bins every point into a grid cell using additive blending. Each cell accumulates
(sumX, sumY, sumSize, count). - Resolve Phase: A fullscreen pass reads the cell averages in a point's 3×3 neighborhood and computes a push-apart velocity. This is accumulated additively across the 4 offsets.
Key Technical Details:
- Grid Sizing:
cellSize = max(effectiveRadius, 8). ThegridTextureSizeis clamped between 32 and 512. - Stability: To prevent 'ping-ponging' (overshooting) in dense regions, the force is clamped to ~10% of the collision radius per pass (roughly 40% per frame across 4 passes).
- Density Damping: The force is scaled down when a point has many neighbors to reduce jitter.