diff --git a/simulator/src/main.rs b/simulator/src/main.rs index e9f1f70..378d823 100644 --- a/simulator/src/main.rs +++ b/simulator/src/main.rs @@ -1,4 +1,9 @@ use std::cmp::min; +use std::collections::HashMap; +use std::f32::consts::TAU; +use std::ptr; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use macroquad::prelude::*; use parry2d::math::Pose; @@ -12,16 +17,50 @@ use parry2d::shape::Shape; const VIEW_DIST: f32 = 180.0; const BOT_RADIUS: f32 = 16.0; +const KILL_RADIUS: f32 = 140.0; + +trait Mortal { + fn collider(&self) -> (&Pose, &dyn Shape); + fn kill(&self); + fn living(&self) -> bool; + + fn draw(&self); +} struct Robot { pose: Pose, - alive: bool, + alive: AtomicBool, + collider: Ball, + sensor: Sensor, + team: Color, +} + +impl Mortal for Robot { + fn draw(&self) { + let tl = self.pose.translation; + let tl2 = self.view_end(); + draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK); + draw_line(tl.x, tl.y, tl2.x, tl2.y, 2.0, BLUE); + draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, self.team); + } + + fn collider(&self) -> (&Pose, &dyn Shape) { + (&self.pose, &self.collider) + } + + fn kill (&self) { + self.alive.store(false, Ordering::Relaxed); + } + fn living(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } } impl Robot { - fn new(position: Vec2) -> Self { - let pose:Pose = Pose::from_translation(position.to_array().into()); - Self { pose, alive: true } + fn new(position: Vec2, team: Color) -> Self { + let rand_angle = rand::gen_range(0, 1000) as f32 * TAU / 1000.0; + let pose:Pose = Pose::from_parts(position.to_array().into(), Rot2::from_angle(rand_angle)); + Self { pose, alive: AtomicBool::new(true), collider: Ball::new(BOT_RADIUS), sensor: Sensor::None, team} } fn move_step(&mut self, forward: f32, right: f32) { @@ -33,18 +72,11 @@ impl Robot { Vec2::new(self.pose.rotation.re, self.pose.rotation.im) } - pub fn draw(&self) { - let tl = self.pose.translation; - let tl2 = self.view_end(); - draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK); - draw_line(tl.x, tl.y, tl2.x, tl2.y, 2.0, BLUE); - draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, RED); - } - fn view_end(&self) -> Vec2 { self.pose.translation + self.ahead() * VIEW_DIST } + fn detect<'a>(&self, things: impl Iterator) -> Option { let collider = Segment::new(self.pose.translation, self.view_end()); things @@ -52,73 +84,212 @@ impl Robot { .map(|contact| contact.point1.distance(self.pose.translation)).reduce(|x: f32,y: f32| x.min(y)) } - pub fn policy(&mut self, sensor: Sensor){ + fn draw_weapon(&self) { + let tl = self.pose.translation; + draw_circle(tl.x, tl.y, KILL_RADIUS, ORANGE); + } + + fn weapon<'a>(&self, peers: impl Iterator) { + let weapon = Ball::new(KILL_RADIUS); + + for peer in peers { + let (p_p, p_c) = peer.collider(); + + if let Some(_) = contact(&self.pose, &weapon, p_p , p_c, 0.0).unwrap() { + peer.kill(); + } + + } + } + + pub fn policy(&mut self, sensor: &Sensor) -> bool{ match sensor { Sensor::Food => self.move_step(1.0, 0.0), - Sensor::None => self.move_step(1.0, 0.01), + Sensor::Kin => self.move_step(-0.3, 0.02), + Sensor::NonKin => self.move_step(0.3, -0.02), + Sensor::None => self.move_step(0.3, 0.01), } + + return *sensor == Sensor::NonKin; } } struct Food { pose: Pose, collider: Ball, - alive: bool, + alive: AtomicBool, } +#[derive(PartialEq, Eq)] enum Sensor { Food, + Kin, + NonKin, None } -impl Food { - fn new(position: Vec2) -> Self { - let pose:Pose = Pose::from_translation(position.to_array().into()); - Self { pose, alive: true, collider: Ball::new(BOT_RADIUS) } - } - - pub fn draw(&self) { +impl Mortal for Food { + fn draw(&self) { let tl = self.pose.translation; draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK); draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, GREEN); } - pub fn collider(&self) -> (&Pose, &dyn Shape) { + fn collider(&self) -> (&Pose, &dyn Shape) { (&self.pose, &self.collider) } + + fn kill (&self) { + self.alive.store(false, Ordering::Relaxed); + } + + fn living(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } +} + +impl Food { + fn new(position: Vec2) -> Self { + let pose:Pose = Pose::from_translation(position.to_array().into()); + Self { pose, alive: AtomicBool::new(true), collider: Ball::new(BOT_RADIUS) } + } + + + fn detect<'a>(&self, things: impl Iterator) -> Option { + things + .map(|robot| contact(&self.pose, &self.collider, &robot.pose, &robot.collider, 0.0).unwrap().map(|a| (a,robot.team))).flatten() + .map(|(contact,team)| (contact.point1.distance(self.pose.translation),team)).reduce(|x ,y| if x.0 < y.0 {x} else{y} ).map(|(_, team)| team) + } +} + +async fn run_simulation() -> (i32, i32) { + let mut watchdog = 0; // iterations since something interesting + let mut robots = Vec::new(); + + let mut score = HashMap::new(); + + for i in 5..20 { + robots.push(Robot::new(Vec2 { x: 100.0, y: i as f32*50.0 }, BLUE)); + robots.push(Robot::new(Vec2 { x: 1200.0, y: i as f32*50.0 }, RED)); + } + + let mut food = Vec::new(); + + for i in 0..120 { + let x = rand::gen_range(200, 1100) as f32; + let y = rand::gen_range(200, 900) as f32; + food.push(Food::new(Vec2 { x, y })); + } + + //for j in 5..20 { + // for i in 5..20 { + // food.push(Food::new(Vec2 { x: i as f32*60.0, y: j as f32*50.0 })); + // } + //} + + fn color_hash(color: Color) -> [u32; 4] { + color.to_vec().to_array().map(|f| f.to_bits()) + } + + + let mut loo = 0; + loop { + let rendered = loo %90 == 0; + //let rendered = false; + clear_background(LIGHTGRAY); + + for food in &mut food{ + if let Some(team) = food.detect(robots.iter()) { + if food.living() { + score.entry(color_hash(team)).and_modify(|s| *s +=1 ).or_insert(1); + food.kill(); + watchdog = 0; + } + } + if rendered { food.draw(); } + } + + food = food.into_iter().filter(Mortal::living).collect(); // remove dead food + robots = robots.into_iter().filter(Mortal::living).collect(); // remove dead robots + + let mut sensors = Vec::new(); + for robot in &*robots { + let detect_food = robot.detect(food.iter().map(Food::collider)); + let detect_kin = robot.detect(robots.iter().filter(|o| o.team == robot.team).filter(|r| !ptr::eq(&**r , &**&robot)).map(Robot::collider)); + let detect_non_kin = robot.detect(robots.iter().filter(|o| o.team != robot.team).filter(|r| !ptr::eq(&**r , &**&robot)).map(Robot::collider)); + + let mut sensor = Sensor::None; + let mut closest: Option = None; + + for (dist, detection) in [(detect_food, Sensor::Food), (detect_kin, Sensor::Kin), (detect_non_kin, Sensor::NonKin)] { + if let (Some(close), Some(dist)) = (closest, dist) { + if close < dist {continue;} + } + + if let Some(_) = dist { + sensor = detection; + closest = dist; + } + + } + + sensors.push(sensor); + } + for idx in 0..robots.len() { + let (before, after) = robots.split_at_mut(idx); + let (robot, after) = after.split_first_mut().unwrap(); + let robots = before.iter().chain(after.iter()); + + let robots = robots.map(|r| r as &dyn Mortal); + let peers = robots.chain(food.iter().map(|f| f as &dyn Mortal)); + + let mut death = robot.policy(&sensors[idx]); + if robot.team == BLUE { + death = false; // pacifists + } + if death { + if true {robot.draw_weapon();} + robot.weapon(peers); + } + if rendered { robot.draw();} + } + if rendered { + draw_text(format!("RED: {}", score.get(&color_hash(RED)).unwrap_or(&0)), 20.0, 20.0, 30.0, DARKGRAY); + draw_text(format!("BLUE: {}", score.get(&color_hash(BLUE)).unwrap_or(&0)), 20.0, 40.0, 30.0, DARKGRAY); + } + loo += 1; + if rendered { + next_frame().await // TODO: framerate cap + } + + watchdog += 1; + if food.is_empty() || watchdog > 1000 { + let red = score.get(&color_hash(RED)).unwrap_or(&0); + let blu = score.get(&color_hash(BLUE)).unwrap_or(&0); + return (*red, *blu); + } + } } #[macroquad::main("Adversarial Foraging Simulator")] async fn main() { - let mut robots = Vec::new(); - robots.push(Robot::new(Vec2 { x: 100.0, y: 100.0 })); - robots.push(Robot::new(Vec2 { x: 140.0, y: 100.0 })); - robots.push(Robot::new(Vec2 { x: 140.0, y: 200.0 })); - robots.push(Robot::new(Vec2 { x: 180.0, y: 150.0 })); + let mut rtot = 0; + let mut btot = 0; + for i in 0..100 { + rand::srand(i); - let mut food = Vec::new(); - food.push(Food::new(Vec2 { x: 160.0, y: 100.0 })); - food.push(Food::new(Vec2 { x: 360.0, y: 100.0 })); - food.push(Food::new(Vec2 { x: 360.0, y: 300.0 })); + let (red, blu) = run_simulation().await; - loop { - clear_background(LIGHTGRAY); + rtot += red; + btot += blu; - for food in &food{ - food.draw(); - } - - for robot in &mut robots { - println!("loop"); - let detect = robot.detect(food.iter().map(Food::collider)); - let sensor = if detect.is_some() {Sensor::Food} else {Sensor::None}; - robot.policy(sensor); - println!("Food detection: {:?}",detect); - robot.draw(); - } - draw_text("HELLO", 20.0, 20.0, 30.0, DARKGRAY); - next_frame().await // TODO: framerate cap + println!("{} wins! RED: {red}, BLU: {blu}", if red > blu {"red"} else {"blue"}); } + + let red = rtot / 100; + let blu = btot / 100; + println!("{} wins on average! RED: {red}, BLU: {blu}", if red > blu {"red"} else {"blue"}); + }