🐦 Simulation #46 — Emergence & Complex Systems

Boids Flocking Simulation

Three simple local rules — separation, alignment, cohesion — give rise to breathtaking collective behaviour entirely without central coordination.

Preset: Standard
Prey: 150
Predators: 0
Frame: 0
Presets
Flock Parameters
150
25
50
Motion Parameters
50
3.0

The Boids Model

In 1987 Craig Reynolds published Flocks, Herds and Schools: A Distributed Behavioral Model, introducing three deceptively simple steering rules that could reproduce the fluid, coordinated motion seen in bird flocks and fish schools. The boids model became one of computer science's defining demonstrations of emergent behaviour: global order arising from local interactions alone.

Each boid is an autonomous agent with a position and velocity. At every time step it samples the positions and velocities of neighbouring boids within fixed radii and updates its steering accordingly. No boid has global knowledge; no leader exists; yet the flock self-organises.

Separation
Rule 1
Steer away from boids within the collision radius. Prevents crowding and maintains personal space.
Alignment
Rule 2
Steer toward the average heading of local neighbours. Synchronises direction across the flock.
Cohesion
Rule 3
Steer toward the average position of local neighbours. Holds the group together as a coherent flock.
Emergence
O(1)
Each rule is purely local, yet the collective produces splitting, merging, and obstacle avoidance globally.

Mathematical Formulation

Each boid i has position xi and velocity vi. The steering acceleration is a weighted sum of three components:

a_i = w_sep · f_sep(i) + w_ali · f_ali(i) + w_coh · f_coh(i)

Separation Force

Sum of inverse-distance repulsion vectors from boids within radius rsep:

f_sep(i) = Σ_{j∈N_sep(i)} (x_i − x_j) / |x_i − x_j|²

Alignment Force

Steering toward the average normalised velocity of boids within radius rali:

f_ali(i) = (1/|N_ali|) Σ_{j∈N_ali(i)} v_j / |v_j| · v_max − v_i

Cohesion Force

Seek vector toward the centroid of the local neighbourhood within radius rcoh:

f_coh(i) = seek( (1/|N_coh|) Σ_{j∈N_coh(i)} x_j )

All forces are capped by a maximum force magnitude to prevent unrealistic accelerations, and velocities are clamped to [vmin, vmax]. Boids wrap around boundaries (periodic BC), maintaining a toroidal world.

"A flock is not a thing — it is a happening." — Craig Reynolds, 1987. No boid thinks about the flock; they think only about their immediate neighbours.

Presets Explained

PresetNSep (r)Ali (r)Coh (r)Pattern
Standard150255050Natural-looking mixed flocking with fluid sub-flock merging
Tight Flock200156060Dense cohesive ellipsoids; strong alignment dominates
Murmurations300188080Large-scale swirling waves reminiscent of starling displays
Chaotic100302020Weak alignment → turbulent, exploratory motion
Predator150+2255050Red predators chase prey; prey produce panic waves
Sparse50458080Thin, far-ranging lines; long-range alignment without crowding

Emergent Phenomena

A properly tuned Boids simulation reproduces many observed phenomena in natural collectives:

PhenomenonMechanismReal-world observation
Flock splittingObstacle or noise breaks cohesion; groups diverge until cohesion radius failsStarlings splitting around a peregrine falcon
Flock mergingTwo sub-flocks approach cohesion radius; cohesion overcomes separationFish schools merging in open water
Wave motionPerturbation propagates through alignment field at speed > individual boid speedMurmuration "black sun" rolling waves
Predator evasionFlee force overrides cohesion; panic spreads through alignment chainBaitball formation around predatory tuna
Density regulationSeparation provides effective pressure preventing interpenetrationConstant inter-individual distance in pigeon flocks (≈1.1 m)
Leader-free turningSpontaneous symmetry breaking in alignment field triggers collective turnsNo defined leader in any observed natural flock

Swarm Intelligence & Agent-Based Modelling

Boids is a canonical example of swarm intelligence — computation distributed across many autonomous agents. This paradigm underpins:

FieldBoids-inspired methodApplication
RoboticsReynolds rules on differential drive robotsUAV swarm search-and-rescue, warehouse fleets
Computer graphicsOriginal Boids in Batman Returns (1992)Crowd simulation in film and games
OptimisationParticle Swarm Optimisation (PSO, Kennedy & Eberhart 1995)Hyperparameter search, antenna design
TransportVelocity Obstacles for multi-agent planningAutonomous vehicles, pedestrian simulation
BiologySelf-propelled particle models (Vicsek 1995)Cell migration, bacterial colonies
EcologyIBMs with perception radiusPredator-prey spatial dynamics

Computational Implementation

The naive Boids algorithm checks all n² pairs each frame — feasible for small n but 10,000 boids would require 108 distance computations per second. This simulation uses a spatial hash grid: the canvas is divided into cells of side CELL_SIZE. Each boid is inserted into its cell; only boids in neighbouring cells are tested as candidates. This reduces average neighbour lookup to O(n·k) where k is the number of nearby boids — effectively O(n) for uniform distributions.

ApproachBuildQueryOverall (n boids)
Brute forceO(n)O(n²)
Spatial hash gridO(n)O(k)O(n) amortised
k-d treeO(n log n)O(log n + k)O(n log n)
BVH (bounding volume hierarchy)O(n log n)O(log n)O(n log n)

Phase Transitions in Collective Motion

Tamás Vicsek (1995) studied a simpler variant: particles with fixed speed, directions perturbed by noise η. At low η and high density, all particles align (ordered phase). As η increases, the system undergoes a continuous phase transition analogous to ferromagnetic ordering, with order parameter:

φ = (1/Nv_0) | Σ_i v_i | → 1 (ordered), 0 (disordered)

Later work (Chaté et al. 2008) showed the transition is actually discontinuous (first-order) in two dimensions — a subtle result resolving debate about whether flocking belongs to the universality class of the XY model.

Educational Context

LevelConceptsExtensions
GCSE / A-LevelVelocity vectors, Newton's second law, feedbackMeasure average flock speed vs N slider
Undergraduate CSSpatial hash tables, O() analysis, agent-based modellingImplement k-d tree; compare query times
Undergraduate PhysicsVicsek model, order parameter, phase transitionsMeasure φ vs noise and compare with theory
Graduate / ResearchTopological interaction radius (Cavagna 2010), information propagation speedReplace metric radius with topological k-nearest neighbours

Frequently Asked Questions

Why do real flocks avoid obstacles without explicit programming?

Separation and cohesion together act as effective pressure: boids on the flock boundary are pushed outward by cohesion from the interior and pushed inward by separation from the gap. When an obstacle breaks this balance, the gap propagates around the obstacle via the alignment field, causing the flock to flow around it — much like fluid past a cylinder.

What is the Predator mode showing?

Two red predator agents compute a seek force toward the nearest prey boid and move at 1.4× the prey speed. Each prey boid within flee-detection range computes a flee force (reversed seek) that overwhelms its cohesion and alignment forces. The resulting evasion cascades through the alignment field, producing long streaks of escaping prey — a panic wave resembling natural escape responses in fish schools.

How do I get Murmurations-style rolling wave behaviour?

Select the Murmurations preset (N=300, large alignment radius). The large alignment radius means that directional perturbations propagate across the flock faster than the boids themselves travel — just like seen in real European starling murmurations where turn waves travel at ~8 m/s though birds fly at ~6 m/s. Reduce the cohesion slightly or click the canvas to introduce a perturbation and observe how the wave self-amplifies and then damps.

Related Simulations & Articles