use crate::{ astar::{Astar, PathResult}, terrain::Block, vol::{BaseVol, ReadVol}, }; use hashbrown::hash_map::DefaultHashBuilder; use rand::{thread_rng, Rng}; use std::iter::FromIterator; use vek::*; // Path #[derive(Clone, Debug)] pub struct Path { nodes: Vec, } impl Default for Path { fn default() -> Self { Self { nodes: Vec::default(), } } } impl FromIterator for Path { fn from_iter>(iter: I) -> Self { Self { nodes: iter.into_iter().collect(), } } } #[allow(clippy::len_without_is_empty)] // TODO: Pending review in #587 impl Path { pub fn len(&self) -> usize { self.nodes.len() } pub fn iter(&self) -> impl Iterator { self.nodes.iter() } pub fn start(&self) -> Option<&T> { self.nodes.first() } pub fn end(&self) -> Option<&T> { self.nodes.last() } pub fn nodes(&self) -> &[T] { &self.nodes } } // Route: A path that can be progressed along #[derive(Default, Clone, Debug)] pub struct Route { path: Path>, next_idx: usize, } impl From>> for Route { fn from(path: Path>) -> Self { Self { path, next_idx: 0 } } } impl Route { pub fn path(&self) -> &Path> { &self.path } pub fn next(&self, i: usize) -> Option> { self.path.nodes.get(self.next_idx + i).copied() } pub fn is_finished(&self) -> bool { self.next(0).is_none() } pub fn traverse( &mut self, vol: &V, pos: Vec3, vel: Vec3, traversal_tolerance: f32, ) -> Option<(Vec3, f32)> where V: BaseVol + ReadVol, { let next0 = self.next(0).unwrap_or_else(|| pos.map(|e| e.floor() as i32)); let next1 = self.next(1).unwrap_or(next0); if vol.get(next0).map(|b| b.is_solid()).unwrap_or(false) { None } else { let next_tgt = next0.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0); if pos.xy().distance_squared(next_tgt.xy()) < traversal_tolerance.powf(2.0) && next_tgt.z - pos.z < 0.2 && next_tgt.z - pos.z > -2.2 && vel.z <= 0.0 && vol .ray(pos + Vec3::unit_z() * 0.5, next_tgt + Vec3::unit_z() * 0.5) .until(|block| block.is_solid()) .cast() .0 > pos.distance(next_tgt) * 0.9 { self.next_idx += 1; } let line = LineSegment2 { start: pos.xy(), end: pos.xy() + vel.xy() * 100.0, }; let align = |block_pos: Vec3| { (0..2) .map(|i| (0..2).map(move |j| Vec2::new(i, j))) .flatten() .map(|rpos| block_pos + rpos) .map(|block_pos| { let block_posf = block_pos.xy().map(|e| e as f32); let proj = line.projected_point(block_posf); let clamped = proj.clamped( block_pos.xy().map(|e| e as f32), block_pos.xy().map(|e| e as f32), ); (proj.distance_squared(clamped), clamped) }) .min_by_key(|(d2, _)| (d2 * 1000.0) as i32) .unwrap() .1 }; let cb = CubicBezier2 { start: pos.xy(), ctrl0: pos.xy() + vel.xy().try_normalized().unwrap_or_else(Vec2::zero), ctrl1: align(next0), end: align(next1), }; let tgt2d = cb.evaluate(0.5); let tgt = Vec3::from(tgt2d) + Vec3::unit_z() * next_tgt.z; let tgt_dir = (tgt - pos).xy().try_normalized().unwrap_or_else(Vec2::unit_y); let next_dir = cb .evaluate_derivative(0.5) .try_normalized() .unwrap_or(tgt_dir); //let vel_dir = vel.xy().try_normalized().unwrap_or(Vec2::zero()); //let avg_dir = (tgt_dir * 0.2 + vel_dir * // 0.8).try_normalized().unwrap_or(Vec2::zero()); let bearing = // Vec3::::from(avg_dir * (tgt - pos).xy().magnitude()) + Vec3::unit_z() * // (tgt.z - pos.z); Some(( tgt - pos, next_dir .dot(vel.xy().try_normalized().unwrap_or_else(Vec2::zero)) .max(0.0) * 0.75 + 0.25, )) } } } /// A self-contained system that attempts to chase a moving target, only /// performing pathfinding if necessary #[derive(Default, Clone, Debug)] pub struct Chaser { last_search_tgt: Option>, route: Option, /// We use this hasher (AAHasher) because: /// (1) we care about DDOS attacks (ruling out FxHash); /// (2) we don't care about determinism across computers (we can use /// AAHash). astar: Option, DefaultHashBuilder>>, } impl Chaser { pub fn chase( &mut self, vol: &V, pos: Vec3, vel: Vec3, tgt: Vec3, min_dist: f32, traversal_tolerance: f32, ) -> Option<(Vec3, f32)> where V: BaseVol + ReadVol, { let pos_to_tgt = pos.distance(tgt); if ((pos - tgt) * Vec3::new(1.0, 1.0, 2.0)).magnitude_squared() < min_dist.powf(2.0) { return None; } let bearing = if let Some(end) = self.route.as_ref().and_then(|r| r.path().end().copied()) { let end_to_tgt = end.map(|e| e as f32).distance(tgt); if end_to_tgt > pos_to_tgt * 0.3 + 5.0 || thread_rng().gen::() < 0.005 { None } else { self.route .as_mut() .and_then(|r| r.traverse(vol, pos, vel, traversal_tolerance)) } } else { None }; // TODO: What happens when we get stuck? if let Some(bearing) = bearing { Some(bearing) } else { if self .last_search_tgt .map(|last_tgt| last_tgt.distance(tgt) > pos_to_tgt * 0.15 + 5.0) .unwrap_or(true) { let (start_pos, path) = find_path(&mut self.astar, vol, pos, tgt); if start_pos.distance_squared(pos) < 4.0f32.powf(2.0) { self.route = path.map(Route::from); } else { self.route = None; } } Some(((tgt - pos) * Vec3::new(1.0, 1.0, 0.0), 0.75)) } } } #[allow(clippy::float_cmp)] // TODO: Pending review in #587 fn find_path( astar: &mut Option, DefaultHashBuilder>>, vol: &V, startf: Vec3, endf: Vec3, ) -> (Vec3, Option>>) where V: BaseVol + ReadVol, { let is_walkable = |pos: &Vec3| { vol.get(*pos - Vec3::new(0, 0, 1)) .map(|b| b.is_solid() && b.get_height() == 1.0) .unwrap_or(false) && vol .get(*pos + Vec3::new(0, 0, 0)) .map(|b| !b.is_solid()) .unwrap_or(true) && vol .get(*pos + Vec3::new(0, 0, 1)) .map(|b| !b.is_solid()) .unwrap_or(true) }; let get_walkable_z = |pos| { let mut z_incr = 0; for _ in 0..32 { let test_pos = pos + Vec3::unit_z() * z_incr; if is_walkable(&test_pos) { return Some(test_pos); } z_incr = -z_incr + if z_incr <= 0 { 1 } else { 0 }; } None }; let (start, end) = match ( get_walkable_z(startf.map(|e| e.floor() as i32)), get_walkable_z(endf.map(|e| e.floor() as i32)), ) { (Some(start), Some(end)) => (start, end), _ => return (startf, None), }; let heuristic = |pos: &Vec3| (pos.distance_squared(end) as f32).sqrt(); let neighbors = |pos: &Vec3| { let pos = *pos; const DIRS: [Vec3; 17] = [ Vec3::new(0, 1, 0), // Forward Vec3::new(0, 1, 1), // Forward upward Vec3::new(0, 1, 2), // Forward Upwardx2 Vec3::new(0, 1, -1), // Forward downward Vec3::new(1, 0, 0), // Right Vec3::new(1, 0, 1), // Right upward Vec3::new(1, 0, 2), // Right Upwardx2 Vec3::new(1, 0, -1), // Right downward Vec3::new(0, -1, 0), // Backwards Vec3::new(0, -1, 1), // Backward Upward Vec3::new(0, -1, 2), // Backward Upwardx2 Vec3::new(0, -1, -1), // Backward downward Vec3::new(-1, 0, 0), // Left Vec3::new(-1, 0, 1), // Left upward Vec3::new(-1, 0, 2), // Left Upwardx2 Vec3::new(-1, 0, -1), // Left downward Vec3::new(0, 0, -1), // Downwards ]; let walkable = [ is_walkable(&(pos + Vec3::new(1, 0, 0))), is_walkable(&(pos + Vec3::new(-1, 0, 0))), is_walkable(&(pos + Vec3::new(0, 1, 0))), is_walkable(&(pos + Vec3::new(0, -1, 0))), ]; const DIAGONALS: [(Vec3, [usize; 2]); 8] = [ (Vec3::new(1, 1, 0), [0, 2]), (Vec3::new(-1, 1, 0), [1, 2]), (Vec3::new(1, -1, 0), [0, 3]), (Vec3::new(-1, -1, 0), [1, 3]), (Vec3::new(1, 1, 1), [0, 2]), (Vec3::new(-1, 1, 1), [1, 2]), (Vec3::new(1, -1, 1), [0, 3]), (Vec3::new(-1, -1, 1), [1, 3]), ]; DIRS.iter() .map(move |dir| (pos, dir)) .filter(move |(pos, dir)| { is_walkable(pos) && is_walkable(&(*pos + **dir)) && ((dir.z < 1 || vol .get(pos + Vec3::unit_z() * 2) .map(|b| !b.is_solid()) .unwrap_or(true)) && (dir.z < 2 || vol .get(pos + Vec3::unit_z() * 3) .map(|b| !b.is_solid()) .unwrap_or(true)) && (dir.z >= 0 || vol .get(pos + *dir + Vec3::unit_z() * 2) .map(|b| !b.is_solid()) .unwrap_or(true))) }) .map(move |(pos, dir)| pos + dir) .chain( DIAGONALS .iter() .filter(move |(dir, [a, b])| { is_walkable(&(pos + *dir)) && walkable[*a] && walkable[*b] }) .map(move |(dir, _)| pos + *dir), ) }; let crow_line = LineSegment2 { start: startf.xy(), end: endf.xy(), }; let transition = |a: &Vec3, b: &Vec3| { 1.0 + crow_line.distance_to_point(b.xy().map(|e| e as f32)) * 0.025 + (b.z - a.z - 1).max(0) as f32 * 3.0 }; let satisfied = |pos: &Vec3| pos == &end; let mut new_astar = match astar.take() { None => Astar::new(25_000, start, heuristic, DefaultHashBuilder::default()), Some(astar) => astar, }; let path_result = new_astar.poll(100, heuristic, neighbors, transition, satisfied); *astar = Some(new_astar); (startf, match path_result { PathResult::Path(path) => { *astar = None; Some(path) }, PathResult::None(path) => { *astar = None; Some(path) }, PathResult::Exhausted(path) => { *astar = None; Some(path) }, PathResult::Pending => None, }) }