LINE1 10 20 30 40 50 60 70 80 901use serde::Serialize;23const WIDTH: f64 = 100.0;4const HEIGHT: f64 = 70.0;5const RESTITUTION: f64 = 0.94;678#[derive(Clone, Debug, Serialize)]9pub struct Body {10 11 pub id: u8,12 13 pub x: f64,14 15 pub y: f64,16 17 pub vx: f64,18 19 pub vy: f64,20 21 pub radius: f64,22 23 pub mass: f64,24}252627#[derive(Clone, Debug, Serialize)]28pub struct Collision {29 30 pub first: u8,31 32 pub second: u8,33 34 pub x: f64,35 36 pub y: f64,37 38 pub tick: u64,39}404142#[derive(Clone, Debug, Serialize)]43pub struct Snapshot {44 45 pub bodies: Vec<Body>,46 47 pub collisions: u64,48 49 pub running: bool,50 51 pub tick: u64,52 53 pub width: f64,54 55 pub height: f64,56}575859pub struct Simulation {60 bodies: Vec<Body>,61 collisions: u64,62 running: bool,63 tick: u64,64}6566impl Simulation {67 68 #[must_use]69 pub fn new() -> Self {70 Self {71 bodies: initial_bodies(),72 collisions: 0,73 running: true,74 tick: 0,75 }76 }7778 79 #[must_use]80 pub fn snapshot(&self) -> Snapshot {81 Snapshot {82 bodies: self.bodies.clone(),83 collisions: self.collisions,84 running: self.running,85 tick: self.tick,86 width: WIDTH,87 height: HEIGHT,88 }89 }9091 92 pub fn set_running(&mut self, running: bool) {93 self.running = running;94 }9596 97 pub fn reset(&mut self) {98 *self = Self::new();99 }100101 102 #[must_use]103 pub fn step(&mut self, delta_seconds: f64) -> Vec<Collision> {104 if !self.running || !delta_seconds.is_finite() || delta_seconds <= 0.0 {105 return Vec::new();106 }107108 self.tick += 1;109 for body in &mut self.bodies {110 body.x += body.vx * delta_seconds;111 body.y += body.vy * delta_seconds;112 bounce_from_walls(body);113 }114115 let mut impacts = Vec::new();116 for first_index in 0..self.bodies.len() {117 for second_index in (first_index + 1)..self.bodies.len() {118 let (before_second, second_and_after) = self.bodies.split_at_mut(second_index);119 if let Some(impact) = resolve_pair(120 &mut before_second[first_index],121 &mut second_and_after[0],122 self.tick,123 ) {124 impacts.push(impact);125 self.collisions += 1;126 }127 }128 }129 impacts130 }131}132133impl Default for Simulation {134 fn default() -> Self {135 Self::new()136 }137}138139fn initial_bodies() -> Vec<Body> {140 vec![141 body(1, 25.0, 35.0, 18.0, 0.0, 4.0, 1.0),142 body(2, 75.0, 35.0, -18.0, 0.0, 4.0, 1.0),143 body(3, 50.0, 17.0, 9.0, 8.0, 3.2, 0.8),144 body(4, 24.0, 55.0, 8.0, -13.0, 3.6, 1.2),145 body(5, 76.0, 54.0, -8.0, -11.0, 3.0, 0.9),146 body(6, 50.0, 51.0, 0.0, 12.0, 3.4, 1.1),147 ]148}149150fn body(id: u8, x: f64, y: f64, vx: f64, vy: f64, radius: f64, mass: f64) -> Body {151 Body {152 id,153 x,154 y,155 vx,156 vy,157 radius,158 mass,159 }160}161162fn bounce_from_walls(body: &mut Body) {163 if body.x < body.radius {164 body.x = body.radius;165 body.vx = body.vx.abs();166 } else if body.x > WIDTH - body.radius {167 body.x = WIDTH - body.radius;168 body.vx = -body.vx.abs();169 }170 if body.y < body.radius {171 body.y = body.radius;172 body.vy = body.vy.abs();173 } else if body.y > HEIGHT - body.radius {174 body.y = HEIGHT - body.radius;175 body.vy = -body.vy.abs();176 }177}178179fn resolve_pair(first: &mut Body, second: &mut Body, tick: u64) -> Option<Collision> {180 let dx = second.x - first.x;181 let dy = second.y - first.y;182 let distance_squared = dx.mul_add(dx, dy * dy);183 let minimum_distance = first.radius + second.radius;184 if distance_squared >= minimum_distance * minimum_distance {185 return None;186 }187188 let distance = distance_squared.sqrt();189 let (normal_x, normal_y) = if distance > f64::EPSILON {190 (dx / distance, dy / distance)191 } else {192 (1.0, 0.0)193 };194 let relative_speed =195 (second.vx - first.vx).mul_add(normal_x, (second.vy - first.vy) * normal_y);196 let impact = Collision {197 first: first.id,198 second: second.id,199 x: first.x + normal_x * first.radius,200 y: first.y + normal_y * first.radius,201 tick,202 };203204 let inverse_first_mass = 1.0 / first.mass;205 let inverse_second_mass = 1.0 / second.mass;206 let inverse_mass_sum = inverse_first_mass + inverse_second_mass;207 let overlap = minimum_distance - distance;208 first.x -= normal_x * overlap * inverse_first_mass / inverse_mass_sum;209 first.y -= normal_y * overlap * inverse_first_mass / inverse_mass_sum;210 second.x += normal_x * overlap * inverse_second_mass / inverse_mass_sum;211 second.y += normal_y * overlap * inverse_second_mass / inverse_mass_sum;212213 if relative_speed < 0.0 {214 let impulse = -(1.0 + RESTITUTION) * relative_speed / inverse_mass_sum;215 first.vx -= impulse * inverse_first_mass * normal_x;216 first.vy -= impulse * inverse_first_mass * normal_y;217 second.vx += impulse * inverse_second_mass * normal_x;218 second.vy += impulse * inverse_second_mass * normal_y;219 Some(impact)220 } else {221 None222 }223}224225#[cfg(test)]226mod tests {227 use super::{Body, Simulation, body};228229 #[test]230 fn bodies_advance_and_reflect_at_world_edges() {231 let mut simulation = Simulation::new();232 simulation.bodies = vec![body(1, 95.0, 20.0, 10.0, 0.0, 4.0, 1.0)];233234 assert!(simulation.step(0.5).is_empty());235236 assert!((simulation.bodies[0].x - 96.0).abs() < f64::EPSILON);237 assert!((simulation.bodies[0].vx + 10.0).abs() < f64::EPSILON);238 }239240 #[test]241 fn approaching_bodies_resolve_an_impact_and_separate() {242 let mut simulation = Simulation::new();243 simulation.bodies = vec![244 body(1, 40.0, 30.0, 5.0, 0.0, 4.0, 1.0),245 body(2, 47.0, 30.0, -5.0, 0.0, 4.0, 1.0),246 ];247248 let impacts = simulation.step(0.01);249250 assert_eq!(impacts.len(), 1);251 assert_eq!((impacts[0].first, impacts[0].second), (1, 2));252 assert!(simulation.bodies[1].x - simulation.bodies[0].x >= 8.0);253 assert!(simulation.bodies[0].vx < 0.0);254 assert!(simulation.bodies[1].vx > 0.0);255 assert_eq!(simulation.collisions, 1);256 }257258 #[test]259 fn overlapping_bodies_moving_apart_do_not_report_new_impact() {260 let mut simulation = Simulation::new();261 simulation.bodies = vec![262 body(1, 40.0, 30.0, -2.0, 0.0, 4.0, 1.0),263 body(2, 47.0, 30.0, 2.0, 0.0, 4.0, 1.0),264 ];265266 assert!(simulation.step(0.01).is_empty());267 assert_eq!(simulation.collisions, 0);268 }269270 #[test]271 fn pause_blocks_updates_and_reset_restores_initial_scene() {272 let mut simulation = Simulation::new();273 let initial: Vec<Body> = simulation.bodies.clone();274 simulation.set_running(false);275276 assert!(simulation.step(1.0).is_empty());277 assert_eq!(simulation.tick, 0);278 assert!((simulation.bodies[0].x - initial[0].x).abs() < f64::EPSILON);279280 simulation.set_running(true);281 assert!(simulation.step(0.1).is_empty());282 simulation.reset();283 assert_eq!(simulation.tick, 0);284 assert_eq!(simulation.collisions, 0);285 assert!((simulation.bodies[0].x - initial[0].x).abs() < f64::EPSILON);286 }287}