👦🏻

🤖 Swarm Robotics Interactive Simulator

Interactive 3D visualization of swarm robotics algorithms including Reynolds Flocking (boids), Formation Control (circle/line/grid), and Consensus-Based coordination with real-time parameter tuning
7 min read
Tech Stack:
TypeScript
React Three Fiber
Three.js
Leva
Loading 3D scene...

Swarm Robotics Interactive Simulator

An interactive 3D visualization of swarm robotics algorithms featuring Reynolds Flocking (boids), Formation Control, and Consensus-Based coordination. Watch 15-50 robots coordinate autonomously using distributed algorithms with no central controller.

Overview

Swarm robotics studies how large groups of simple robots can exhibit complex collective behaviors through local interactions. Inspired by biological systems like bird flocks, fish schools, and ant colonies, these algorithms enable emergent behaviors without centralized control.

This interactive simulator demonstrates three fundamental approaches to swarm coordination:

  • Reynolds Flocking: Mimics natural flocking behavior through separation, alignment, and cohesion
  • Formation Control: Achieves geometric patterns (circle, line, grid) using proportional feedback
  • Consensus-Based: Coordinates through distributed averaging of positions and velocities

Features

Three Coordination Algorithms

Reynolds Flocking (Boids)

  • Separation: Avoid crowding neighbors
  • Alignment: Match velocity with neighbors
  • Cohesion: Steer toward center of neighbors
  • Optional goal attraction for directed movement

Formation Control

  • Circle: Evenly distributed around a center point
  • Line: Aligned in a single file
  • Grid: Rectangular pattern spacing
  • Proportional control with damping to prevent oscillations

Consensus-Based Coordination

  • Distributed position averaging
  • Velocity synchronization
  • No leader required
  • Convergence to group center

Interactive Features

  • Click-to-Set-Goal: Click ground plane to direct the swarm
  • Real-time Parameter Tuning: Adjust weights, speeds, and convergence rates
  • Communication Visualization: See neighbor connections as green lines
  • Draggable Goal Marker: Move the goal while algorithm runs
  • Live Statistics: Track velocity, neighbors, goal distance, iteration count

Performance Optimizations

  • Device-Adaptive: 50 robots (desktop), 30 (tablet), 15 (mobile)
  • GPU Acceleration: InstancedMesh for single-draw-call rendering
  • Spatial Hashing: O(n) neighbor queries instead of O(n²)
  • Batched Geometry: All communication lines in one buffer

Algorithm Details

Reynolds Flocking (1987)

Craig Reynolds' seminal boids algorithm models natural flocking through three steering behaviors:

Separation Force

F_sep = Σ normalize(pos - neighbor_pos) / distance

Pushes away from neighbors too close (within separation radius).

Alignment Force

F_align = (avg_neighbor_velocity - current_velocity) × weight

Matches velocity direction and speed with nearby neighbors.

Cohesion Force

F_coh = (avg_neighbor_position - current_position) × weight

Steers toward the local center of mass.

Total Force

F_total = w_sep × F_sep + w_align × F_align + w_coh × F_coh

With goal attraction:

F_total += w_goal × normalize(goal - position)

Formation Control

Assigns each robot a target position in the formation and uses proportional control to reach it:

Circle Formation

target = center + radius × [cos(2πi/n), 0, sin(2πi/n)]

Line Formation

target = center + [i × spacing, 0, 0]

Grid Formation

cols = ceil(√n), row = floor(i / cols), col = i % cols
target = center + [col × spacing, 0, row × spacing]

Control Law

F = k × (target - position) - damping × velocity

The damping term prevents overshooting and oscillations.

Consensus-Based Coordination

Implements distributed averaging protocol:

p_new = p + ε × Σ(p_neighbor - p) / |neighbors|
v_new = v + ε × Σ(v_neighbor - v) / |neighbors|

Each robot averages its state with neighbors, leading to group convergence without any robot knowing the group center.

With goal bias:

p_new += k × (goal - p)

Implementation Details

Technology Stack

  • React Three Fiber: Declarative 3D rendering
  • Three.js: WebGL graphics engine
  • TypeScript: Type-safe algorithm implementations
  • Generator Functions: Pausable/steppable execution for animation
  • Leva: Real-time parameter controls
  • Spatial Hashing: Efficient neighbor detection

Generator Pattern

All algorithms use generator functions for frame-by-frame execution:

export function* flockingStep(robots, params, config) { while (true) { // Find neighbors (O(n) spatial hash) const neighborMap = findNeighbors(robots, sensingRadius); // Calculate forces and integrate const updatedRobots = robots.map(robot => { const force = calculateFlockingForce(robot, neighbors); const newVelocity = integrate(robot.velocity, force, dt); const newPosition = integrate(robot.position, newVelocity, dt); return { ...robot, position: newPosition, velocity: newVelocity }; }); yield updatedRobots; } }

This pattern enables:

  • Play/pause/step controls
  • Real-time parameter updates
  • Smooth 60 FPS animation
  • No web worker complexity

Spatial Hashing for Neighbor Queries

Naive neighbor detection is O(n²). For 50 robots checking within a 5-unit radius, that's 2,500 distance calculations per frame at 30 FPS = 75,000 ops/sec.

Solution: Partition space into a grid where cell size = sensing radius.

class SpatialHash { hash(position) { const x = floor(position.x / cellSize); const z = floor(position.z / cellSize); return `${x},${z}`; } query(position, radius) { // Check 9 cells (current + 8 neighbors) return nearbyRobots; } }

This reduces to O(n) since each robot only checks ~9 cells containing ~constant robots.

Rendering Optimization

InstancedMesh renders all robots in a single draw call:

robots.forEach((robot, i) => { tempObject.position.set(...robot.position); tempObject.updateMatrix(); instancedMesh.setMatrixAt(i, tempObject.matrix); const color = getRobotColor(robot.status); instancedMesh.setColorAt(i, color); });

Color-coding by status:

  • Gray: Idle
  • Blue: Moving
  • Green: At goal

Batched Communication Lines use BufferGeometry to render all neighbor connections at once instead of individual line segments.

Controls

Mouse/Touch

  • Drag: Rotate camera view
  • Scroll/Pinch: Zoom in/out
  • Click Ground: Set swarm goal position
  • Drag Goal Marker: Move goal (when paused)
  • Algorithm: Switch between Flocking, Formation, Consensus
  • Play/Pause: Start/stop simulation
  • Reset: Clear goal and reinitialize swarm
  • Speed: Adjust steps per second (1-60)
  • Parameters: Real-time tuning of algorithm weights

Visualization Options

  • Communication Lines: Show/hide neighbor connections
  • Velocity Vectors: Display robot velocities (planned)

Relevance to Robotics

Real-World Applications

Search and Rescue Multiple small drones can cover large areas faster than a single large drone. Flocking keeps them spread out while staying coordinated.

Environmental Monitoring Robot boats or underwater vehicles can survey oceans, lakes, or rivers in formation while maintaining communication range.

Warehouse Automation Fleets of mobile robots coordinate to move inventory without collision, using consensus algorithms for traffic management.

Agricultural Automation Swarms of small robots can monitor crops, applying water or pesticides only where needed, reducing waste.

Construction Multiple robots working together to build structures, like 3D printing or assembly, require precise formation control.

Connections to Other Projects

Astrobee (ISS Robots) While Astrobee robots navigate individually, swarm algorithms could enable multi-robot ISS operations like synchronized inspection or cargo transfer.

Path Planning Swarms need path planning but at a local level—each robot plans simple collision-free motion while the swarm handles global coordination.

Visual SLAM Multi-robot SLAM systems use consensus algorithms to merge individual maps into a shared global map without centralized processing.

Educational Value

This simulator demonstrates:

  1. Emergence: Complex global behavior from simple local rules
  2. Distributed Systems: No central controller required
  3. Local vs Global: Each robot only knows neighbors, yet group coordinates
  4. Trade-offs: Flocking is flexible, formation is precise, consensus converges
  5. Parameter Sensitivity: Small weight changes significantly affect behavior
  6. Scalability: Algorithms work with 5 or 500 robots (hardware permitting)

Try It Yourself

Experiments to Run

Flocking Behavior

  • Set high separation weight: Robots spread out
  • Set high cohesion weight: Tight clustering
  • Set high alignment weight: Synchronized movement
  • Add goal: Watch swarm navigate collectively

Formation Control

  • Switch formations: Circle → Line → Grid
  • Increase scale: Larger formations
  • Adjust convergence rate: Faster/slower reaching formation
  • Move goal while running: Formation follows

Consensus Coordination

  • No goal: Robots converge to center
  • With goal: Balanced convergence + goal pursuit
  • High convergence weight: Faster agreement
  • Multiple starts: Watch distributed averaging

Parameter Exploration

  • What happens with zero separation weight?
  • Can robots get stuck in local minima?
  • How does swarm size affect convergence time?
  • What's the optimal sensing radius?

Technical References

Seminal Papers

  • Reynolds, C. W. (1987). Flocks, herds and schools: A distributed behavioral model. SIGGRAPH.
  • Olfati-Saber, R. (2006). Flocking for multi-agent dynamic systems. IEEE TAC.
  • Fax, J. A., & Murray, R. M. (2004). Information flow and cooperative control. IEEE TAC.

Books

  • Swarm Intelligence by Kennedy & Eberhart (2001)
  • Multi-Robot Systems by Dudek & Jenkin (2010)
  • Introduction to Autonomous Mobile Robots by Siegwart et al. (2011)

Online Resources

Future Enhancements

Planned features for future versions:

Algorithms

  • Obstacle Avoidance: Integrate potential fields or RVO
  • Multi-Target Assignment: Hungarian algorithm for task allocation
  • Leader-Follower: Designated leaders with followers
  • Predator-Prey: Competing swarms simulation

Visualizations

  • 3D Flight: Full 3D movement (not just ground plane)
  • Velocity Vectors: Arrow indicators on each robot
  • Trail History: Show robot paths over time
  • Formation Targets: Visualize target positions

Interactions

  • Multi-Goal: Different subgroups target different goals
  • Dynamic Obstacles: Moving barriers to avoid
  • Robot Failure: Handle communication loss or breakdowns
  • Manual Control: Take direct control of one robot

Performance

  • Web Workers: Off-thread computation for 100+ robots
  • LOD System: Reduce detail for distant robots
  • Instanced Rendering: Even more efficient GPU usage

Technical Notes

Coordinate System

  • X-axis: Left (-) to Right (+)
  • Y-axis: Down (0) to Up (+), robots stay at Y=0
  • Z-axis: Back (-) to Front (+)

Bounds

Default workspace: [-20, 0, -20] to [20, 5, 20] Robots bounce off boundaries with velocity reversal.

Sensing Radius

Default: 5.0 units Robots only communicate with neighbors within this distance.

Time Step

Default: 0.016 seconds (~60 FPS) Integration uses forward Euler: v_new = v + a × dt

Stability

Algorithms are tuned for stability but can diverge with extreme parameters:

  • Too high forces → chaotic oscillations
  • Too low damping → overshoot
  • Zero separation → collisions

If robots behave strangely, click "Reset" to restore defaults.


Note: This is an educational simulator. Real-world swarm robotics systems must handle communication delays, sensor noise, localization errors, and physical constraints not modeled here.

Case Study

Problem

Traditional robotics simulators lack interactive, real-time visualizations of swarm algorithms, making it difficult for students and researchers to understand emergent behaviors and parameter sensitivity.

Solution

Built an interactive 3D web-based simulator using React Three Fiber that allows real-time parameter tuning and visualization of three swarm algorithms: Reynolds Flocking, Formation Control, and Consensus-Based coordination.

Impact

60 FPS
Performance
Maintains smooth rendering with 50+ agents on mobile devices
3
Algorithms
Flocking, Formation Control, and Consensus-Based
15+
Parameters
Live adjustment of algorithm behavior

Timeline

3 months (Jun 2024 - Sep 2024)

Role

Solo Developer & Designer

Technical Challenges

Future Work

Add obstacle avoidance, 3D formations, and export simulation data for analysis.