mod bends;
pub(crate) mod one_bend;
use alloc::vec::Vec;
use heuristic_search::{Limits, Successors, a_star, heuristic_fn};
use crate::error::Error;
use crate::geom::{DirSet, Direction};
use crate::graph::{RoutingGraph, VertexId};
use crate::route::Route;
use crate::scene::{PortId, Scene};
pub use bends::min_bends;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Objective {
#[default]
ShortestThenFewestBends,
FewestBendsThenShortest,
Weighted {
length: u64,
bend: u64,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Weights {
pub length: u64,
pub bend: u64,
}
impl Objective {
pub fn weights(self, graph: &RoutingGraph) -> Result<Weights, Error> {
match self {
Self::Weighted { length, bend } => Ok(Weights { length, bend }),
Self::ShortestThenFewestBends => Ok(Weights {
length: u64::try_from(graph.len()).map_err(|_| Error::CostOverflow)? + 1,
bend: 1,
}),
Self::FewestBendsThenShortest => {
let total = graph.edges().try_fold(0_u64, |sum, (a, b)| {
sum.checked_add(graph.point(a).manhattan(graph.point(b)))
});
let bound = total
.and_then(|t| t.checked_mul(2))
.and_then(|t| t.checked_add(1))
.ok_or(Error::CostOverflow)?;
Ok(Weights {
length: 1,
bend: bound,
})
}
}
}
}
pub trait EdgeCosts {
fn edge(&self, from: VertexId, dir: Direction, to: VertexId, length_cost: u64) -> u64 {
let _ = (from, dir, to);
length_cost
}
fn pass(&self, at: VertexId, entry: Option<Direction>, exit: Direction) -> u64 {
let _ = (at, entry, exit);
0
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct PlainCosts;
impl EdgeCosts for PlainCosts {}
#[derive(Debug, Clone, Copy)]
pub struct Endpoints {
pub source: VertexId,
pub source_directions: DirSet,
pub target: VertexId,
pub target_directions: DirSet,
}
type State = (u32, u8);
const NOT_MOVED: u8 = 4;
struct StateGraph<'a, E> {
graph: &'a RoutingGraph,
endpoints: Endpoints,
weights: Weights,
costs: &'a E,
}
impl<E: EdgeCosts> Successors for StateGraph<'_, E> {
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);
let entry = (state.1 != NOT_MOVED).then(|| Direction::from_index(usize::from(state.1)));
let options: [Option<Direction>; 4] = if let Some(h) = entry {
[Some(h), Some(h.right()), Some(h.left()), None]
} else {
let mut options = [None; 4];
for (slot, d) in options
.iter_mut()
.zip(self.endpoints.source_directions.iter())
{
*slot = Some(d);
}
options
};
let here = self.graph.point(v);
for dir in options.into_iter().flatten() {
let Some(w) = self.graph.neighbor(v, dir) else {
continue;
};
let length = here.manhattan(self.graph.point(w));
let length_cost = self.weights.length.saturating_mul(length);
let bend = if entry.is_some_and(|h| h != dir) {
self.weights.bend
} else {
0
};
let cost = self
.costs
.edge(v, dir, w, length_cost)
.saturating_add(bend)
.saturating_add(self.costs.pass(v, entry, dir));
let index = u8::try_from(dir.index()).expect("four directions");
emit(dir, (w.0, index), cost);
}
}
}
fn estimate(
graph: &RoutingGraph,
endpoints: &Endpoints,
weights: Weights,
state: State,
) -> Option<u64> {
let here = graph.point(VertexId(state.0));
let target = graph.point(endpoints.target);
let arrivals = endpoints.target_directions.reversed();
let bends = if state.1 == NOT_MOVED {
if state.0 == endpoints.target.0 {
0
} else {
endpoints
.source_directions
.iter()
.filter_map(|d| min_bends(here, d, target, arrivals))
.min()?
}
} else {
min_bends(
here,
Direction::from_index(usize::from(state.1)),
target,
arrivals,
)?
};
Some(
weights
.length
.saturating_mul(here.manhattan(target))
.saturating_add(weights.bend.saturating_mul(u64::from(bends))),
)
}
#[must_use]
pub fn route_vertices<E: EdgeCosts>(
graph: &RoutingGraph,
endpoints: Endpoints,
weights: Weights,
costs: &E,
) -> Option<Route> {
let states = StateGraph {
graph,
endpoints,
weights,
costs,
};
let arrivals = endpoints.target_directions.reversed();
let target = endpoints.target.0;
let goal = move |s: &State| {
s.0 == target
&& (s.1 == NOT_MOVED || arrivals.contains(Direction::from_index(usize::from(s.1))))
};
let heuristic = heuristic_fn(|s: &State| estimate(graph, &endpoints, weights, *s));
let result = a_star(
&states,
(endpoints.source.0, NOT_MOVED),
&goal,
heuristic,
Limits::NONE,
);
let solution = result.into_solution()?;
let vertices: Vec<VertexId> = solution.states.iter().map(|s| VertexId(s.0)).collect();
Some(Route::from_vertices(graph, vertices, solution.cost))
}
pub fn endpoints(scene: &Scene, source: PortId, target: PortId) -> Result<Endpoints, Error> {
let vertex = |id: PortId| -> Result<(VertexId, DirSet), Error> {
let port = scene.port(id).ok_or(Error::UnknownPort)?;
let v = scene
.port_vertex(id)
.ok_or(Error::PortBlocked(port.point))?;
Ok((v, port.directions))
};
let (source, source_directions) = vertex(source)?;
let (target, target_directions) = vertex(target)?;
Ok(Endpoints {
source,
source_directions,
target,
target_directions,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Search {
#[default]
Ovg,
OneBend,
}
pub fn route(
scene: &Scene,
source: PortId,
target: PortId,
objective: Objective,
search: Search,
) -> Result<Route, Error> {
let endpoints = endpoints(scene, source, target)?;
let weights = objective.weights(scene.graph())?;
let found = match search {
Search::Ovg => route_vertices(scene.graph(), endpoints, weights, &PlainCosts),
Search::OneBend => one_bend::route(scene, endpoints, weights)
.or_else(|| route_vertices(scene.graph(), endpoints, weights, &PlainCosts)),
};
found.ok_or(Error::NoRoute { connector: 0 })
}
#[must_use]
pub fn cost_of(weights: Weights, length: u64, bends: u32) -> u64 {
weights
.length
.saturating_mul(length)
.saturating_add(weights.bend.saturating_mul(u64::from(bends)))
}