src/pathfinding.rs 13.4 K · 420 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 pub fn search_reach(max_tiles: usize) -> u32 {
87 (max_tiles as f32).sqrt().ceil() as u32
88 }
89
90 pub fn nearest_of(
91 map: &WorldMap,
92 start: UVec2,
93 max_tiles: usize,
94 targets: &HashSet<UVec2>,
95 ) -> Option<UVec2> {
96 let reach = search_reach(max_tiles) as i32;
97 let in_reach = |p: &&UVec2| (p.as_ivec2() - start.as_ivec2()).abs().max_element() <= reach;
98 if !targets.iter().any(|p| in_reach(&p)) {
99 return None;
100 }
101 nearest_tile(map, start, max_tiles, |p| targets.contains(&p))
102 }
103
104 fn astar(
105 map: &WorldMap,
106 start: UVec2,
107 is_goal: impl Fn(IVec2) -> bool,
108 heuristic: impl Fn(IVec2) -> u32,
109 ) -> Option<Vec<UVec2>> {
110 let start = start.as_ivec2();
111 if !map.in_bounds(start) {
112 return None;
113 }
114 if is_goal(start) {
115 return Some(vec![]);
116 }
117
118 let width = map.size.x as usize;
119 let index = |p: IVec2| p.y as usize * width + p.x as usize;
120 let tiles = map.size.element_product() as usize;
121 let mut cost_so_far = vec![u32::MAX; tiles];
122 let mut came_from = vec![None::<IVec2>; tiles];
123 let mut open = BinaryHeap::new();
124
125 cost_so_far[index(start)] = 0;
126 open.push(Reverse((heuristic(start), start.x, start.y)));
127
128 while let Some(Reverse((_, x, y))) = open.pop() {
129 let current = IVec2::new(x, y);
130 if is_goal(current) {
131 return Some(reconstruct(&came_from, index, start, current));
132 }
133 let current_cost = cost_so_far[index(current)];
134 for step in NEIGHBORS {
135 let next = current + step;
136 if !can_step(map, current, step) {
137 continue;
138 }
139 let Some(terrain_cost) = map.step_cost(current, next) else {
140 continue;
141 };
142 let diagonal = step.x != 0 && step.y != 0;
143 let base = if diagonal { DIAGONAL } else { STRAIGHT };
144 let new_cost = current_cost + base * terrain_cost;
145 if new_cost < cost_so_far[index(next)] {
146 cost_so_far[index(next)] = new_cost;
147 came_from[index(next)] = Some(current);
148 open.push(Reverse((new_cost + heuristic(next), next.x, next.y)));
149 }
150 }
151 }
152 None
153 }
154
155 fn octile(a: IVec2, b: IVec2) -> u32 {
156 let d = (a - b).abs();
157 let (min, max) = (d.x.min(d.y) as u32, d.x.max(d.y) as u32);
158 (DIAGONAL * min + STRAIGHT * (max - min)) * MIN_TERRAIN_COST
159 }
160
161 fn reconstruct(
162 came_from: &[Option<IVec2>],
163 index: impl Fn(IVec2) -> usize,
164 start: IVec2,
165 goal: IVec2,
166 ) -> Vec<UVec2> {
167 let mut path = vec![goal.as_uvec2()];
168 let mut current = goal;
169 while let Some(prev) = came_from[index(current)] {
170 if prev == start {
171 break;
172 }
173 path.push(prev.as_uvec2());
174 current = prev;
175 }
176 path.reverse();
177 path
178 }
179
180 #[cfg(test)]
181 mod tests {
182 use super::*;
183 use crate::world::Terrain;
184
185 // Target searches must use the same no-corner-cutting rule as A*. A stack on a tile touching
186 // the colony only diagonally between two rocks was "found" by the search, A* then explored
187 // the whole map before failing, and the job was picked again at once: ~10 ms, many times a
188 // second, which made Max speed crawl on a 50-day colony.
189 #[test]
190 fn searches_never_pick_targets_that_paths_cannot_reach() {
191 let mut map = WorldMap::filled(UVec2::splat(6), Terrain::Grass);
192 for y in 3..6 {
193 for x in 0..6 {
194 map.set(UVec2::new(x, y), Terrain::Stone);
195 }
196 }
197 map.set(UVec2::new(2, 3), Terrain::Grass);
198 map.set(UVec2::new(3, 4), Terrain::Gravel);
199 let pocket = UVec2::new(3, 4);
200 assert!(map.move_cost(IVec2::new(2, 3)).is_some());
201 assert_eq!(find_path(&map, UVec2::ZERO, pocket), None);
202 let targets = HashSet::from([pocket]);
203 assert_eq!(nearest_of(&map, UVec2::ZERO, 100, &targets), None);
204 }
205
206 // Idle colonists look for food and cooking input several times per game minute. A stack far
207 // beyond what the flood fill can cover made every one of those searches visit the full tile
208 // budget and fail, which dominated frame time at high speeds.
209 #[test]
210 fn target_searches_skip_targets_beyond_their_reach() {
211 let map = WorldMap::filled(UVec2::splat(300), Terrain::Grass);
212 let start = UVec2::splat(10);
213 let max_tiles = 400;
214 let near = start + UVec2::new(search_reach(max_tiles) / 4, 0);
215 let far = start + UVec2::new(search_reach(max_tiles) + 1, 0);
216 assert_eq!(
217 nearest_of(&map, start, max_tiles, &HashSet::from([far])),
218 None
219 );
220 assert_eq!(
221 nearest_of(&map, start, max_tiles, &HashSet::from([far, near])),
222 Some(near)
223 );
224 }
225
226 fn map_from(rows: &[&str]) -> WorldMap {
227 let size = UVec2::new(rows[0].len() as u32, rows.len() as u32);
228 let mut map = WorldMap::filled(size, Terrain::Grass);
229 for (row, line) in rows.iter().enumerate() {
230 let y = size.y - 1 - row as u32;
231 for (x, c) in line.chars().enumerate() {
232 let terrain = match c {
233 '#' => Terrain::Stone,
234 '~' => Terrain::ShallowWater,
235 _ => Terrain::Grass,
236 };
237 map.set(UVec2::new(x as u32, y), terrain);
238 }
239 }
240 map
241 }
242
243 fn is_connected(start: UVec2, path: &[UVec2]) -> bool {
244 std::iter::once(start)
245 .chain(path.iter().copied())
246 .collect::<Vec<_>>()
247 .windows(2)
248 .all(|w| (w[0].as_ivec2() - w[1].as_ivec2()).abs().max_element() == 1)
249 }
250
251 #[test]
252 fn path_excludes_start_and_ends_at_goal() {
253 let map = map_from(&["....."]);
254 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
255 assert_eq!(
256 path,
257 vec![
258 UVec2::new(1, 0),
259 UVec2::new(2, 0),
260 UVec2::new(3, 0),
261 UVec2::new(4, 0)
262 ]
263 );
264 }
265
266 #[test]
267 fn path_to_self_is_empty() {
268 let map = map_from(&["..."]);
269 assert_eq!(find_path(&map, UVec2::ZERO, UVec2::ZERO), Some(vec![]));
270 }
271
272 #[test]
273 fn path_goes_around_walls() {
274 let map = map_from(&[
275 ".....", //
276 ".###.", ".#.#.", "...#.",
277 ]);
278 let start = UVec2::new(2, 1);
279 let goal = UVec2::new(4, 0);
280 let path = find_path(&map, start, goal).unwrap();
281 assert!(is_connected(start, &path));
282 assert_eq!(path.last(), Some(&goal));
283 assert!(path.iter().all(|p| map.move_cost(p.as_ivec2()).is_some()));
284 }
285
286 #[test]
287 fn unreachable_or_impassable_goal_has_no_path() {
288 let map = map_from(&[
289 "..#..", //
290 "..#..",
291 ]);
292 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)), None);
293 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(2, 0)), None);
294 }
295
296 // Colonists move in straight lines between tile centers, so a diagonal step between two
297 // blocked orthogonal neighbours would visually clip through the corners of walls.
298 #[test]
299 fn diagonal_steps_never_cut_wall_corners() {
300 let map = map_from(&[
301 "#.", //
302 ".#",
303 ]);
304 assert_eq!(find_path(&map, UVec2::new(0, 0), UVec2::new(1, 1)), None);
305 let map = map_from(&[
306 "..", //
307 "#.",
308 ]);
309 let path = find_path(&map, UVec2::new(0, 1), UVec2::new(1, 0)).unwrap();
310 assert_eq!(path, vec![UVec2::new(1, 1), UVec2::new(1, 0)]);
311 }
312
313 #[test]
314 fn prefers_detour_over_slow_terrain() {
315 let map = map_from(&[
316 ".....", //
317 "..~..",
318 ]);
319 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
320 assert!(!path.contains(&UVec2::new(2, 0)));
321 }
322
323 #[test]
324 fn walks_around_a_hill_rather_than_over_it() {
325 let mut map = map_from(&[
326 ".....", //
327 ".....",
328 ]);
329 map.set_height(UVec2::new(2, 0), 10.0);
330 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
331 assert!(!path.contains(&UVec2::new(2, 0)));
332 }
333
334 #[test]
335 fn detours_along_paths_when_they_are_faster() {
336 let mut map = map_from(&[
337 "..........", //
338 "..........",
339 ]);
340 for x in 0..10 {
341 map.set(UVec2::new(x, 1), Terrain::Paved);
342 }
343 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(9, 0)).unwrap();
344 assert!(path.iter().filter(|p| p.y == 1).count() >= 6);
345 }
346
347 // A wall can go up on a tile a colonist is standing on (or just about to enter); routes must
348 // still start from that tile so nobody gets permanently stuck inside a wall.
349 #[test]
350 fn colonists_can_walk_out_of_a_blocked_tile() {
351 let mut map = map_from(&["....."]);
352 map.set_wall(UVec2::new(2, 0), true);
353 let path = find_path(&map, UVec2::new(2, 0), UVec2::new(4, 0)).unwrap();
354 assert_eq!(path, vec![UVec2::new(3, 0), UVec2::new(4, 0)]);
355 }
356
357 #[test]
358 fn crosses_slow_terrain_when_it_is_the_only_way() {
359 let map = map_from(&["..~.."]);
360 let path = find_path(&map, UVec2::new(0, 0), UVec2::new(4, 0)).unwrap();
361 assert!(path.contains(&UVec2::new(2, 0)));
362 }
363
364 #[test]
365 fn path_adjacent_stops_next_to_target() {
366 let map = map_from(&["......"]);
367 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(5, 0)).unwrap();
368 assert_eq!(path.last(), Some(&UVec2::new(4, 0)));
369 }
370
371 #[test]
372 fn path_adjacent_works_for_impassable_targets() {
373 let map = map_from(&["...#"]);
374 let path = find_path_adjacent(&map, UVec2::new(0, 0), UVec2::new(3, 0)).unwrap();
375 assert_eq!(path.last(), Some(&UVec2::new(2, 0)));
376 }
377
378 #[test]
379 fn path_adjacent_from_neighbor_is_empty() {
380 let map = map_from(&["..."]);
381 let path = find_path_adjacent(&map, UVec2::new(1, 0), UVec2::new(2, 0));
382 assert_eq!(path, Some(vec![]));
383 }
384
385 #[test]
386 fn path_adjacent_to_enclosed_target_is_none() {
387 let walled = map_from(&[
388 "#####", //
389 "#...#", "#####", ".....",
390 ]);
391 assert_eq!(
392 find_path_adjacent(&walled, UVec2::new(0, 0), UVec2::new(2, 2)),
393 None
394 );
395 }
396
397 #[test]
398 fn nearest_tile_finds_closest_match_by_walking_distance() {
399 let map = map_from(&[
400 ".#...", //
401 ".#.#.", "...#.",
402 ]);
403 let found = nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 4);
404 assert_eq!(found, Some(UVec2::new(4, 2)));
405 assert_eq!(
406 nearest_tile(&map, UVec2::new(0, 0), 100, |p| p.x == 9),
407 None
408 );
409 }
410
411 #[test]
412 fn finds_paths_across_a_generated_world() {
413 let map = crate::worldgen::generate(crate::worldgen::WORLD_SIZE, 1);
414 let region = crate::worldgen::largest_region(&map);
415 let (start, goal) = (region[0], region[region.len() - 1]);
416 let path = find_path(&map, start, goal).unwrap();
417 assert!(is_connected(start, &path));
418 assert_eq!(path.last(), Some(&goal));
419 }
420 }