# misc/pathfinder (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/pathfinder/

Grid pathfinding. (A*)
- A port of the original misc/pathfinder.js. 4-directional movement, Manhattan distance heuristic, and a binary min heap managing the open list.
- A cell is blocked if is_blocked_handler(column, row) is true.
- The result is the list of cells up to the goal cell, excluding the start cell. None if there is no path.
- Differences from the original:
  { column, row } is GridCell, and null is None.
  The heap is ported as is from the original code, so when several paths have the same cost it picks the same path as the original. (the standard BinaryHeap picks in a different order)

## PathFinder (struct)

Grid pathfinding. (a set of static functions)
- Stateless. Call find_path directly.

Example: A path around a wall

```rust
use vanilla::{GridCell, PathFinder};

let map = [
	"....",
	".##.",
	".###",
];
let is_wall = |column: i32, row: i32| -> bool {
	map[row as usize].as_bytes()[column as usize] == b'#'
};
let path = PathFinder::find_path(4, 3, GridCell::create(0, 1), GridCell::create(3, 1), is_wall).unwrap();
assert_eq!(path.len(), 5);
assert_eq!(path[0], GridCell::create(0, 0));
assert_eq!(*path.last().unwrap(), GridCell::create(3, 1));
```

- `pub fn find_path(column_count: i32, row_count: i32, start: GridCell, goal: GridCell, mut is_blocked_handler: impl FnMut(i32, i32) -> bool) -> Option<Vec<GridCell>>` (static, since 0.3.2): Finds a path. (None if the start or goal is outside or the goal is blocked, an empty list if the start and goal are the same)
  - Shortest path moving in 4 directions at a cost of 1 per cell. Does not check whether the start cell is blocked.
  - `column_count` i32: Grid column count. (cell indexes are 0 ~ column_count - 1)
  - `row_count` i32: Grid row count. (cell indexes are 0 ~ row_count - 1)
  - `start` GridCell: Start cell.
  - `goal` GridCell: Goal cell.
  - `is_blocked_handler` impl FnMut(i32, i32) -> bool: Callback that returns true if the (column, row) cell is blocked. Only called for cells inside the grid.
  - returns Option<Vec<GridCell>>: List of adjacent connected cells up to the goal cell, excluding the start cell. None if there is no path.

  Example: A straight path with no obstacles, None if the goal is blocked

  ```rust
  use vanilla::{GridCell, PathFinder};
  
  let straight_path = PathFinder::find_path(3, 1, GridCell::create(0, 0), GridCell::create(2, 0), |_, _| false);
  assert_eq!(straight_path, Some(vec![GridCell::create(1, 0), GridCell::create(2, 0)]));
  
  let blocked_path = PathFinder::find_path(3, 1, GridCell::create(0, 0), GridCell::create(2, 0), |column, _| column == 2);
  assert!(blocked_path.is_none());
  ```

