| 1 |
use std::{ |
| 2 |
cmp::Reverse, |
| 3 |
collections::{BinaryHeap, HashSet, VecDeque}, |
| 4 |
}; |
| 5 |
|
| 6 |
use bevy::prelude::*; |
| 7 |
|
| 8 |
use crate::world::{CHEAPEST_MOVE_COST, WorldMap}; |
| 9 |
|
| 10 |
const STRAIGHT: u32 = 10; |
| 11 |
const DIAGONAL: u32 = 14; |
| 12 |
const MIN_TERRAIN_COST: u32 = CHEAPEST_MOVE_COST; |
| 13 |
|
| 14 |
const NEIGHBORS: [IVec2; 8] = [ |
| 15 |
IVec2::new(1, 0), |
| 16 |
IVec2::new(-1, 0), |
| 17 |
IVec2::new(0, 1), |
| 18 |
IVec2::new(0, -1), |
| 19 |
IVec2::new(1, 1), |
| 20 |
IVec2::new(1, -1), |
| 21 |
IVec2::new(-1, 1), |
| 22 |
IVec2::new(-1, -1), |
| 23 |
]; |
| 24 |
|
| 25 |
pub fn find_path(map: &WorldMap, start: UVec2, goal: UVec2) -> Option<Vec<UVec2>> { |
| 26 |
map.move_cost(goal.as_ivec2())?; |
| 27 |
let goal = goal.as_ivec2(); |
| 28 |
astar(map, start, |p| p == goal, |p| octile(p, goal)) |
| 29 |
} |
| 30 |
|
| 31 |
pub fn find_path_adjacent(map: &WorldMap, start: UVec2, target: UVec2) -> Option<Vec<UVec2>> { |
| 32 |
let target = target.as_ivec2(); |
| 33 |
astar( |
| 34 |
map, |
| 35 |
start, |
| 36 |
|p| is_adjacent(p, target), |
| 37 |
|p| octile(p, target).saturating_sub(DIAGONAL * MIN_TERRAIN_COST), |
| 38 |
) |
| 39 |
} |
| 40 |
|
| 41 |
pub fn is_adjacent(a: IVec2, b: IVec2) -> bool { |
| 42 |
a != b && (a - b).abs().max_element() == 1 |
| 43 |
} |
| 44 |
|
| 45 |
pub fn can_step(map: &WorldMap, from: IVec2, step: IVec2) -> bool { |
| 46 |
let next = from + step; |
| 47 |
map.move_cost(next).is_some() |
| 48 |
&& (step.x == 0 |
| 49 |
|| step.y == 0 |
| 50 |
|| (map.move_cost(from + IVec2::new(step.x, 0)).is_some() |
| 51 |
&& map.move_cost(from + IVec2::new(0, step.y)).is_some())) |
| 52 |
} |
| 53 |
|
| 54 |
pub fn nearest_tile( |
| 55 |
map: &WorldMap, |
| 56 |
start: UVec2, |
| 57 |
max_tiles: usize, |
| 58 |
mut is_target: impl FnMut(UVec2) -> bool, |
| 59 |
) -> Option<UVec2> { |
| 60 |
let index = |p: UVec2| (p.y * map.size.x + p.x) as usize; |
| 61 |
let mut seen = vec![false; (map.size.x * map.size.y) as usize]; |
| 62 |
let mut seen_count = 1; |
| 63 |
if let Some(cell) = seen.get_mut(index(start)) { |
| 64 |
*cell = true; |
| 65 |
} |
| 66 |
let mut queue = VecDeque::from([start]); |
| 67 |
while let Some(pos) = queue.pop_front() { |
| 68 |
if is_target(pos) { |
| 69 |
return Some(pos); |
| 70 |
} |
| 71 |
if seen_count >= max_tiles { |
| 72 |
continue; |
| 73 |
} |
| 74 |
for step in NEIGHBORS { |
| 75 |
let next = pos.as_ivec2() + step; |
| 76 |
if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] { |
| 77 |
seen[index(next.as_uvec2())] = true; |
| 78 |
seen_count += 1; |
| 79 |
queue.push_back(next.as_uvec2()); |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
None |
| 84 |
} |
| 85 |
|
| 86 |
#[derive(Default, Debug, Clone)] |
| 87 |
pub struct Reach { |
| 88 |
width: u32, |
| 89 |
seen: Vec<bool>, |
| 90 |
} |
| 91 |
|
| 92 |
#[derive(Resource, Default, Debug, Clone)] |
| 93 |
pub struct ColonyReach(pub Option<Reach>); |
| 94 |
|
| 95 |
impl ColonyReach { |
| 96 |
pub fn allows(&self, tile: UVec2) -> bool { |
| 97 |
self.0.as_ref().is_none_or(|reach| reach.contains(tile)) |
| 98 |
} |
| 99 |
|
| 100 |
pub fn allows_near(&self, tile: UVec2) -> bool { |
| 101 |
self.0.as_ref().is_none_or(|reach| reach.near(tile)) |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
impl Reach { |
| 106 |
pub fn flood(map: &WorldMap, start: UVec2) -> Self { |
| 107 |
let width = map.size.x; |
| 108 |
let mut seen = vec![false; map.size.element_product() as usize]; |
| 109 |
let index = |p: UVec2| (p.y * width + p.x) as usize; |
| 110 |
if map.move_cost(start.as_ivec2()).is_some() { |
| 111 |
seen[index(start)] = true; |
| 112 |
let mut queue = VecDeque::from([start]); |
| 113 |
while let Some(pos) = queue.pop_front() { |
| 114 |
for step in NEIGHBORS { |
| 115 |
let next = pos.as_ivec2() + step; |
| 116 |
if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] { |
| 117 |
seen[index(next.as_uvec2())] = true; |
| 118 |
queue.push_back(next.as_uvec2()); |
| 119 |
} |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
Self { width, seen } |
| 124 |
} |
| 125 |
|
| 126 |
pub fn contains(&self, p: UVec2) -> bool { |
| 127 |
p.x < self.width |
| 128 |
&& self |
| 129 |
.seen |
| 130 |
.get((p.y * self.width + p.x) as usize) |
| 131 |
.copied() |
| 132 |
.unwrap_or(false) |
| 133 |
} |
| 134 |
|
| 135 |
pub fn near(&self, p: UVec2) -> bool { |
| 136 |
(-1..=1).any(|dy| { |
| 137 |
(-1..=1).any(|dx| { |
| 138 |
let q = p.as_ivec2() + IVec2::new(dx, dy); |
| 139 |
q.min_element() >= 0 && self.contains(q.as_uvec2()) |
| 140 |
}) |
| 141 |
}) |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
pub fn search_reach(max_tiles: usize) -> u32 { |
| 146 |
((max_tiles as f32).sqrt() / 2.0).ceil() as u32 |
| 147 |
} |
| 148 |
|
| 149 |
pub fn nearest_of( |
| 150 |
map: &WorldMap, |
| 151 |
start: UVec2, |
| 152 |
max_tiles: usize, |
| 153 |
targets: &HashSet<UVec2>, |
| 154 |
) -> Option<UVec2> { |
| 155 |
let reach = search_reach(max_tiles) as i32; |
| 156 |
let in_reach = |p: &&UVec2| (p.as_ivec2() - start.as_ivec2()).abs().max_element() <= reach; |
| 157 |
if !targets.iter().any(|p| in_reach(&p)) { |
| 158 |
return None; |
| 159 |
} |
| 160 |
nearest_tile(map, start, max_tiles, |p| targets.contains(&p)) |
| 161 |
} |
| 162 |
|
| 163 |
fn astar( |
| 164 |
map: &WorldMap, |
| 165 |
start: UVec2, |
| 166 |
is_goal: impl Fn(IVec2) -> bool, |
| 167 |
heuristic: impl Fn(IVec2) -> u32, |
| 168 |
) -> Option<Vec<UVec2>> { |
| 169 |
let start = start.as_ivec2(); |
| 170 |
if !map.in_bounds(start) { |
| 171 |
return None; |
| 172 |
} |
| 173 |
if is_goal(start) { |
| 174 |
return Some(vec![]); |
| 175 |
} |
| 176 |
|
| 177 |
let width = map.size.x as usize; |
| 178 |
let index = |p: IVec2| p.y as usize * width + p.x as usize; |
| 179 |
let tiles = map.size.element_product() as usize; |
| 180 |
let mut cost_so_far = vec![u32::MAX; tiles]; |
| 181 |
let mut came_from = vec![None::<IVec2>; tiles]; |
| 182 |
let mut open = BinaryHeap::new(); |
| 183 |
|
| 184 |
cost_so_far[index(start)] = 0; |
| 185 |
open.push(Reverse((heuristic(start), start.x, start.y))); |
| 186 |
|
| 187 |
while let Some(Reverse((_, x, y))) = open.pop() { |
| 188 |
let current = IVec2::new(x, y); |
| 189 |
if is_goal(current) { |
| 190 |
return Some(reconstruct(&came_from, index, start, current)); |
| 191 |
} |
| 192 |
let current_cost = cost_so_far[index(current)]; |
| 193 |
for step in NEIGHBORS { |
| 194 |
let next = current + step; |
| 195 |
if !can_step(map, current, step) { |
| 196 |
continue; |
| 197 |
} |
| 198 |
let Some(terrain_cost) = map.step_cost(current, next) else { |
| 199 |
continue; |
| 200 |
}; |
| 201 |
let diagonal = step.x != 0 && step.y != 0; |
| 202 |
let base = if diagonal { DIAGONAL } else { STRAIGHT }; |
| 203 |
let new_cost = current_cost + base * terrain_cost; |
| 204 |
if new_cost < cost_so_far[index(next)] { |
| 205 |
cost_so_far[index(next)] = new_cost; |
| 206 |
came_from[index(next)] = Some(current); |
| 207 |
open.push(Reverse((new_cost + heuristic(next), next.x, next.y))); |
| 208 |
} |
| 209 |
} |
| 210 |
} |
| 211 |
None |
| 212 |
} |
| 213 |
|
| 214 |
fn octile(a: IVec2, b: IVec2) -> u32 { |
| 215 |
let d = (a - b).abs(); |
| 216 |
let (min, max) = (d.x.min(d.y) as u32, d.x.max(d.y) as u32); |
| 217 |
(DIAGONAL * min + STRAIGHT * (max - min)) * MIN_TERRAIN_COST |
| 218 |
} |
| 219 |
|
| 220 |
fn reconstruct( |
| 221 |
came_from: &[Option<IVec2>], |
| 222 |
index: impl Fn(IVec2) -> usize, |
| 223 |
start: IVec2, |
| 224 |
goal: IVec2, |
| 225 |
) -> Vec<UVec2> { |
| 226 |
let mut path = vec![goal.as_uvec2()]; |
| 227 |
let mut current = goal; |
| 228 |
while let Some(prev) = came_from[index(current)] { |
| 229 |
if prev == start { |
| 230 |
break; |
| 231 |
} |
| 232 |
path.push(prev.as_uvec2()); |
| 233 |
current = prev; |
| 234 |
} |
| 235 |
path.reverse(); |
| 236 |
path |
| 237 |
} |
| 238 |
|
| 239 |
#[cfg(test)] |
| 240 |
mod tests { |
| 241 |
use super::*; |
| 242 |
use crate::world::Terrain; |
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
#[test] |
| 249 |
fn searches_never_pick_targets_that_paths_cannot_reach() { |
| 250 |
let mut map = WorldMap::filled(UVec2::splat(6), Terrain::Grass); |
| 251 |
for y in 3..6 { |
| 252 |
for x in 0..6 { |
| 253 |
map.set(UVec2::new(x, y), Terrain::Stone); |
| 254 |
} |
| 255 |
} |
| 256 |
map.set(UVec2::new(2, 3), Terrain::Grass); |
| 257 |
map.set(UVec2::new(3, 4), Terrain::Gravel); |
| 258 |
let pocket = UVec2::new(3, 4); |
| 259 |
assert!(map.move_cost(IVec2::new(2, 3)).is_some()); |
| 260 |
assert_eq!(find_path(&map, UVec2::ZERO, pocket), None); |
| 261 |
let targets = HashSet::from([pocket]); |
| 262 |
assert_eq!(nearest_of(&map, UVec2::ZERO, 100, &targets), None); |
| 263 |
} |
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
#[test] |
| 270 |
fn target_searches_skip_targets_beyond_their_reach() { |
| 271 |
let map = WorldMap::filled(UVec2::splat(300), Terrain::Grass); |
| 272 |
let start = UVec2::splat(10); |
| 273 |
let max_tiles = 400; |
| 274 |
let near = start + UVec2::new(search_reach(max_tiles) / 4, 0); |
| 275 |
let far = start + UVec2::new(search_reach(max_tiles) + 1, 0); |
| 276 |
assert_eq!( |
| 277 |
nearest_of(&map, start, max_tiles, &HashSet::from([far])), |
| 278 |
None |
| 279 |
); |
| 280 |
assert_eq!( |
| 281 |
nearest_of(&map, start, max_tiles, &HashSet::from([far, near])), |
| 282 |
Some(near) |
| 283 |
); |
| 284 |
let edge = start + UVec2::new(search_reach(max_tiles) - 1, 0); |
| 285 |
assert_eq!( |
| 286 |
nearest_of(&map, start, max_tiles, &HashSet::from([edge])), |
| 287 |
Some(edge) |
| 288 |
); |
| 289 |
} |
| 290 |
|
| 291 |
fn map_from(rows: &[&str]) -> WorldMap { |
| 292 |
let size = UVec2::new(rows[0].len() as u32, rows.len() as u32); |
| 293 |
let mut map = WorldMap::filled(size, Terrain::Grass); |
| 294 |
for (row, line) in rows.iter().enumerate() { |
| 295 |
let y = size.y - 1 - row as u32; |
| 296 |
for (x, c) in line.chars().enumerate() { |
| 297 |
let terrain = match c { |
| 298 |
'#' => Terrain::Stone, |
| 299 |
'~' => Terrain::ShallowWater, |
| 300 |
_ => Terrain::Grass, |
| 301 |
}; |
| 302 |
map.set(UVec2::new(x as u32, y), terrain); |
| 303 |
} |
| 304 |
} |
| 305 |
map |
| 306 |
} |
| 307 |
|
| 308 |
fn is_connected(start: UVec2, path: &[UVec2]) -> bool { |
| 309 |
std::iter::once(start) |
| 310 |
.chain(path.iter().copied()) |
| 311 |
.collect::<Vec<_>>() |
| 312 |
.windows(2) |
| 313 |
.all(|w| (w[0].as_ivec2() - w[1].as_ivec2()).abs().max_element() == 1) |
| 314 |
} |
| 315 |
|
| 316 |
#[test] |
| 317 |
fn path_excludes_start_and_ends_at_goal() { |
| 318 |
let map = map_from(&["....."]); |
| 319 |
let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap(); |
| 320 |
assert_eq!( |
| 321 |
path, |
| 322 |
vec![ |
| 323 |
UVec2::new(1, 0), |
| 324 |
UVec2::new(2, 0), |
| 325 |
UVec2::new(3, 0), |
| 326 |
UVec2::new(4, 0) |
| 327 |
] |
| 328 |
); |
| 329 |
} |
| 330 |
|
| 331 |
#[test] |
| 332 |
fn path_to_self_is_empty() { |
| 333 |
let map = map_from(&["..."]); |
| 334 |
assert_eq!(find_path(&map, UVec2::ZERO, UVec2::ZERO), Some(vec![])); |
| 335 |
} |
| 336 |
|
| 337 |
#[test] |
| 338 |
fn path_goes_around_walls() { |
| 339 |
let map = map_from(&[ |
| 340 |
".....", |
| 341 |
".###.", ".#.#.", "...#.", |
| 342 |
]); |
| 343 |
let start = UVec2::new(2, 1); |
| 344 |
let goal = UVec2::new(4, 0); |
| 345 |
let path = find_path(&map, start, goal).unwrap(); |
| 346 |
assert!(is_connected(start, &path)); |
| 347 |
assert_eq!(path.last(), Some(&goal)); |
| 348 |
assert!(path.iter().all(|p| map.move_cost(p.as_ivec2()).is_some())); |
| 349 |
} |
| 350 |
|
| 351 |
#[test] |
| 352 |
fn unreachable_or_impassable_goal_has_no_path() { |
| 353 |
let map = map_from(&[ |
| 354 |
"..#..", |
| 355 |
"..#..", |
| 356 |
]); |
| 357 |
assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)), None); |
| 358 |
assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(2, 0)), None); |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
#[test] |
| 364 |
fn diagonal_steps_never_cut_wall_corners() { |
| 365 |
let map = map_from(&[ |
| 366 |
"#.", |
| 367 |
".#", |
| 368 |
]); |
| 369 |
assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(1, 1)), None); |
| 370 |
let map = map_from(&[ |
| 371 |
"..", |
| 372 |
"#.", |
| 373 |
]); |
| 374 |
let path = find_path(&map, UVec2::new(0, 1), UVec2::new(1, 0)).unwrap(); |
| 375 |
assert_eq!(path, vec![UVec2::new(1, 1), UVec2::new(1, 0)]); |
| 376 |
} |
| 377 |
|
| 378 |
#[test] |
| 379 |
fn prefers_detour_over_slow_terrain() { |
| 380 |
let map = map_from(&[ |
| 381 |
".....", |
| 382 |
"..~..", |
| 383 |
]); |
| 384 |
let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap(); |
| 385 |
assert!(!path.contains(&UVec2::new(2, 0))); |
| 386 |
} |
| 387 |
|
| 388 |
#[test] |
| 389 |
fn walks_around_a_hill_rather_than_over_it() { |
| 390 |
let mut map = map_from(&[ |
| 391 |
".....", |
| 392 |
".....", |
| 393 |
]); |
| 394 |
map.set_height(UVec2::new(2, 0), 10.0); |
| 395 |
let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap(); |
| 396 |
assert!(!path.contains(&UVec2::new(2, 0))); |
| 397 |
} |
| 398 |
|
| 399 |
#[test] |
| 400 |
fn detours_along_paths_when_they_are_faster() { |
| 401 |
let mut map = map_from(&[ |
| 402 |
"..........", |
| 403 |
"..........", |
| 404 |
]); |
| 405 |
for x in 0..10 { |
| 406 |
map.set(UVec2::new(x, 1), Terrain::Paved); |
| 407 |
} |
| 408 |
let path = find_path(&map, UVec2::new(0, 0), UVec2::new(9, 0)).unwrap(); |
| 409 |
assert!(path.iter().filter(|p| p.y == 1).count() >= 6); |
| 410 |
} |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
#[test] |
| 415 |
fn colonists_can_walk_out_of_a_blocked_tile() { |
| 416 |
let mut map = map_from(&["....."]); |
| 417 |
map.set_wall(UVec2::new(2, 0), true); |
| 418 |
let path = find_path(&map, UVec2::new(2, 0), UVec2::new(4, 0)).unwrap(); |
| 419 |
assert_eq!(path, vec![UVec2::new(3, 0), UVec2::new(4, 0)]); |
| 420 |
} |
| 421 |
|
| 422 |
#[test] |
| 423 |
fn crosses_slow_terrain_when_it_is_the_only_way() { |
| 424 |
let map = map_from(&["..~.."]); |
| 425 |
let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap(); |
| 426 |
assert!(path.contains(&UVec2::new(2, 0))); |
| 427 |
} |
| 428 |
|
| 429 |
#[test] |
| 430 |
fn path_adjacent_stops_next_to_target() { |
| 431 |
let map = map_from(&["......"]); |
| 432 |
let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(5, 0)).unwrap(); |
| 433 |
assert_eq!(path.last(), Some(&UVec2::new(4, 0))); |
| 434 |
} |
| 435 |
|
| 436 |
#[test] |
| 437 |
fn path_adjacent_works_for_impassable_targets() { |
| 438 |
let map = map_from(&["...#"]); |
| 439 |
let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(3, 0)).unwrap(); |
| 440 |
assert_eq!(path.last(), Some(&UVec2::new(2, 0))); |
| 441 |
} |
| 442 |
|
| 443 |
#[test] |
| 444 |
fn path_adjacent_from_neighbor_is_empty() { |
| 445 |
let map = map_from(&["..."]); |
| 446 |
let path = find_path_adjacent(&map, UVec2::new(1, 0), UVec2::new(2, 0)); |
| 447 |
assert_eq!(path, Some(vec![])); |
| 448 |
} |
| 449 |
|
| 450 |
#[test] |
| 451 |
fn path_adjacent_to_enclosed_target_is_none() { |
| 452 |
let walled = map_from(&[ |
| 453 |
"#####", |
| 454 |
"#...#", "#####", ".....", |
| 455 |
]); |
| 456 |
assert_eq!( |
| 457 |
find_path_adjacent(&walled, UVec2::new(0, 0), UVec2::new(2, 2)), |
| 458 |
None |
| 459 |
); |
| 460 |
} |
| 461 |
|
| 462 |
#[test] |
| 463 |
fn nearest_tile_finds_closest_match_by_walking_distance() { |
| 464 |
let map = map_from(&[ |
| 465 |
".#...", |
| 466 |
".#.#.", "...#.", |
| 467 |
]); |
| 468 |
let found = nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 4); |
| 469 |
assert_eq!(found, Some(UVec2::new(4, 2))); |
| 470 |
assert_eq!( |
| 471 |
nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 9), |
| 472 |
None |
| 473 |
); |
| 474 |
} |
| 475 |
|
| 476 |
#[test] |
| 477 |
fn finds_paths_across_a_generated_world() { |
| 478 |
let map = crate::worldgen::generate(crate::worldgen::WORLD_SIZE, 1); |
| 479 |
let region = crate::worldgen::largest_region(&map); |
| 480 |
let (start, goal) = (region[0], region[region.len() - 1]); |
| 481 |
let path = find_path(&map, start, goal).unwrap(); |
| 482 |
assert!(is_connected(start, &path)); |
| 483 |
assert_eq!(path.last(), Some(&goal)); |
| 484 |
} |
| 485 |
} |