Flocking in three dimensions
Boids (flocking in 3D) Every boid follows three rules and only looks at neighbors inside its view radius, a sphere around it: separation (do not crowd your neighbors), alignment (steer like your neighbors) and cohesion (move toward the center of your neighbors). No boid knows the flock. Still, flocks form, split and merge. The color shows the flight direction: the x, y and z part of the direction are the red, green and blue part of the color. Wikipedia
Particle Life Particles have a type, shown by color. A random matrix says how strongly type A is attracted to or repelled by type B. Very close particles always repel each other, so they do not collapse into one point. From these simple pair forces, cells, chains and orbiting groups appear. Re-roll the matrix to get a new world. particle-life.com
GPU Parallelization Each agent needs the state of all other agents. If the agents were updated in place, some would read new and some old values. So every frame has two passes: first the current state is copied, then one GPU thread per agent reads the copy and writes the new state. 64 threads form one workgroup. Wikipedia
Original work
- Craig W. Reynolds (1987): Flocks, Herds, and Schools: A Distributed Behavioral Model
- Jeffrey Ventrella (2017): Clusters (Particle Life)
How it works
How the simulation runs, step by step:
- Data layout: positions are stored as vec4 [x, y, z, type] and velocities as vec4 [vx, vy, vz, 0], 16 bytes per agent, so the GPU reads aligned blocks.
- Each frame runs two compute dispatches: copy (current to previous) and step (read previous, write current). The renderer always reads the current buffer.
- The step kernel runs one thread per agent, 64 threads per workgroup. Each thread loops over all agents, so the work grows with N².
- The world wraps around at the six faces of the box. Neighbor distances use the shortest way around on each axis, so flocks can cross a face.
- Without WebGPU the same math runs on the CPU in JavaScript, capped at 1200 agents. The GPU path allows up to 8192.
- Each agent is drawn as two crossed triangles along its velocity. On WebGPU the vertex shader reads the agent from the storage buffer by vertex index.
Source code:boids-3d.shader.tsboids-3d-cpu-physics.tsboids-gpu.strategy.ts
Note Simplifications in this demo:
- Every agent checks every other agent (O(N²)). There is no spatial grid. This is why the GPU is limited to 8192 agents and the CPU path to 1200.
- The world is a wrap-around box: an agent that leaves one face enters at the opposite face, and distances are measured the short way.
- The force constants are tuned by eye, not by physics. Friction is applied per frame, so the look depends slightly on the frame rate.
Drag to rotate the camera, scroll to zoom.
