src/pathfinding.rs 17.7 K · 550 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 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 octile(a: IVec2, b: IVec2) -> u32 {
164 let d = (a - b).abs();
165 let (min, max) = (d.x.min(d.y) as u32, d.x.max(d.y) as u32);
166 (DIAGONAL * min + STRAIGHT * (max - min)) * MIN_TERRAIN_COST
167 }
168
169 #[derive(Default)]
170 struct Scratch {
171 generation: u32,
172 stamp: Vec<u32>,
173 cost: Vec<u32>,
174 from: Vec<IVec2>,
175 open: BinaryHeap<Reverse<(u32, i32, i32)>>,
176 }
177
178 thread_local! {
179 static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
180 }
181
182 fn astar(
183 map: &WorldMap,
184 start: UVec2,
185 is_goal: impl Fn(IVec2) -> bool,
186 heuristic: impl Fn(IVec2) -> u32,
187 ) -> Option<Vec<UVec2>> {
188 astar_limited(map, start, is_goal, heuristic, usize::MAX)
189 }
190
191 fn astar_limited(
192 map: &WorldMap,
193 start: UVec2,
194 is_goal: impl Fn(IVec2) -> bool,
195 heuristic: impl Fn(IVec2) -> u32,
196 max_expanded: usize,
197 ) -> Option<Vec<UVec2>> {
198 let start = start.as_ivec2();
199 if !map.in_bounds(start) {
200 return None;
201 }
202 if is_goal(start) {
203 return Some(vec![]);
204 }
205 SCRATCH.with_borrow_mut(|scratch| {
206 let tiles = map.size.element_product() as usize;
207 if scratch.stamp.len() != tiles {
208 *scratch = Scratch {
209 stamp: vec![0; tiles],
210 cost: vec![0; tiles],
211 from: vec![IVec2::ZERO; tiles],
212 ..default()
213 };
214 }
215 scratch.generation = scratch.generation.wrapping_add(1);
216 if scratch.generation == 0 {
217 scratch.stamp.fill(0);
218 scratch.generation = 1;
219 }
220 let Scratch {
221 generation,
222 stamp,
223 cost,
224 from,
225 open,
226 } = scratch;
227 let generation = *generation;
228 let width = map.size.x as usize;
229 let index = |p: IVec2| p.y as usize * width + p.x as usize;
230 open.clear();
231 stamp[index(start)] = generation;
232 cost[index(start)] = 0;
233 from[index(start)] = start;
234 open.push(Reverse((heuristic(start), start.x, start.y)));
235 let mut expanded = 0;
236 while let Some(Reverse((_, x, y))) = open.pop() {
237 let current = IVec2::new(x, y);
238 if is_goal(current) {
239 let mut path = vec![current.as_uvec2()];
240 let mut at = current;
241 while from[index(at)] != start {
242 at = from[index(at)];
243 path.push(at.as_uvec2());
244 }
245 path.reverse();
246 return Some(path);
247 }
248 expanded += 1;
249 if expanded > max_expanded {
250 return None;
251 }
252 let current_cost = cost[index(current)];
253 for step in NEIGHBORS {
254 let next = current + step;
255 if !can_step(map, current, step) {
256 continue;
257 }
258 let Some(terrain_cost) = map.step_cost(current, next) else {
259 continue;
260 };
261 let diagonal = step.x != 0 && step.y != 0;
262 let base = if diagonal { DIAGONAL } else { STRAIGHT };
263 let new_cost = current_cost + base * terrain_cost;
264 let i = index(next);
265 if stamp[i] != generation || new_cost < cost[i] {
266 stamp[i] = generation;
267 cost[i] = new_cost;
268 from[i] = current;
269 open.push(Reverse((new_cost + heuristic(next), next.x, next.y)));
270 }
271 }
272 }
273 None
274 })
275 }
276
277 pub const WANDER_SEARCH: usize = 800;
278
279 pub fn find_nearby_path(
280 map: &WorldMap,
281 start: UVec2,
282 goal: UVec2,
283 max_expanded: usize,
284 ) -> Option<Vec<UVec2>> {
285 map.move_cost(goal.as_ivec2())?;
286 let goal = goal.as_ivec2();
287 astar_limited(map, start, |p| p == goal, |p| octile(p, goal), max_expanded)
288 }
289
290 #[cfg(test)]
291 mod tests {
292 use super::*;
293 use crate::world::Terrain;
294
295 // Wandering picks random nearby goals; one walled off by a river or cliff made A* search the
296 // whole connected region before failing. Short trips cap the search instead.
297 #[test]
298 fn nearby_paths_give_up_early_on_unreachable_goals() {
299 let mut map = WorldMap::filled(UVec2::splat(100), Terrain::Grass);
300 for y in 0..100 {
301 map.set(UVec2::new(50, y), Terrain::DeepWater);
302 }
303 let start = UVec2::new(45, 50);
304 assert!(find_nearby_path(&map, start, UVec2::new(40, 52), 200).is_some());
305 assert_eq!(find_nearby_path(&map, start, UVec2::new(55, 50), 200), None);
306 assert_eq!(find_path(&map, start, UVec2::new(55, 50)), None);
307 }
308
309 // Target searches must use the same no-corner-cutting rule as A*. A stack on a tile touching
310 // the colony only diagonally between two rocks was "found" by the search, A* then explored
311 // the whole map before failing, and the job was picked again at once: ~10 ms, many times a
312 // second, which made Max speed crawl on a 50-day colony.
313 #[test]
314 fn searches_never_pick_targets_that_paths_cannot_reach() {
315 let mut map = WorldMap::filled(UVec2::splat(6), Terrain::Grass);
316 for y in 3..6 {
317 for x in 0..6 {
318 map.set(UVec2::new(x, y), Terrain::Stone);
319 }
320 }
321 map.set(UVec2::new(2, 3), Terrain::Grass);
322 map.set(UVec2::new(3, 4), Terrain::Gravel);
323 let pocket = UVec2::new(3, 4);
324 assert!(map.move_cost(IVec2::new(2, 3)).is_some());
325 assert_eq!(find_path(&map, UVec2::ZERO, pocket), None);
326 let targets = HashSet::from([pocket]);
327 assert_eq!(nearest_of(&map, UVec2::ZERO, 100, &targets), None);
328 }
329
330 // Idle colonists look for food and cooking input several times per game minute. A stack far
331 // beyond what the flood fill can cover made every one of those searches visit the full tile
332 // budget and fail, which dominated frame time at high speeds. The reach is a radius: the
333 // flood fills a square, so its half-width (not its width, as it once was) bounds it.
334 #[test]
335 fn target_searches_skip_targets_beyond_their_reach() {
336 let map = WorldMap::filled(UVec2::splat(300), Terrain::Grass);
337 let start = UVec2::splat(10);
338 let max_tiles = 400;
339 let near = start + UVec2::new(search_reach(max_tiles) / 4, 0);
340 let far = start + UVec2::new(search_reach(max_tiles) + 1, 0);
341 assert_eq!(
342 nearest_of(&map, start, max_tiles, &HashSet::from([far])),
343 None
344 );
345 assert_eq!(
346 nearest_of(&map, start, max_tiles, &HashSet::from([far, near])),
347 Some(near)
348 );
349 let edge = start + UVec2::new(search_reach(max_tiles) - 1, 0);
350 assert_eq!(
351 nearest_of(&map, start, max_tiles, &HashSet::from([edge])),
352 Some(edge)
353 );
354 }
355
356 fn map_from(rows: &[&str]) -> WorldMap {
357 let size = UVec2::new(rows[0].len() as u32, rows.len() as u32);
358 let mut map = WorldMap::filled(size, Terrain::Grass);
359 for (row, line) in rows.iter().enumerate() {
360 let y = size.y - 1 - row as u32;
361 for (x, c) in line.chars().enumerate() {
362 let terrain = match c {
363 '#' => Terrain::Stone,
364 '~' => Terrain::ShallowWater,
365 _ => Terrain::Grass,
366 };
367 map.set(UVec2::new(x as u32, y), terrain);
368 }
369 }
370 map
371 }
372
373 fn is_connected(start: UVec2, path: &[UVec2]) -> bool {
374 std::iter::once(start)
375 .chain(path.iter().copied())
376 .collect::<Vec<_>>()
377 .windows(2)
378 .all(|w| (w[0].as_ivec2() - w[1].as_ivec2()).abs().max_element() == 1)
379 }
380
381 #[test]
382 fn path_excludes_start_and_ends_at_goal() {
383 let map = map_from(&["....."]);
384 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
385 assert_eq!(
386 path,
387 vec![
388 UVec2::new(1, 0),
389 UVec2::new(2, 0),
390 UVec2::new(3, 0),
391 UVec2::new(4, 0)
392 ]
393 );
394 }
395
396 #[test]
397 fn path_to_self_is_empty() {
398 let map = map_from(&["..."]);
399 assert_eq!(find_path(&map, UVec2::ZERO, UVec2::ZERO), Some(vec![]));
400 }
401
402 #[test]
403 fn path_goes_around_walls() {
404 let map = map_from(&[
405 ".....", //
406 ".###.", ".#.#.", "...#.",
407 ]);
408 let start = UVec2::new(2, 1);
409 let goal = UVec2::new(4, 0);
410 let path = find_path(&map, start, goal).unwrap();
411 assert!(is_connected(start, &path));
412 assert_eq!(path.last(), Some(&goal));
413 assert!(path.iter().all(|p| map.move_cost(p.as_ivec2()).is_some()));
414 }
415
416 #[test]
417 fn unreachable_or_impassable_goal_has_no_path() {
418 let map = map_from(&[
419 "..#..", //
420 "..#..",
421 ]);
422 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)), None);
423 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(2, 0)), None);
424 }
425
426 // Colonists move in straight lines between tile centers, so a diagonal step between two
427 // blocked orthogonal neighbours would visually clip through the corners of walls.
428 #[test]
429 fn diagonal_steps_never_cut_wall_corners() {
430 let map = map_from(&[
431 "#.", //
432 ".#",
433 ]);
434 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(1, 1)), None);
435 let map = map_from(&[
436 "..", //
437 "#.",
438 ]);
439 let path = find_path(&map, UVec2::new(0, 1), UVec2::new(1, 0)).unwrap();
440 assert_eq!(path, vec![UVec2::new(1, 1), UVec2::new(1, 0)]);
441 }
442
443 #[test]
444 fn prefers_detour_over_slow_terrain() {
445 let map = map_from(&[
446 ".....", //
447 "..~..",
448 ]);
449 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
450 assert!(!path.contains(&UVec2::new(2, 0)));
451 }
452
453 #[test]
454 fn walks_around_a_hill_rather_than_over_it() {
455 let mut map = map_from(&[
456 ".....", //
457 ".....",
458 ]);
459 map.set_height(UVec2::new(2, 0), 10.0);
460 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
461 assert!(!path.contains(&UVec2::new(2, 0)));
462 }
463
464 #[test]
465 fn detours_along_paths_when_they_are_faster() {
466 let mut map = map_from(&[
467 "..........", //
468 "..........",
469 ]);
470 for x in 0..10 {
471 map.set(UVec2::new(x, 1), Terrain::Paved);
472 }
473 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(9, 0)).unwrap();
474 assert!(path.iter().filter(|p| p.y == 1).count() >= 6);
475 }
476
477 // A wall can go up on a tile a colonist is standing on (or just about to enter); routes must
478 // still start from that tile so nobody gets permanently stuck inside a wall.
479 #[test]
480 fn colonists_can_walk_out_of_a_blocked_tile() {
481 let mut map = map_from(&["....."]);
482 map.set_wall(UVec2::new(2, 0), true);
483 let path = find_path(&map, UVec2::new(2, 0), UVec2::new(4, 0)).unwrap();
484 assert_eq!(path, vec![UVec2::new(3, 0), UVec2::new(4, 0)]);
485 }
486
487 #[test]
488 fn crosses_slow_terrain_when_it_is_the_only_way() {
489 let map = map_from(&["..~.."]);
490 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
491 assert!(path.contains(&UVec2::new(2, 0)));
492 }
493
494 #[test]
495 fn path_adjacent_stops_next_to_target() {
496 let map = map_from(&["......"]);
497 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(5, 0)).unwrap();
498 assert_eq!(path.last(), Some(&UVec2::new(4, 0)));
499 }
500
501 #[test]
502 fn path_adjacent_works_for_impassable_targets() {
503 let map = map_from(&["...#"]);
504 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(3, 0)).unwrap();
505 assert_eq!(path.last(), Some(&UVec2::new(2, 0)));
506 }
507
508 #[test]
509 fn path_adjacent_from_neighbor_is_empty() {
510 let map = map_from(&["..."]);
511 let path = find_path_adjacent(&map, UVec2::new(1, 0), UVec2::new(2, 0));
512 assert_eq!(path, Some(vec![]));
513 }
514
515 #[test]
516 fn path_adjacent_to_enclosed_target_is_none() {
517 let walled = map_from(&[
518 "#####", //
519 "#...#", "#####", ".....",
520 ]);
521 assert_eq!(
522 find_path_adjacent(&walled, UVec2::new(0, 0), UVec2::new(2, 2)),
523 None
524 );
525 }
526
527 #[test]
528 fn nearest_tile_finds_closest_match_by_walking_distance() {
529 let map = map_from(&[
530 ".#...", //
531 ".#.#.", "...#.",
532 ]);
533 let found = nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 4);
534 assert_eq!(found, Some(UVec2::new(4, 2)));
535 assert_eq!(
536 nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 9),
537 None
538 );
539 }
540
541 #[test]
542 fn finds_paths_across_a_generated_world() {
543 let map = crate::worldgen::generate(crate::worldgen::WORLD_SIZE, 1);
544 let region = crate::worldgen::largest_region(&map);
545 let (start, goal) = (region[0], region[region.len() - 1]);
546 let path = find_path(&map, start, goal).unwrap();
547 assert!(is_connected(start, &path));
548 assert_eq!(path.last(), Some(&goal));
549 }
550 }