use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use heuristic_search::{Limits, Successors, a_star, heuristic_fn};
use crate::geom::{DirSet, Direction, Point};
use crate::graph::{RoutingGraph, VertexId};
use crate::route::Route;
use crate::scene::Scene;
use super::{Endpoints, NOT_MOVED, State, Weights, estimate};
struct OneBendGraph<'a> {
graph: &'a RoutingGraph,
hugging: BTreeMap<Point, DirSet>,
endpoints: Endpoints,
weights: Weights,
}
const ALONG: [[Direction; 2]; 4] = [
[Direction::Right, Direction::Up],
[Direction::Left, Direction::Up],
[Direction::Left, Direction::Down],
[Direction::Right, Direction::Down],
];
fn hugging_headings(scene: &Scene) -> BTreeMap<Point, DirSet> {
let mut hugging: BTreeMap<Point, DirSet> = BTreeMap::new();
for (_, rect) in scene.obstacles() {
for (corner, along) in rect.corners().into_iter().zip(ALONG) {
if scene.graph().vertex_at(corner).is_some() {
*hugging.entry(corner).or_default() |= DirSet::only(along[0]) | along[1];
}
}
}
hugging
}
fn add_endpoint_nodes(
graph: &RoutingGraph,
endpoints: &Endpoints,
nodes: &mut BTreeMap<Point, DirSet>,
) {
for d in endpoints.source_directions.iter() {
let mut ray = graph.neighbor(endpoints.source, d);
while let Some(b) = ray {
for p in [d.left(), d.right()] {
let mut walk = graph.neighbor(b, p);
while let Some(w) = walk {
*nodes.entry(graph.point(w)).or_default() |= DirSet::only(p);
walk = graph.neighbor(w, p);
}
}
ray = graph.neighbor(b, d);
}
}
for a in endpoints.target_directions.reversed().iter() {
let mut ray = graph.neighbor(endpoints.target, a.reverse());
while let Some(b) = ray {
*nodes.entry(graph.point(b)).or_default() |= DirSet::only(a.left()) | a.right();
ray = graph.neighbor(b, a.reverse());
}
}
}
const IN_PLACE: u8 = 8;
fn heading_of(state: State) -> Direction {
Direction::from_index(usize::from(state.1 & 3))
}
fn plain(state: State) -> State {
if state.1 == NOT_MOVED {
state
} else {
(state.0, state.1 & 3)
}
}
impl OneBendGraph<'_> {
fn edges_from(
&self,
from: VertexId,
heading: Direction,
bend_here: bool,
emit: &mut impl FnMut(Direction, State, u64),
) {
let start = self.graph.point(from);
let mut bend_at = Some(from);
while let Some(b) = bend_at {
let at = self.graph.point(b);
let run = start.manhattan(at);
if b != from {
self.emit_node(b, heading, run, 0, false, emit);
}
if b != from || bend_here {
for turn in [heading.right(), heading.left()] {
self.emit_node(b, turn, run, 1, true, emit);
let mut next = self.graph.neighbor(b, turn);
while let Some(w) = next {
let length = run + at.manhattan(self.graph.point(w));
self.emit_node(w, turn, length, 1, false, emit);
next = self.graph.neighbor(w, turn);
}
}
}
bend_at = self.graph.neighbor(b, heading);
}
}
fn emit_node(
&self,
w: VertexId,
heading: Direction,
length: u64,
bends: u64,
in_place: bool,
emit: &mut impl FnMut(Direction, State, u64),
) {
let point = self.graph.point(w);
let hugs = self
.hugging
.get(&point)
.is_some_and(|set| set.contains(heading));
let arrives = !in_place
&& w == self.endpoints.target
&& self
.endpoints
.target_directions
.reversed()
.contains(heading);
if !hugs && !arrives {
return;
}
let cost = self
.weights
.length
.saturating_mul(length)
.saturating_add(self.weights.bend.saturating_mul(bends));
let mut index = u8::try_from(heading.index()).expect("four directions");
if in_place {
index |= IN_PLACE;
}
emit(heading, (w.0, index), cost);
}
}
impl Successors for OneBendGraph<'_> {
type State = State;
type Action = Direction;
type Cost = u64;
fn successors(&self, state: &State, mut emit: impl FnMut(Direction, State, u64)) {
let v = VertexId(state.0);
if state.1 == NOT_MOVED {
for d in self.endpoints.source_directions.iter() {
self.edges_from(v, d, false, &mut emit);
}
return;
}
self.edges_from(v, heading_of(*state), state.1 & IN_PLACE == 0, &mut emit);
}
}
pub(crate) fn route(scene: &Scene, endpoints: Endpoints, weights: Weights) -> Option<Route> {
let graph = scene.graph();
let mut hugging = hugging_headings(scene);
add_endpoint_nodes(graph, &endpoints, &mut hugging);
let nodes = OneBendGraph {
graph,
hugging,
endpoints,
weights,
};
let arrivals = endpoints.target_directions.reversed();
let target = endpoints.target.0;
let goal = move |s: &State| {
s.0 == target
&& (s.1 == NOT_MOVED || (s.1 & IN_PLACE == 0 && arrivals.contains(heading_of(*s))))
};
let heuristic = heuristic_fn(|s: &State| estimate(graph, &endpoints, weights, plain(*s)));
let result = a_star(
&nodes,
(endpoints.source.0, NOT_MOVED),
&goal,
heuristic,
Limits::NONE,
);
let solution = result.into_solution()?;
let points = bend_points(graph, &solution.states);
Route::from_points(graph, &points, solution.cost)
}
fn bend_points(graph: &RoutingGraph, states: &[State]) -> Vec<Point> {
let mut points = alloc::vec![graph.point(VertexId(states[0].0))];
for pair in states.windows(2) {
let from = graph.point(VertexId(pair[0].0));
let to = graph.point(VertexId(pair[1].0));
let heading = heading_of(pair[1]);
let bend = match heading.axis() {
crate::geom::Axis::X => Point::new(from.x, to.y),
crate::geom::Axis::Y => Point::new(to.x, from.y),
};
points.push(bend);
points.push(to);
}
points
}