1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Generic A* pathfinding implementation for tile-based grids and coordinate systems.
//!
//! This module provides a flexible A* pathfinding algorithm that works with any
//! coordinate system implementing the required traits. The implementation is optimized
//! for tile-based games including strategy games, RPGs, puzzle games, and roguelikes.
//!
//! # Algorithm
//!
//! The A* (A-star) algorithm finds the shortest path between two points by:
//! 1. Maintaining an open set of nodes to explore
//! 2. Using a heuristic to estimate remaining distance to goal
//! 3. Always exploring the most promising node next
//! 4. Guaranteeing an optimal path if one exists
//!
//! # Performance Characteristics
//!
//! - **Time Complexity**: O(b^d) where b is branching factor and d is solution depth
//! - **Space Complexity**: O(b^d) for storing the search frontier
//! - **Optimality**: Guaranteed optimal path with admissible heuristic
//! - **Completeness**: Always finds a path if one exists
//!
//! # Coordinate System Support
//!
//! Works with all coordinate systems in this crate:
//! - **Square grids**: 4-connected or 8-connected movement
//! - **Hexagonal grids**: 6-neighbor movement patterns
//! - **Triangular grids**: 12-neighbor connectivity
//! - **Isometric grids**: Diamond-projected square grids
//!
//! # Examples
//!
//! ## Basic Pathfinding on Square Grid
//!
//! ```rust
//! use tiles_tools::pathfind::astar;
//! use tiles_tools::coordinates::square::{Coordinate as SquareCoord, FourConnected};
//! use std::collections::HashSet;
//!
//! // Create start and goal positions
//! let start = SquareCoord::<FourConnected>::new(0, 0);
//! let goal = SquareCoord::<FourConnected>::new(5, 5);
//!
//! // Define obstacles
//! let obstacles: HashSet<_> = [
//! SquareCoord::<FourConnected>::new(2, 2),
//! SquareCoord::<FourConnected>::new(2, 3),
//! SquareCoord::<FourConnected>::new(2, 4),
//! ].into_iter().collect();
//!
//! // Find path avoiding obstacles
//! let result = astar(
//! &start,
//! &goal,
//! |coord| !obstacles.contains(coord), // Accessibility function
//! |_coord| 1, // Uniform cost function
//! );
//!
//! if let Some((path, total_cost)) = result {
//! println!("Found path with {} steps, total cost: {}", path.len(), total_cost);
//! for (i, pos) in path.iter().enumerate() {
//! println!("Step {}: ({}, {})", i, pos.x, pos.y);
//! }
//! } else {
//! println!("No path found!");
//! }
//! ```
//!
//! ## Hexagonal Grid with Variable Terrain Costs
//!
//! ```rust
//! use tiles_tools::pathfind::astar;
//! use tiles_tools::coordinates::hexagonal::{Coordinate as HexCoord, Axial, Pointy};
//! use std::collections::HashMap;
//!
//! let start = HexCoord::<Axial, Pointy>::new(-2, 2);
//! let goal = HexCoord::<Axial, Pointy>::new(3, -1);
//!
//! // Define terrain costs (higher cost = harder to traverse)
//! let mut terrain_costs = HashMap::new();
//! terrain_costs.insert(HexCoord::<Axial, Pointy>::new(0, 0), 5); // Difficult terrain
//! terrain_costs.insert(HexCoord::<Axial, Pointy>::new(1, -1), 10); // Very difficult
//!
//! let result = astar(
//! &start,
//! &goal,
//! |_coord| true, // All positions accessible
//! |coord| terrain_costs.get(coord).copied().unwrap_or(1), // Variable costs
//! );
//!
//! if let Some((path, cost)) = result {
//! println!("Found hexagonal path with total cost: {}", cost);
//! }
//! ```
//!
//! ## Pathfinding with Dynamic Obstacles
//!
//! ```rust
//! use tiles_tools::pathfind::astar;
//! use tiles_tools::coordinates::square::{Coordinate as SquareCoord, EightConnected};
//! use tiles_tools::coordinates::Distance;
//!
//! // Dynamic obstacle system
//! struct GameState {
//! player_positions: Vec<SquareCoord<EightConnected>>,
//! walls: Vec<SquareCoord<EightConnected>>,
//! }
//!
//! let game_state = GameState {
//! player_positions: vec![
//! SquareCoord::<EightConnected>::new(3, 3),
//! SquareCoord::<EightConnected>::new(4, 4),
//! ],
//! walls: vec![
//! SquareCoord::<EightConnected>::new(5, 0),
//! SquareCoord::<EightConnected>::new(5, 1),
//! ],
//! };
//!
//! let start = SquareCoord::<EightConnected>::new(0, 0);
//! let goal = SquareCoord::<EightConnected>::new(7, 7);
//!
//! let result = astar(
//! &start,
//! &goal,
//! |coord| {
//! // Position is accessible if not blocked by walls or other players
//! !game_state.walls.contains(coord) &&
//! !game_state.player_positions.contains(coord)
//! },
//! |coord| {
//! // Higher cost near other players (for AI avoidance behavior)
//! let base_cost = 1;
//! let player_penalty = game_state.player_positions.iter()
//! .map(|player| {
//! let distance = coord.distance(player);
//! if distance <= 2 { 2 } else { 0 }
//! })
//! .sum::<u32>();
//! base_cost + player_penalty
//! },
//! );
//! ```
//!
//! # Integration with Game Systems
//!
//! The pathfinding system integrates well with other modules:
//! - Use with **Field of View** for line-of-sight pathfinding
//! - Combine with **Flow Fields** for multi-unit movement
//! - Works with **ECS systems** for entity movement
//! - Compatible with all **coordinate conversion** utilities
use crate;
use Hash;
use ;
/// Finds the shortest path between a start and goal coordinate using the A* algorithm.
///
/// This function is a generic wrapper around the `pathfinding::prelude::astar` function,
/// tailored for coordinate systems that implement `Distance` and `Neighbors`.
///
/// # Type Parameters
/// * `C`: The type of the coordinate, which must support distance calculation, neighbor finding,
/// equality checks, cloning, and hashing.
/// * `Fa`: A closure that takes a coordinate and returns `true` if it is traversable.
/// * `Fc`: A closure that takes a coordinate and returns the cost `u32` of moving onto it.
///
/// # Arguments
/// * `start`: The starting coordinate for the path.
/// * `goal`: The target coordinate for the path.
/// * `is_accessible`: A function that determines if a given coordinate can be part of the path.
/// * `cost`: A function that provides the cost for moving to a specific coordinate.
///
/// # Returns
/// An `Option` containing a tuple with the path as a `Vec<C>` and the total cost as a `u32`.
/// Returns `None` if no path from `start` to `goal` can be found.
/// Enhanced A* pathfinding with edge costs (movement from one coordinate to another).
///
/// This version allows specifying different costs for movement between specific coordinates,
/// enabling more sophisticated pathfinding scenarios.
///
/// # Arguments
/// * `start`: The starting coordinate for the path.
/// * `goal`: The target coordinate for the path.
/// * `is_accessible`: A function that determines if a given coordinate can be part of the path.
/// * `edge_cost`: A function that provides the cost for moving from one coordinate to another.
///
/// # Examples
/// ```rust
/// use tiles_tools::pathfind::astar_with_edge_costs;
/// use tiles_tools::coordinates::square::{Coordinate as SquareCoord, EightConnected};
///
/// let start = SquareCoord::<EightConnected>::new(0, 0);
/// let goal = SquareCoord::<EightConnected>::new(3, 3);
///
/// let result = astar_with_edge_costs(
/// &start,
/// &goal,
/// |_coord| true,
/// |from, to| {
/// // Diagonal movement costs more
/// let dx = (to.x - from.x).abs();
/// let dy = (to.y - from.y).abs();
/// if dx == 1 && dy == 1 { 14 } else { 10 } // ~1.4x cost for diagonal
/// },
/// );
/// ```
/// Pathfinding configuration for complex scenarios.
///
/// This struct provides a builder pattern for configuring advanced pathfinding
/// with multiple constraint types and optimization options.
/// Advanced pathfinding with comprehensive configuration support.
///
/// This function provides sophisticated pathfinding capabilities including:
/// - Obstacle avoidance
/// - Variable terrain costs
/// - Entity blocking
/// - Movement constraints
/// - Search distance limits
///
/// # Examples
/// ```rust
/// use tiles_tools::pathfind::{ astar_advanced, PathfindingConfig };
/// use tiles_tools::coordinates::square::{Coordinate as SquareCoord, FourConnected};
/// use std::collections::{ HashMap, HashSet };
///
/// let start = SquareCoord::<FourConnected>::new(0, 0);
/// let goal = SquareCoord::<FourConnected>::new(10, 10);
///
/// let config = PathfindingConfig::new()
/// .with_max_distance(20)
/// .with_obstacles([
/// SquareCoord::<FourConnected>::new(5, 5),
/// SquareCoord::<FourConnected>::new(5, 6),
/// ])
/// .with_terrain_cost(SquareCoord::<FourConnected>::new(3, 3), 5)
/// .with_base_cost(1);
///
/// if let Some((path, cost)) = astar_advanced(&start, &goal, &config) {
/// println!("Found advanced path with cost: {}", cost);
/// }
/// ```
/// Finds multiple paths to different goals, returning the best path.
///
/// This function is useful for AI that has multiple possible targets and wants
/// to choose the closest or most efficient one to reach.
///
/// # Arguments
/// * `start`: The starting coordinate.
/// * `goals`: A slice of potential goal coordinates.
/// * `is_accessible`: Function to determine if a coordinate is accessible.
/// * `cost`: Function to determine movement cost.
///
/// # Returns
/// The best path found among all goals, along with the target goal that was reached.
///
/// # Examples
/// ```rust
/// use tiles_tools::pathfind::astar_multi_goal;
/// use tiles_tools::coordinates::hexagonal::{Coordinate as HexCoord, Axial, Pointy};
///
/// let start = HexCoord::<Axial, Pointy>::new(0, 0);
/// let goals = [
/// HexCoord::<Axial, Pointy>::new(5, 2),
/// HexCoord::<Axial, Pointy>::new(-3, 4),
/// HexCoord::<Axial, Pointy>::new(2, -5),
/// ];
///
/// if let Some((path, cost, goal)) = astar_multi_goal(&start, &goals, |_| true, |_| 1) {
/// println!("Best path leads to {:?} with cost {}", goal, cost);
/// }
/// ```