diff --git a/astraweave-destruction/src/fracture.rs b/astraweave-destruction/src/fracture.rs index 9c20fb2daa..98ed21bf50 100644 --- a/astraweave-destruction/src/fracture.rs +++ b/astraweave-destruction/src/fracture.rs @@ -184,11 +184,38 @@ mod tests { #[test] fn planar_cut_is_stable() { - let a = planar_children(&parent()); - let b = planar_children(&parent()); + let source = parent(); + let a = planar_children(&source); + let b = planar_children(&source); assert_eq!(a, b); - assert!(a[0].id < a[1].id || a[0].id != a[1].id); - assert_eq!(a[0].mass.saturating_add(a[1].mass), parent().mass); + assert_ne!(a[0].id, a[1].id); + assert_eq!(a[0].id, mix_sim_seed(source.id, 0, SIM_SYSTEM_DESTRUCTION)); + assert_eq!(a[1].id, mix_sim_seed(source.id, 1, SIM_SYSTEM_DESTRUCTION)); + let shift = source.half[0].mul_ratio(1, 2); + assert_eq!(a[0].half[0], shift); + assert_eq!(a[1].half[0], shift); + assert_eq!(a[0].pos[0], source.pos[0].saturating_sub(shift)); + assert_eq!(a[1].pos[0], source.pos[0].saturating_add(shift)); + for axis in 1..3 { + assert_eq!(a[0].pos[axis], source.pos[axis]); + assert_eq!(a[1].pos[axis], source.pos[axis]); + assert_eq!(a[0].half[axis], source.half[axis]); + assert_eq!(a[1].half[axis], source.half[axis]); + } + assert_eq!(a[0].mass, source.mass.mul_ratio(1, 2)); + assert_eq!(a[1].mass, source.mass.saturating_sub(a[0].mass)); + assert_eq!(a[0].mass.saturating_add(a[1].mass), source.mass); + assert_eq!(a[0].flags, source.flags); + assert_eq!(a[1].flags, source.flags); + assert_eq!(a[0].structure, source.structure); + assert_eq!(a[1].structure, source.structure); + assert_eq!(a[0].island, source.island); + assert_eq!(a[1].island, source.island); + } + + #[test] + fn stone_break_strength_is_one_hundred() { + assert_eq!(BreakRule::stone().strength, Fixed64::from_int(100)); } #[test] diff --git a/astraweave-physics/Cargo.toml b/astraweave-physics/Cargo.toml index 52e8d1fea5..13aad5ded8 100644 --- a/astraweave-physics/Cargo.toml +++ b/astraweave-physics/Cargo.toml @@ -71,10 +71,6 @@ harness = false name = "vehicle" harness = false -[[bench]] -name = "destruction" -harness = false - [[bench]] name = "ragdoll" harness = false diff --git a/astraweave-physics/README.md b/astraweave-physics/README.md index bea137a690..eb85c07d36 100644 --- a/astraweave-physics/README.md +++ b/astraweave-physics/README.md @@ -4,7 +4,7 @@ Full-featured physics simulation for AstraWeave, wrapping **Rapier3D 0.22**. ## Overview -Provides rigid body dynamics, character controllers, broadphase spatial hashing, projectiles, ragdolls, vehicles, cloth, gravity zones, wind/water environments, and destructible objects. +Provides rigid body dynamics, character controllers, broadphase spatial hashing, projectiles, ragdolls, vehicles, cloth, and wind/water environments. `break_destructible` only removes a Rapier body. Fracture is `astraweave-destruction`. ## Key Types @@ -17,9 +17,9 @@ Provides rigid body dynamics, character controllers, broadphase spatial hashing, | `Ragdoll` / `RagdollBuilder` | Multi-bone ragdoll creation | | `Vehicle` / `VehicleManager` | Vehicle dynamics with drivetrain | | `ClothManager` | Particle-based cloth with distance constraints | -| `DestructionManager` | Fracture patterns and debris | +| `break_destructible` | Removes a Rapier body. Fracture and debris are `astraweave-destruction` | | `EnvironmentManager` | Wind zones, water volumes, buoyancy | -| `GravityManager` | Composable gravity zones | +| `PhysicsWorld::gravity` | Rapier gravity vector. `gravity.rs` and `GravityManager` are removed (#330) | ## Feature Flags diff --git a/astraweave-physics/benches/destruction.rs b/astraweave-physics/benches/destruction.rs deleted file mode 100644 index c76c1ad35b..0000000000 --- a/astraweave-physics/benches/destruction.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! Destruction System Benchmarks (Phase 8.8) -//! -//! Benchmarks for destruction physics performance. - -use astraweave_physics::destruction::{DestructibleConfig, DestructionManager, FracturePattern}; -use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; -use glam::Vec3; -use std::hint::black_box; - -fn destruction_creation(c: &mut Criterion) { - let mut group = c.benchmark_group("destruction_creation"); - - for debris_count in [4, 8, 16, 32].iter() { - group.throughput(Throughput::Elements(*debris_count as u64)); - group.bench_with_input( - BenchmarkId::from_parameter(debris_count), - debris_count, - |b, &count| { - b.iter(|| { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(count, Vec3::splat(0.5), 10.0), - ..Default::default() - }; - black_box(mgr.add_destructible(config, Vec3::ZERO)) - }); - }, - ); - } - - group.finish(); -} - -fn destruction_apply_damage(c: &mut Criterion) { - let mut group = c.benchmark_group("destruction_damage"); - - for count in [10, 50, 100].iter() { - group.throughput(Throughput::Elements(*count as u64)); - group.bench_with_input(BenchmarkId::from_parameter(count), count, |b, &count| { - let mut mgr = DestructionManager::new(); - let mut ids = Vec::new(); - let config = DestructibleConfig::default(); - - for i in 0..count { - ids.push(mgr.add_destructible(config.clone(), Vec3::new(i as f32, 0.0, 0.0))); - } - - b.iter(|| { - for id in &ids { - mgr.apply_damage(*id, 1.0); - } - black_box(()) - }); - }); - } - - group.finish(); -} - -const GRAVITY: Vec3 = Vec3::new(0.0, -9.81, 0.0); - -fn destruction_update(c: &mut Criterion) { - let mut group = c.benchmark_group("destruction_update"); - let dt = 1.0 / 60.0; - - for count in [10, 50, 100].iter() { - group.throughput(Throughput::Elements(*count as u64)); - group.bench_with_input(BenchmarkId::from_parameter(count), count, |b, &count| { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig::default(); - - for i in 0..count { - mgr.add_destructible(config.clone(), Vec3::new(i as f32, 0.0, 0.0)); - } - - b.iter(|| { - mgr.update(dt, GRAVITY); - black_box(()) - }); - }); - } - - group.finish(); -} - -fn destruction_full_destroy(c: &mut Criterion) { - // Benchmark destroying objects (applying enough damage to trigger destruction) - c.bench_function("destruction_destroy_single", |b| { - b.iter_with_setup( - || { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(8, Vec3::splat(0.5), 10.0), - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - (mgr, id) - }, - |(mut mgr, id)| { - mgr.destroy(id); - mgr.update(1.0 / 60.0, GRAVITY); - black_box(()) - }, - ); - }); -} - -fn destruction_fracture_patterns(c: &mut Criterion) { - let mut group = c.benchmark_group("destruction_patterns"); - - let patterns = [ - ( - "small_4", - FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - ), - ( - "medium_16", - FracturePattern::uniform(16, Vec3::splat(0.5), 10.0), - ), - ( - "large_64", - FracturePattern::uniform(64, Vec3::splat(0.5), 20.0), - ), - ]; - - for (name, pattern) in patterns.iter() { - group.bench_with_input(BenchmarkId::from_parameter(name), pattern, |b, pattern| { - b.iter(|| { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: pattern.clone(), - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - black_box(id) - }); - }); - } - - group.finish(); -} - -fn destruction_many_objects(c: &mut Criterion) { - let mut group = c.benchmark_group("destruction_scale"); - - for count in [100, 500, 1000].iter() { - group.throughput(Throughput::Elements(*count as u64)); - group.bench_with_input(BenchmarkId::from_parameter(count), count, |b, &count| { - b.iter_with_setup( - || { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig::default(); - for i in 0..count { - mgr.add_destructible(config.clone(), Vec3::new(i as f32 * 2.0, 0.0, 0.0)); - } - mgr - }, - |mut mgr| { - mgr.update(1.0 / 60.0, GRAVITY); - black_box(()) - }, - ); - }); - } - - group.finish(); -} - -criterion_group!( - benches, - destruction_creation, - destruction_apply_damage, - destruction_update, - destruction_full_destroy, - destruction_fracture_patterns, - destruction_many_objects, -); -criterion_main!(benches); diff --git a/astraweave-physics/src/destruction.rs b/astraweave-physics/src/destruction.rs deleted file mode 100644 index 61ccc23f8d..0000000000 --- a/astraweave-physics/src/destruction.rs +++ /dev/null @@ -1,2793 +0,0 @@ -//! Destruction System -//! -//! Dormant float manager. The deterministic system is `astraweave-destruction`. -//! This module stays until its tests are moved and the file is deleted. -//! See deferred-failure issue #255. -//! Do not add callers. -//! -//! Provides physics-based destruction for breakable objects: -//! - Pre-fractured mesh system (swap intact → debris) -//! - Structural integrity (health-based breaking) -//! - Debris generation and lifetime -//! - Force-based destruction triggers - -use glam::Vec3; -use std::collections::HashMap; - -/// Unique identifier for destructible objects -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct DestructibleId(pub u64); - -/// Unique identifier for debris pieces -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct DebrisId(pub u64); - -/// Shape of debris pieces -#[derive(Debug, Clone, Copy, PartialEq)] -#[non_exhaustive] -pub enum DebrisShape { - /// Box-shaped debris - Box { half_extents: Vec3 }, - /// Spherical debris - Sphere { radius: f32 }, - /// Convex hull (represented as box for simplicity) - ConvexHull { half_extents: Vec3 }, -} - -impl Default for DebrisShape { - fn default() -> Self { - Self::Box { - half_extents: Vec3::splat(0.2), - } - } -} - -/// Configuration for a debris piece -#[derive(Debug, Clone)] -pub struct DebrisConfig { - /// Shape of the debris - pub shape: DebrisShape, - /// Relative position from object center - pub local_position: Vec3, - /// Mass of debris piece - pub mass: f32, - /// Initial velocity multiplier (from destruction force) - pub velocity_factor: f32, - /// Angular velocity multiplier - pub angular_velocity_factor: f32, - /// Lifetime in seconds (0 = permanent) - pub lifetime: f32, - /// Whether debris can cause secondary destruction - pub can_damage: bool, - /// Damage amount if hits another destructible - pub damage_on_hit: f32, -} - -impl Default for DebrisConfig { - fn default() -> Self { - Self { - shape: DebrisShape::default(), - local_position: Vec3::ZERO, - mass: 1.0, - velocity_factor: 1.0, - angular_velocity_factor: 0.5, - lifetime: 10.0, - can_damage: false, - damage_on_hit: 0.0, - } - } -} - -/// Fracture pattern for pre-fractured meshes -#[derive(Debug, Clone)] -pub struct FracturePattern { - /// Debris pieces that make up this object when broken - pub debris: Vec, - /// Center of mass for the intact object - pub center_of_mass: Vec3, -} - -impl FracturePattern { - /// Create a simple uniform fracture pattern - pub fn uniform(piece_count: usize, object_half_extents: Vec3, mass: f32) -> Self { - let mut debris = Vec::with_capacity(piece_count); - let piece_mass = mass / piece_count as f32; - - // Create a simple grid of debris - let pieces_per_axis = (piece_count as f32).cbrt().ceil() as i32; - let piece_size = object_half_extents * 2.0 / pieces_per_axis as f32; - - for x in 0..pieces_per_axis { - for y in 0..pieces_per_axis { - for z in 0..pieces_per_axis { - if debris.len() >= piece_count { - break; - } - - let local_pos = Vec3::new( - (x as f32 + 0.5) * piece_size.x - object_half_extents.x, - (y as f32 + 0.5) * piece_size.y - object_half_extents.y, - (z as f32 + 0.5) * piece_size.z - object_half_extents.z, - ); - - debris.push(DebrisConfig { - shape: DebrisShape::Box { - half_extents: piece_size * 0.4, - }, - local_position: local_pos, - mass: piece_mass, - ..Default::default() - }); - } - } - } - - Self { - debris, - center_of_mass: Vec3::ZERO, - } - } - - /// Create a radial fracture pattern (for explosions) - pub fn radial(piece_count: usize, radius: f32, mass: f32) -> Self { - let mut debris = Vec::with_capacity(piece_count); - let piece_mass = mass / piece_count as f32; - - // Golden angle distribution for even spacing - let golden_angle = std::f32::consts::PI * (3.0 - (5.0_f32).sqrt()); - - for i in 0..piece_count { - let t = i as f32 / piece_count as f32; - let inclination = (1.0 - 2.0 * t).acos(); - let azimuth = golden_angle * i as f32; - - let local_pos = Vec3::new( - inclination.sin() * azimuth.cos() * radius * 0.8, - inclination.cos() * radius * 0.8, - inclination.sin() * azimuth.sin() * radius * 0.8, - ); - - debris.push(DebrisConfig { - shape: DebrisShape::Sphere { - radius: radius * 0.15, - }, - local_position: local_pos, - mass: piece_mass, - velocity_factor: 1.5, // Radial patterns fly outward faster - ..Default::default() - }); - } - - Self { - debris, - center_of_mass: Vec3::ZERO, - } - } - - /// Create a layered fracture pattern (for walls) - pub fn layered(layers: usize, pieces_per_layer: usize, half_extents: Vec3, mass: f32) -> Self { - let total_pieces = layers * pieces_per_layer; - let mut debris = Vec::with_capacity(total_pieces); - let piece_mass = mass / total_pieces as f32; - - let layer_height = half_extents.y * 2.0 / layers as f32; - - for layer in 0..layers { - let y = (layer as f32 + 0.5) * layer_height - half_extents.y; - - for piece in 0..pieces_per_layer { - let angle = piece as f32 * std::f32::consts::TAU / pieces_per_layer as f32; - let x = angle.cos() * half_extents.x * 0.7; - let z = angle.sin() * half_extents.z * 0.7; - - debris.push(DebrisConfig { - shape: DebrisShape::Box { - half_extents: Vec3::new( - half_extents.x * 0.3, - layer_height * 0.4, - half_extents.z * 0.3, - ), - }, - local_position: Vec3::new(x, y, z), - mass: piece_mass, - ..Default::default() - }); - } - } - - Self { - debris, - center_of_mass: Vec3::ZERO, - } - } -} - -/// Destruction trigger type -#[derive(Debug, Clone, Copy, PartialEq)] -#[non_exhaustive] -pub enum DestructionTrigger { - /// Destroy when force exceeds threshold - Force { threshold: f32 }, - /// Destroy when health reaches zero - Health, - /// Destroy on any collision - Collision, - /// Manual destruction only - Manual, -} - -impl Default for DestructionTrigger { - fn default() -> Self { - Self::Force { threshold: 1000.0 } - } -} - -/// Configuration for a destructible object -#[derive(Debug, Clone)] -pub struct DestructibleConfig { - /// Fracture pattern (debris layout) - pub fracture_pattern: FracturePattern, - /// How destruction is triggered - pub trigger: DestructionTrigger, - /// Maximum health (for Health trigger) - pub max_health: f32, - /// Minimum force to deal damage - pub damage_threshold: f32, - /// Force-to-damage conversion factor - pub force_to_damage: f32, - /// Explosion force when destroyed - pub destruction_force: f32, - /// Sound effect ID (for audio integration) - pub destruction_sound: Option, - /// Particle effect ID (for VFX integration) - pub destruction_particles: Option, -} - -impl Default for DestructibleConfig { - fn default() -> Self { - Self { - fracture_pattern: FracturePattern::uniform(8, Vec3::splat(0.5), 10.0), - trigger: DestructionTrigger::default(), - max_health: 100.0, - damage_threshold: 10.0, - force_to_damage: 0.1, - destruction_force: 5.0, - destruction_sound: None, - destruction_particles: None, - } - } -} - -/// State of a destructible object -#[derive(Debug, Clone, Copy, PartialEq)] -#[non_exhaustive] -pub enum DestructibleState { - /// Object is intact - Intact, - /// Object is damaged but functional - Damaged, - /// Object is being destroyed (playing animation/effects) - Destroying, - /// Object has been destroyed - Destroyed, -} - -/// Runtime data for a destructible object -#[derive(Debug, Clone)] -pub struct Destructible { - pub id: DestructibleId, - pub config: DestructibleConfig, - pub state: DestructibleState, - /// Current health - pub health: f32, - /// World position - pub position: Vec3, - /// Accumulated force this frame - pub accumulated_force: f32, - /// Body ID in physics world (if any) - pub body_id: Option, -} - -impl Destructible { - /// Create a new destructible - pub fn new(id: DestructibleId, config: DestructibleConfig, position: Vec3) -> Self { - Self { - id, - health: config.max_health, - config, - state: DestructibleState::Intact, - position, - accumulated_force: 0.0, - body_id: None, - } - } - - /// Apply damage to the object - pub fn apply_damage(&mut self, damage: f32) { - if self.state != DestructibleState::Intact && self.state != DestructibleState::Damaged { - return; - } - - self.health = (self.health - damage).max(0.0); - - if self.health <= 0.0 { - self.state = DestructibleState::Destroying; - } else if self.health < self.config.max_health * 0.5 { - self.state = DestructibleState::Damaged; - } - } - - /// Apply force to the object - pub fn apply_force(&mut self, force: f32) { - self.accumulated_force += force; - - // Check force threshold trigger - if let DestructionTrigger::Force { threshold } = self.config.trigger { - if self.accumulated_force >= threshold { - self.state = DestructibleState::Destroying; - } - } - - // Apply force-based damage for Health trigger - if matches!(self.config.trigger, DestructionTrigger::Health) - && force >= self.config.damage_threshold - { - let damage = (force - self.config.damage_threshold) * self.config.force_to_damage; - self.apply_damage(damage); - } - } - - /// Handle collision - pub fn on_collision(&mut self, impact_force: f32) { - if let DestructionTrigger::Collision = self.config.trigger { - self.state = DestructibleState::Destroying; - } else { - self.apply_force(impact_force); - } - } - - /// Manually trigger destruction - pub fn destroy(&mut self) { - self.state = DestructibleState::Destroying; - } - - /// Check if object should spawn debris - pub fn should_spawn_debris(&self) -> bool { - self.state == DestructibleState::Destroying - } - - /// Mark destruction as complete - pub fn complete_destruction(&mut self) { - self.state = DestructibleState::Destroyed; - } - - /// Reset accumulated force (call at end of frame) - pub fn reset_frame(&mut self) { - self.accumulated_force = 0.0; - } - - /// Get health percentage - pub fn health_percent(&self) -> f32 { - self.health / self.config.max_health - } - - /// Check if destroyed - pub fn is_destroyed(&self) -> bool { - self.state == DestructibleState::Destroyed - } -} - -/// Active debris piece in the world -#[derive(Debug, Clone)] -pub struct Debris { - pub id: DebrisId, - /// Source destructible ID - pub source: DestructibleId, - pub config: DebrisConfig, - /// World position - pub position: Vec3, - /// Linear velocity - pub velocity: Vec3, - /// Angular velocity - pub angular_velocity: Vec3, - /// Time alive - pub age: f32, - /// Physics body ID (if any) - pub body_id: Option, -} - -impl Debris { - /// Create new debris - pub fn new( - id: DebrisId, - source: DestructibleId, - config: DebrisConfig, - position: Vec3, - velocity: Vec3, - ) -> Self { - Self { - id, - source, - config, - position, - velocity, - angular_velocity: Vec3::ZERO, - age: 0.0, - body_id: None, - } - } - - /// Update debris (if not physics-driven) - pub fn update(&mut self, dt: f32, gravity: Vec3) { - self.age += dt; - - // Simple physics if not driven by physics engine - if self.body_id.is_none() { - self.velocity += gravity * dt; - self.position += self.velocity * dt; - } - } - - /// Check if debris should be removed - pub fn should_remove(&self) -> bool { - self.config.lifetime > 0.0 && self.age >= self.config.lifetime - } -} - -/// Destruction event for callbacks -#[derive(Debug, Clone)] -pub struct DestructionEvent { - /// ID of destroyed object - pub destructible_id: DestructibleId, - /// Position of destruction - pub position: Vec3, - /// Force that caused destruction - pub force: f32, - /// Direction of force - pub force_direction: Vec3, - /// Number of debris spawned - pub debris_count: usize, -} - -/// Manager for destruction system -#[derive(Debug, Default)] -pub struct DestructionManager { - destructibles: HashMap, - debris: HashMap, - pending_events: Vec, - next_destructible_id: u64, - next_debris_id: u64, - /// Maximum active debris pieces - pub max_debris: usize, - /// Default debris lifetime - pub default_debris_lifetime: f32, -} - -impl DestructionManager { - /// Create a new destruction manager - pub fn new() -> Self { - Self { - destructibles: HashMap::new(), - debris: HashMap::new(), - pending_events: Vec::new(), - next_destructible_id: 1, - next_debris_id: 1, - max_debris: 500, - default_debris_lifetime: 10.0, - } - } - - // === Destructible Management === - - /// Add a destructible object - pub fn add_destructible( - &mut self, - config: DestructibleConfig, - position: Vec3, - ) -> DestructibleId { - let id = DestructibleId(self.next_destructible_id); - self.next_destructible_id += 1; - self.destructibles - .insert(id, Destructible::new(id, config, position)); - id - } - - /// Remove a destructible (and its debris) - pub fn remove_destructible(&mut self, id: DestructibleId) -> bool { - // Remove associated debris - self.debris.retain(|_, d| d.source != id); - self.destructibles.remove(&id).is_some() - } - - /// Get a destructible - pub fn get(&self, id: DestructibleId) -> Option<&Destructible> { - self.destructibles.get(&id) - } - - /// Get a mutable destructible - pub fn get_mut(&mut self, id: DestructibleId) -> Option<&mut Destructible> { - self.destructibles.get_mut(&id) - } - - /// Apply damage to a destructible - pub fn apply_damage(&mut self, id: DestructibleId, damage: f32) { - if let Some(dest) = self.destructibles.get_mut(&id) { - dest.apply_damage(damage); - } - } - - /// Apply force to a destructible - pub fn apply_force(&mut self, id: DestructibleId, force: f32) { - if let Some(dest) = self.destructibles.get_mut(&id) { - dest.apply_force(force); - } - } - - /// Handle collision for a destructible - pub fn on_collision(&mut self, id: DestructibleId, impact_force: f32) { - if let Some(dest) = self.destructibles.get_mut(&id) { - dest.on_collision(impact_force); - } - } - - /// Manually destroy an object - pub fn destroy(&mut self, id: DestructibleId) { - if let Some(dest) = self.destructibles.get_mut(&id) { - dest.destroy(); - } - } - - // === Debris Management === - - /// Get debris by ID - pub fn get_debris(&self, id: DebrisId) -> Option<&Debris> { - self.debris.get(&id) - } - - /// Iterate over all debris - pub fn debris_iter(&self) -> impl Iterator { - self.debris.values() - } - - /// Spawn debris for a destructible - fn spawn_debris(&mut self, dest: &Destructible, force_direction: Vec3) -> Vec { - let mut spawned = Vec::new(); - - // Respect debris limit - let available_slots = self.max_debris.saturating_sub(self.debris.len()); - let debris_to_spawn = dest - .config - .fracture_pattern - .debris - .len() - .min(available_slots); - - for debris_config in dest - .config - .fracture_pattern - .debris - .iter() - .take(debris_to_spawn) - { - let id = DebrisId(self.next_debris_id); - self.next_debris_id += 1; - - // Calculate debris world position - let position = dest.position + debris_config.local_position; - - // Calculate initial velocity (outward from center + force direction) - let outward = debris_config.local_position.normalize_or_zero(); - let velocity = (outward * dest.config.destruction_force - + force_direction * dest.config.destruction_force * 0.5) - * debris_config.velocity_factor; - - let mut debris = Debris::new(id, dest.id, debris_config.clone(), position, velocity); - - // Random angular velocity - debris.angular_velocity = Vec3::new( - (id.0 as f32 * 1.234).sin() * 5.0, - (id.0 as f32 * 2.345).sin() * 5.0, - (id.0 as f32 * 3.456).sin() * 5.0, - ) * debris_config.angular_velocity_factor; - - self.debris.insert(id, debris); - spawned.push(id); - } - - spawned - } - - // === Update === - - /// Update the destruction system - pub fn update(&mut self, dt: f32, gravity: Vec3) { - // Process destructibles that need debris spawning - let mut to_process = Vec::new(); - for (id, dest) in &self.destructibles { - if dest.should_spawn_debris() { - to_process.push(*id); - } - } - - for id in to_process { - if let Some(dest) = self.destructibles.get(&id) { - // Clone needed data before mutable borrow - let position = dest.position; - let force = dest.accumulated_force; - let dest_clone = dest.clone(); - - // Spawn debris - let debris_ids = self.spawn_debris(&dest_clone, Vec3::Y); // Default upward force direction - - // Create event - self.pending_events.push(DestructionEvent { - destructible_id: id, - position, - force, - force_direction: Vec3::Y, - debris_count: debris_ids.len(), - }); - } - - // Mark as destroyed - if let Some(dest) = self.destructibles.get_mut(&id) { - dest.complete_destruction(); - } - } - - // Update debris - for debris in self.debris.values_mut() { - debris.update(dt, gravity); - } - - // Remove expired debris - self.debris.retain(|_, d| !d.should_remove()); - - // Reset frame state for destructibles - for dest in self.destructibles.values_mut() { - dest.reset_frame(); - } - } - - /// Take pending destruction events - pub fn take_events(&mut self) -> Vec { - std::mem::take(&mut self.pending_events) - } - - /// Get counts - pub fn destructible_count(&self) -> usize { - self.destructibles.len() - } - - pub fn debris_count(&self) -> usize { - self.debris.len() - } - - pub fn active_debris_count(&self) -> usize { - self.debris.values().filter(|d| !d.should_remove()).count() - } - - /// Clean up destroyed destructibles - pub fn cleanup_destroyed(&mut self) { - self.destructibles.retain(|_, d| !d.is_destroyed()); - } -} - -// ============================================================================ -// Unit Tests -// ============================================================================ - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_destructible_creation() { - let config = DestructibleConfig::default(); - let dest = Destructible::new(DestructibleId(1), config.clone(), Vec3::ZERO); - - assert_eq!(dest.state, DestructibleState::Intact); - assert_eq!(dest.health, config.max_health); - } - - #[test] - fn test_damage_application() { - let config = DestructibleConfig { - max_health: 100.0, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - dest.apply_damage(30.0); - assert_eq!(dest.health, 70.0); - assert_eq!(dest.state, DestructibleState::Intact); - - dest.apply_damage(30.0); - assert_eq!(dest.health, 40.0); - assert_eq!(dest.state, DestructibleState::Damaged); - - dest.apply_damage(50.0); - assert_eq!(dest.health, 0.0); - assert_eq!(dest.state, DestructibleState::Destroying); - } - - #[test] - fn test_force_trigger() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Force { threshold: 100.0 }, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - dest.apply_force(50.0); - assert_eq!(dest.state, DestructibleState::Intact); - - dest.apply_force(60.0); - assert_eq!(dest.state, DestructibleState::Destroying); - } - - #[test] - fn test_collision_trigger() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Collision, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - dest.on_collision(1.0); - assert_eq!(dest.state, DestructibleState::Destroying); - } - - #[test] - fn test_manual_destruction() { - let mut dest = - Destructible::new(DestructibleId(1), DestructibleConfig::default(), Vec3::ZERO); - - dest.destroy(); - assert_eq!(dest.state, DestructibleState::Destroying); - } - - #[test] - fn test_health_percent() { - let config = DestructibleConfig { - max_health: 200.0, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - assert_eq!(dest.health_percent(), 1.0); - dest.apply_damage(100.0); - assert_eq!(dest.health_percent(), 0.5); - } - - #[test] - fn test_uniform_fracture_pattern() { - let pattern = FracturePattern::uniform(8, Vec3::splat(1.0), 10.0); - - assert_eq!(pattern.debris.len(), 8); - - let total_mass: f32 = pattern.debris.iter().map(|d| d.mass).sum(); - assert!( - (total_mass - 10.0).abs() < 0.01, - "Total mass should be preserved" - ); - } - - #[test] - fn test_radial_fracture_pattern() { - let pattern = FracturePattern::radial(20, 2.0, 5.0); - - assert_eq!(pattern.debris.len(), 20); - } - - #[test] - fn test_layered_fracture_pattern() { - let pattern = FracturePattern::layered(3, 4, Vec3::new(2.0, 3.0, 2.0), 12.0); - - assert_eq!(pattern.debris.len(), 12); // 3 layers × 4 pieces - } - - #[test] - fn test_debris_lifetime() { - let config = DebrisConfig { - lifetime: 5.0, - ..Default::default() - }; - let mut debris = Debris::new( - DebrisId(1), - DestructibleId(1), - config, - Vec3::ZERO, - Vec3::ZERO, - ); - - assert!(!debris.should_remove()); - - debris.update(3.0, Vec3::ZERO); - assert!(!debris.should_remove()); - - debris.update(3.0, Vec3::ZERO); - assert!(debris.should_remove()); - } - - #[test] - fn test_permanent_debris() { - let config = DebrisConfig { - lifetime: 0.0, // Permanent - ..Default::default() - }; - let mut debris = Debris::new( - DebrisId(1), - DestructibleId(1), - config, - Vec3::ZERO, - Vec3::ZERO, - ); - - debris.update(100.0, Vec3::ZERO); - assert!(!debris.should_remove()); - } - - #[test] - fn test_destruction_manager_add_remove() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible(DestructibleConfig::default(), Vec3::ZERO); - assert_eq!(manager.destructible_count(), 1); - - assert!(manager.get(id).is_some()); - assert!(manager.remove_destructible(id)); - assert_eq!(manager.destructible_count(), 0); - } - - #[test] - fn test_destruction_spawns_debris() { - let mut manager = DestructionManager::new(); - - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(5, Vec3::splat(0.5), 5.0), - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - - // Update to process destruction - manager.update(0.016, Vec3::new(0.0, -9.81, 0.0)); - - assert_eq!(manager.debris_count(), 5); - - // Check events were generated - let events = manager.take_events(); - assert_eq!(events.len(), 1); - assert_eq!(events[0].debris_count, 5); - } - - #[test] - fn test_debris_limit() { - let mut manager = DestructionManager::new(); - manager.max_debris = 3; - - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(10, Vec3::splat(0.5), 10.0), - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - // Should only spawn up to max_debris - assert_eq!(manager.debris_count(), 3); - } - - #[test] - fn test_debris_cleanup() { - let mut manager = DestructionManager::new(); - - let config = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![DebrisConfig { - lifetime: 0.5, - ..Default::default() - }], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - assert_eq!(manager.debris_count(), 1); - - // Age debris past lifetime - manager.update(1.0, Vec3::ZERO); - assert_eq!(manager.debris_count(), 0); - } - - #[test] - fn test_cleanup_destroyed() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible( - DestructibleConfig { - trigger: DestructionTrigger::Manual, - fracture_pattern: FracturePattern { - debris: vec![], - center_of_mass: Vec3::ZERO, - }, - ..Default::default() - }, - Vec3::ZERO, - ); - - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - assert_eq!(manager.destructible_count(), 1); - manager.cleanup_destroyed(); - assert_eq!(manager.destructible_count(), 0); - } - - #[test] - fn test_debris_gravity() { - let config = DebrisConfig::default(); - let mut debris = Debris::new( - DebrisId(1), - DestructibleId(1), - config, - Vec3::new(0.0, 10.0, 0.0), - Vec3::ZERO, - ); - - let gravity = Vec3::new(0.0, -9.81, 0.0); - debris.update(1.0, gravity); - - // Should have fallen - assert!(debris.position.y < 10.0); - assert!(debris.velocity.y < 0.0); - } - - // ============================================================================ - // CHAIN REACTION TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_damaging_debris_flag() { - let config = DebrisConfig { - can_damage: true, - damage_on_hit: 25.0, - ..Default::default() - }; - - assert!(config.can_damage); - assert_eq!(config.damage_on_hit, 25.0); - } - - #[test] - fn test_multiple_destructibles_independent() { - let mut manager = DestructionManager::new(); - - let id1 = manager.add_destructible(DestructibleConfig::default(), Vec3::ZERO); - let id2 = - manager.add_destructible(DestructibleConfig::default(), Vec3::new(10.0, 0.0, 0.0)); - - manager.apply_damage(id1, 1000.0); - manager.update(0.016, Vec3::ZERO); - - // id1 should be destroyed, id2 should be intact - let d1 = manager.get(id1).unwrap(); - let d2 = manager.get(id2).unwrap(); - - assert_eq!(d1.state, DestructibleState::Destroyed); - assert_eq!(d2.state, DestructibleState::Intact); - } - - #[test] - fn test_sequential_destruction() { - let mut manager = DestructionManager::new(); - - let ids: Vec<_> = (0..5) - .map(|i| { - manager.add_destructible( - DestructibleConfig { - trigger: DestructionTrigger::Manual, - fracture_pattern: FracturePattern::uniform(2, Vec3::splat(0.5), 1.0), - ..Default::default() - }, - Vec3::new(i as f32 * 2.0, 0.0, 0.0), - ) - }) - .collect(); - - // Destroy all in sequence - for id in &ids { - manager.destroy(*id); - } - - manager.update(0.016, Vec3::ZERO); - - assert_eq!(manager.debris_count(), 10); // 5 objects × 2 debris each - - let events = manager.take_events(); - assert_eq!(events.len(), 5); - } - - // ============================================================================ - // STRESS PROPAGATION TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_incremental_force_accumulation() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Force { threshold: 100.0 }, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - // Apply force in small increments - for _ in 0..10 { - dest.apply_force(10.0); - } - - assert_eq!(dest.accumulated_force, 100.0); - assert_eq!(dest.state, DestructibleState::Destroying); - } - - #[test] - fn test_force_reset_between_frames() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Force { threshold: 100.0 }, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - dest.apply_force(50.0); - dest.reset_frame(); - - assert_eq!(dest.accumulated_force, 0.0); - - // Object should still be intact after reset - assert_eq!(dest.state, DestructibleState::Intact); - } - - #[test] - fn test_health_trigger_force_conversion() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Health, - max_health: 100.0, - damage_threshold: 10.0, - force_to_damage: 0.5, // 50% of excess force becomes damage - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - // Force of 30, threshold 10, so 20 excess × 0.5 = 10 damage - dest.apply_force(30.0); - assert_eq!(dest.health, 90.0); - } - - #[test] - fn test_sub_threshold_force_no_damage() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Health, - max_health: 100.0, - damage_threshold: 50.0, - force_to_damage: 1.0, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - dest.apply_force(49.0); - assert_eq!(dest.health, 100.0); // No damage, below threshold - } - - // ============================================================================ - // DEBRIS PHYSICS TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_debris_initial_velocity() { - let mut manager = DestructionManager::new(); - - let config = DestructibleConfig { - fracture_pattern: FracturePattern::radial(8, 1.0, 4.0), - trigger: DestructionTrigger::Manual, - destruction_force: 10.0, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.001, Vec3::ZERO); - - // Check debris has non-zero velocity - for debris in manager.debris_iter() { - assert!( - debris.velocity.length() > 0.0, - "Debris should have initial velocity" - ); - } - } - - #[test] - fn test_debris_angular_velocity() { - let mut manager = DestructionManager::new(); - - let debris_config = DebrisConfig { - angular_velocity_factor: 2.0, - ..Default::default() - }; - - let config = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![debris_config], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.001, Vec3::ZERO); - - let debris = manager.debris_iter().next().unwrap(); - assert!( - debris.angular_velocity.length() > 0.0, - "Debris should have angular velocity" - ); - } - - #[test] - fn test_debris_position_from_local_offset() { - let mut manager = DestructionManager::new(); - - let debris_config = DebrisConfig { - local_position: Vec3::new(5.0, 0.0, 0.0), - ..Default::default() - }; - - let config = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![debris_config], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::new(10.0, 0.0, 0.0)); - manager.destroy(id); - manager.update(0.001, Vec3::ZERO); - - let debris = manager.debris_iter().next().unwrap(); - // Position should be destructible position + local offset - assert!((debris.position.x - 15.0).abs() < 0.01); - } - - // ============================================================================ - // EDGE CASE TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_zero_health_destructible() { - let config = DestructibleConfig { - max_health: 0.0, - ..Default::default() - }; - let dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - // health_percent with max_health 0 should handle gracefully - // (NaN or 0 depending on implementation) - let pct = dest.health_percent(); - assert!(pct.is_nan() || pct == 0.0 || pct == 1.0); - } - - #[test] - fn test_empty_fracture_pattern() { - let pattern = FracturePattern { - debris: vec![], - center_of_mass: Vec3::ZERO, - }; - - let mut manager = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: pattern, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - assert_eq!(manager.debris_count(), 0); - } - - #[test] - fn test_negative_damage() { - let mut dest = Destructible::new( - DestructibleId(1), - DestructibleConfig { - max_health: 100.0, - ..Default::default() - }, - Vec3::ZERO, - ); - - dest.apply_damage(-50.0); // Negative damage (healing?) - - // Implementation should allow this (health goes up) - // or clamp to max health - assert!(dest.health >= 100.0 && dest.health <= 150.0); - } - - #[test] - fn test_destroyed_ignores_damage() { - let mut dest = - Destructible::new(DestructibleId(1), DestructibleConfig::default(), Vec3::ZERO); - - dest.destroy(); - dest.complete_destruction(); - - let health_before = dest.health; - dest.apply_damage(50.0); - - // Destroyed objects should ignore damage - assert_eq!(dest.health, health_before); - } - - #[test] - fn test_destroying_state_ignores_damage() { - let mut dest = - Destructible::new(DestructibleId(1), DestructibleConfig::default(), Vec3::ZERO); - - dest.destroy(); // Now in Destroying state - - let health_before = dest.health; - dest.apply_damage(50.0); - - // Destroying objects should also ignore damage - assert_eq!(dest.health, health_before); - } - - // ============================================================================ - // DEFAULT CONFIG TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_debris_shape_default() { - let shape = DebrisShape::default(); - if let DebrisShape::Box { half_extents } = shape { - assert_eq!(half_extents, Vec3::splat(0.2)); - } else { - panic!("Default debris shape should be Box"); - } - } - - #[test] - fn test_debris_config_default() { - let config = DebrisConfig::default(); - - assert_eq!(config.mass, 1.0); - assert_eq!(config.velocity_factor, 1.0); - assert_eq!(config.angular_velocity_factor, 0.5); - assert_eq!(config.lifetime, 10.0); - assert!(!config.can_damage); - assert_eq!(config.damage_on_hit, 0.0); - } - - #[test] - fn test_destructible_config_default() { - let config = DestructibleConfig::default(); - - assert_eq!(config.max_health, 100.0); - assert_eq!(config.damage_threshold, 10.0); - assert_eq!(config.force_to_damage, 0.1); - assert_eq!(config.destruction_force, 5.0); - assert!(config.destruction_sound.is_none()); - assert!(config.destruction_particles.is_none()); - } - - #[test] - fn test_destruction_trigger_default() { - let trigger = DestructionTrigger::default(); - if let DestructionTrigger::Force { threshold } = trigger { - assert_eq!(threshold, 1000.0); - } else { - panic!("Default trigger should be Force"); - } - } - - // ============================================================================ - // MANAGER TESTS (Phase 8.8 - New) - // ============================================================================ - - #[test] - fn test_manager_get_nonexistent() { - let manager = DestructionManager::new(); - assert!(manager.get(DestructibleId(999)).is_none()); - } - - #[test] - fn test_manager_remove_nonexistent() { - let mut manager = DestructionManager::new(); - assert!(!manager.remove_destructible(DestructibleId(999))); - } - - #[test] - fn test_manager_apply_damage_nonexistent() { - let mut manager = DestructionManager::new(); - // Should not panic - manager.apply_damage(DestructibleId(999), 50.0); - } - - #[test] - fn test_manager_apply_force_nonexistent() { - let mut manager = DestructionManager::new(); - // Should not panic - manager.apply_force(DestructibleId(999), 100.0); - } - - #[test] - fn test_manager_on_collision_nonexistent() { - let mut manager = DestructionManager::new(); - // Should not panic - manager.on_collision(DestructibleId(999), 50.0); - } - - #[test] - fn test_manager_destroy_nonexistent() { - let mut manager = DestructionManager::new(); - // Should not panic - manager.destroy(DestructibleId(999)); - } - - #[test] - fn test_manager_get_debris_nonexistent() { - let manager = DestructionManager::new(); - assert!(manager.get_debris(DebrisId(999)).is_none()); - } - - #[test] - fn test_manager_default_limits() { - let manager = DestructionManager::new(); - assert_eq!(manager.max_debris, 500); - assert_eq!(manager.default_debris_lifetime, 10.0); - } - - #[test] - fn test_active_debris_count() { - let mut manager = DestructionManager::new(); - - let config = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![ - DebrisConfig { - lifetime: 1.0, - ..Default::default() - }, - DebrisConfig { - lifetime: 10.0, - ..Default::default() - }, - ], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - assert_eq!(manager.active_debris_count(), 2); - - // Age past first debris lifetime - manager.update(2.0, Vec3::ZERO); - assert_eq!(manager.debris_count(), 1); // One removed - } - - // ═══════════════════════════════════════════════════════════════ - // DEEP REMEDIATION v3.6 — destruction system tests - // ═══════════════════════════════════════════════════════════════ - - #[test] - fn mutation_uniform_piece_count_exact() { - let pattern = FracturePattern::uniform(8, Vec3::splat(1.0), 100.0); - assert_eq!(pattern.debris.len(), 8, "Should have exactly 8 pieces"); - } - - #[test] - fn mutation_uniform_mass_conservation() { - let total_mass = 120.0; - let count = 6; - let pattern = FracturePattern::uniform(count, Vec3::splat(2.0), total_mass); - let sum: f32 = pattern.debris.iter().map(|d| d.mass).sum(); - assert!( - (sum - total_mass).abs() < 0.01, - "Total debris mass {} should equal input mass {}", - sum, - total_mass - ); - // Each piece should have equal mass - for d in &pattern.debris { - assert!( - (d.mass - total_mass / count as f32).abs() < 0.01, - "Each piece should have mass {}, got {}", - total_mass / count as f32, - d.mass - ); - } - } - - #[test] - fn mutation_uniform_grid_positions_bounded() { - let he = Vec3::new(2.0, 3.0, 1.0); - let pattern = FracturePattern::uniform(27, he, 50.0); - for d in &pattern.debris { - assert!( - d.local_position.x.abs() <= he.x + 0.01, - "X {} out of bounds ±{}", - d.local_position.x, - he.x - ); - assert!( - d.local_position.y.abs() <= he.y + 0.01, - "Y {} out of bounds ±{}", - d.local_position.y, - he.y - ); - assert!( - d.local_position.z.abs() <= he.z + 0.01, - "Z {} out of bounds ±{}", - d.local_position.z, - he.z - ); - } - } - - #[test] - fn mutation_radial_piece_count_and_mass() { - let pattern = FracturePattern::radial(20, 5.0, 80.0); - assert_eq!(pattern.debris.len(), 20); - let sum: f32 = pattern.debris.iter().map(|d| d.mass).sum(); - assert!( - (sum - 80.0).abs() < 0.01, - "Radial mass sum {} should be 80", - sum - ); - } - - #[test] - fn mutation_radial_positions_within_radius() { - let radius = 3.0; - let pattern = FracturePattern::radial(30, radius, 50.0); - for d in &pattern.debris { - let dist = d.local_position.length(); - assert!( - dist <= radius, - "Piece at dist {} should be within radius {}", - dist, - radius - ); - } - } - - #[test] - fn mutation_radial_velocity_factor() { - let pattern = FracturePattern::radial(5, 2.0, 10.0); - for d in &pattern.debris { - assert!( - (d.velocity_factor - 1.5).abs() < 1e-6, - "Radial velocity_factor should be 1.5, got {}", - d.velocity_factor - ); - } - } - - #[test] - fn mutation_layered_count_exact() { - let layers = 4; - let per_layer = 6; - let pattern = FracturePattern::layered(layers, per_layer, Vec3::new(2.0, 5.0, 2.0), 100.0); - assert_eq!( - pattern.debris.len(), - layers * per_layer, - "Should have {} total pieces", - layers * per_layer - ); - } - - #[test] - fn mutation_layered_mass_conservation() { - let total = 200.0; - let pattern = FracturePattern::layered(3, 8, Vec3::splat(2.0), total); - let sum: f32 = pattern.debris.iter().map(|d| d.mass).sum(); - assert!( - (sum - total).abs() < 0.01, - "Layered mass sum {} should be {}", - sum, - total - ); - } - - #[test] - fn mutation_layered_height_distribution() { - let he = Vec3::new(1.0, 5.0, 1.0); - let layers = 5; - let pattern = FracturePattern::layered(layers, 4, he, 50.0); - // Each layer should have pieces at a distinct Y level - let mut y_values: Vec = pattern.debris.iter().map(|d| d.local_position.y).collect(); - y_values.sort_by(|a, b| a.partial_cmp(b).unwrap()); - y_values.dedup_by(|a, b| (*a - *b).abs() < 0.01); - assert_eq!( - y_values.len(), - layers, - "Should have {} distinct Y layers, got {:?}", - layers, - y_values - ); - } - - #[test] - fn mutation_apply_damage_state_transitions() { - let config = DestructibleConfig { - max_health: 100.0, - trigger: DestructionTrigger::Health, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(0), config, Vec3::ZERO); - - assert_eq!(d.state, DestructibleState::Intact); - assert_eq!(d.health, 100.0); - - // 30 damage: still above 50%, stays Intact - d.apply_damage(30.0); - assert_eq!(d.state, DestructibleState::Intact); - assert!((d.health - 70.0).abs() < 0.01); - - // 30 more: at 40, below 50% threshold → Damaged - d.apply_damage(30.0); - assert_eq!(d.state, DestructibleState::Damaged); - assert!((d.health - 40.0).abs() < 0.01); - - // Finish it off - d.apply_damage(50.0); - assert_eq!(d.state, DestructibleState::Destroying); - assert!((d.health - 0.0).abs() < 0.01); - } - - #[test] - fn mutation_apply_damage_immune_when_destroying() { - let config = DestructibleConfig { - max_health: 50.0, - trigger: DestructionTrigger::Health, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(0), config, Vec3::ZERO); - d.state = DestructibleState::Destroying; - let hp_before = d.health; - - d.apply_damage(999.0); - - assert_eq!( - d.health, hp_before, - "Health should not change when Destroying" - ); - } - - #[test] - fn mutation_apply_damage_immune_when_destroyed() { - let config = DestructibleConfig { - max_health: 50.0, - trigger: DestructionTrigger::Health, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(0), config, Vec3::ZERO); - d.state = DestructibleState::Destroyed; - - d.apply_damage(999.0); - - assert_eq!(d.health, 50.0, "Health should not change when Destroyed"); - } - - // ═══════════════════════════════════════════════════════════════ - // DEEP REMEDIATION v3.6.1 — destruction Round 2 arithmetic tests - // ═══════════════════════════════════════════════════════════════ - - // --- FracturePattern::radial golden angle distribution --- - #[test] - fn mutation_radial_golden_angle_positions() { - let pattern = FracturePattern::radial(10, 5.0, 50.0); - // Verify positions use golden angle distribution - let golden_angle = std::f32::consts::PI * (3.0 - (5.0_f32).sqrt()); - for (i, d) in pattern.debris.iter().enumerate() { - let t = i as f32 / 10.0; - let inclination = (1.0 - 2.0 * t).acos(); - let azimuth = golden_angle * i as f32; - let expected = Vec3::new( - inclination.sin() * azimuth.cos() * 5.0 * 0.8, - inclination.cos() * 5.0 * 0.8, - inclination.sin() * azimuth.sin() * 5.0 * 0.8, - ); - assert!( - (d.local_position - expected).length() < 1e-4, - "Piece {} position mismatch: {:?} vs {:?}", - i, - d.local_position, - expected - ); - } - } - - #[test] - fn mutation_radial_piece_shape_is_sphere() { - let pattern = FracturePattern::radial(5, 3.0, 10.0); - for d in &pattern.debris { - match d.shape { - DebrisShape::Sphere { radius } => { - assert!( - (radius - 3.0 * 0.15).abs() < 1e-5, - "Radial debris radius should be radius*0.15={}, got {}", - 3.0 * 0.15, - radius - ); - } - _ => panic!("Radial debris should be Sphere shape"), - } - } - } - - // --- FracturePattern::uniform grid arithmetic --- - #[test] - fn mutation_uniform_piece_size_proportional() { - let he = Vec3::new(1.0, 2.0, 3.0); - let count = 8; - let pattern = FracturePattern::uniform(count, he, 40.0); - // pieces_per_axis = ceil(cbrt(8)) = 2 - let ppa = (count as f32).cbrt().ceil() as i32; - let expected_piece_size = he * 2.0 / ppa as f32; - for d in &pattern.debris { - if let DebrisShape::Box { half_extents } = d.shape { - assert!( - (half_extents - expected_piece_size * 0.4).length() < 1e-4, - "Piece half_extents {:?} should be {:?}", - half_extents, - expected_piece_size * 0.4 - ); - } else { - panic!("Uniform debris should be Box shape"); - } - } - } - - #[test] - fn mutation_uniform_single_piece() { - let pattern = FracturePattern::uniform(1, Vec3::splat(1.0), 5.0); - assert_eq!(pattern.debris.len(), 1); - assert!((pattern.debris[0].mass - 5.0).abs() < 1e-5); - } - - // --- FracturePattern::layered layer Y spacing --- - #[test] - fn mutation_layered_y_positions_correct() { - let he = Vec3::new(1.0, 6.0, 1.0); - let layers = 3; - let per_layer = 2; - let pattern = FracturePattern::layered(layers, per_layer, he, 60.0); - let layer_height = he.y * 2.0 / layers as f32; // 12/3 = 4 - for layer in 0..layers { - let expected_y = (layer as f32 + 0.5) * layer_height - he.y; - for p in 0..per_layer { - let idx = layer * per_layer + p; - assert!( - (pattern.debris[idx].local_position.y - expected_y).abs() < 1e-4, - "Layer {} piece {} Y should be {}, got {}", - layer, - p, - expected_y, - pattern.debris[idx].local_position.y - ); - } - } - } - - #[test] - fn mutation_layered_xz_uses_angle() { - let he = Vec3::new(2.0, 3.0, 2.0); - let layers = 1; - let per_layer = 4; - let pattern = FracturePattern::layered(layers, per_layer, he, 20.0); - for (i, d) in pattern.debris.iter().enumerate() { - let angle = i as f32 * std::f32::consts::TAU / per_layer as f32; - let expected_x = angle.cos() * he.x * 0.7; - let expected_z = angle.sin() * he.z * 0.7; - assert!( - (d.local_position.x - expected_x).abs() < 1e-4, - "Piece {} X: expected {}, got {}", - i, - expected_x, - d.local_position.x - ); - assert!( - (d.local_position.z - expected_z).abs() < 1e-4, - "Piece {} Z: expected {}, got {}", - i, - expected_z, - d.local_position.z - ); - } - } - - #[test] - fn mutation_layered_box_shape_dimensions() { - let he = Vec3::new(3.0, 5.0, 2.0); - let layers = 2; - let pattern = FracturePattern::layered(layers, 3, he, 30.0); - let layer_height = he.y * 2.0 / layers as f32; - for d in &pattern.debris { - if let DebrisShape::Box { half_extents } = d.shape { - assert!((half_extents.x - he.x * 0.3).abs() < 1e-4); - assert!((half_extents.y - layer_height * 0.4).abs() < 1e-4); - assert!((half_extents.z - he.z * 0.3).abs() < 1e-4); - } else { - panic!("Layered debris should be Box shape"); - } - } - } - - // --- DestructionManager::spawn_debris velocity arithmetic --- - #[test] - fn mutation_spawn_debris_velocity_outward() { - let mut mgr = DestructionManager::new(); - let cfg = DestructibleConfig { - fracture_pattern: FracturePattern::radial(4, 2.0, 10.0), - trigger: DestructionTrigger::Manual, - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(cfg, Vec3::ZERO); - mgr.destroy(id); - mgr.update(0.001, Vec3::ZERO); - for debris in mgr.debris_iter() { - // velocity direction should be generally outward from center - let dot = debris - .velocity - .dot(debris.config.local_position.normalize_or_zero()); - assert!( - dot > 0.0 || debris.config.local_position.length() < 0.01, - "Debris velocity should have outward component, dot={}", - dot - ); - } - } - - #[test] - fn mutation_spawn_debris_respects_velocity_factor() { - let mut mgr = DestructionManager::new(); - let slow = DebrisConfig { - velocity_factor: 0.5, - local_position: Vec3::X, - ..Default::default() - }; - let fast = DebrisConfig { - velocity_factor: 2.0, - local_position: Vec3::X, - ..Default::default() - }; - let cfg = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![slow, fast], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(cfg, Vec3::ZERO); - mgr.destroy(id); - mgr.update(0.001, Vec3::ZERO); - let speeds: Vec = mgr.debris_iter().map(|d| d.velocity.length()).collect(); - assert!(speeds.len() == 2); - // The fast debris should have higher velocity - assert!( - speeds[1] > speeds[0] * 1.5 || speeds[0] > speeds[1] * 1.5, - "Different velocity_factors should produce different speeds: {:?}", - speeds - ); - } - - #[test] - fn mutation_spawn_debris_angular_velocity_deterministic() { - let mut mgr = DestructionManager::new(); - let d1 = DebrisConfig { - angular_velocity_factor: 1.0, - ..Default::default() - }; - let d2 = DebrisConfig { - angular_velocity_factor: 1.0, - ..Default::default() - }; - let cfg = DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![d1, d2], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - let id = mgr.add_destructible(cfg, Vec3::ZERO); - mgr.destroy(id); - mgr.update(0.001, Vec3::ZERO); - // Angular velocities should be derived from debris IDs (deterministic pseudo-random) - let angvels: Vec = mgr.debris_iter().map(|d| d.angular_velocity).collect(); - assert!(angvels.len() == 2); - // Different IDs → different angular velocities - assert_ne!( - angvels[0], angvels[1], - "Different debris IDs should have different angular velocities" - ); - } - - // --- Debris::update physics --- - #[test] - fn mutation_debris_update_gravity_velocity() { - let cfg = DebrisConfig::default(); - let mut debris = Debris::new(DebrisId(1), DestructibleId(1), cfg, Vec3::ZERO, Vec3::ZERO); - let gravity = Vec3::new(0.0, -9.81, 0.0); - debris.update(1.0, gravity); - // v += gravity * dt = (0, -9.81, 0), pos += v * dt = (0, -9.81, 0) - assert!( - (debris.velocity.y - (-9.81)).abs() < 1e-3, - "velocity.y should be -9.81, got {}", - debris.velocity.y - ); - assert!( - (debris.position.y - (-9.81)).abs() < 1e-3, - "position.y should be -9.81, got {}", - debris.position.y - ); - assert!((debris.age - 1.0).abs() < 1e-6, "age should be 1.0"); - } - - #[test] - fn mutation_debris_update_with_initial_velocity() { - let cfg = DebrisConfig::default(); - let mut debris = Debris::new( - DebrisId(2), - DestructibleId(1), - cfg, - Vec3::ZERO, - Vec3::new(10.0, 0.0, 0.0), - ); - debris.update(0.5, Vec3::ZERO); - assert!( - (debris.position.x - 5.0).abs() < 1e-3, - "x should be ~5 with v=10, dt=0.5" - ); - } - - // ===== DEEP REMEDIATION v3.6.2 — destruction Round 3 remaining mutations ===== - - // --- Destructible::apply_damage health threshold --- - #[test] - fn mutation_r3_apply_damage_health_boundary() { - // health < max_health * 0.5 (mutation: < → <=) - let config = DestructibleConfig { - max_health: 100.0, - ..Default::default() - }; - let mut obj = Destructible::new(DestructibleId(800), config, Vec3::ZERO); - // health starts at 100. Apply 50 damage → health = 50 - obj.apply_damage(50.0); - // 50 < 100*0.5 = 50 is FALSE, so state should still be Intact - assert_eq!( - obj.state, - DestructibleState::Intact, - "Health=50, threshold=50: should stay Intact" - ); - // Apply 0.01 more → health = 49.99 < 50 → Damaged - obj.apply_damage(0.01); - assert_eq!( - obj.state, - DestructibleState::Damaged, - "Health<50 should become Damaged" - ); - } - - #[test] - fn mutation_r3_apply_damage_zero_health() { - // health <= 0 → Destroying (mutation: <= → < or ==) - let config = DestructibleConfig { - max_health: 10.0, - ..Default::default() - }; - let mut obj = Destructible::new(DestructibleId(801), config, Vec3::ZERO); - obj.apply_damage(10.0); // health = 0 exactly - assert_eq!( - obj.state, - DestructibleState::Destroying, - "Health=0 should trigger Destroying" - ); - } - - #[test] - fn mutation_r3_apply_damage_ignores_non_eligible_states() { - let config = DestructibleConfig { - max_health: 10.0, - ..Default::default() - }; - let mut obj = Destructible::new(DestructibleId(802), config, Vec3::ZERO); - obj.state = DestructibleState::Destroyed; - let health_before = obj.health; - obj.apply_damage(5.0); - assert_eq!( - obj.health, health_before, - "Destroyed object should ignore damage" - ); - } - - // --- DestructionManager::remove_destructible --- - #[test] - fn mutation_r3_remove_destructible_cleans_debris() { - // self.debris.retain(|_, d| d.source != id) (mutation: != → ==) - let mut mgr = DestructionManager::new(); - let d_id = mgr.add_destructible( - DestructibleConfig { - max_health: 10.0, - ..Default::default() - }, - Vec3::ZERO, - ); - // Manually add debris associated with this destructible - let debris_cfg = DebrisConfig::default(); - let debris_id = DebrisId(1); - mgr.debris.insert( - debris_id, - Debris::new(debris_id, d_id, debris_cfg.clone(), Vec3::ZERO, Vec3::ZERO), - ); - // Add debris from different source - let other_id = DestructibleId(999); - let debris_id2 = DebrisId(2); - mgr.debris.insert( - debris_id2, - Debris::new(debris_id2, other_id, debris_cfg, Vec3::ZERO, Vec3::ZERO), - ); - assert_eq!(mgr.debris.len(), 2); - // Remove the destructible - let removed = mgr.remove_destructible(d_id); - assert!(removed, "Should return true"); - // Debris from d_id should be gone, debris from other_id should remain - assert_eq!( - mgr.debris.len(), - 1, - "Only other source's debris should remain" - ); - assert!( - mgr.debris.contains_key(&debris_id2), - "Other debris should survive" - ); - } - - // ===== ECS INTEGRATION SCAFFOLDING v3.7.0 — Destruction integration tests ===== - - // --- spawn_debris via update() (24 misses) --- - #[test] - fn integration_spawn_debris_via_damage_and_update() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 50.0, - fracture_pattern: FracturePattern::uniform(8, Vec3::splat(0.5), 10.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::new(1.0, 2.0, 3.0)); - - // Damage to zero health → Destroying state - mgr.apply_damage(id, 100.0); - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroying); - - // update() should spawn debris and move to Destroyed - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroyed); - assert!( - mgr.debris_count() > 0, - "Debris should be spawned: count={}", - mgr.debris_count() - ); - } - - #[test] - fn integration_spawn_debris_position_offset() { - let mut mgr = DestructionManager::new(); - let origin = Vec3::new(10.0, 20.0, 30.0); - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(1.0), 5.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, origin); - mgr.apply_damage(id, 100.0); - mgr.update(1.0 / 60.0, Vec3::ZERO); - - // Each debris position should be origin + local_position - for debris in mgr.debris_iter() { - let dist = (debris.position - origin).length(); - assert!( - dist < 10.0, - "Debris should be near the origin: pos={:?}, dist={}", - debris.position, - dist - ); - } - } - - #[test] - fn integration_spawn_debris_velocity_has_outward_component() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::radial(12, 1.0, 10.0), - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.apply_damage(id, 100.0); - mgr.update(1.0 / 60.0, Vec3::ZERO); - - // Debris should have velocity (outward + force direction component) - let mut any_has_velocity = false; - for debris in mgr.debris_iter() { - if debris.velocity.length() > 0.1 { - any_has_velocity = true; - } - } - assert!( - any_has_velocity, - "At least some debris should have velocity" - ); - } - - #[test] - fn integration_spawn_debris_max_limit() { - let mut mgr = DestructionManager::new(); - mgr.max_debris = 3; // Very low limit - - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::uniform(20, Vec3::splat(1.0), 10.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.apply_damage(id, 100.0); - mgr.update(1.0 / 60.0, Vec3::ZERO); - - assert!( - mgr.debris_count() <= 3, - "Should respect max_debris limit: count={}", - mgr.debris_count() - ); - } - - #[test] - fn integration_spawn_debris_angular_velocity() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::radial(6, 1.0, 5.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.apply_damage(id, 100.0); - mgr.update(1.0 / 60.0, Vec3::ZERO); - - // Debris should have angular velocity from sin-based pseudo-random - let mut any_spin = false; - for debris in mgr.debris_iter() { - if debris.angular_velocity.length() > 0.01 { - any_spin = true; - } - } - assert!(any_spin, "At least some debris should spin"); - } - - #[test] - fn integration_spawn_debris_event_emitted() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::new(5.0, 0.0, 0.0)); - mgr.apply_damage(id, 100.0); - mgr.update(1.0 / 60.0, Vec3::ZERO); - - let events = mgr.take_events(); - assert_eq!(events.len(), 1, "Should emit one destruction event"); - assert_eq!(events[0].destructible_id, id); - assert!(events[0].debris_count > 0); - assert!((events[0].position.x - 5.0).abs() < 0.01); - } - - #[test] - fn integration_debris_update_applies_gravity() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::uniform(1, Vec3::splat(0.1), 1.0), - destruction_force: 0.0, // No initial velocity - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::new(0.0, 10.0, 0.0)); - mgr.apply_damage(id, 100.0); - mgr.update(0.0, Vec3::ZERO); // Spawn debris at dt=0 - - // Now update with gravity for 1 second - mgr.update(1.0, Vec3::new(0.0, -9.81, 0.0)); - - for debris in mgr.debris_iter() { - assert!( - debris.velocity.y < -1.0, - "Debris should fall: vel.y={}", - debris.velocity.y - ); - } - } - - #[test] - fn integration_debris_removed_after_lifetime() { - let mut mgr = DestructionManager::new(); - mgr.default_debris_lifetime = 10.0; - - let config = DestructibleConfig { - max_health: 1.0, - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 5.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.apply_damage(id, 100.0); - mgr.update(0.0, Vec3::ZERO); // Spawn debris - - let count_before = mgr.debris_count(); - assert!(count_before > 0); - - // Advance time well past lifetime - // Debris lifetime is from DebrisConfig::default() which has lifetime: 5.0 - mgr.update(10.0, Vec3::ZERO); - - assert!( - mgr.debris_count() < count_before, - "Old debris should be removed: before={}, after={}", - count_before, - mgr.debris_count() - ); - } - - #[test] - fn integration_force_trigger_destroys() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 1000.0, - trigger: DestructionTrigger::Force { threshold: 500.0 }, - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Below threshold - mgr.apply_force(id, 400.0); - assert_ne!(mgr.get(id).unwrap().state, DestructibleState::Destroying); - - mgr.update(0.0, Vec3::ZERO); // reset_frame - - // At threshold - mgr.apply_force(id, 500.0); - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroying); - - mgr.update(1.0 / 60.0, Vec3::ZERO); - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroyed); - } - - #[test] - fn integration_fracture_radial_debris_count() { - let fp = FracturePattern::radial(10, 1.0, 5.0); - assert_eq!(fp.debris.len(), 10, "Should create exactly 10 pieces"); - - // Verify golden angle distribution - consecutive angles differ - if fp.debris.len() >= 2 { - let p0 = fp.debris[0].local_position; - let p1 = fp.debris[1].local_position; - assert!( - (p0 - p1).length() > 0.01, - "Adjacent pieces should have different positions" - ); - } - } - - #[test] - fn integration_fracture_layered_debris_layout() { - let fp = FracturePattern::layered(3, 4, Vec3::splat(1.0), 12.0); - assert_eq!(fp.debris.len(), 12, "3 layers x 4 pieces = 12"); - - // Verify mass conservation - let total_mass: f32 = fp.debris.iter().map(|d| d.mass).sum(); - assert!( - (total_mass - 12.0).abs() < 0.01, - "Mass should be conserved: {}", - total_mass - ); - - // Verify layer distribution - let mut y_values: Vec = fp.debris.iter().map(|d| d.local_position.y).collect(); - y_values.sort_by(|a, b| a.partial_cmp(b).unwrap()); - y_values.dedup_by(|a, b| (*a - *b).abs() < 0.01); - assert_eq!(y_values.len(), 3, "Should have 3 distinct layers"); - } - - #[test] - fn integration_fracture_uniform_grid_spacing() { - let fp = FracturePattern::uniform(8, Vec3::new(2.0, 1.0, 2.0), 8.0); - assert_eq!(fp.debris.len(), 8, "Should create exactly 8 pieces"); - - // All debris should be within half_extents - for d in &fp.debris { - assert!( - d.local_position.x.abs() <= 2.1, - "X should be within half_extents: {}", - d.local_position.x - ); - assert!( - d.local_position.y.abs() <= 1.1, - "Y should be within half_extents: {}", - d.local_position.y - ); - assert!( - d.local_position.z.abs() <= 2.1, - "Z should be within half_extents: {}", - d.local_position.z - ); - } - } - - #[test] - fn integration_destroy_manual_then_update() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 10000.0, - fracture_pattern: FracturePattern::uniform(6, Vec3::splat(0.5), 5.0), - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Manual destroy bypasses health/force checks - mgr.destroy(id); - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroying); - - mgr.update(1.0 / 60.0, Vec3::ZERO); - assert_eq!(mgr.get(id).unwrap().state, DestructibleState::Destroyed); - assert!(mgr.debris_count() > 0); - } - - // ===== ROUND 7 ===== - - #[test] - fn r7_is_destroyed_only_when_destroyed() { - let config = DestructibleConfig { - max_health: 10.0, - fracture_pattern: FracturePattern::uniform(2, Vec3::splat(0.5), 1.0), - ..Default::default() - }; - let mut mgr = DestructionManager::new(); - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Initially not destroyed - let d = mgr.get(id).unwrap(); - assert!(!d.is_destroyed(), "Should not be destroyed initially"); - - // After taking damage but still alive - mgr.apply_damage(id, 5.0); - let d = mgr.get(id).unwrap(); - assert!(!d.is_destroyed(), "Should not be destroyed at half health"); - - // After being destroyed - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::ZERO); - let d = mgr.get(id).unwrap(); - assert!(d.is_destroyed(), "Should be destroyed after destroy+update"); - } - - // ===== ROUND 8: spawn_debris/get_mut/on_collision/get_debris ===== - - #[test] - fn r8_get_mut_returns_mutable_ref() { - let mut mgr = DestructionManager::new(); - let id = mgr.add_destructible(DestructibleConfig::default(), Vec3::ZERO); - let d = mgr.get_mut(id); - assert!(d.is_some(), "get_mut should return Some for existing id"); - - let bad_id = DestructibleId(9999); - assert!( - mgr.get_mut(bad_id).is_none(), - "get_mut on invalid id should be None" - ); - } - - #[test] - fn r8_on_collision_applies_damage() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 50.0, - damage_threshold: 5.0, - force_to_damage: 1.0, - trigger: DestructionTrigger::Health, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Collision below threshold should not damage - mgr.on_collision(id, 3.0); - let d = mgr.get(id).unwrap(); - assert_eq!( - d.health, 50.0, - "Below-threshold collision should not damage" - ); - - // Collision above threshold should damage (force=20, threshold=5, damage=(20-5)*1.0=15) - mgr.on_collision(id, 20.0); - let d = mgr.get(id).unwrap(); - assert!( - d.health < 50.0, - "Above-threshold collision should damage: health={}", - d.health - ); - } - - #[test] - fn r8_get_debris_returns_spawned() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.3), 5.0), - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::new(1.0, 2.0, 3.0)); - - // Destroy and update to spawn debris - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Get debris - should have spawned some - let debris_count = mgr.debris_iter().count(); - assert!( - debris_count > 0, - "Should have spawned debris after destruction" - ); - - // Each debris should be retrievable by ID - let first_debris = mgr.debris_iter().next().unwrap(); - let retrieved = mgr.get_debris(first_debris.id); - assert!(retrieved.is_some(), "get_debris should find spawned debris"); - } - - #[test] - fn r8_spawn_debris_positions_near_parent() { - let mut mgr = DestructionManager::new(); - let spawn_pos = Vec3::new(5.0, 10.0, 15.0); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(6, Vec3::splat(0.5), 8.0), - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, spawn_pos); - - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Debris positions should be near the parent object - for debris in mgr.debris_iter() { - let dist = (debris.position - spawn_pos).length(); - assert!( - dist < 10.0, - "Debris should be near parent: pos={:?}, parent={:?}, dist={}", - debris.position, - spawn_pos, - dist - ); - } - } - - #[test] - fn r8_spawn_debris_has_velocity() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.3), 5.0), - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // At least some debris should have non-zero velocity - let has_velocity = mgr.debris_iter().any(|d| d.velocity.length() > 0.1); - assert!( - has_velocity, - "Some debris should have velocity from destruction force" - ); - } - - #[test] - fn r8_spawn_debris_angular_velocity_varies() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.3), 5.0), - destruction_force: 10.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Different debris should have different angular velocities (pseudo-random based on ID) - let angulars: Vec = mgr.debris_iter().map(|d| d.angular_velocity).collect(); - if angulars.len() >= 2 { - assert!( - (angulars[0] - angulars[1]).length() > 0.01, - "Different debris should have different angular velocities" - ); - } - } - - #[test] - fn r8_spawn_debris_respects_force_direction() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.3), 5.0), - destruction_force: 20.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Apply large force from +X direction before destroying - mgr.apply_force(id, 1000.0); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Debris should exist - let count = mgr.debris_iter().count(); - assert!(count > 0, "Should have debris after force + destroy"); - } - - // ===== ROUND 9: FracturePattern precision + spawn_debris velocity ===== - - #[test] - fn r9_fracture_uniform_piece_positions_correct() { - // uniform(8, half_extents=(1,1,1), mass=10) - // pieces_per_axis = ceil(8^(1/3)) = ceil(2.0) = 2 - // piece_size = (2.0, 2.0, 2.0) / 2 = (1.0, 1.0, 1.0) - // First piece at (x=0,y=0,z=0): pos = (0.5*1.0 - 1.0, 0.5*1.0 - 1.0, 0.5*1.0 - 1.0) = (-0.5, -0.5, -0.5) - let frac = FracturePattern::uniform(8, Vec3::splat(1.0), 10.0); - assert_eq!(frac.debris.len(), 8, "Should have 8 pieces"); - - let first = &frac.debris[0]; - let expected_pos = Vec3::new(-0.5, -0.5, -0.5); - assert!( - (first.local_position - expected_pos).length() < 0.01, - "First debris position should be ({:?}), got {:?}", - expected_pos, - first.local_position - ); - - // Loop order is x(outer) → y → z(inner), so index 1 = (x=0,y=0,z=1): - // pos = (0.5*1.0 - 1.0, 0.5*1.0 - 1.0, 1.5*1.0 - 1.0) = (-0.5, -0.5, 0.5) - let second = &frac.debris[1]; - let expected_pos2 = Vec3::new(-0.5, -0.5, 0.5); - assert!( - (second.local_position - expected_pos2).length() < 0.01, - "Second debris position should be ({:?}), got {:?}", - expected_pos2, - second.local_position - ); - } - - #[test] - fn r9_fracture_uniform_piece_mass_correct() { - let total_mass = 20.0_f32; - let count = 8_usize; - let frac = FracturePattern::uniform(count, Vec3::splat(2.0), total_mass); - - for (i, d) in frac.debris.iter().enumerate() { - let expected_mass = total_mass / count as f32; - assert!( - (d.mass - expected_mass).abs() < 0.01, - "Piece {} mass should be {}, got {}", - i, - expected_mass, - d.mass - ); - } - } - - #[test] - fn r9_fracture_uniform_piece_size_correct() { - // half_extents = (3, 3, 3), pieces=8 → pieces_per_axis=2 - // piece_size = (6/2, 6/2, 6/2) = (3, 3, 3) - // shape half_extents = piece_size * 0.4 = (1.2, 1.2, 1.2) - let frac = FracturePattern::uniform(8, Vec3::splat(3.0), 10.0); - let first = &frac.debris[0]; - match &first.shape { - DebrisShape::Box { half_extents } => { - let expected = 3.0 * 0.4; // = 1.2 - assert!( - (half_extents.x - expected).abs() < 0.01, - "Piece half_extent.x should be ~{}, got {}", - expected, - half_extents.x - ); - } - _ => panic!("Expected Box shape from FracturePattern::uniform"), - } - } - - #[test] - fn r9_fracture_uniform_local_position_field_set() { - // Test that local_position is explicitly set (catches "delete field local_position" mutation) - let frac = FracturePattern::uniform(1, Vec3::splat(1.0), 5.0); - let piece = &frac.debris[0]; - // With 1 piece: pieces_per_axis=1, piece_size=2.0/1=2.0, pos = (0.5*2.0-1.0) = 0.0 - assert!( - piece.local_position.length() < 0.01, - "Single piece should be at origin, got {:?}", - piece.local_position - ); - - // With 8 pieces, first piece should be at (-0.5, -0.5, -0.5) — NOT at default (0,0,0) for all - let frac2 = FracturePattern::uniform(8, Vec3::splat(1.0), 10.0); - let last = &frac2.debris[7]; - // Last piece at (1,1,1): pos = (1.5*1-1, 1.5*1-1, 1.5*1-1) = (0.5,0.5,0.5) - assert!( - last.local_position.length() > 0.1, - "Last piece should NOT be at origin: got {:?}", - last.local_position - ); - } - - #[test] - fn r9_spawn_debris_velocity_has_outward_component() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 50.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::new(0.0, 5.0, 0.0)); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Check debris velocities: they should have nonzero velocity from the destruction force - for debris in mgr.debris_iter() { - assert!( - debris.velocity.length() > 0.01, - "Debris should have velocity from destruction force, got {:?}", - debris.velocity - ); - } - } - - #[test] - fn r9_spawn_debris_force_direction_affects_velocity() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 100.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - - // Apply large force from +X to trigger destruction with force direction - mgr.apply_force(id, 50000.0); // Exceed force threshold to trigger destruction - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Debris should exist and have been pushed in +X direction due to force - let count = mgr.debris_iter().count(); - if count > 0 { - let avg_vx: f32 = mgr.debris_iter().map(|d| d.velocity.x).sum::() / count as f32; - // Force was applied in +X direction, so average velocity should lean positive x - // (At minimum, debris should have non-trivial velocity) - let avg_speed: f32 = - mgr.debris_iter().map(|d| d.velocity.length()).sum::() / count as f32; - assert!( - avg_speed > 0.5, - "Debris should have speed from destruction_force=100, got {}", - avg_speed - ); - } - } - - #[test] - fn r9_spawn_debris_angular_velocity_uses_factor() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 50.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Check debris angular velocities: they should be nonzero (pseudo-random based on id) - let mut has_angular = false; - for debris in mgr.debris_iter() { - if debris.angular_velocity.length() > 0.01 { - has_angular = true; - } - } - assert!( - has_angular, - "At least some debris should have angular velocity" - ); - } - - // ===== ROUND 10: spawn_debris exact arithmetic verification ===== - - #[test] - fn r10_spawn_debris_angular_velocity_exact_id1() { - // Debris IDs start at 1 (next_debris_id = 1 in DestructionManager::new). - // Angular velocity formula for id N: - // Vec3(sin(N*1.234)*5, sin(N*2.345)*5, sin(N*3.456)*5) * ang_factor - // Default ang_factor from DebrisConfig = 0.5 - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 50.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Access specific debris by ID - let d1 = mgr.get_debris(DebrisId(1)).expect("Debris 1 should exist"); - let ang_factor = 0.5_f32; - let expected_x = (1.0_f32 * 1.234).sin() * 5.0 * ang_factor; - let expected_y = (1.0_f32 * 2.345).sin() * 5.0 * ang_factor; - let expected_z = (1.0_f32 * 3.456).sin() * 5.0 * ang_factor; - let expected = Vec3::new(expected_x, expected_y, expected_z); - - assert!( - (d1.angular_velocity - expected).length() < 0.01, - "Debris 1 angular vel should match formula: expected={:?}, got={:?}", - expected, - d1.angular_velocity - ); - } - - #[test] - fn r10_spawn_debris_angular_velocity_exact_id2() { - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 50.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - let d2 = mgr.get_debris(DebrisId(2)).expect("Debris 2 should exist"); - let ang_factor = 0.5_f32; - let expected = Vec3::new( - (2.0_f32 * 1.234).sin() * 5.0 * ang_factor, - (2.0_f32 * 2.345).sin() * 5.0 * ang_factor, - (2.0_f32 * 3.456).sin() * 5.0 * ang_factor, - ); - assert!( - (d2.angular_velocity - expected).length() < 0.01, - "Debris 2 angular vel: expected={:?}, got={:?}", - expected, - d2.angular_velocity - ); - } - - #[test] - fn r10_spawn_debris_velocity_formula_outward_plus_force() { - // velocity = (outward * destruction_force + force_dir * destruction_force * 0.5) - // * velocity_factor - // force_direction defaults to Vec3::Y in update() - let mut mgr = DestructionManager::new(); - let config = DestructibleConfig { - fracture_pattern: FracturePattern::uniform(4, Vec3::splat(0.5), 5.0), - destruction_force: 100.0, - ..Default::default() - }; - let id = mgr.add_destructible(config, Vec3::ZERO); - mgr.destroy(id); - mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // First debris (ID=1) has local_position from FracturePattern::uniform - let d1 = mgr.get_debris(DebrisId(1)).expect("Debris 1"); - // After one update frame, velocity has been modified by gravity - // But the initial velocity was set during spawn. Let's check that it has a Y - // component above zero (force_direction * 0.5 gives +Y bias of 50) - // Even after 1 frame of gravity (9.81 * 1/60 ≈ 0.16), the Y component should - // still be positive if force direction contributed - - // Check velocity is non-trivial (destruction_force=100 gives high initial speed) - assert!( - d1.velocity.length() > 10.0, - "Debris velocity should be significant: {:?}", - d1.velocity - ); - - // Y component should include the force_direction (Vec3::Y) contribution - // At minimum, some debris should have positive Y velocity from the +Y force component - let has_positive_y = mgr.debris_iter().any(|d| d.velocity.y > 5.0); - assert!( - has_positive_y, - "Force direction +Y should give some debris positive Y velocity" - ); - } - - #[test] - fn r10_spawn_debris_velocity_factor_scales() { - // If velocity_factor matters, changing it should change debris speed - // Create two destructibles with different velocity_factor patterns - let make_pattern = |vel_factor: f32| FracturePattern { - debris: vec![DebrisConfig { - local_position: Vec3::new(0.5, 0.0, 0.0), - velocity_factor: vel_factor, - angular_velocity_factor: 0.5, - mass: 1.0, - ..Default::default() - }], - center_of_mass: Vec3::ZERO, - }; - - let mut mgr1 = DestructionManager::new(); - let c1 = DestructibleConfig { - fracture_pattern: make_pattern(1.0), - destruction_force: 100.0, - ..Default::default() - }; - let id1 = mgr1.add_destructible(c1, Vec3::ZERO); - mgr1.destroy(id1); - mgr1.update(0.0, Vec3::ZERO); // dt=0, no gravity - - let mut mgr2 = DestructionManager::new(); - let c2 = DestructibleConfig { - fracture_pattern: make_pattern(0.5), - destruction_force: 100.0, - ..Default::default() - }; - let id2 = mgr2.add_destructible(c2, Vec3::ZERO); - mgr2.destroy(id2); - mgr2.update(0.0, Vec3::ZERO); - - let v1 = mgr1.get_debris(DebrisId(1)).unwrap().velocity.length(); - let v2 = mgr2.get_debris(DebrisId(1)).unwrap().velocity.length(); - - assert!( - (v1 - v2 * 2.0).abs() < v1 * 0.1, - "velocity_factor 1.0 should be ~2x of 0.5: v1={}, v2={}", - v1, - v2 - ); - } -} diff --git a/astraweave-physics/src/lib.rs b/astraweave-physics/src/lib.rs index bc389f2af3..f4a6b562ca 100644 --- a/astraweave-physics/src/lib.rs +++ b/astraweave-physics/src/lib.rs @@ -31,7 +31,7 @@ //! - **[`Ragdoll`] / [`RagdollBuilder`]** — Multi-bone ragdoll creation and simulation. //! - **[`Vehicle`] / [`VehicleManager`]** — Vehicle dynamics with drivetrain and wheels. //! - **[`EnvironmentManager`]** — Wind zones, water volumes, and buoyancy. -//! - **[`DestructionManager`]** — Fracture patterns and debris spawning. +//! - **`break_destructible`** — removes a rigid body. Fracture and debris live in `astraweave-destruction`. //! - **[`ClothManager`]** — Particle-based cloth with distance constraints. //! //! # Feature Flags @@ -169,13 +169,6 @@ pub use environment::{ EnvironmentManager, GustEvent, WindType, WindZone, WindZoneConfig, WindZoneId, WindZoneShape, }; -// Destruction system -pub mod destruction; -pub use destruction::{ - Debris, DebrisConfig, DebrisId, DebrisShape, Destructible, DestructibleConfig, DestructibleId, - DestructibleState, DestructionEvent, DestructionManager, DestructionTrigger, FracturePattern, -}; - // Cloth simulation pub mod cloth; pub use cloth::{ @@ -1678,12 +1671,6 @@ impl PhysicsWorld { self.remove_body(id); } - /// Empty on purpose. Hits that change destruction state go through - /// `astraweave-destruction`'s command log. Deletion of this stub is part - /// of retiring `destruction.rs` (deferred-failure issue #255). - #[allow(dead_code)] - fn process_destructible_hits(&mut self) {} - pub fn set_body_position(&mut self, id: BodyId, pos: Vec3) { if let Some(h) = self.handle_of(id) { if let Some(rb) = self.bodies.get_mut(h) { diff --git a/astraweave-physics/tests/behavioral_correctness_tests.rs b/astraweave-physics/tests/behavioral_correctness_tests.rs index 9b72aaa990..899b65a2cd 100644 --- a/astraweave-physics/tests/behavioral_correctness_tests.rs +++ b/astraweave-physics/tests/behavioral_correctness_tests.rs @@ -13,7 +13,6 @@ //! Phase 8.8: Production-Ready Physics Validation use astraweave_physics::cloth::{Cloth, ClothConfig, ClothId, ClothParticle, DistanceConstraint}; -use astraweave_physics::destruction::{DestructibleConfig, DestructionManager, FracturePattern}; use astraweave_physics::projectile::{ ExplosionConfig, FalloffCurve, ProjectileConfig, ProjectileManager, }; @@ -717,64 +716,6 @@ fn test_suspension_hookes_law() { ); } -// ============================================================================ -// DESTRUCTION PHYSICS CORRECTNESS -// ============================================================================ - -/// Verify damage reduces health correctly (mutation: adding instead of subtracting) -#[test] -fn test_destruction_damage_reduces_health() { - let mut manager = DestructionManager::new(); - let config = DestructibleConfig { - max_health: 100.0, - ..Default::default() - }; - - let id = manager.add_destructible(config, Vec3::ZERO); - - let initial_health = manager.get(id).unwrap().health; - assert!( - (initial_health - 100.0).abs() < 0.01, - "Initial health should be max" - ); - - // Apply 30 damage - manager.apply_damage(id, 30.0); - let after_damage = manager.get(id).unwrap().health; - - assert!( - (after_damage - 70.0).abs() < 0.01, - "Health should be 70 after 30 damage. Got {}", - after_damage - ); - - // Apply more damage - manager.apply_damage(id, 50.0); - let final_health = manager.get(id).unwrap().health; - - assert!( - (final_health - 20.0).abs() < 0.01, - "Health should be 20 after total 80 damage. Got {}", - final_health - ); -} - -/// Verify debris count matches fracture pattern -#[test] -fn test_destruction_debris_count_matches_pattern() { - for piece_count in [4, 8, 16, 32] { - let pattern = FracturePattern::uniform(piece_count, Vec3::splat(0.5), 10.0); - - assert!( - pattern.debris.len() >= piece_count / 2, - "Pattern with {} pieces should have at least {} debris configs, got {}", - piece_count, - piece_count / 2, - pattern.debris.len() - ); - } -} - // ============================================================================ // RAGDOLL PHYSICS CORRECTNESS // ============================================================================ diff --git a/astraweave-physics/tests/coverage_boost_tests.rs b/astraweave-physics/tests/coverage_boost_tests.rs index e32a7df706..d33d463490 100644 --- a/astraweave-physics/tests/coverage_boost_tests.rs +++ b/astraweave-physics/tests/coverage_boost_tests.rs @@ -397,126 +397,6 @@ mod cloth_coverage { } } -// ============================================================================ -// DESTRUCTION SYSTEM COVERAGE TESTS -// ============================================================================ - -mod destruction_coverage { - use super::*; - use astraweave_physics::destruction::*; - - #[test] - fn test_destruction_manager_crud() { - let mut manager = DestructionManager::new(); - - let config = DestructibleConfig::default(); - let id = manager.add_destructible(config, Vec3::ZERO); - - assert!(manager.get(id).is_some()); - - if let Some(dest) = manager.get_mut(id) { - dest.health = 50.0; - } - assert!((manager.get(id).unwrap().health - 50.0).abs() < 0.01); - - assert!(manager.remove_destructible(id)); - assert!(!manager.remove_destructible(id)); - } - - #[test] - fn test_destruction_triggers() { - let mut manager = DestructionManager::new(); - - // Force trigger - let config1 = DestructibleConfig { - trigger: DestructionTrigger::Force { threshold: 100.0 }, - ..Default::default() - }; - let id1 = manager.add_destructible(config1, Vec3::ZERO); - manager.apply_force(id1, 150.0); - assert_eq!( - manager.get(id1).unwrap().state, - DestructibleState::Destroying - ); - - // Health trigger - let config2 = DestructibleConfig { - trigger: DestructionTrigger::Health, - max_health: 50.0, - damage_threshold: 0.0, - force_to_damage: 1.0, - ..Default::default() - }; - let id2 = manager.add_destructible(config2, Vec3::new(5.0, 0.0, 0.0)); - manager.apply_damage(id2, 100.0); - assert_eq!( - manager.get(id2).unwrap().state, - DestructibleState::Destroying - ); - - // Collision trigger - let config3 = DestructibleConfig { - trigger: DestructionTrigger::Collision, - ..Default::default() - }; - let id3 = manager.add_destructible(config3, Vec3::new(10.0, 0.0, 0.0)); - manager.on_collision(id3, 1.0); - assert_eq!( - manager.get(id3).unwrap().state, - DestructibleState::Destroying - ); - - // Manual trigger - let config4 = DestructibleConfig { - trigger: DestructionTrigger::Manual, - ..Default::default() - }; - let id4 = manager.add_destructible(config4, Vec3::new(15.0, 0.0, 0.0)); - manager.destroy(id4); - assert_eq!( - manager.get(id4).unwrap().state, - DestructibleState::Destroying - ); - } - - #[test] - fn test_fracture_patterns() { - let uniform = FracturePattern::uniform(10, Vec3::ONE, 1.0); - assert_eq!(uniform.debris.len(), 10); - - let radial = FracturePattern::radial(8, 2.0, 0.5); - assert!(!radial.debris.is_empty()); - - let layered = FracturePattern::layered(3, 4, Vec3::ONE, 0.5); - assert!(!layered.debris.is_empty()); - } - - #[test] - fn test_destructible_methods() { - let config = DestructibleConfig { - max_health: 100.0, - ..Default::default() - }; - let mut dest = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - assert_eq!(dest.health_percent(), 1.0); - assert!(!dest.is_destroyed()); - - dest.apply_damage(50.0); - assert!((dest.health_percent() - 0.5).abs() < 0.01); - - dest.apply_damage(50.0); - // After health <= 0, state is Destroying, not Destroyed - assert_eq!(dest.state, DestructibleState::Destroying); - assert!(dest.should_spawn_debris()); - - // Must call complete_destruction to reach Destroyed state - dest.complete_destruction(); - assert!(dest.is_destroyed()); - assert_eq!(dest.state, DestructibleState::Destroyed); - } -} - // ============================================================================ // ENVIRONMENT SYSTEM COVERAGE TESTS // ============================================================================ diff --git a/astraweave-physics/tests/cross_subsystem_validation.rs b/astraweave-physics/tests/cross_subsystem_validation.rs index 610be86ce2..42abc5f122 100644 --- a/astraweave-physics/tests/cross_subsystem_validation.rs +++ b/astraweave-physics/tests/cross_subsystem_validation.rs @@ -6,7 +6,6 @@ use astraweave_physics::{ cloth::{ClothConfig, ClothManager}, - destruction::{DestructibleConfig, DestructibleId, DestructionManager}, projectile::{ProjectileConfig, ProjectileKind, ProjectileManager}, ragdoll::RagdollConfig, spatial_hash::SpatialHash, @@ -76,50 +75,6 @@ fn test_cloth_responds_to_gravity() { } } -// ============================================================================ -// VEHICLE + DESTRUCTION INTEGRATION -// ============================================================================ - -#[test] -fn test_vehicle_config_with_destruction_compatible_mass() { - let vehicle_config = VehicleConfig::default(); - let destruction_config = DestructibleConfig::default(); - - // Vehicle mass should be reasonable for destruction calculations - // Impact force = mass * acceleration - let impact_velocity = 10.0; // m/s collision - let impact_force = vehicle_config.mass * impact_velocity; - - assert!( - impact_force > destruction_config.damage_threshold * 0.1, - "Vehicle mass should generate meaningful destruction forces" - ); -} - -#[test] -fn test_destruction_debris_generation() { - let mut destruction_mgr = DestructionManager::new(); - - let config = DestructibleConfig { - max_health: 100.0, - ..Default::default() - }; - - let id = destruction_mgr.add_destructible(config, Vec3::ZERO); - - // Apply enough damage to destroy - destruction_mgr.apply_damage(id, 150.0); - destruction_mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Object should be destroyed or have spawned debris - let obj = destruction_mgr.get(id); - // After heavy damage, object may be destroyed - assert!( - obj.is_none() || obj.unwrap().health <= 0.0, - "Object should be destroyed after excessive damage" - ); -} - // ============================================================================ // RAGDOLL + GRAVITY INTEGRATION // ============================================================================ @@ -299,47 +254,14 @@ fn test_projectile_trajectory_determinism() { #[test] fn test_empty_managers_handle_updates() { let mut cloth_mgr = ClothManager::new(); - let mut destruction_mgr = DestructionManager::new(); let mut projectile_mgr = ProjectileManager::new(); - // Should not panic with no objects cloth_mgr.update(1.0 / 60.0); - destruction_mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); projectile_mgr.update(1.0 / 60.0, |_, _, _| None); assert_eq!(cloth_mgr.count(), 0); } -#[test] -fn test_many_simultaneous_objects() { - let mut destruction_mgr = DestructionManager::new(); - - // Create many destructibles - for i in 0..100 { - destruction_mgr.add_destructible( - DestructibleConfig::default(), - Vec3::new(i as f32 * 2.0, 0.0, 0.0), - ); - } - - // Update should handle all - destruction_mgr.update(1.0 / 60.0, Vec3::new(0.0, -9.81, 0.0)); - - // Should have all objects - // Count active destructibles - let mut count = 0; - for i in 1..=100 { - if destruction_mgr.get(DestructibleId(i)).is_some() { - count += 1; - } - } - assert!( - count >= 50, - "Should maintain many simultaneous objects, got {}", - count - ); -} - // ============================================================================ // FRICTION CURVE VALIDATION // ============================================================================ diff --git a/astraweave-physics/tests/environment_tests.rs b/astraweave-physics/tests/environment_tests.rs index 87f323d03c..18c43cdc2c 100644 --- a/astraweave-physics/tests/environment_tests.rs +++ b/astraweave-physics/tests/environment_tests.rs @@ -1,12 +1,10 @@ -//! Integration tests for Phase 6: Environmental & Soft Body Physics +//! Integration tests for wind zones, cloth, and buoyancy. //! -//! Tests wind zones, destruction, cloth, and buoyancy systems. +//! The float destruction tests left with `destruction.rs`. use astraweave_physics::{ cloth::{Cloth, ClothCollider, ClothConfig, ClothId, ClothManager}, - destruction::{DestructibleConfig, DestructionManager, DestructionTrigger, FracturePattern}, environment::{EnvironmentManager, WindType, WindZoneConfig, WindZoneShape}, - PhysicsWorld, }; use glam::Vec3; @@ -154,163 +152,6 @@ fn test_gust_events() { assert_eq!(force_after, Vec3::ZERO, "Gust should expire"); } -// ============================================================================ -// Destruction Integration Tests -// ============================================================================ - -/// Test basic destruction workflow -#[test] -fn test_destruction_workflow() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern::uniform(10, Vec3::splat(1.0), 10.0), - trigger: DestructionTrigger::Health, - max_health: 100.0, - ..Default::default() - }, - Vec3::ZERO, - ); - - // Apply damage - manager.apply_damage(id, 50.0); - assert_eq!(manager.get(id).unwrap().health, 50.0); - - // Destroy - manager.apply_damage(id, 60.0); - - // Update to process destruction - manager.update(0.016, Vec3::new(0.0, -9.81, 0.0)); - - // Should have spawned debris - assert!(manager.debris_count() > 0); - - // Should have generated event - let events = manager.take_events(); - assert_eq!(events.len(), 1); -} - -/// Test force-based destruction -#[test] -fn test_force_destruction() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern::uniform(5, Vec3::splat(0.5), 5.0), - trigger: DestructionTrigger::Force { threshold: 100.0 }, - ..Default::default() - }, - Vec3::ZERO, - ); - - // Below threshold (force is reset each frame, so needs 100+ in one frame) - manager.apply_force(id, 50.0); - manager.update(0.016, Vec3::ZERO); - assert_eq!( - manager.debris_count(), - 0, - "Should not break below threshold" - ); - - // Above threshold - apply enough force in single frame - manager.apply_force(id, 110.0); - manager.update(0.016, Vec3::ZERO); - assert!(manager.debris_count() > 0, "Should break above threshold"); -} - -/// Test collision-triggered destruction -#[test] -fn test_collision_destruction() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern::uniform(3, Vec3::splat(0.3), 3.0), - trigger: DestructionTrigger::Collision, - ..Default::default() - }, - Vec3::ZERO, - ); - - // Any collision should destroy - manager.on_collision(id, 1.0); - manager.update(0.016, Vec3::ZERO); - - assert!(manager.debris_count() > 0); -} - -/// Test radial fracture pattern -#[test] -fn test_radial_fracture() { - let pattern = FracturePattern::radial(20, 2.0, 10.0); - assert_eq!(pattern.debris.len(), 20); - - // All debris should be within radius - for debris in &pattern.debris { - let dist = debris.local_position.length(); - assert!(dist <= 2.0, "Debris should be within radius"); - } -} - -/// Test layered fracture pattern -#[test] -fn test_layered_fracture() { - let pattern = FracturePattern::layered(4, 6, Vec3::new(2.0, 4.0, 2.0), 24.0); - assert_eq!(pattern.debris.len(), 24); -} - -/// Test debris lifetime and cleanup -#[test] -fn test_debris_lifetime() { - let mut manager = DestructionManager::new(); - - let id = manager.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern { - debris: vec![astraweave_physics::destruction::DebrisConfig { - lifetime: 0.5, - ..Default::default() - }], - center_of_mass: Vec3::ZERO, - }, - trigger: DestructionTrigger::Manual, - ..Default::default() - }, - Vec3::ZERO, - ); - - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - assert_eq!(manager.debris_count(), 1); - - // After lifetime - manager.update(1.0, Vec3::ZERO); - assert_eq!(manager.debris_count(), 0, "Debris should expire"); -} - -/// Test debris limit -#[test] -fn test_debris_limit() { - let mut manager = DestructionManager::new(); - manager.max_debris = 5; - - let id = manager.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern::uniform(20, Vec3::splat(1.0), 20.0), - trigger: DestructionTrigger::Manual, - ..Default::default() - }, - Vec3::ZERO, - ); - - manager.destroy(id); - manager.update(0.016, Vec3::ZERO); - - assert!(manager.debris_count() <= 5, "Should respect debris limit"); -} - // ============================================================================ // Cloth Simulation Integration Tests // ============================================================================ @@ -597,30 +438,3 @@ fn test_environment_cloth_integration() { moved ); } - -/// Test destruction with physics world integration -#[test] -fn test_destruction_physics_integration() { - let mut _physics = PhysicsWorld::new(Vec3::new(0.0, -9.81, 0.0)); - let mut destruction = DestructionManager::new(); - - // Create destructible wall - let wall_id = destruction.add_destructible( - DestructibleConfig { - fracture_pattern: FracturePattern::layered(3, 4, Vec3::new(2.0, 3.0, 0.5), 50.0), - trigger: DestructionTrigger::Force { threshold: 500.0 }, - destruction_force: 10.0, - ..Default::default() - }, - Vec3::new(0.0, 1.5, 0.0), - ); - - // Simulate projectile impact - destruction.apply_force(wall_id, 600.0); - destruction.update(0.016, Vec3::new(0.0, -9.81, 0.0)); - - // Wall should be destroyed - let events = destruction.take_events(); - assert_eq!(events.len(), 1); - assert!(events[0].debris_count > 0); -} diff --git a/astraweave-physics/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-physics/tests/mutation_resistant_comprehensive_tests.rs index cc7d16a618..672c505b68 100644 --- a/astraweave-physics/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-physics/tests/mutation_resistant_comprehensive_tests.rs @@ -948,242 +948,6 @@ mod environment_wind_mutations { } } -// ============================================================================ -// P5: Destruction System (~15 estimated surviving mutants) -// ============================================================================ - -mod destruction_mutations { - use super::*; - use astraweave_physics::destruction::*; - #[allow(unused_imports)] - #[test] - fn fracture_uniform_piece_count_uses_cbrt() { - let fp = FracturePattern::uniform(27, Vec3::splat(3.0), 27.0); - // pieces_per_axis = cbrt(27).ceil() = 3 - // total pieces = 3*3*3 = 27 - assert_eq!(fp.debris.len(), 27); - } - - #[test] - fn fracture_uniform_piece_count_rounds_up() { - let fp = FracturePattern::uniform(10, Vec3::splat(3.0), 10.0); - // pieces_per_axis = cbrt(10).ceil() = ceil(2.154) = 3 - // The loop caps at piece_count via `if debris.len() >= piece_count { break; }` - // So we get exactly 10, not 3*3*3=27 - assert_eq!(fp.debris.len(), 10); - // Verify cbrt().ceil() determines grid subdivision (3, not 2) - // With axis=3, piece_size = half_extents * 2 / 3 = 2.0 - let piece_size = Vec3::splat(3.0) * 2.0 / 3.0; - if let DebrisShape::Box { half_extents } = fp.debris[0].shape { - let expected = piece_size * 0.4; - assert!((half_extents - expected).length() < 0.01); - } - } - - #[test] - fn fracture_uniform_debris_half_extents_use_04_factor() { - let fp = FracturePattern::uniform(8, Vec3::splat(2.0), 8.0); - // pieces_per_axis = cbrt(8) = 2 - // piece_size = half_extents * 2.0 / 2 = half_extents - // debris half_extents = piece_size * 0.4 - let piece_size = Vec3::splat(2.0) * 2.0 / 2.0; // = (2.0, 2.0, 2.0) - let expected_he = piece_size * 0.4; // = (0.8, 0.8, 0.8) - if let DebrisShape::Box { half_extents } = fp.debris[0].shape { - assert!( - (half_extents - expected_he).length() < 0.01, - "Debris half_extents: got {:?} expected {:?}", - half_extents, - expected_he - ); - } else { - panic!("Expected Box debris shape"); - } - } - - #[test] - fn fracture_uniform_mass_distribution() { - let total_mass = 100.0; - let fp = FracturePattern::uniform(8, Vec3::splat(1.0), total_mass); - let piece_mass = total_mass / fp.debris.len() as f32; - for d in &fp.debris { - assert!( - (d.mass - piece_mass).abs() < 0.01, - "Each debris mass should be {}. got {}", - piece_mass, - d.mass - ); - } - } - - #[test] - fn fracture_radial_golden_angle() { - let fp = FracturePattern::radial(10, 5.0, 10.0); - assert_eq!(fp.debris.len(), 10); - // Each piece should have velocity_factor = 1.5 (radial) - for d in &fp.debris { - assert_eq!( - d.velocity_factor, 1.5, - "Radial velocity_factor should be 1.5" - ); - } - } - - #[test] - fn debris_config_defaults() { - let d = DebrisConfig::default(); - assert_eq!(d.velocity_factor, 1.0); - assert_eq!(d.angular_velocity_factor, 0.5); - assert_eq!(d.lifetime, 10.0); - } - - #[test] - fn destructible_apply_damage_reduces_health() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - assert_eq!(d.health, 100.0); - - d.apply_damage(30.0); - assert_eq!(d.health, 70.0); - assert_eq!(d.state, DestructibleState::Intact); // 70% > 50% - } - - #[test] - fn destructible_damage_threshold_50_percent() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - d.apply_damage(51.0); // health = 49, < 50% of 100 - assert_eq!(d.state, DestructibleState::Damaged); - } - - #[test] - fn destructible_fatal_damage() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - d.apply_damage(100.0); - assert_eq!(d.health, 0.0); - assert_eq!(d.state, DestructibleState::Destroying); - } - - #[test] - fn destructible_health_clamped_at_zero() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - d.apply_damage(200.0); // overkill - assert_eq!(d.health, 0.0); // .max(0.0) prevents negative - } - - #[test] - fn destructible_no_damage_when_destroying() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - d.state = DestructibleState::Destroying; - - d.apply_damage(50.0); - assert_eq!(d.health, 100.0); // should be unchanged - } - - #[test] - fn destructible_force_trigger() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Force { threshold: 500.0 }, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - d.apply_force(400.0); - assert_eq!(d.state, DestructibleState::Intact); - - d.apply_force(100.0); // accumulated = 500 - assert_eq!(d.state, DestructibleState::Destroying); - } - - #[test] - fn destructible_health_trigger_with_damage_threshold() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Health, - damage_threshold: 10.0, - force_to_damage: 0.1, - max_health: 100.0, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - // Force below damage_threshold → no damage - d.apply_force(5.0); - assert_eq!(d.health, 100.0); - - // Force above threshold → damage = (force - threshold) * conversion - d.apply_force(110.0); // damage = (110-10)*0.1 = 10.0 - assert!( - (d.health - 90.0).abs() < 0.01, - "Health should be ~90, got {}", - d.health - ); - } - - #[test] - fn destructible_collision_trigger() { - let config = DestructibleConfig { - trigger: DestructionTrigger::Collision, - ..Default::default() - }; - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - - d.on_collision(1.0); // any collision → destroying - assert_eq!(d.state, DestructibleState::Destroying); - } - - #[test] - fn destructible_health_percent() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - assert_eq!(d.health_percent(), 1.0); - d.apply_damage(25.0); - assert!((d.health_percent() - 0.75).abs() < 0.01); - } - - #[test] - fn destructible_should_spawn_debris_only_when_destroying() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - assert!(!d.should_spawn_debris()); - - d.state = DestructibleState::Destroying; - assert!(d.should_spawn_debris()); - - d.complete_destruction(); - assert!(!d.should_spawn_debris()); - assert!(d.is_destroyed()); - } - - #[test] - fn destructible_reset_frame() { - let config = DestructibleConfig::default(); - let mut d = Destructible::new(DestructibleId(1), config, Vec3::ZERO); - d.accumulated_force = 123.0; - d.reset_frame(); - assert_eq!(d.accumulated_force, 0.0); - } - - #[test] - fn destruction_trigger_default_is_force_1000() { - let t = DestructionTrigger::default(); - assert_eq!(t, DestructionTrigger::Force { threshold: 1000.0 }); - } - - #[test] - fn destructible_config_defaults() { - let c = DestructibleConfig::default(); - assert_eq!(c.max_health, 100.0); - assert_eq!(c.damage_threshold, 10.0); - assert_eq!(c.force_to_damage, 0.1); - assert_eq!(c.destruction_force, 5.0); - } -} - // ============================================================================ // P7: PhysicsConfig & BuoyancyData (~8 estimated surviving mutants) // ============================================================================ diff --git a/docs/architecture/destruction.md b/docs/architecture/destruction.md index 0f7e75898d..723fdfaccf 100644 --- a/docs/architecture/destruction.md +++ b/docs/architecture/destruction.md @@ -9,8 +9,8 @@ lifecycle_status: active integration_status: wired summary: "Greybox digs with a sphere Subtract brush on ColumnFns. FlatColumnBase keeps the destruction replay hash." owns: [astraweave-destruction] -doc_version: "1.5" -last_verified_commit: 7a5fd4f6 +doc_version: "1.6" +last_verified_commit: 6c238fc0 runtime_edges: - to: astraweave-core note: "The core replay test calls demolition_bytes." @@ -26,9 +26,9 @@ runtime_edges: |---|---| | **System name** | Deterministic destruction | | **Primary crates** | `astraweave-destruction` | -| **Document version** | 1.5 | -| **Last verified against commit** | `7a5fd4f6` | -| **Last verified date** | 2026-10-16 | +| **Document version** | 1.6 | +| **Last verified against commit** | `6c238fc0` | +| **Last verified date** | 2026-10-21 | | **Status** | Active. Headless showcase and the required replay case. The Aravath greybox binds integer columns through `ColumnFns` and digs with a sphere `Subtract` brush. `Greybox::step` calls `BridgeAgent::step` after the motor. `apply_brush_now` loads every chunk in `(origin ± radius) / CHUNK_EXTENT` before the tick. A checkpoint stores `persist_bytes` and `restore_dug` replays that log before the next dig. `FlatColumnBase` remains the terrain when no functions are bound, so the `destruction` replay hash is unchanged. The greybox golden is `b6a9d5a2c5da28a6` (#330). The earlier #329 value was `0a576578512f25d2`. | | **Owner notes** | Design: `docs/current/DESTRUCTION_DESIGN.md`. Survey: `docs/current/DESTRUCTION_ARCHAEOLOGY.md`. `Fixed64` lives in `astraweave-math` (PR #245). | @@ -40,7 +40,7 @@ runtime_edges: Applies an ordered command log inside a 60 Hz tick. The log breaks a support graph, edits integer terrain, and steps a fixed debris pool. The per-tick SHA-256 is the replay hash. **Why it exists:** -The physics crate's `DestructionManager` is a float `HashMap` with no production caller, and Rapier is not in the cross-OS hash. +The physics crate's float `DestructionManager` is deleted. Rapier is not in the cross-OS hash. `PhysicsWorld` does not write `DestructionCommand`. **Where it primarily lives:** `astraweave-destruction`. `astraweave-core` holds `SIM_SYSTEM_DESTRUCTION` and the replay test. `examples/aravath_destruction` prints the showcase lines. @@ -90,7 +90,7 @@ Floats do not enter this pipeline. Rapier is not called. ### Not touched -- `astraweave-physics` `DestructionManager`, `add_destructible_box`, Rapier +- `astraweave-physics` `break_destructible` (Rapier body removal only), `add_destructible_box`. The float `DestructionManager` is removed. - `astraweave-terrain` column generator (the greybox passes function pointers; this crate does not import that crate) - `astraweave-render` passes (PR #216) - `astraweave-combat` (PR #212) @@ -122,7 +122,7 @@ Floats do not enter this pipeline. Rapier is not called. | Abstraction | Status | Disposition | |---|---|---| -| `astraweave-physics` `DestructionManager` | Dormant float toy | Left in place. New calls do not go through it | +| `astraweave-physics` `DestructionManager` | **Removed** (historical) | Deleted with `destruction.rs`, `benches/destruction.rs`, and `process_destructible_hits`. `break_destructible` only removes the Rapier body. `PhysicsWorld` does not write `DestructionCommand` | | `PhysicsWorld::add_destructible_box` | Stub | Not extended | | Greybox `dig_sphere` | Calls `apply_brush_now` | Sphere `Subtract` brush. Every chunk the radius touches is loaded before `tick`. The island mesh is carved by `seed - surface_y`. A checkpoint replays `persist_bytes` on load. A full command log returns before that carve | | #215 `surface_height` | Bound by the greybox | `column_gen` stays in `astraweave-terrain`. `ColumnFns` is the hook. `FlatColumnBase` stays for the replay case | @@ -205,3 +205,4 @@ Update this trace when the command set, the stress iteration count, the pool siz | 1.4 | 2026-10-16 | Merge `84d3888a`. `Greybox::step` calls `BridgeAgent`. Greybox golden is `0a576578512f25d2`. #249, #250, and #261 are still open on the tracker. | | 1.3 | 2026-10-16 | `ColumnFns` and `apply_brush_now`. Greybox digs with a brush. `FlatColumnBase` stays the unbound terrain. Issues #249 and #250 | | 1.5 | 2026-10-16 | `apply_brush_now` loads the brush span, not only the centre chunk. Greybox save stores the command log and replays it on restore. The `destruction` replay case and the greybox golden are unchanged. | +| 1.6 | 2026-10-21 | §6: the float `DestructionManager` is removed, not left in place. `break_destructible` only removes the Rapier body. | diff --git a/docs/architecture/physics.md b/docs/architecture/physics.md index 337e76d312..020e954e3c 100644 --- a/docs/architecture/physics.md +++ b/docs/architecture/physics.md @@ -11,8 +11,8 @@ runtime_edges: - to: astraweave-water note: "buoyancy (apply_buoyancy_forces, lib.rs:1464) consumes WaterQuery/AnalyticWater" owns: [astraweave-physics] -doc_version: "1.12" -last_verified_commit: 36cb2df9 +doc_version: "1.15" +last_verified_commit: d98b1657 --- # Architecture Trace: Physics @@ -23,10 +23,10 @@ last_verified_commit: 36cb2df9 |---|---| | **System name** | Physics (Rigid Body Simulation + Subsystems) | | **Primary crates** | `astraweave-physics` (12 source files / ~31K LoC), wraps `rapier3d 0.22` | -| **Document version** | 1.12 | -| **Last verified against commit** | `36cb2df9` | -| **Last verified date** | 2026-10-18 (v1.12: `benches/raycast.rs` `raycast_with_and_without_normal` steps once so the query pipeline sees the ground. v1.11: `deformed_step` takes `ClimbTick`. v1.10: `[patch.crates-io]` points `rapier3d` at `third_party/rapier3d` (crates.io 0.22). A settled step allocates nothing. Vendoring is the current choice. An in-house physics engine is not planned work. v1.9: `PhysicsWorld::step` no longer follows Rapier's step with a full `QueryPipeline::update`. The workspace patches `rapier3d` 0.22 so the drained modified-collider buffer is returned to the set. `one_physics_step_allocates_nothing` stays at 0 allocs.) | -| **Status** | **Active core** (`PhysicsWorld` + `CharacterController` + Rapier broadphase) **with feature-gated and dormant subsystems** (async-physics, ECS plugin, in-house SpatialHash). The core rigid-body / character / raycast surface is production-wired through `astraweave-gameplay` and `astraweave-npc`. 1.3: `PhysicsWorld::remove_body` is the shared removal path; `break_destructible` delegates to it. `aravath_runtime` uses it to replace chunk trimeshes. Several subsystems (projectile, gravity zones, ragdoll, vehicle, environment, destruction, cloth) are independent managers with rich APIs but limited production wiring — most have tests + benches but no game-loop consumer yet. The `SpatialHash` module is **dormant** despite being advertised in the crate doc-comment. | +| **Document version** | 1.15 | +| **Last verified against commit** | `d98b1657` | +| **Last verified date** | 2026-10-21 | +| **Status** | **Active core** (`PhysicsWorld` + `CharacterController` + Rapier broadphase) **with feature-gated and dormant subsystems** (async-physics, ECS plugin, in-house SpatialHash). The core rigid-body / character / raycast surface is production-wired through `astraweave-gameplay` and `astraweave-npc`. 1.14: `destruction.rs`, `DestructionManager`, `process_destructible_hits`, and `benches/destruction.rs` are removed. `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body. Fracture lives in `astraweave-destruction` and is not called from `PhysicsWorld`. 1.3: `PhysicsWorld::remove_body` is the shared removal path; `break_destructible` delegates to it. `aravath_runtime` uses it to replace chunk trimeshes. Several subsystems (projectile, ragdoll, vehicle, environment, cloth) are independent managers with rich APIs but limited production wiring. The `SpatialHash` module is **dormant** despite being advertised in the crate doc-comment. | | **Owner notes** | 1.12 (2026-10-18): `raycast_with_and_without_normal` calls `step()` before casting. The query pipeline is empty until then, so the ground ray missed and the bench exited 101. 1.11 (2026-10-17): `deformed_step` takes `ClimbTick` (flags + tick) so the function stays within Clippy's argument limit. The step body is unchanged. 1.10 (2026-10-17): `[patch.crates-io]` points `rapier3d` at `third_party/rapier3d` (crates.io 0.22). A settled step allocates nothing. Vendoring is the current choice. An in-house physics engine is not planned work. #262 stays open. 1.9 (2026-10-17): `PhysicsWorld::step` no longer follows Rapier's step with a full `QueryPipeline::update`. The workspace patches `rapier3d` 0.22 so the drained modified-collider buffer is returned to the set. `one_physics_step_allocates_nothing` stays at 0 allocs. 1.8 (2026-10-16): `gravity.rs` deleted in #330. #336 is closed. `PhysicsWorld::step` still reads the Rapier vector. Cell acceleration is `gravity_mm_s2`. 1.7 (2026-10-16): delete `gravity.rs` with the local sim (#336). 1.6 (2026-10-16): `GravityManager` stays off `PhysicsWorld::step`. This trace is forensic, not aspirational — it documents what is wired today, not what the doc-comments imply. Scale: 12 source files, 31K LoC, 20 test files, 10 benchmarks, 9 consumer Cargo deps (5 production + 4 examples). **Verification pass 2026-05-12 (version 1.1):** resolved 3 markers — (a) `astraweave-scripting` is a real production consumer that uses `PhysicsWorld` as an ECS resource AND wraps it in a `*const PhysicsWorld` raw pointer via `PhysicsProxy` for Rhai bindings (§4 Downstream row corrected); (b) `PhysicsWorld` IS `Send + Sync` (auto-derived, proven by compile-time obligations of `World::get_resource` — §8 Invariant 18 corrected, previous "Send but NOT Sync" claim was wrong); (c) `process_destructible_hits` has zero callers workspace-wide (closed in §11). Decision Log "[Reasoning not recovered]" markers (8 entries) remain — git log searches returned no physics-specific decision commits. **Deep investigation pass 2026-05-12 (version 1.2):** corrected 4 factual errors and enriched 2 Open Questions. Corrections: (a) the crate has **5 features**, not 3 — `alloc-counter` and `fast-alloc` were missing from §1, §5, Appendix A; (b) `alloc-counter` feature location in §9 was wrong (was "Cargo.toml:67-69 — wait that's astraweave-ai", actually `Cargo.toml:17` + bench gating at `:77-80`); (c) `SpatialHash` test surface in §11 was significantly under-counted (claimed "3 dedicated tests" — actually 20+ tests across 4 files: `behavioral_correctness_tests.rs`, `coverage_boost_tests.rs`, `cross_subsystem_validation.rs`, `spatial_hash_character_tests.rs` with 33 `#[test]` attributes); (d) the claim that "`benches/raycast.rs` mentions spatial-hash patterns" was wrong — zero `SpatialHash` references in any bench file. Enrichments: (a) §11 `ecs` feature question now documents three de facto consumer patterns (direct passthrough / `World::insert_resource` without feature / designed `PhysicsPlugin` with feature) — `astraweave-scripting` uses pattern (b) which sits between the existing two; (b) `SpatialHash` Open Question enriched with comprehensive test surface inventory + "no bench" correction. | --- @@ -34,7 +34,7 @@ last_verified_commit: 36cb2df9 ## 1. Executive Summary **What this system does:** -Provides 3D rigid-body simulation, kinematic character control, and a collection of optional physics subsystems (projectiles, gravity zones, ragdolls, vehicles, environmental effects, destruction, cloth) by wrapping Rapier3D 0.22 inside a higher-level `PhysicsWorld` facade with engine-native IDs (`BodyId: u64`) and glam vector types. +Provides 3D rigid-body simulation, kinematic character control, and optional physics subsystems (projectiles, ragdolls, vehicles, environmental effects, cloth) by wrapping Rapier3D 0.22 inside a higher-level `PhysicsWorld` facade with engine-native IDs (`BodyId: u64`) and glam vector types. Gravity zones and the float destruction manager are removed. **Why it exists:** Game-side code needs to manage rigid bodies, ground-aware character movement, raycasts, and joint constraints without exposing Rapier's lifetime-heavy raw handles or doing direct nalgebra↔glam conversions at every call site. `PhysicsWorld` is the single mutable state owner and `BodyId` is the stable identifier consumers store. @@ -45,11 +45,11 @@ Game-side code needs to manage rigid bodies, ground-aware character movement, ra - `astraweave-physics/src/async_scheduler.rs` (979 LoC) — `AsyncPhysicsScheduler` + `PhysicsStepProfile` (feature `async-physics`, dormant outside benches) - `astraweave-physics/src/ecs.rs` (84 LoC) — `PhysicsPlugin` + `PhysicsBodyComponent` (feature `ecs`, dormant) - `astraweave-physics/src/projectile.rs` (2,659 LoC) — `ProjectileManager`, `ProjectileConfig`, `ProjectileKind` (`Hitscan`/`Kinematic`) -- `astraweave-physics/src/gravity.rs` (1,425 LoC) — `GravityManager` + `GravityZone` + `GravityZoneShape` (`Box`/`Sphere`/`Point`) +- `astraweave-physics/src/gravity.rs` is removed (#330). `GravityManager` is historical. `PhysicsWorld::step` reads the Rapier gravity vector. - `astraweave-physics/src/ragdoll.rs` (3,062 LoC) — `Ragdoll`, `RagdollBuilder`, `BoneShape` (`Capsule`/`Sphere`/`Box`) - `astraweave-physics/src/vehicle.rs` (4,869 LoC) — `Vehicle`, `VehicleManager`, `WheelConfig`, drivetrain + friction curves - `astraweave-physics/src/environment.rs` (3,401 LoC) — `EnvironmentManager`, `WindZone` (`Global`/`Box`/`Sphere`/`Cylinder` shapes, `Directional`/`Vortex`/`Turbulent` types), `WaterVolume` (buoyancy) -- `astraweave-physics/src/destruction.rs` (2,788 LoC) — `DestructionManager`, `Destructible`, `FracturePattern`, `Debris` +- `astraweave-physics/src/destruction.rs` is removed, along with `DestructionManager`, `process_destructible_hits`, and `benches/destruction.rs`. `PhysicsWorld` does not write `DestructionCommand`. `add_destructible_box` ignores health and break impulse and creates a dynamic box. `break_destructible` only removes that Rapier body. Fracture is `astraweave-destruction` (`planar_children` is two pieces; `BreakRule::stone` strength is 100) and is not invoked from this crate. - `astraweave-physics/src/cloth.rs` (4,359 LoC) — `ClothManager`, `Cloth`, `ClothParticle` (Verlet integration), `DistanceConstraint` **Status note (read first):** @@ -212,12 +212,12 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b | **`SpatialHash` + `AABB`** | Independent grid broadphase data structure. `AABB { min: Vec3, max: Vec3 }` with `from_center_extents`/`from_sphere`/`intersects`. `SpatialHash::new(cell_size)` + `insert(id, aabb)` + `query(aabb)` + `query_unique` + `clear`. **NOT used by `PhysicsWorld`** (which uses Rapier's `DefaultBroadPhase`). | `spatial_hash.rs` | | **`ProjectileKind`** | `#[non_exhaustive]` 2-variant enum: `Hitscan` (instant raycast) / `Kinematic` (gravity + drag + bounce + penetrate). | `projectile.rs:43-52` | | **`ProjectileConfig`** | Spawn parameters: position, velocity, gravity_scale, drag, radius, max_lifetime, max_bounces, restitution, penetration, owner (`Option`), user_data. | `projectile.rs:55-84` | -| **`GravityZoneShape`** | `#[non_exhaustive]` 3-variant enum: `Box { min, max }`, `Sphere { center, radius }`, `Point { center, radius, strength }` (attractor/repulsor). | `gravity.rs:57-72` | -| **`GravityZone`** | A region overriding gravity for bodies inside. Has `priority: u32` — higher priority zones win. | `gravity.rs` | +| **`GravityZoneShape`** | Historical. The enum left with `gravity.rs` (#330). It is not a type in this crate. | removed `gravity.rs` | +| **`GravityZone`** | Historical. Zonal gravity left with `gravity.rs`. `PhysicsWorld.gravity` is the Rapier vector. | removed `gravity.rs` | | **`BoneShape`** | `#[non_exhaustive]` 3-variant enum for ragdoll bones: `Capsule { radius, half_height }`, `Sphere { radius }`, `Box { half_extents }`. Each has `volume()` for mass distribution. | `ragdoll.rs:39-65` | | **`WindZoneShape`** | `#[non_exhaustive]` 4-variant enum: `Global` (infinite), `Box { half_extents }`, `Sphere { radius }`, `Cylinder { radius, height }`. | `environment.rs:22-31` | | **`WindType`** | `#[non_exhaustive]` 3-variant enum: `Directional`, `Vortex { tangential_speed, inward_pull, updraft }`, `Turbulent { intensity, frequency }`. | `environment.rs:42-61` | -| **`DebrisShape`** | `#[non_exhaustive]` 3-variant enum: `Box { half_extents }`, `Sphere { radius }`, `ConvexHull { half_extents }` (currently approximated as Box per inline comment at `destruction.rs:28`). | `destruction.rs:23-30` | +| **`DebrisShape`** | Historical. The enum left with `destruction.rs`. It is not a type in this crate. | removed `destruction.rs` | | **`ClothParticle`** | Verlet integration state per particle: `position`, `prev_position`, `acceleration`, `inv_mass` (0 = pinned), `pinned: bool`. | `cloth.rs:17-29` | | **`PhysicsStepProfile`** | Per-step telemetry struct (`async-physics` feature only): `total_duration`, `broad_phase_duration`, `narrow_phase_duration`, `integration_duration`, `active_body_count`, `collision_pair_count`, `solver_iterations`. Percentage helpers: `broad_phase_percent` / `narrow_phase_percent` / `integration_percent`. | `async_scheduler.rs:17-74` | | **`AsyncPhysicsScheduler`** | `{ thread_count, last_profile, enable_profiling }`. `with_threads(n)` constructor. Records step durations. Active only behind feature `async-physics`. | `async_scheduler.rs:78-100` | @@ -226,9 +226,9 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b - **Rapier `RigidBodyHandle` vs engine `BodyId`**: `RigidBodyHandle` is Rapier's internal generational index. `BodyId` is the engine-stable `u64` handle. Game code uses `BodyId`; only `PhysicsWorld` internals translate via `body_ids: HashMap` and `handle_of` accessor. - **`SpatialHash` (in-crate) vs `DefaultBroadPhase` (Rapier)**: The in-crate `SpatialHash` is a standalone data structure with its own tests + doc-comments claiming "99.96% pair reduction." It is NOT used by `PhysicsWorld` — Rapier's `DefaultBroadPhase` is the actual broadphase. See §6 Conflict Map. -- **`PhysicsWorld::gravity` vs `GravityManager::default_gravity` vs `PhysicsConfig::gravity`**: Three places gravity is stated. `PhysicsConfig::gravity` is the constructor parameter; `PhysicsWorld::gravity: Vector` is the live setting Rapier consumes each step; `GravityManager` (in `gravity.rs`) is a separate optional system for per-body / zone-based gravity overrides — it is NOT wired into `PhysicsWorld::step` automatically. Consumers must drive `GravityManager` themselves and call `PhysicsWorld::apply_force` per body. -- **`buoyancy_bodies` (per-body) vs `add_water_aabb` (volume)**: `add_buoyancy(id, volume, drag)` (`lib.rs:1413`) tags a single body for buoyancy. `add_water_aabb` (`lib.rs:1449`) takes `_min`, `_max`, `_density`, `_linear_damp` but its body is a stub — **all parameters are underscored and the function body is empty** (`pub fn add_water_aabb(...) {}`). Water-volume-based buoyancy is not implemented in `PhysicsWorld`; only per-body buoyancy is. -- **`break_destructible(id)` (`PhysicsWorld`) vs `DestructionManager` (`destruction.rs`)**: `PhysicsWorld::break_destructible` removes a rigid body wholesale (cleans up Rapier maps + `char_map` + `buoyancy_bodies`). `DestructionManager` is a separate subsystem with `FracturePattern` + `Debris` for richer destruction. They are not coupled. +- **`PhysicsWorld::gravity` vs `PhysicsConfig::gravity`**: `PhysicsConfig::gravity` is the constructor parameter. `PhysicsWorld::gravity` is the Rapier vector consumed each step. `GravityManager` left with `gravity.rs` (#330). +- **`buoyancy_bodies` (per-body) vs `add_water_aabb` (volume)**: `add_buoyancy` (`lib.rs:1462`) stores volume and drag for one body. `add_water_aabb` (`lib.rs:1522`) calls `self.water.add_aabb` and is not a stub. `apply_buoyancy_forces` samples that volume only for bodies already in `buoyancy_bodies`, and the impulse multiplies `BuoyancyData.drag`. The AABB `linear_drag` is stored authoring data. +- **`break_destructible(id)` vs the removed `DestructionManager`**: `DestructionManager` is historical. `break_destructible` only calls `remove_body`. `PhysicsWorld` does not write `DestructionCommand`. --- @@ -281,20 +281,23 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b | `astraweave-physics/src/async_scheduler.rs` (979 LoC) | `AsyncPhysicsScheduler`, `PhysicsStepProfile` (per-step telemetry) | Active (feature `async-physics`); dormant in production | Cargo.toml gates the entire module on `#[cfg(feature = "async-physics")]`. Verified 2026-05-12: only `astraweave-physics/Cargo.toml:55` (`physics_async` bench `required-features = ["async-physics"]`) enables the feature; no production consumer enables it. | | `astraweave-physics/src/ecs.rs` (84 LoC) | `PhysicsPlugin` (`Plugin`), `PhysicsBodyComponent`, `physics_step_system`, `sync_physics_to_transform_system` | Active (feature `ecs`); dormant in production | Gated on `#[cfg(feature = "ecs")]`. Verified 2026-05-12: workspace grep for `astraweave-physics.*features.*ecs` or `astraweave-physics/features = ["ecs"]` returned zero matches in `.toml` files. No consumer enables the `ecs` feature. | | `astraweave-physics/src/projectile.rs` (2,659 LoC) | `ProjectileManager`, `ProjectileConfig`, `Projectile`, `ProjectileKind`, `ExplosionConfig`, `ExplosionResult`, `FalloffCurve`, `ProjectileHit`, `ProjectileId`, `predict_trajectory`, `hitscan`, `update` with caller-provided `raycast_fn` | Active (module-level) | Independent of `PhysicsWorld` — caller provides a `raycast_fn: F` closure to `ProjectileManager::update`. Consumer integration left to game code. | -| `astraweave-physics/src/gravity.rs` (1,425 LoC) | `GravityManager`, `GravityZone`, `GravityZoneShape` (`Box`/`Sphere`/`Point`), `BodyGravitySettings`, `BodyGravityId`, `GravityZoneId` | Active (module-level) | Independent of `PhysicsWorld::gravity`. Caller must apply forces back through `PhysicsWorld::apply_force` (no auto-integration). | +| `astraweave-physics/src/gravity.rs` | `GravityManager`, `GravityZone`, `GravityZoneShape` | **Removed** (historical) | Deleted in #330. Not a `pub mod`. `PhysicsWorld::step` still reads the Rapier gravity vector. | | `astraweave-physics/src/ragdoll.rs` (3,062 LoC) | `Ragdoll`, `RagdollBuilder`, `BoneDef`, `BoneJointType`, `BoneShape`, `RagdollConfig`, `RagdollId`, `RagdollPresets`, `RagdollState` | Active (module-level) | `RagdollBuilder::build(&mut PhysicsWorld, spawn_pos)` is the Bridge into `PhysicsWorld`. Per `ragdoll.rs:25-28` doc-comment. | | `astraweave-physics/src/vehicle.rs` (4,869 LoC) | `Vehicle`, `VehicleManager`, `VehicleConfig`, `WheelConfig`, `WheelPosition`, `WheelState`, `DrivetrainType`, `EngineConfig`, `FrictionCurve`, `TransmissionConfig`, `VehicleInput`, `VehicleId` | Active (module-level) | Raycast-suspension model (industry standard). Per `vehicle.rs:1-7` doc-comment. | | `astraweave-physics/src/environment.rs` (3,401 LoC) | `EnvironmentManager`, `WindZone`, `WindZoneConfig`, `WindType`, `WindZoneShape`, `WindZoneId`, `WaterVolume`, `WaterVolumeId`, `GustEvent` | Active (module-level) | Separate from `PhysicsWorld::wind: Vec3` (a bare global wind vector on `PhysicsWorld` itself). | -| `astraweave-physics/src/destruction.rs` (2,788 LoC) | `DestructionManager`, `Destructible`, `DestructibleConfig`, `DestructibleId`, `DestructibleState`, `DestructionEvent`, `DestructionTrigger`, `FracturePattern`, `Debris`, `DebrisConfig`, `DebrisId`, `DebrisShape` | Active (module-level) | Separate from `PhysicsWorld::add_destructible_box` (`lib.rs:1556`) which is a passthrough to `add_dynamic_box`. | +| `astraweave-physics/src/destruction.rs` | `DestructionManager`, `Destructible`, `FracturePattern`, `Debris`, `DebrisShape`, `process_destructible_hits` | **Removed** (historical) | Deleted. Not a `pub mod`. `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body. Fracture is `astraweave-destruction`. | | `astraweave-physics/src/cloth.rs` (4,359 LoC) | `Cloth`, `ClothManager`, `ClothCollider`, `ClothConfig`, `ClothId`, `ClothParticle`, `DistanceConstraint` | Active (module-level) | Verlet integration + distance constraints. Per `cloth.rs:1-7` doc-comment. | | `astraweave-physics/src/mutation_tests.rs` (1,259 LoC) | Mutation-killing inline tests inside `#[cfg(test)] mod mutation_tests` | Active (test-only) | | -| `astraweave-physics/tests/*` (20 files) | `behavioral_correctness_tests`, `buoyancy_test`, `coverage_boost_tests`, `cross_subsystem_validation`, `debug_render_test`, `determinism`, `ecs_integration_test`, `environment_tests`, `gravity_tests`, `mutation_resistant_*_tests` (×2), `nan_infinity_tests`, `panic_safety_tests`, `phase1_verification`, `physics_core_tests`, `physics_laws_tests`, `projectile_tests`, `ragdoll_tests`, `spatial_hash_character_tests`, `vehicle_tests` | Active | Comprehensive integration test surface | -| `astraweave-physics/benches/*` (10 files) | `alloc_measure` (`required-features = ["alloc-counter"]` per `Cargo.toml:77-80`), `character_controller`, `cloth`, `destruction`, `gravity`, `physics_async` (`required-features = ["async-physics"]` per `:52-55`), `ragdoll`, `raycast`, `rigid_body`, `vehicle` | Active | Benchmark surface. Two of the 10 benches are feature-gated: `physics_async` is the only consumer of `async-physics`; `alloc_measure` is the only consumer of `alloc-counter`. The `fast-alloc` feature (`Cargo.toml:20`) is bench-only (per inline comment "Does nothing to the library itself") but no bench currently declares `required-features = ["fast-alloc"]`. | +| `astraweave-physics/tests/*` (22 files) | `behavioral_correctness_tests`, `buoyancy_test`, `coverage_boost_tests`, `cross_subsystem_validation`, `debug_render_test`, `deformed_tick_alloc`, `determinism`, `ecs_integration_test`, `environment_tests`, `mutation_resistant_comprehensive_tests`, `mutation_resistant_tests`, `nan_infinity_tests`, `panic_safety_tests`, `phase1_verification`, `physics_core_tests`, `physics_laws_tests`, `projectile_tests`, `ragdoll_tests`, `spatial_hash_character_tests`, `traversal_replay`, `vehicle_tests`, `zero_alloc_step` | Active | `gravity_tests` is removed with `gravity.rs` | +| `astraweave-physics/benches/*` (8 files) | `alloc_measure` (`required-features = ["alloc-counter"]`), `character_controller`, `cloth`, `physics_async` (`required-features = ["async-physics"]`), `ragdoll`, `raycast`, `rigid_body`, `vehicle` | Active | `benches/destruction.rs` and `benches/gravity.rs` are **removed**. `physics_async` is the only consumer of `async-physics`. `alloc_measure` is the only consumer of `alloc-counter`. | + +Public modules, in `lib.rs` declaration order: `deformed`, `traversal`, `async_scheduler` (feature `async-physics`), `ecs` (feature `ecs`), `spatial_hash`, `projectile`, `ragdoll`, `vehicle`, `environment`, `cloth`. Private modules: `detmath`, and `mutation_tests` under `cfg(test)`. `destruction` and `gravity` are not modules. **Status definitions:** - **Active**: Canonical, load-bearing, edit with care - **Active (feature `X`)**: Compiles only when the named Cargo feature is enabled - **Dormant**: Compiles but has no production consumers (verified workspace grep) +- **Removed (historical)**: The file is gone. The row records what used to live there. --- @@ -309,11 +312,13 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b | `PhysicsWorld::wind: Vec3` (bare global) | `lib.rs:923` (struct field) | Active | Single global wind vector on `PhysicsWorld` itself. | | `EnvironmentManager::WindZone` family | `environment.rs` (3,401 LoC) | Active (module-level) | Richer zonal wind system with `WindZoneShape` + `WindType` enums. Independent of `PhysicsWorld.wind`. | | `PhysicsWorld::gravity: Vector` (single global) | `lib.rs:904` (struct field) | Active | Rapier consumes this each step (`:1086-1100`). | -| `GravityManager` + `GravityZone` (zonal/point attractors) | `gravity.rs` (1,425 LoC) | Active (module-level) | Independent of `PhysicsWorld.gravity`. Caller must drive `GravityManager` separately and apply per-body forces via `PhysicsWorld::apply_force`. | -| `PhysicsWorld::add_destructible_box` (passthrough) | `lib.rs:1556-1565` | Active | Wraps `add_dynamic_box`; `_health`/`_break_impulse` parameters are underscored and ignored. | -| `DestructionManager` + `Destructible` + `FracturePattern` | `destruction.rs` (2,788 LoC) | Active (module-level) | Richer destruction system. NOT coupled to `PhysicsWorld::break_destructible`. | -| `PhysicsWorld::add_water_aabb` (stub) | `lib.rs:1449` | **Stub** | All parameters (`_min, _max, _density, _linear_damp`) underscored; function body is `{}`. Water-volume-based buoyancy in `PhysicsWorld` is not implemented; per-body buoyancy via `add_buoyancy(id, volume, drag)` (`:1413`) IS implemented. | -| `EnvironmentManager::WaterVolume` + `WaterVolumeId` | `environment.rs` | Active (module-level) | Volume-based water system exists in environment module independent of the stub. | +| `GravityManager` + `GravityZone` (zonal/point attractors) | `gravity.rs` (removed) | **Removed** (historical) | Deleted in #330. `PhysicsWorld.gravity` is the Rapier vector. | +| `PhysicsWorld::add_destructible_box` (passthrough) | `lib.rs` | Active | Wraps `add_dynamic_box`; `_health`/`_break_impulse` parameters are underscored and ignored. | +| `DestructionManager` + `Destructible` + `FracturePattern` | `destruction.rs` (removed) | **Removed** (historical) | Deleted. `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body. Fracture is `astraweave-destruction`. | +| `process_destructible_hits` | was `lib.rs` | **Removed** | The stub is deleted. No symbol remains in `astraweave-physics`. | +| `benches/destruction.rs` | removed bench | **Removed** (historical) | The `[[bench]] name = "destruction"` entry is gone. The integer fracture bench is `astraweave-destruction/benches/destruction.rs`. | +| `PhysicsWorld::add_water_aabb` | `lib.rs:1522` | Active | Calls `self.water.add_aabb`. The box and density are live on `AnalyticWater`. Buoyancy impulses still require a `buoyancy_bodies` entry and use `BuoyancyData.drag`. The AABB `linear_drag` is stored and is not that drag. | +| `EnvironmentManager::WaterVolume` + `WaterVolumeId` | `environment.rs` | Active (module-level) | Separate volume manager. It is not `PhysicsWorld.water`. | | `astraweave-physics::ecs::PhysicsPlugin` (`ecs` feature) | `ecs.rs` (84 LoC) | Dormant | Feature-gated; no production consumer enables `ecs` feature. The plugin is the designed ECS integration path. | | `astraweave-gameplay::combat_physics::perform_attack_sweep` (direct `&mut PhysicsWorld`) | `astraweave-gameplay/src/combat_physics.rs` | Active | Bypasses ECS integration; takes raw `&mut PhysicsWorld` argument. The canonical production combat path. | | `astraweave-physics::AsyncPhysicsScheduler` (`async-physics` feature) | `async_scheduler.rs` (979 LoC) | Dormant | Feature-gated; only the bench `physics_async` enables it (`Cargo.toml:55`). | @@ -324,8 +329,8 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b - **`broad_phase`**: In `PhysicsWorld.broad_phase: DefaultBroadPhase` (`lib.rs:907`), means Rapier's broadphase. In `spatial_hash.rs` doc-comment, refers to the dormant in-crate `SpatialHash` advertised as "broad-phase collision optimization." Two different things in the same crate. - **`step` / `step_internal`**: `step` is the public entry point (`lib.rs:1039`); `step_internal` is the private body (`:1070`). `step` chooses between async and sync paths. - **Wind**: `PhysicsWorld.wind: Vec3` is a bare global. `EnvironmentManager::WindZone` is zonal. Both exist in the same crate. -- **`add_water_aabb` vs `add_buoyancy`**: `add_water_aabb` (`lib.rs:1449`) is a body-less stub. `add_buoyancy(body, volume, drag)` (`lib.rs:1413`) is the actual buoyancy attachment. Don't expect the former to do anything. -- **`break_destructible` (`PhysicsWorld`) vs `DestructionManager`**: Despite the name, `PhysicsWorld::break_destructible` is a wholesale-removal helper (deletes the body and cleans up internal maps). The richer fracture/debris system lives in `destruction.rs` and is independent. +- **`add_water_aabb` vs `add_buoyancy`**: `add_water_aabb` (`lib.rs:1522`) registers the volume. `add_buoyancy` (`lib.rs:1462`) attaches volume and drag to one body. The impulse uses the body's drag. +- **`break_destructible` (`PhysicsWorld`) vs the removed `DestructionManager`**: `DestructionManager` is historical. `break_destructible` only calls `remove_body`. It does not fracture, spawn debris, or read health. `PhysicsWorld` does not write `DestructionCommand`. - **`Layers` (bitflags, in-crate) vs Rapier's `Group`**: `Layers::DEFAULT | Layers::CHARACTER` is the engine-side bitset (`lib.rs:383-389`). Rapier's `InteractionGroups::new(Group::from_bits_truncate(layers.bits()), Group::ALL)` is the per-collider filter. Conversion happens at collider construction time inside `add_*` methods. - **Two `RigidBodyHandle ↔ BodyId` maps**: `body_ids: HashMap` and `body_kinds: HashMap` are parallel. The first translates handles to engine IDs; the second tracks actor kind per handle. Both have the same key set after `tag_body`. @@ -334,17 +339,17 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b - **Trap**: Reading the crate doc-comment at `lib.rs:25-26` ("`SpatialHash` — Grid-based broadphase for O(n log n) collision culling (99.96% pair reduction vs brute-force)") and assuming `PhysicsWorld` uses it. **What's actually true**: `PhysicsWorld` uses Rapier's `DefaultBroadPhase` (`lib.rs:907`). `SpatialHash` is a standalone data structure with its own tests but no production consumers. Verified 2026-05-12. -- **Trap**: Calling `add_water_aabb(min, max, density, linear_damp)` expecting it to enable water-volume buoyancy. - **What's actually true**: The function body is `{}` (`lib.rs:1449`); all parameters are underscored. Use `add_buoyancy(body, volume, drag)` (`:1413`) for per-body buoyancy. Volume-based water requires either `EnvironmentManager::WaterVolume` or a custom integration. +- **Trap**: Calling `add_water_aabb(min, max, density, linear_damp)` and expecting every body inside the box to float, or expecting `linear_damp` to be the impulse drag. + **What's actually true**: `lib.rs:1522` stores the box on `AnalyticWater`. `apply_buoyancy_forces` samples it only for bodies already in `buoyancy_bodies`. The impulse multiplies `BuoyancyData.drag`. The AABB damp is authoring data. - **Trap**: Reading `add_destructible_box(pos, half, mass, health, break_impulse)` and assuming `health` / `break_impulse` are tracked. - **What's actually true**: `_health` and `_break_impulse` are underscored (`lib.rs:1556-1565`). The function delegates to `add_dynamic_box` and returns the same `BodyId`. The richer destruction system lives in `destruction.rs` independently. + **What's actually true**: `_health` and `_break_impulse` are ignored. The function calls `add_dynamic_box` and returns that `BodyId`. `destruction.rs` and `DestructionManager` are removed. Fracture is `astraweave-destruction`. - **Trap**: Calling `physics_world.raycast(...)` BEFORE `physics_world.step()` and expecting it to reflect post-step geometry. **What's actually true**: `step_internal` updates the query pipeline at `lib.rs:1105` (`self.query_pipeline.update(&self.colliders)`) AFTER Rapier's step. Raycasts before `step()` see geometry from the previous frame's post-step state. This was the bug fixed in "Week 2 Day 3" per the inline comment at `:1102-1104`. - **Trap**: Treating `PhysicsWorld::break_destructible(id)` as just a "mark for destruction" hook. - **What's actually true**: It immediately removes the body from Rapier's set + `body_ids` + `body_kinds` + `char_map` + `buoyancy_bodies` (`lib.rs:1566-1584`). Caller code that holds the `BodyId` after this call gets `None` from `handle_of(id)` on subsequent queries. + **What's actually true**: It calls `remove_body` (`lib.rs:1652`), which removes the Rapier body and clears `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`, and `climb_flags`. A later `handle_of(id)` returns `None`. - **Trap**: Enabling the `ecs` feature on `astraweave-physics` and expecting it to wire automatically with `astraweave-ecs`. **What's actually true**: The `ecs` feature exists in `Cargo.toml:13` (`ecs = ["astraweave-ecs", "astraweave-scene"]`) and provides `PhysicsPlugin` (`ecs.rs:11-23`), but no production crate enables it. Production consumers (`astraweave-gameplay`, `astraweave-npc`) take `&mut PhysicsWorld` directly and call `step()` themselves. @@ -435,7 +440,7 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b | 4 | `apply_buoyancy_forces` runs BEFORE `pipeline.step` | Yes (code) | `lib.rs:1084` precedes `:1086` | | 5 | `add_character` always creates a `RigidBodyType::KinematicPositionBased` body, NOT dynamic | Yes (code) | `lib.rs:1206`: `RigidBodyBuilder::kinematic_position_based()` | | 6 | `add_character` always inserts a `CharacterController` entry into `char_map` keyed by the new `BodyId` | Yes (code) | `lib.rs:1218-1235`: `self.char_map.insert(id, CharacterController { ... })` | -| 7 | `break_destructible(id)` removes the body from ALL internal maps (`body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`) | Yes (code) | `lib.rs:1566-1584`: explicit 4-line cleanup after Rapier `bodies.remove` | +| 7 | `break_destructible(id)` calls `remove_body`, which removes the Rapier body and clears five maps: `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`, and `climb_flags` | Yes (code) | `lib.rs:1670` calls `remove_body` at `lib.rs:1652` | | 8 | `PhysicsConfig::default()` time_step = `1.0/60.0` (60 Hz target) | Yes (code) | `lib.rs:618` | | 8b | `traversal::step` advances exactly one `TICK_DT` and does not read `Instant` | Yes (code) | `traversal.rs` `TICK_DT`; replay test `traversal_replay` | | 9 | `PhysicsConfig::default()` gravity = `(0.0, -9.81, 0.0)` (Earth-like) | Yes (code) | `lib.rs:615` | @@ -446,12 +451,12 @@ Note: This path requires `astraweave-physics/features = ["ecs"]` to be enabled b | 14 | `CharState` is `#[non_exhaustive]` with exactly 1 variant: Grounded | Yes (code) | `lib.rs:391-395` | | 15 | `JointType` is `#[non_exhaustive]` with exactly 4 variants: Fixed / Revolute / Prismatic / Spherical | Yes (code) | `lib.rs:635-648` | | 16 | `ProjectileKind` is `#[non_exhaustive]` with exactly 2 variants: Hitscan / Kinematic; default = Kinematic | Yes (code) | `projectile.rs:43-52` | -| 17 | `add_water_aabb` is a no-op stub (function body is `{}`) | Yes (code) | `lib.rs:1449`: `pub fn add_water_aabb(&mut self, _min: Vec3, _max: Vec3, _density: f32, _linear_damp: f32) {}` | +| 17 | `add_water_aabb` registers an AABB on `PhysicsWorld.water`. It is not a stub | Yes (code) | `lib.rs:1522` calls `self.water.add_aabb`. `AnalyticWater::sample` can return that box's top face and density. `apply_buoyancy_forces` uses the sample only for bodies in `buoyancy_bodies`, and the impulse multiplies `BuoyancyData.drag` | | 18 | `PhysicsWorld` is `Send + Sync` (auto-derived) — must hold for use as `astraweave-ecs::World` resource | Yes (compile-time, transitively proven) | Verified 2026-05-12: `astraweave-ecs::World::get_resource` / `insert_resource` require `T: 'static + Send + Sync` (per `astraweave-ecs/src/lib.rs:466, 482, 486`). Multiple call sites compile: `astraweave-scripting/src/lib.rs:148, 336, 453, 506` (`world.get_resource::()`) and `astraweave-physics/tests/ecs_integration_test.rs:20` (`app.world.get_resource_mut::().unwrap()`). Therefore `PhysicsWorld` MUST be `Send + Sync`. The previous trace claim "Send but NOT Sync" was incorrect. | -| 19 | `process_destructible_hits` is a no-op stub with `#[allow(dead_code)]` | Yes (code) | `lib.rs:1586-1587`: `#[allow(dead_code)] fn process_destructible_hits(&mut self) {}` | +| 19 | `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body | Yes | `break_destructible` calls `remove_body` and stops. It does not fracture, spawn debris, or read health. `process_destructible_hits` is deleted. | | 20 | Crate uses `#![forbid(unsafe_code)]`; no unsafe blocks in any of the source files | Yes (compile-time + grep) | `lib.rs:1` | | 21 | Rapier is built with `enhanced-determinism`, and the character jump impulse and slope angle use `libm` | Yes (Cargo.toml + `detmath.rs`) | Root `Cargo.toml` `rapier3d` features include `enhanced-determinism` (`simba/libm_force`, `parry3d/enhanced-determinism`). `jump` calls `detmath::sqrt`. The ground snap calls `detmath::acos`. `build.rs` rejects `target-cpu=native` and `fma`. | -| 22 | `PhysicsWorld::step` and `step_internal` do not read `GravityManager` | Yes | `gravity.rs` `physics_step_does_not_read_gravity_manager`. The zone `HashMap` and `f32` values stay off the weave hash | +| 22 | `PhysicsWorld::step` and `step_internal` do not read `GravityManager` | Yes | `gravity.rs` is removed (#330). `step` reads the Rapier vector on `PhysicsWorld`. There is no zone `HashMap` in this crate. | --- @@ -479,7 +484,7 @@ Per the crate-level doc-comment at `lib.rs:43-48`: | Path | Frequency | Budget | |---|---|---| | `add_dynamic_box` / `add_static_trimesh` / `add_character` | At spawn time | Looser budget; can afford HashMap inserts and Rapier builder chains | -| `break_destructible` | On destruction events | Looser budget; one body removal + 4 HashMap cleanups | +| `break_destructible` | On destruction events | Looser budget; one body removal plus five map clears: `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`, `climb_flags` | | `add_joint` | At spawn time | Single `ImpulseJointSet::insert` after a `match joint_type` chain | | `enable_ccd(id)` | On-demand toggle | Single `rb.enable_ccd(true)` | | `set_body_position(id, pos)` | Editor-driven or scripted | Single `rb.set_translation` | @@ -492,7 +497,7 @@ Per the crate-level doc-comment at `lib.rs:43-48`: | `RigidBodySet`, `ColliderSet`, `ImpulseJointSet`, `MultibodyJointSet` | `PhysicsWorld` (public fields) | `PhysicsWorld` lifetime | Mutated only during `step`, `add_*`, `break_destructible`, `set_*` | | `PhysicsPipeline`, `IslandManager`, `DefaultBroadPhase`, `NarrowPhase`, `QueryPipeline`, `CCDSolver` | `PhysicsWorld` (public fields) | `PhysicsWorld` lifetime | Mutated during `step` | | `ChannelEventCollector` + crossbeam channels (`collision_recv`, `contact_force_recv`) | `PhysicsWorld` | `PhysicsWorld` lifetime | Events emitted during `step`; caller drains via `try_recv` / `recv` | -| `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies` HashMaps | `PhysicsWorld` (private + public) | `PhysicsWorld` lifetime | Inserted on `add_*`, removed on `break_destructible` | +| `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`, `climb_flags` | `PhysicsWorld` | `PhysicsWorld` lifetime | Inserted on `add_*` or climb setup; `remove_body` clears all five | | `DebugRenderPipeline` | `PhysicsWorld` (private field) | `PhysicsWorld` lifetime | Used by debug-render API; otherwise idle | ### Allocation profile @@ -504,13 +509,13 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 ## 10. Testing & Validation - **Unit tests:** Inline `#[cfg(test)]` modules in every source file (e.g. `lib.rs:2980-…` `control_character_applies_gravity_when_not_climbing`, etc.). 1,259 LoC of dedicated `mutation_tests.rs` inside `src/`. -- **Integration tests:** 20 files in `astraweave-physics/tests/`: - - `behavioral_correctness_tests`, `buoyancy_test`, `coverage_boost_tests`, `cross_subsystem_validation`, `debug_render_test`, `determinism`, `ecs_integration_test`, `environment_tests`, `gravity_tests`, `mutation_resistant_comprehensive_tests`, `mutation_resistant_tests`, `nan_infinity_tests`, `panic_safety_tests`, `phase1_verification`, `physics_core_tests`, `physics_laws_tests`, `projectile_tests`, `ragdoll_tests`, `spatial_hash_character_tests`, `vehicle_tests` +- **Integration tests:** 22 files in `astraweave-physics/tests/`. `gravity_tests` is removed with `gravity.rs`: + - `behavioral_correctness_tests`, `buoyancy_test`, `coverage_boost_tests`, `cross_subsystem_validation`, `debug_render_test`, `deformed_tick_alloc`, `determinism`, `ecs_integration_test`, `environment_tests`, `mutation_resistant_comprehensive_tests`, `mutation_resistant_tests`, `nan_infinity_tests`, `panic_safety_tests`, `phase1_verification`, `physics_core_tests`, `physics_laws_tests`, `projectile_tests`, `ragdoll_tests`, `spatial_hash_character_tests`, `traversal_replay`, `vehicle_tests`, `zero_alloc_step` - **Mutation testing:** Two mutation-resistant test files (`mutation_resistant_tests.rs`, `mutation_resistant_comprehensive_tests.rs`) plus the inline `src/mutation_tests.rs` (1,259 LoC). Status: included in workspace-wide mutation-testing campaign per CLAUDE.md (specific coverage stats out of scope for this trace). - **Miri validation:** Not directly applicable — the crate uses `#![forbid(unsafe_code)]` so no unsafe blocks exist locally. Miri validation of upstream Rapier3D is out of scope. -- **Benchmarks:** 10 files in `astraweave-physics/benches/`: +- **Benchmarks:** 8 files in `astraweave-physics/benches/`. `benches/destruction.rs` and `benches/gravity.rs` are removed: - `alloc_measure` (allocation profiling) - - `character_controller`, `cloth`, `destruction`, `gravity`, `ragdoll`, `raycast`, `rigid_body`, `vehicle` (per-subsystem). `raycast_with_and_without_normal` steps once after inserting the ground so `QueryPipeline` is not empty. + - `character_controller`, `cloth`, `ragdoll`, `raycast`, `rigid_body`, `vehicle`. `raycast_with_and_without_normal` steps once after inserting the ground so `QueryPipeline` is not empty. - `physics_async` (`required-features = ["async-physics"]`, the only consumer of the async feature) - **NaN/Infinity safety tests:** `tests/nan_infinity_tests.rs` exercises pathological inputs to verify no panics or NaN-propagation through the API - **Panic safety tests:** `tests/panic_safety_tests.rs` exercises invalid `BodyId` / `JointId` cases to verify graceful failure (no panics) @@ -525,11 +530,11 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 - **`SpatialHash` module — wire in or remove?** [Decisional / factual, **enriched 2026-05-12 deep investigation**.] Factual state (re-verified 2026-05-12): the `spatial_hash.rs` module (1,038 LoC) defines a complete grid-broadphase data structure with `AABB` + `SpatialHash` and is advertised in the crate-level doc-comment at `lib.rs:25-26` as the broadphase. Workspace grep for `use astraweave_physics::SpatialHash` or `use astraweave_physics::spatial_hash` outside the crate's own `src` + `tests` returned zero matches. `PhysicsWorld` uses Rapier's `DefaultBroadPhase` (`lib.rs:907`). **Test surface is more extensive than previously documented:** 4 test files reference `SpatialHash` — `tests/behavioral_correctness_tests.rs` (3+ tests including `test_spatial_hash_no_false_negatives` at `:652`, `test_spatial_hash_no_false_positives` at `:684`, `test_mutation_spatial_hash_cell_boundary` at `:996`), `tests/coverage_boost_tests.rs:868-…` (`spatial_hash_coverage` mod with multiple tests), `tests/cross_subsystem_validation.rs:13, :280-…` (including `test_spatial_hash_with_multiple_physics_objects` and `test_spatial_hash_determinism`), and `tests/spatial_hash_character_tests.rs` (33 `#[test]` attributes total, mixed with character_controller tests — first ~20 are SpatialHash + AABB tests at lines `:18-:240`). **No dedicated benchmark file:** workspace grep for `SpatialHash\|spatial_hash` in `benches/*.rs` returned zero matches; the previous trace claim about `benches/raycast.rs` mentioning spatial-hash patterns was incorrect (`grep -c "SpatialHash\|spatial_hash" benches/raycast.rs` returned `0`). The "3.77 ms vs 5.61 ms" comparison cited at `lib.rs:48` and `Cargo.toml:32` was a Phase B measurement preserved in code comments, not an ongoing bench harness. Whether to wire `SpatialHash` into `PhysicsWorld` (replacing or supplementing `DefaultBroadPhase`), expose it as a public utility for external broadphase needs, or remove it is undecided. The doc-comment claim "99.96% pair reduction vs brute-force" is sourced from the Phase B comment, not from a currently-running bench. - **`async-physics` feature — production-wire or experimental?** [Decisional.] Factual: the `async-physics` feature gates `AsyncPhysicsScheduler` + `PhysicsStepProfile` + `enable_async_physics` (`lib.rs:1010-1031`). Verified 2026-05-12: only `astraweave-physics/Cargo.toml:55` (the `physics_async` bench) enables it. No production consumer sets `features = ["async-physics"]`. The scheduler integrates by recording telemetry inside the existing `step()` path; Rapier itself uses Rayon's global thread pool when available (per inline comment at `lib.rs:1045-1047`). Whether to enable the feature by default, make it on-by-default opt-out, or keep as opt-in experimental is undecided. - **`ecs` feature — production-wire `PhysicsPlugin` or rely on direct `&mut PhysicsWorld` passthrough?** [Decisional, **enriched 2026-05-12 deep investigation**.] Factual: `PhysicsPlugin` exists in `ecs.rs:11-23` and registers `physics_step_system` + `sync_physics_to_transform_system` on `SystemStage::PHYSICS`. Verified 2026-05-12: no production consumer enables `features = ["ecs"]` (workspace grep for `astraweave-physics.*features.*ecs` in `.toml` files returned zero matches outside the physics crate's own declaration at `Cargo.toml:11`). **Three de facto consumer patterns exist today:** (a) Direct `&mut PhysicsWorld` passthrough — `astraweave-gameplay::combat_physics::perform_attack_sweep` (`combat_physics.rs:36`), `astraweave-npc::NpcManager` (`runtime.rs:21`). (b) ECS-resource pattern WITHOUT the `ecs` feature — `astraweave-scripting/src/lib.rs:148, 336, 453, 506` uses `World::insert_resource(physics)` + `get_resource::()` which works because `World::*_resource` only requires `T: 'static + Send + Sync`, NOT the physics-side `ecs` feature. (c) The designed `PhysicsPlugin` path — gated on the `ecs` feature, exercised only by `tests/ecs_integration_test.rs:1` (which declares `#[cfg(feature = "ecs")]`). The decisional question is whether to migrate (a) and (b) onto (c), keep all three patterns in parallel, or formalize (b) as a documented third pattern. -- **`add_water_aabb` stub — implement or remove?** [Decisional / factual.] Factual: `lib.rs:1449` defines `pub fn add_water_aabb(&mut self, _min: Vec3, _max: Vec3, _density: f32, _linear_damp: f32) {}` — all parameters underscored, function body is `{}`. The per-body `add_buoyancy` (`:1413`) IS implemented. `EnvironmentManager::WaterVolume` (`environment.rs`) exists as a parallel volume-based system. Whether to implement `add_water_aabb` (integrating with `EnvironmentManager::WaterVolume`), document the stub status, or remove the function entirely is undecided. -- **`add_destructible_box` — passthrough or distinct?** [Decisional / factual.] Factual: `lib.rs:1556-1565` defines `add_destructible_box(pos, half, mass, _health, _break_impulse) -> BodyId` that ignores `_health` + `_break_impulse` and delegates to `add_dynamic_box`. The richer `DestructionManager` system (`destruction.rs`, 2,788 LoC) is independent. Whether to make `add_destructible_box` actually integrate with `DestructionManager`, document the passthrough behavior, or remove the function is undecided. +- **`add_water_aabb`.** [Closed 2026-10-21.] `lib.rs:1522` calls `self.water.add_aabb(min, max, density, linear_damp)`. The empty body is gone. `AnalyticWater::sample` can return that box. `apply_buoyancy_forces` still iterates only `buoyancy_bodies`, and the impulse uses `BuoyancyData.drag`. `EnvironmentManager::WaterVolume` stays a separate manager. +- **`add_destructible_box` — passthrough.** [Closed as a passthrough, 2026-10-21.] `add_destructible_box` ignores `_health` and `_break_impulse` and calls `add_dynamic_box`. `DestructionManager`, `destruction.rs`, `process_destructible_hits`, and `benches/destruction.rs` are removed. `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body. Fracture is `astraweave-destruction`. `examples/physics_demo3d` key M still only deletes a body. That window is deferred in #411. - **`PhysicsWorld.wind: Vec3` vs `EnvironmentManager::WindZone` — unify or document parallel intent?** [Decisional / factual.] Factual: `PhysicsWorld.wind: Vec3` (`lib.rs:923`) is a bare global wind vector. `EnvironmentManager::WindZone` (`environment.rs`, 3,401 LoC) is a zonal wind system with shape + type variants. The two are not integrated. Whether to drive `PhysicsWorld.wind` from `EnvironmentManager`, keep them parallel, or remove the bare field is undecided. - **`PhysicsWorld.gravity` vs zonal `GravityManager`.** [Closed 2026-10-16, #330.] `astraweave-physics/src/gravity.rs` is deleted. #336 is closed. `PhysicsWorld::step` still reads the Rapier vector. Cell acceleration is `astraweave_weaving::gravity_mm_s2` of the zone's milli-g, sampled by `LocalSim`. Older paragraphs in this trace that cite `gravity.rs` describe the removed file. - + - **`astraweave-physics::ecs::PhysicsBodyComponent.0` is `BodyId` (`u64`) wrapped in tuple struct — match `astraweave-ecs` patterns?** [Factual / decisional.] `ecs.rs:8` defines `pub struct PhysicsBodyComponent(pub BodyId)`. The pub-tuple-struct pattern is consistent with simple ECS component conventions. Whether to add helper methods, `Display` impl, or migrate to a richer component shape is undecided. @@ -539,15 +544,21 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 ## 12. Maintenance Notes +**Revision 1.15 (2026-10-21):** `add_water_aabb` is not a stub. `lib.rs:1522` registers an AABB on `AnalyticWater`. Invariant 17, the §6 row, the §11 question, and Appendix A items 4 and 5 match that. Invariant 7 and Appendix A item 11: `remove_body` clears five maps, including `climb_flags`. + +**Revision 1.14 (2026-10-21):** §5 matches the `pub mod` list. `destruction.rs`, `DestructionManager`, `process_destructible_hits`, and `benches/destruction.rs` are removed (historical), as is `gravity.rs`. Invariant 19: `PhysicsWorld` does not write `DestructionCommand`. `break_destructible` only removes the Rapier body. + +**Revision 1.13 (2026-10-21):** Deleted the dormant float `destruction.rs` manager and `process_destructible_hits`. Piece count and break strength stay on `astraweave-destruction` (`planar_children`, `BreakRule::stone`). `break_destructible` still calls `remove_body`. The render path is unchanged. + **Update this doc when:** -- A new variant is added to any `#[non_exhaustive]` enum: `ActorKind`, `CharState`, `JointType`, `ProjectileKind`, `GravityZoneShape`, `BoneShape`, `WindZoneShape`, `WindType`, `DebrisShape` (touch §3 vocabulary + §8 invariants) +- A new variant is added to any `#[non_exhaustive]` enum: `ActorKind`, `CharState`, `JointType`, `ProjectileKind`, `BoneShape`, `WindZoneShape`, `WindType` (touch §3 vocabulary + §8 invariants). `GravityZoneShape` and `DebrisShape` are removed. - A new `add_*` body-creation method is added to `PhysicsWorld` (touch §4 upstream interfaces + §5 file map + §8 invariants if a new actor-kind tagging behavior is introduced) - The order of operations inside `step_internal` changes (touch §2.1 pipeline + §7 decision log if rationale changes) - A new feature gate is added to `Cargo.toml` (touch §5 file map status + §11 if production wiring is in question) - `SpatialHash` is wired into `PhysicsWorld` or removed (touch §5 status + §6 conflict map + §11 closure) - `async-physics` or `ecs` features gain production consumers (touch §5 status + §11 closure) - A new consumer crate adds an `astraweave-physics` dep (touch §4 downstream table + §5 file map) -- `process_destructible_hits`, `add_water_aabb`, or other stub methods are implemented or removed (touch §6 stub list + §8 invariants) +- `add_water_aabb` sampling or the buoyancy impulse changes (touch §6 and invariant 17). `process_destructible_hits` is already removed. - Rapier3D is upgraded to a new major version (touch §1 status + crate-level doc-comment + every public re-export at `lib.rs:53-103`) **Verification process:** @@ -567,20 +578,20 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 1. **`PhysicsWorld` is the single mutable owner.** All add/remove/step/query operations require `&mut PhysicsWorld`. Game code stores `BodyId: u64` (NOT Rapier `RigidBodyHandle`). 2. **`step()` always updates `query_pipeline` AFTER Rapier's step.** Raycasts within the same tick see post-step geometry (per `lib.rs:1102-1104` "Week 2 Day 3" fix). 3. **`SpatialHash` is dormant.** The crate doc-comment advertises it as the broadphase but `PhysicsWorld` uses Rapier's `DefaultBroadPhase`. Do not assume `SpatialHash` is in the live path. -4. **`add_water_aabb`, `process_destructible_hits`, and the `_health`/`_break_impulse` params of `add_destructible_box` are stubs** — calling them is harmless but does nothing. -5. **Per-body `add_buoyancy` works.** Volume-based water buoyancy in `PhysicsWorld` is not implemented; for richer water you need `EnvironmentManager::WaterVolume` from `environment.rs`. -6. **`PhysicsWorld.wind: Vec3` and `EnvironmentManager::WindZone` are parallel systems**, not unified. Same for `PhysicsWorld.gravity` vs `GravityManager`. +4. **`add_water_aabb` registers a water volume** at `lib.rs:1522` (`self.water.add_aabb`). It is not a stub. The `_health` and `_break_impulse` params of `add_destructible_box` are still ignored. `process_destructible_hits` is removed. `break_destructible` only calls `remove_body`. +5. **`add_buoyancy` stores per-body volume and drag.** `add_water_aabb` supplies the box and density that `water.sample` can return. The impulse multiplies `BuoyancyData.drag`, not the AABB's stored damp. `EnvironmentManager::WaterVolume` is a separate manager. +6. **`PhysicsWorld.wind: Vec3` and `EnvironmentManager::WindZone` are parallel systems**, not unified. `GravityManager` left with `gravity.rs` (#330). `PhysicsWorld.gravity` is the Rapier vector. 7. **All AI/game-loop callers pass fixed `dt = 1.0/60.0` to `control_character`.** The function uses `dt` internally for timer + gravity updates, but `astraweave-npc/src/runtime.rs:33-34` hardcodes the value. Variable-dt callers must call themselves at game-tick rate. 8. **All event channels (`collision_recv`, `contact_force_recv`) are unbounded.** Unconsumed events accumulate in memory; drain them every tick. 9. **`#![forbid(unsafe_code)]` is enforced at crate level.** No SIMD intrinsics or raw FFI here; rely on glam auto-vectorization + Rapier's internal optimizations. -10. **All `#[non_exhaustive]` enums are forward-compatible.** Adding a variant within the crate works; external matches must include a wildcard arm. Adding a variant to `ActorKind`, `CharState`, `JointType`, `ProjectileKind`, `BoneShape`, `WindZoneShape`, `WindType`, `GravityZoneShape`, or `DebrisShape` requires touching dispatch + dependents per CLAUDE.md Integration Completeness #2. -11. **`break_destructible(id)` is wholesale.** It deletes the body from Rapier + 4 internal HashMaps. Subsequent `handle_of(id)` returns `None`. +10. **All `#[non_exhaustive]` enums are forward-compatible.** Adding a variant within the crate works; external matches must include a wildcard arm. Adding a variant to `ActorKind`, `CharState`, `JointType`, `ProjectileKind`, `BoneShape`, `WindZoneShape`, or `WindType` requires touching dispatch + dependents per CLAUDE.md Integration Completeness #2. `GravityZoneShape` and `DebrisShape` left with the removed `gravity.rs` and `destruction.rs`. +11. **`break_destructible(id)` calls `remove_body`.** That deletes the Rapier body and clears five maps: `body_ids`, `body_kinds`, `char_map`, `buoyancy_bodies`, and `climb_flags`. Subsequent `handle_of(id)` returns `None`. 12. **Five feature gates exist but none are production-wired today**: `async-physics`, `profiling`, `ecs`, `alloc-counter`, `fast-alloc`. The first three are designed (`AsyncPhysicsScheduler`, Tracy spans, `PhysicsPlugin`); the last two are bench-only (`alloc_measure` bench `required-features`, `fast-alloc` for benchmark allocator swap). Production wiring of any of them is undecided. **Files you'll most likely touch:** - `astraweave-physics/src/lib.rs` — `PhysicsWorld` + `CharacterController` + core APIs -- `astraweave-physics/src/projectile.rs` / `gravity.rs` / `ragdoll.rs` / `vehicle.rs` / `environment.rs` / `destruction.rs` / `cloth.rs` — per-subsystem managers +- `astraweave-physics/src/projectile.rs` / `ragdoll.rs` / `vehicle.rs` / `environment.rs` / `cloth.rs` — per-subsystem managers. `gravity.rs` and `destruction.rs` are removed. - `astraweave-gameplay/src/combat_physics.rs` — canonical production combat sweep using `&mut PhysicsWorld` **Files you should NOT touch without strong reason:** @@ -593,7 +604,7 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 **Common mistakes when changing this system:** - **Assuming `SpatialHash` is wired in.** It isn't. The lib.rs doc-comment is aspirational. Don't extend `SpatialHash` thinking it affects production performance. -- **Calling `add_water_aabb` and expecting buoyancy.** Use `add_buoyancy(body, volume, drag)` instead. +- **Calling `add_water_aabb` and expecting every body in the box to float.** The box is registered. Buoyancy still needs `add_buoyancy`, and the impulse uses that body's drag. - **Forgetting to drain `collision_recv` + `contact_force_recv`.** Unbounded channels grow forever. - **Adding a variant to a `#[non_exhaustive]` enum without checking dispatch.** Match arms in subsystems (e.g. `add_joint` matching `JointType`) need updates. - **Trying to share `PhysicsWorld` across threads.** Even if `Send + Sync` auto-derive permits it, the API requires exclusive `&mut` access for the entire `step` + `add_*` + `set_*` surface. @@ -605,7 +616,7 @@ Per inline `lib.rs:1071-1075`: "Allocation-measurement instrumentation (audit 20 The crate wraps Rapier3D — the de-facto Rust physics engine — to provide engine-stable handles and glam-native types. Two recurring patterns shape the trace: -1. **Subsystem proliferation pre-dating integration.** The crate contains seven feature-rich subsystems (projectile, gravity zones, ragdoll, vehicle, environment, destruction, cloth) each with its own manager type and rich enum vocabulary. Each was developed in parallel as a self-contained module with tests + benches, but most have not yet been wired into `PhysicsWorld`'s step cycle or into a production consumer's game loop. Per the documented performance numbers (114 ns character move, 6.52 µs step, etc.) the core has been profile-optimized; the subsystems await integration campaigns. +1. **Subsystem proliferation pre-dating integration.** The crate still has projectile, ragdoll, vehicle, environment, and cloth managers. Gravity zones and the float destruction manager are removed. The remaining managers were developed as self-contained modules, and most are not wired into `PhysicsWorld`'s step. Per the documented performance numbers (114 ns character move, 6.52 µs step, etc.) the core has been profile-optimized. 2. **In-house broadphase vs Rapier broadphase.** The `SpatialHash` module (1,038 LoC, FxHashMap-optimized per the `Cargo.toml:35` "Phase B" comment) was authored as an alternative or supplement to Rapier's broadphase. The crate-level doc-comment at `lib.rs:25-26` advertises it as the broadphase, but the actual implementation in `PhysicsWorld` uses `DefaultBroadPhase` from Rapier directly. Whether `SpatialHash` is intended as a future replacement, a supplemental high-coherency tier, or vestigial is recorded as an Open Question in §11. diff --git a/examples/physics_demo3d/src/main.rs b/examples/physics_demo3d/src/main.rs index a98c82b9dc..4ea254879b 100644 --- a/examples/physics_demo3d/src/main.rs +++ b/examples/physics_demo3d/src/main.rs @@ -224,6 +224,9 @@ impl ApplicationHandler for PhysicsApp { println!("Spawned destructible"); } KeyCode::KeyM if down => { + // Deferred: #411. This only deletes the Rapier body. + // Health and break impulse are ignored. A DestructionWorld + // retarget needs a mesh this window does not have. if let Some(id) = self.destruct_ids.pop() { self.phys.break_destructible(id); println!("Break destructible");