src/pathfinding.rs 19.6 K · 605 lines · raw · history

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 find_path_adjacent_within(map, start, target, usize::MAX)
33 }
34
35 pub fn find_path_adjacent_within(
36 map: &WorldMap,
37 start: UVec2,
38 target: UVec2,
39 max_expanded: usize,
40 ) -> Option<Vec<UVec2>> {
41 let target = target.as_ivec2();
42 astar_limited(
43 map,
44 start,
45 |p| is_adjacent(p, target),
46 |p| octile(p, target).saturating_sub(DIAGONAL * MIN_TERRAIN_COST),
47 max_expanded,
48 )
49 }
50
51 pub fn is_adjacent(a: IVec2, b: IVec2) -> bool {
52 a != b && (a - b).abs().max_element() == 1
53 }
54
55 pub fn can_step(map: &WorldMap, from: IVec2, step: IVec2) -> bool {
56 let next = from + step;
57 map.move_cost(next).is_some()
58 && (step.x == 0
59 || step.y == 0
60 || (map.move_cost(from + IVec2::new(step.x, 0)).is_some()
61 && map.move_cost(from + IVec2::new(0, step.y)).is_some()))
62 }
63
64 pub fn nearest_tile(
65 map: &WorldMap,
66 start: UVec2,
67 max_tiles: usize,
68 mut is_target: impl FnMut(UVec2) -> bool,
69 ) -> Option<UVec2> {
70 let index = |p: UVec2| (p.y * map.size.x + p.x) as usize;
71 let mut seen = vec![false; (map.size.x * map.size.y) as usize];
72 let mut seen_count = 1;
73 if let Some(cell) = seen.get_mut(index(start)) {
74 *cell = true;
75 }
76 let mut queue = VecDeque::from([start]);
77 while let Some(pos) = queue.pop_front() {
78 if is_target(pos) {
79 return Some(pos);
80 }
81 if seen_count >= max_tiles {
82 continue;
83 }
84 for step in NEIGHBORS {
85 let next = pos.as_ivec2() + step;
86 if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] {
87 seen[index(next.as_uvec2())] = true;
88 seen_count += 1;
89 queue.push_back(next.as_uvec2());
90 }
91 }
92 }
93 None
94 }
95
96 #[derive(Default, Debug, Clone)]
97 pub struct Reach {
98 width: u32,
99 seen: Vec<bool>,
100 }
101
102 #[derive(Resource, Default, Debug, Clone)]
103 pub struct ColonyReach(pub Option<Reach>);
104
105 impl ColonyReach {
106 pub fn allows(&self, tile: UVec2) -> bool {
107 self.0.as_ref().is_none_or(|reach| reach.contains(tile))
108 }
109
110 pub fn allows_near(&self, tile: UVec2) -> bool {
111 self.0.as_ref().is_none_or(|reach| reach.near(tile))
112 }
113
114 pub fn nearest(
115 &self,
116 map: &WorldMap,
117 from: UVec2,
118 max_tiles: usize,
119 targets: &HashSet<UVec2>,
120 ) -> Option<UVec2> {
121 match &self.0 {
122 Some(reach) if reach.contains(from) => targets
123 .iter()
124 .filter(|t| {
125 let radius = search_reach(max_tiles) as i32;
126 reach.contains(**t)
127 && (t.as_ivec2() - from.as_ivec2()).abs().max_element() <= radius
128 })
129 .min_by_key(|t| {
130 let d = t.as_ivec2() - from.as_ivec2();
131 (d.length_squared(), t.y, t.x)
132 })
133 .copied(),
134 _ => nearest_of(map, from, max_tiles, targets),
135 }
136 }
137 }
138
139 impl Reach {
140 pub fn flood(map: &WorldMap, start: UVec2) -> Self {
141 let width = map.size.x;
142 let mut seen = vec![false; map.size.element_product() as usize];
143 let index = |p: UVec2| (p.y * width + p.x) as usize;
144 if map.move_cost(start.as_ivec2()).is_some() {
145 seen[index(start)] = true;
146 let mut queue = VecDeque::from([start]);
147 while let Some(pos) = queue.pop_front() {
148 for step in NEIGHBORS {
149 let next = pos.as_ivec2() + step;
150 if can_step(map, pos.as_ivec2(), step) && !seen[index(next.as_uvec2())] {
151 seen[index(next.as_uvec2())] = true;
152 queue.push_back(next.as_uvec2());
153 }
154 }
155 }
156 }
157 Self { width, seen }
158 }
159
160 pub fn contains(&self, p: UVec2) -> bool {
161 p.x < self.width
162 && self
163 .seen
164 .get((p.y * self.width + p.x) as usize)
165 .copied()
166 .unwrap_or(false)
167 }
168
169 pub fn near(&self, p: UVec2) -> bool {
170 (-1..=1).any(|dy| {
171 (-1..=1).any(|dx| {
172 let q = p.as_ivec2() + IVec2::new(dx, dy);
173 q.min_element() >= 0 && self.contains(q.as_uvec2())
174 })
175 })
176 }
177 }
178
179 pub fn search_reach(max_tiles: usize) -> u32 {
180 ((max_tiles as f32).sqrt() / 2.0).ceil() as u32
181 }
182
183 pub fn nearest_of(
184 map: &WorldMap,
185 start: UVec2,
186 max_tiles: usize,
187 targets: &HashSet<UVec2>,
188 ) -> Option<UVec2> {
189 let reach = search_reach(max_tiles) as i32;
190 let in_reach = |p: &&UVec2| (p.as_ivec2() - start.as_ivec2()).abs().max_element() <= reach;
191 if !targets.iter().any(|p| in_reach(&p)) {
192 return None;
193 }
194 nearest_tile(map, start, max_tiles, |p| targets.contains(&p))
195 }
196
197 fn octile(a: IVec2, b: IVec2) -> u32 {
198 let d = (a - b).abs();
199 let (min, max) = (d.x.min(d.y) as u32, d.x.max(d.y) as u32);
200 (DIAGONAL * min + STRAIGHT * (max - min)) * MIN_TERRAIN_COST
201 }
202
203 #[derive(Default)]
204 struct Scratch {
205 generation: u32,
206 stamp: Vec<u32>,
207 cost: Vec<u32>,
208 from: Vec<IVec2>,
209 open: BinaryHeap<Reverse<(u32, i32, i32)>>,
210 }
211
212 thread_local! {
213 static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
214 }
215
216 fn astar(
217 map: &WorldMap,
218 start: UVec2,
219 is_goal: impl Fn(IVec2) -> bool,
220 heuristic: impl Fn(IVec2) -> u32,
221 ) -> Option<Vec<UVec2>> {
222 astar_limited(map, start, is_goal, heuristic, usize::MAX)
223 }
224
225 fn astar_limited(
226 map: &WorldMap,
227 start: UVec2,
228 is_goal: impl Fn(IVec2) -> bool,
229 heuristic: impl Fn(IVec2) -> u32,
230 max_expanded: usize,
231 ) -> Option<Vec<UVec2>> {
232 let start = start.as_ivec2();
233 if !map.in_bounds(start) {
234 return None;
235 }
236 if is_goal(start) {
237 return Some(vec![]);
238 }
239 SCRATCH.with_borrow_mut(|scratch| {
240 let tiles = map.size.element_product() as usize;
241 if scratch.stamp.len() != tiles {
242 *scratch = Scratch {
243 stamp: vec![0; tiles],
244 cost: vec![0; tiles],
245 from: vec![IVec2::ZERO; tiles],
246 ..default()
247 };
248 }
249 scratch.generation = scratch.generation.wrapping_add(1);
250 if scratch.generation == 0 {
251 scratch.stamp.fill(0);
252 scratch.generation = 1;
253 }
254 let Scratch {
255 generation,
256 stamp,
257 cost,
258 from,
259 open,
260 } = scratch;
261 let generation = *generation;
262 let width = map.size.x as usize;
263 let index = |p: IVec2| p.y as usize * width + p.x as usize;
264 open.clear();
265 stamp[index(start)] = generation;
266 cost[index(start)] = 0;
267 from[index(start)] = start;
268 open.push(Reverse((heuristic(start), start.x, start.y)));
269 let mut expanded = 0;
270 while let Some(Reverse((_, x, y))) = open.pop() {
271 let current = IVec2::new(x, y);
272 if is_goal(current) {
273 let mut path = vec![current.as_uvec2()];
274 let mut at = current;
275 while from[index(at)] != start {
276 at = from[index(at)];
277 path.push(at.as_uvec2());
278 }
279 path.reverse();
280 return Some(path);
281 }
282 expanded += 1;
283 if expanded > max_expanded {
284 return None;
285 }
286 let current_cost = cost[index(current)];
287 for step in NEIGHBORS {
288 let next = current + step;
289 if !can_step(map, current, step) {
290 continue;
291 }
292 let Some(terrain_cost) = map.step_cost(current, next) else {
293 continue;
294 };
295 let diagonal = step.x != 0 && step.y != 0;
296 let base = if diagonal { DIAGONAL } else { STRAIGHT };
297 let new_cost = current_cost + base * terrain_cost;
298 let i = index(next);
299 if stamp[i] != generation || new_cost < cost[i] {
300 stamp[i] = generation;
301 cost[i] = new_cost;
302 from[i] = current;
303 open.push(Reverse((new_cost + heuristic(next), next.x, next.y)));
304 }
305 }
306 }
307 None
308 })
309 }
310
311 pub const WANDER_SEARCH: usize = 800;
312
313 pub fn find_nearby_path(
314 map: &WorldMap,
315 start: UVec2,
316 goal: UVec2,
317 max_expanded: usize,
318 ) -> Option<Vec<UVec2>> {
319 map.move_cost(goal.as_ivec2())?;
320 let goal = goal.as_ivec2();
321 astar_limited(map, start, |p| p == goal, |p| octile(p, goal), max_expanded)
322 }
323
324 #[cfg(test)]
325 mod tests {
326 use super::*;
327 use crate::world::Terrain;
328
329 // Inside the colony's flooded reach, the nearest reachable target by distance stands in for
330 // a fresh flood fill per search; with 40+ colonists those floods dominated job choice.
331 #[test]
332 fn colony_reach_picks_the_nearest_reachable_target() {
333 let mut map = WorldMap::filled(UVec2::splat(30), Terrain::Grass);
334 for y in 0..30 {
335 map.set(UVec2::new(10, y), Terrain::DeepWater);
336 }
337 let reach = ColonyReach(Some(Reach::flood(&map, UVec2::new(5, 5))));
338 let across = UVec2::new(12, 5);
339 let far = UVec2::new(5, 20);
340 let targets = HashSet::from([across, far]);
341 assert_eq!(
342 reach.nearest(&map, UVec2::new(5, 5), 1000, &targets),
343 Some(far)
344 );
345 let elsewhere = UVec2::new(20, 5);
346 assert_eq!(reach.nearest(&map, elsewhere, 1000, &targets), Some(across));
347 assert_eq!(reach.nearest(&map, UVec2::new(5, 5), 100, &targets), None);
348 }
349
350 // Wandering picks random nearby goals; one walled off by a river or cliff made A* search the
351 // whole connected region before failing. Short trips cap the search instead.
352 #[test]
353 fn nearby_paths_give_up_early_on_unreachable_goals() {
354 let mut map = WorldMap::filled(UVec2::splat(100), Terrain::Grass);
355 for y in 0..100 {
356 map.set(UVec2::new(50, y), Terrain::DeepWater);
357 }
358 let start = UVec2::new(45, 50);
359 assert!(find_nearby_path(&map, start, UVec2::new(40, 52), 200).is_some());
360 assert_eq!(find_nearby_path(&map, start, UVec2::new(55, 50), 200), None);
361 assert_eq!(find_path(&map, start, UVec2::new(55, 50)), None);
362 }
363
364 // Target searches must use the same no-corner-cutting rule as A*. A stack on a tile touching
365 // the colony only diagonally between two rocks was "found" by the search, A* then explored
366 // the whole map before failing, and the job was picked again at once: ~10 ms, many times a
367 // second, which made Max speed crawl on a 50-day colony.
368 #[test]
369 fn searches_never_pick_targets_that_paths_cannot_reach() {
370 let mut map = WorldMap::filled(UVec2::splat(6), Terrain::Grass);
371 for y in 3..6 {
372 for x in 0..6 {
373 map.set(UVec2::new(x, y), Terrain::Stone);
374 }
375 }
376 map.set(UVec2::new(2, 3), Terrain::Grass);
377 map.set(UVec2::new(3, 4), Terrain::Gravel);
378 let pocket = UVec2::new(3, 4);
379 assert!(map.move_cost(IVec2::new(2, 3)).is_some());
380 assert_eq!(find_path(&map, UVec2::ZERO, pocket), None);
381 let targets = HashSet::from([pocket]);
382 assert_eq!(nearest_of(&map, UVec2::ZERO, 100, &targets), None);
383 }
384
385 // Idle colonists look for food and cooking input several times per game minute. A stack far
386 // beyond what the flood fill can cover made every one of those searches visit the full tile
387 // budget and fail, which dominated frame time at high speeds. The reach is a radius: the
388 // flood fills a square, so its half-width (not its width, as it once was) bounds it.
389 #[test]
390 fn target_searches_skip_targets_beyond_their_reach() {
391 let map = WorldMap::filled(UVec2::splat(300), Terrain::Grass);
392 let start = UVec2::splat(10);
393 let max_tiles = 400;
394 let near = start + UVec2::new(search_reach(max_tiles) / 4, 0);
395 let far = start + UVec2::new(search_reach(max_tiles) + 1, 0);
396 assert_eq!(
397 nearest_of(&map, start, max_tiles, &HashSet::from([far])),
398 None
399 );
400 assert_eq!(
401 nearest_of(&map, start, max_tiles, &HashSet::from([far, near])),
402 Some(near)
403 );
404 let edge = start + UVec2::new(search_reach(max_tiles) - 1, 0);
405 assert_eq!(
406 nearest_of(&map, start, max_tiles, &HashSet::from([edge])),
407 Some(edge)
408 );
409 }
410
411 fn map_from(rows: &[&str]) -> WorldMap {
412 let size = UVec2::new(rows[0].len() as u32, rows.len() as u32);
413 let mut map = WorldMap::filled(size, Terrain::Grass);
414 for (row, line) in rows.iter().enumerate() {
415 let y = size.y - 1 - row as u32;
416 for (x, c) in line.chars().enumerate() {
417 let terrain = match c {
418 '#' => Terrain::Stone,
419 '~' => Terrain::ShallowWater,
420 _ => Terrain::Grass,
421 };
422 map.set(UVec2::new(x as u32, y), terrain);
423 }
424 }
425 map
426 }
427
428 fn is_connected(start: UVec2, path: &[UVec2]) -> bool {
429 std::iter::once(start)
430 .chain(path.iter().copied())
431 .collect::<Vec<_>>()
432 .windows(2)
433 .all(|w| (w[0].as_ivec2() - w[1].as_ivec2()).abs().max_element() == 1)
434 }
435
436 #[test]
437 fn path_excludes_start_and_ends_at_goal() {
438 let map = map_from(&["....."]);
439 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
440 assert_eq!(
441 path,
442 vec![
443 UVec2::new(1, 0),
444 UVec2::new(2, 0),
445 UVec2::new(3, 0),
446 UVec2::new(4, 0)
447 ]
448 );
449 }
450
451 #[test]
452 fn path_to_self_is_empty() {
453 let map = map_from(&["..."]);
454 assert_eq!(find_path(&map, UVec2::ZERO, UVec2::ZERO), Some(vec![]));
455 }
456
457 #[test]
458 fn path_goes_around_walls() {
459 let map = map_from(&[
460 ".....", //
461 ".###.", ".#.#.", "...#.",
462 ]);
463 let start = UVec2::new(2, 1);
464 let goal = UVec2::new(4, 0);
465 let path = find_path(&map, start, goal).unwrap();
466 assert!(is_connected(start, &path));
467 assert_eq!(path.last(), Some(&goal));
468 assert!(path.iter().all(|p| map.move_cost(p.as_ivec2()).is_some()));
469 }
470
471 #[test]
472 fn unreachable_or_impassable_goal_has_no_path() {
473 let map = map_from(&[
474 "..#..", //
475 "..#..",
476 ]);
477 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)), None);
478 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(2, 0)), None);
479 }
480
481 // Colonists move in straight lines between tile centers, so a diagonal step between two
482 // blocked orthogonal neighbours would visually clip through the corners of walls.
483 #[test]
484 fn diagonal_steps_never_cut_wall_corners() {
485 let map = map_from(&[
486 "#.", //
487 ".#",
488 ]);
489 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(1, 1)), None);
490 let map = map_from(&[
491 "..", //
492 "#.",
493 ]);
494 let path = find_path(&map, UVec2::new(0, 1), UVec2::new(1, 0)).unwrap();
495 assert_eq!(path, vec![UVec2::new(1, 1), UVec2::new(1, 0)]);
496 }
497
498 #[test]
499 fn prefers_detour_over_slow_terrain() {
500 let map = map_from(&[
501 ".....", //
502 "..~..",
503 ]);
504 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
505 assert!(!path.contains(&UVec2::new(2, 0)));
506 }
507
508 #[test]
509 fn walks_around_a_hill_rather_than_over_it() {
510 let mut map = map_from(&[
511 ".....", //
512 ".....",
513 ]);
514 map.set_height(UVec2::new(2, 0), 10.0);
515 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
516 assert!(!path.contains(&UVec2::new(2, 0)));
517 }
518
519 #[test]
520 fn detours_along_paths_when_they_are_faster() {
521 let mut map = map_from(&[
522 "..........", //
523 "..........",
524 ]);
525 for x in 0..10 {
526 map.set(UVec2::new(x, 1), Terrain::Paved);
527 }
528 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(9, 0)).unwrap();
529 assert!(path.iter().filter(|p| p.y == 1).count() >= 6);
530 }
531
532 // A wall can go up on a tile a colonist is standing on (or just about to enter); routes must
533 // still start from that tile so nobody gets permanently stuck inside a wall.
534 #[test]
535 fn colonists_can_walk_out_of_a_blocked_tile() {
536 let mut map = map_from(&["....."]);
537 map.set_wall(UVec2::new(2, 0), true);
538 let path = find_path(&map, UVec2::new(2, 0), UVec2::new(4, 0)).unwrap();
539 assert_eq!(path, vec![UVec2::new(3, 0), UVec2::new(4, 0)]);
540 }
541
542 #[test]
543 fn crosses_slow_terrain_when_it_is_the_only_way() {
544 let map = map_from(&["..~.."]);
545 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
546 assert!(path.contains(&UVec2::new(2, 0)));
547 }
548
549 #[test]
550 fn path_adjacent_stops_next_to_target() {
551 let map = map_from(&["......"]);
552 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(5, 0)).unwrap();
553 assert_eq!(path.last(), Some(&UVec2::new(4, 0)));
554 }
555
556 #[test]
557 fn path_adjacent_works_for_impassable_targets() {
558 let map = map_from(&["...#"]);
559 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(3, 0)).unwrap();
560 assert_eq!(path.last(), Some(&UVec2::new(2, 0)));
561 }
562
563 #[test]
564 fn path_adjacent_from_neighbor_is_empty() {
565 let map = map_from(&["..."]);
566 let path = find_path_adjacent(&map, UVec2::new(1, 0), UVec2::new(2, 0));
567 assert_eq!(path, Some(vec![]));
568 }
569
570 #[test]
571 fn path_adjacent_to_enclosed_target_is_none() {
572 let walled = map_from(&[
573 "#####", //
574 "#...#", "#####", ".....",
575 ]);
576 assert_eq!(
577 find_path_adjacent(&walled, UVec2::new(0, 0), UVec2::new(2, 2)),
578 None
579 );
580 }
581
582 #[test]
583 fn nearest_tile_finds_closest_match_by_walking_distance() {
584 let map = map_from(&[
585 ".#...", //
586 ".#.#.", "...#.",
587 ]);
588 let found = nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 4);
589 assert_eq!(found, Some(UVec2::new(4, 2)));
590 assert_eq!(
591 nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 9),
592 None
593 );
594 }
595
596 #[test]
597 fn finds_paths_across_a_generated_world() {
598 let map = crate::worldgen::generate(crate::worldgen::WORLD_SIZE, 1);
599 let region = crate::worldgen::largest_region(&map);
600 let (start, goal) = (region[0], region[region.len() - 1]);
601 let path = find_path(&map, start, goal).unwrap();
602 assert!(is_connected(start, &path));
603 assert_eq!(path.last(), Some(&goal));
604 }
605 }