1pub mod heap;
2pub mod nodemap;
3
4use std::{
5 fmt::{self, Debug},
6 hash::Hash,
7 time::{Duration, Instant},
8};
9
10use num_format::ToFormattedString;
11use tracing::{debug, trace, warn};
12
13use crate::pathfinder::astar::{
14 heap::{PathfinderHeap, WeightedNode},
15 nodemap::NodeMap,
16};
17
18pub struct Path<P, M>
19where
20 P: Eq + Hash + Copy + Debug,
21{
22 pub movements: Vec<Movement<P, M>>,
23 pub is_partial: bool,
24 pub cost: f32,
29}
30
31const COEFFICIENTS: [f32; 7] = [1.5, 2., 2.5, 3., 4., 5., 15.];
36
37const MIN_IMPROVEMENT: f32 = 0.01;
38
39pub fn a_star<P, M, HeuristicFn, SuccessorsFn, SuccessFn>(
44 start: P,
45 heuristic: HeuristicFn,
46 mut successors: SuccessorsFn,
47 success: SuccessFn,
48 min_timeout: PathfinderTimeout,
49 max_timeout: PathfinderTimeout,
50) -> Path<P, M>
51where
52 P: Eq + Hash + Copy + Debug,
53 HeuristicFn: Fn(P) -> f32,
54 SuccessorsFn: FnMut(P) -> Vec<Edge<P, M>>,
55 SuccessFn: Fn(P) -> bool,
56{
57 let start_time = Instant::now();
58
59 let mut open_set = PathfinderHeap::new();
60 open_set.push(WeightedNode {
61 g_score: 0.,
62 f_score: 0.,
63 index: 0,
64 });
65 let mut nodes: NodeMap<P> = NodeMap::default();
66 nodes.insert(
67 start,
68 Node {
69 came_from: u32::MAX,
70 g_score: 0.,
71 },
72 );
73
74 let mut best_paths: [u32; 7] = [0; 7];
75 let mut best_path_scores: [f32; 7] = [heuristic(start); 7];
76
77 let mut num_nodes = 0_usize;
78 let mut num_movements = 0;
79
80 while let Some(WeightedNode { index, g_score, .. }) = open_set.pop() {
81 let (&node, node_data) = nodes.get_index(index).unwrap();
82 if g_score > node_data.g_score {
83 continue;
84 }
85
86 num_nodes += 1;
87
88 if success(node) {
89 let best_path = index;
90 log_perf_info(start_time, num_nodes, num_movements);
91
92 return Path {
93 movements: reconstruct_path(nodes, best_path, successors),
94 is_partial: false,
95 cost: g_score,
96 };
97 }
98
99 for neighbor in successors(node) {
100 let tentative_g_score = g_score + neighbor.cost;
101 let neighbor_heuristic;
103 let neighbor_index;
104
105 num_movements += 1;
106
107 match nodes.entry(neighbor.movement.target) {
108 indexmap::map::Entry::Occupied(mut e) => {
109 if e.get().g_score > tentative_g_score {
110 neighbor_heuristic = heuristic(*e.key());
111 neighbor_index = e.index() as u32;
112 e.insert(Node {
113 came_from: index,
114 g_score: tentative_g_score,
115 });
116 } else {
117 continue;
118 }
119 }
120 indexmap::map::Entry::Vacant(e) => {
121 neighbor_heuristic = heuristic(*e.key());
122 neighbor_index = e.index() as u32;
123 e.insert(Node {
124 came_from: index,
125 g_score: tentative_g_score,
126 });
127 }
128 }
129
130 open_set.push(WeightedNode {
135 index: neighbor_index,
136 g_score: tentative_g_score,
137 f_score: tentative_g_score + neighbor_heuristic,
138 });
139
140 for (coefficient_i, &coefficient) in COEFFICIENTS.iter().enumerate() {
141 let node_score = neighbor_heuristic + tentative_g_score / coefficient;
142 if best_path_scores[coefficient_i] - node_score > MIN_IMPROVEMENT {
143 best_paths[coefficient_i] = neighbor_index;
144 best_path_scores[coefficient_i] = node_score;
145 }
146 }
147 }
148
149 if num_nodes.is_multiple_of(10_000) {
151 let min_timeout_reached = match min_timeout {
152 PathfinderTimeout::Time(max_duration) => start_time.elapsed() >= max_duration,
153 PathfinderTimeout::Nodes(max_nodes) => num_nodes >= max_nodes,
154 };
155
156 if min_timeout_reached {
157 if best_paths[6] != 0 {
159 break;
160 }
161
162 if min_timeout_reached {
163 let max_timeout_reached = match max_timeout {
164 PathfinderTimeout::Time(max_duration) => {
165 start_time.elapsed() >= max_duration
166 }
167 PathfinderTimeout::Nodes(max_nodes) => num_nodes >= max_nodes,
168 };
169
170 if max_timeout_reached {
171 trace!("A* couldn't find a path in time, returning best path");
173 break;
174 }
175 }
176 }
177 }
178 }
179
180 let best_path_idx = determine_best_path_idx(best_paths, 0);
181 log_perf_info(start_time, num_nodes, num_movements);
182 Path {
183 movements: reconstruct_path(nodes, best_paths[best_path_idx], successors),
184 is_partial: true,
185 cost: best_path_scores[best_path_idx],
186 }
187}
188
189fn log_perf_info(start_time: Instant, num_nodes: usize, num_movements: usize) {
190 let elapsed = start_time.elapsed();
191 let elapsed_seconds = elapsed.as_secs_f64();
192 let nodes_per_second = (num_nodes as f64 / elapsed_seconds) as u64;
193 let num_movements_per_second = (num_movements as f64 / elapsed_seconds) as u64;
194 debug!(
195 "Considered {} nodes in {elapsed:?}",
196 num_nodes.to_formatted_string(&num_format::Locale::en)
197 );
198 debug!(
199 "A* ran at {} nodes per second and {} movements per second",
200 nodes_per_second.to_formatted_string(&num_format::Locale::en),
201 num_movements_per_second.to_formatted_string(&num_format::Locale::en),
202 );
203}
204
205fn determine_best_path_idx(best_paths: [u32; 7], start: u32) -> usize {
206 for (i, &node) in best_paths.iter().enumerate() {
209 if node != start {
210 return i;
211 }
212 }
213 warn!("No best node found, returning first node");
214 0
215}
216
217fn reconstruct_path<P, M, SuccessorsFn>(
218 nodes: NodeMap<P>,
219 mut current_index: u32,
220 mut successors: SuccessorsFn,
221) -> Vec<Movement<P, M>>
222where
223 P: Eq + Hash + Copy + Debug,
224 SuccessorsFn: FnMut(P) -> Vec<Edge<P, M>>,
225{
226 let mut path = Vec::new();
227 while let Some((&node_position, node)) = nodes.get_index(current_index) {
228 if node.came_from == u32::MAX {
229 break;
230 }
231 let came_from_position = *nodes.get_index(node.came_from).unwrap().0;
232
233 let mut best_successor = None;
237 let mut best_successor_cost = f32::INFINITY;
238 for successor in successors(came_from_position) {
239 if successor.movement.target == node_position && successor.cost < best_successor_cost {
240 best_successor_cost = successor.cost;
241 best_successor = Some(successor);
242 }
243 }
244 let Some(found_successor) = best_successor else {
245 warn!(
246 "a successor stopped being possible while reconstructing the path, returning empty path"
247 );
248 return vec![];
249 };
250
251 path.push(Movement {
252 target: node_position,
253 data: found_successor.movement.data,
254 });
255
256 current_index = node.came_from;
257 }
258 path.reverse();
259 path
260}
261
262pub struct Node {
263 pub came_from: u32,
264 pub g_score: f32,
265}
266
267#[derive(Clone, Debug)]
268pub struct Edge<P: Hash + Copy, M> {
269 pub movement: Movement<P, M>,
270 pub cost: f32,
271}
272
273pub struct Movement<P: Hash + Copy, M> {
274 pub target: P,
275 pub data: M,
276}
277
278impl<P: Hash + Copy + Debug, M: Debug> Debug for Movement<P, M> {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_struct("Movement")
281 .field("target", &self.target)
282 .field("data", &self.data)
283 .finish()
284 }
285}
286impl<P: Hash + Copy + Clone, M: Clone> Clone for Movement<P, M> {
287 fn clone(&self) -> Self {
288 Self {
289 target: self.target,
290 data: self.data.clone(),
291 }
292 }
293}
294
295#[derive(Clone, Copy, Debug, PartialEq)]
303pub enum PathfinderTimeout {
304 Time(Duration),
309 Nodes(usize),
314}
315impl Default for PathfinderTimeout {
316 fn default() -> Self {
317 Self::Time(Duration::from_secs(1))
318 }
319}
320impl From<Duration> for PathfinderTimeout {
321 fn from(duration: Duration) -> Self {
322 Self::Time(duration)
323 }
324}