RUST ยท NAVIGATION & CROWD AI

detour-crowd-rs โ€” Real-Time Crowd Steering & RVO Collision Avoidance in Rust

detour-crowd-rs is a pure Rust port of RecastNavigation's DetourCrowd module for steering thousands of autonomous agents across 3D navigation meshes. It combines spatial hash proximity grids, reciprocal velocity obstacles (RVO), and local path corridors to prevent agent crowding and deadlocks at 60+ FPS.

$ cargo add detour-crowd-rs
GitHub โ†—
Real-Time Browser Engine

Interactive RVO Crowd Simulation Canvas

Watch 120+ autonomous agents navigate dense environments, resolving head-on deadlocks and bottleneck pinch points. Click anywhere to set a new global attractor target, or switch between pre-configured navigational scenarios.

Active Agents
120
Spatial Hash Queries
120 / frame
Avoidance Samples
1,920 / frame
Physical Collisions
0
Engine Framerate
60.0 FPS
Click canvas to set custom Target Goal โ€ข Shift+Click to inject 10 agents
Scenario: Doorway Bottleneck
Agent Population: 120 agents
Max Agent Speed: 3.5 m/s
Avoidance Horizon: 2.5 s
DetourCrowd Architecture

Battle-Tested Steering Algorithms

A pure Rust port of the industry-standard navigation crowd system powering AAA game engines.

RVO & Velocity Space Sampling

Implements Reciprocal Velocity Obstacles (RVO) where agents reciprocally share the avoidance responsibility. Uses adaptive multi-ring polar velocity space sampling matching Recast's dtObstacleAvoidanceQuery to test candidate velocities against dynamic agent circles and static segments.

  • โœ“ Adaptive multi-pattern velocity candidate sampling
  • โœ“ Time-of-impact (TOI) and velocity deviation penalties
  • โœ“ Side preference for emergent two-way lane formation

Spatial Hashing Proximity Grid

Direct port of Recast's dtProximityGrid. Divides continuous 2D space into discrete cell buckets indexed by large prime hashes. Enables \(O(1)\) neighborhood lookup queries, completely avoiding slow \(O(N^2)\) pairwise distance checks across hundreds of crowd members.

  • โœ“ Prime-multiplier continuous coordinate hashing
  • โœ“ Zero heap allocations during neighbor circle queries
  • โœ“ Scales smoothly to 1,000+ active agents

Corridor Tracking & Waypoint Steering

Agents track local navigation corridors and corner sequences with smooth corner advancement. Automatically calculates optimal lookahead targets, prevents cutting corners into walls, and decelerates naturally upon approaching goal destinations.

  • โœ“ Dynamic corner finding and corridor clipping
  • โœ“ Target arrival radius and smooth slowdown
  • โœ“ State machine: Invalid, Waiting, Walking, Active

Boundary Repulsion & Separation Forces

Static line segments (walls, navmesh perimeter borders) apply repulsive steering forces that prevent agents from scraping against obstacles. In addition, soft separation forces prevent unnatural compression and interpenetration in dense bottleneck clusters.

  • โœ“ Static wall segment distance & normal repulsion
  • โœ“ Inverse-distance soft separation force field
  • โœ“ Acceleration limits with inertia integration
Formal Formulations

Mathematical & Algorithmic Foundations

Exact algorithms ported from Recast's DetourCrowd module.

01. Velocity Obstacle Cone
$$VO_B^A = \left\{ v_A \mid \exists t > 0, \; v_A - v_B \in \frac{B \oplus (-A)}{t} \right\}$$

The set of all relative velocities that will result in a collision between agent A and neighbor B within time horizon \(\tau\).

02. Reciprocal Avoidance (RVO)
$$v_A^{\text{new}} = v_A + \frac{1}{2} \left( \hat{v} - (v_A - v_B) \right)$$

Each agent reciprocally takes half the required velocity change to avoid collision, eliminating mutual oscillatory indecision.

03. Candidate Penalty Evaluation
$$\text{Cost}(v) = w_d \|v - v_{\text{pref}}\| + \frac{w_t}{\text{TOI}(v)} + \text{Pen}_{\text{side}}$$

Samples polar candidate velocities and penalizes deviation from desired heading, time-to-impact (TOI), and incorrect passing side.

04. Prime Spatial Hashing
$$h(x, y) = ((x \cdot p_1) \oplus (y \cdot p_2)) \pmod M$$

Maps continuous floating-point coordinates into discrete hash buckets using large primes \(p_1=73856093\), \(p_2=19349663\).

Developer Quickstart

Fast Integration with Rust & Bevy

Create a crowd instance, set boundary segments, add agents, and update at 60 Hz.

Cargo.toml
[dependencies]
detour-crowd-rs = "0.1"
glam = "0.29"
src/main.rs โ€” Crowd Simulation Loop
use glam::Vec2;
use detour_crowd_rs::{Crowd, CrowdAgentParams};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Create crowd for up to 200 agents with 2.5m grid cells
    let mut crowd = Crowd::new(200, 2.5);

    // 2. Add static boundary walls (e.g. corridor or doorway)
    crowd.add_boundary_segment(Vec2::new(-20.0, 2.0), Vec2::new(20.0, 2.0));
    crowd.add_boundary_segment(Vec2::new(-20.0, -2.0), Vec2::new(20.0, -2.0));

    // 3. Spawn opposing agents
    let agent_a = crowd.add_agent(Vec2::new(-15.0, 0.0), CrowdAgentParams::default())?;
    crowd.set_agent_target(agent_a, Vec2::new(15.0, 0.0))?;

    let agent_b = crowd.add_agent(Vec2::new(15.0, 0.0), CrowdAgentParams::default())?;
    crowd.set_agent_target(agent_b, Vec2::new(-15.0, 0.0))?;

    // 4. Update simulation at 60 Hz
    let dt = 1.0 / 60.0;
    for _ in 0..300 {
        crowd.update(dt);
    }

    if let Some(agent) = crowd.agent(agent_a) {
        println!("Agent A arrived near: {:?}", agent.position);
    }

    Ok(())
}

Agent Parameter Configuration

let params = CrowdAgentParams {
    radius: 0.5,           // Agent body radius (m)
    height: 2.0,           // Physical height
    max_acceleration: 8.0, // Acceleration limit (m/sยฒ)
    max_speed: 3.5,        // Desired walking speed (m/s)
    collision_query_range: 8.0, // Neighbor check distance
    separation_weight: 2.0,     // Separation force factor
    avoidance_profile: 0,       // Quality tier index
};

100% Memory Safe & Pure Rust

Recast and Detour are traditionally C++ libraries with raw pointers and manual memory handling. detour-crowd-rs provides idiomatic, safe Rust APIs with zero unsafe blocks in crowd steering logic and full compile-time thread safety.

Performance Benchmarks & Verification

Microsecond Collision Avoidance vs. C++ DetourCrowd

Comparing native Rust SIMD avoidance and spatial hashing against upstream RecastNavigation. View Full BENCHMARKS.md โ†’

โ— 7.6M Queries/sec ยท 224 ยตs Crowd Step
100 Agents Step Latency
224.6 ยตs / step
<1.5% of a 16.6ms 60 FPS frame
Spatial Proximity Grid
7.65M queries/s
130.7 ns zero-allocation hash bucket lookup
Memory Efficiency vs C++
1.8 MB vs 7.8 MB
4.3ร— lower RAM footprint, bounds-checked
tests/agent_tests.rs 2 / 2 PASS
  • ok test_agent_lifecycle_and_target
  • ok test_agent_corridor_corners
tests/avoidance_tests.rs 3 / 3 PASS
  • ok test_avoidance_clear_path
  • ok test_avoidance_head_on_collision
  • ok test_avoidance_static_wall
tests/crowd_tests.rs 4 / 4 PASS
  • ok test_crowd_agent_management
  • ok test_crowd_corridor_walls
  • ok test_crowd_two_agents_crossing
  • ok test_crowd_separation_clustering
tests/proximity_tests.rs 2 / 2 PASS
  • ok test_proximity_insert_and_query
  • ok test_proximity_large_scale
tests/accuracy_test.rs 3 / 3 PASS
  • ok test_geodesic_path_optimality
  • ok test_rvo_head_on_clearance
  • ok test_velocity_clamping