use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use core::cmp::Ordering;
use crate::check::crossing_point;
use crate::geom::{Direction, Point};
use crate::graph::{RoutingGraph, VertexId};
use crate::route::Route;
use crate::search::{Weights, cost_of};
fn turn_rank(heading: Direction, next: Direction) -> u8 {
if next == heading.left() {
0
} else if next == heading {
1
} else {
2
}
}
fn dir(graph: &RoutingGraph, a: VertexId, b: VertexId) -> Direction {
Direction::between(graph.point(a), graph.point(b)).expect("consecutive vertices are aligned")
}
struct Indexed<'a> {
path: &'a [VertexId],
position: BTreeMap<VertexId, usize>,
edges: BTreeSet<(VertexId, VertexId)>,
}
impl<'a> Indexed<'a> {
fn new(path: &'a [VertexId]) -> Self {
let mut position = BTreeMap::new();
for (i, &v) in path.iter().enumerate() {
position.entry(v).or_insert(i);
}
let edges = path
.windows(2)
.map(|e| (e[0].min(e[1]), e[0].max(e[1])))
.collect();
Self {
path,
position,
edges,
}
}
fn position(&self, v: VertexId) -> Option<usize> {
self.position.get(&v).copied()
}
fn has_edge(&self, u: VertexId, w: VertexId) -> bool {
self.edges.contains(&(u.min(w), u.max(w)))
}
}
fn beyond(path: &[VertexId], at: usize, other: VertexId) -> Option<VertexId> {
let before = at.checked_sub(1).map(|i| path[i]);
let after = path.get(at + 1).copied();
if before == Some(other) { after } else { before }
}
fn side_at(
graph: &RoutingGraph,
a: &Indexed<'_>,
b: &Indexed<'_>,
prev: VertexId,
end: VertexId,
) -> Option<Ordering> {
let heading = dir(graph, prev, end);
let next_a = beyond(a.path, a.position(end)?, prev)?;
let next_b = beyond(b.path, b.position(end)?, prev)?;
Some(
turn_rank(heading, dir(graph, end, next_a))
.cmp(&turn_rank(heading, dir(graph, end, next_b))),
)
}
#[must_use]
pub fn required_crossings(graph: &RoutingGraph, a: &[VertexId], b: &[VertexId]) -> u32 {
indexed_crossings(graph, &Indexed::new(a), &Indexed::new(b))
}
fn indexed_crossings(graph: &RoutingGraph, ia: &Indexed<'_>, ib: &Indexed<'_>) -> u32 {
let a = ia.path;
let mut count = 0;
let mut k = 0;
while k + 1 < a.len() {
if !ib.has_edge(a[k], a[k + 1]) {
count += u32::from(k > 0 && straight_crossing(graph, a, ib, k));
k += 1;
continue;
}
let mut end = k + 1;
while end + 1 < a.len() && ib.has_edge(a[end], a[end + 1]) {
end += 1;
}
let at_end = side_at(graph, ia, ib, a[end - 1], a[end]);
let at_start = side_at(graph, ia, ib, a[k + 1], a[k]).map(Ordering::reverse);
if let (Some(s), Some(e)) = (at_start, at_end) {
count += u32::from(s != e);
}
k = end;
}
count
}
fn straight_crossing(graph: &RoutingGraph, a: &[VertexId], ib: &Indexed<'_>, k: usize) -> bool {
let b = ib.path;
let Some(j) = ib.position(a[k]) else {
return false;
};
if j == 0 || j + 1 >= b.len() || k + 1 >= a.len() {
return false;
}
let da = (dir(graph, a[k - 1], a[k]), dir(graph, a[k], a[k + 1]));
let db = (dir(graph, b[j - 1], b[j]), dir(graph, b[j], b[j + 1]));
da.0 == da.1 && db.0 == db.1 && da.0.axis() != db.0.axis()
}
#[must_use]
pub fn total_crossings(graph: &RoutingGraph, routes: &[Route]) -> u32 {
let indexed: Vec<Indexed<'_>> = routes.iter().map(|r| Indexed::new(&r.vertices)).collect();
sharing_pairs(routes)
.into_iter()
.map(|(i, j)| indexed_crossings(graph, &indexed[i], &indexed[j]))
.sum()
}
fn sharing_pairs(routes: &[Route]) -> BTreeSet<(usize, usize)> {
let mut users: BTreeMap<VertexId, Vec<usize>> = BTreeMap::new();
for (i, r) in routes.iter().enumerate() {
for &v in &r.vertices {
let list = users.entry(v).or_default();
if list.last() != Some(&i) {
list.push(i);
}
}
}
let mut pairs = BTreeSet::new();
for list in users.values() {
for (k, &i) in list.iter().enumerate() {
for &j in &list[k + 1..] {
pairs.insert((i.min(j), i.max(j)));
}
}
}
pairs
}
pub fn reduce_crossings(
graph: &RoutingGraph,
routes: &mut [Route],
weights: Weights,
max_rounds: u32,
) -> u32 {
let mut replaced = 0;
for _ in 0..max_rounds {
let changes = round(graph, routes);
if changes.is_empty() {
break;
}
for (i, vertices) in changes {
let mut route = Route::from_vertices(graph, vertices, 0);
route.cost = cost_of(weights, route.length, route.bends);
routes[i] = route;
replaced += 1;
}
}
replaced
}
fn round(graph: &RoutingGraph, routes: &[Route]) -> Vec<(usize, Vec<VertexId>)> {
let indexed: Vec<Indexed<'_>> = routes.iter().map(|r| Indexed::new(&r.vertices)).collect();
let mut users: BTreeMap<VertexId, Vec<usize>> = BTreeMap::new();
for (i, r) in routes.iter().enumerate() {
for &v in &r.vertices {
let list = users.entry(v).or_default();
if list.last() != Some(&i) {
list.push(i);
}
}
}
let mut dirty = BTreeSet::new();
let mut changes = Vec::new();
for (i, j) in sharing_pairs(routes) {
for (x, y) in [(i, j), (j, i)] {
if dirty.contains(&x) || dirty.contains(&y) {
continue;
}
if let Some(candidate) = replacement(graph, &indexed, &users, x, y) {
dirty.insert(x);
changes.push((x, candidate));
}
}
}
changes
}
fn replacement(
graph: &RoutingGraph,
indexed: &[Indexed<'_>],
users: &BTreeMap<VertexId, Vec<usize>>,
i: usize,
j: usize,
) -> Option<Vec<VertexId>> {
let (ia, ib) = (&indexed[i], &indexed[j]);
if indexed_crossings(graph, ia, ib) < 2 {
return None;
}
let (a, b) = (ia.path, ib.path);
let shared: Vec<usize> = (0..a.len())
.filter(|&k| ib.position(a[k]).is_some())
.collect();
let (&first, &last) = (shared.first()?, shared.last()?);
let (pf, pl) = (ib.position(a[first])?, ib.position(a[last])?);
let mut section: Vec<VertexId> = if pf <= pl {
b[pf..=pl].to_vec()
} else {
b[pl..=pf].iter().rev().copied().collect()
};
let mut candidate = a[..first].to_vec();
candidate.append(&mut section);
candidate.extend_from_slice(&a[last + 1..]);
if !is_simple(&candidate) {
return None;
}
let mut others = BTreeSet::new();
for v in a.iter().chain(&candidate) {
others.extend(
users
.get(v)
.into_iter()
.flatten()
.copied()
.filter(|&k| k != i),
);
}
let ic = Indexed::new(&candidate);
let before: u32 = others
.iter()
.map(|&k| indexed_crossings(graph, ia, &indexed[k]))
.sum();
let after: u32 = others
.iter()
.map(|&k| indexed_crossings(graph, &ic, &indexed[k]))
.sum();
(after < before).then_some(candidate)
}
fn is_simple(path: &[VertexId]) -> bool {
let mut sorted = path.to_vec();
sorted.sort_unstable();
sorted.windows(2).all(|w| w[0] != w[1])
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Crossing {
pub at: Point,
pub horizontal: (usize, usize),
pub vertical: (usize, usize),
}
#[must_use]
pub fn points(routes: &[Vec<Point>]) -> Vec<Crossing> {
iter_points(routes).collect()
}
pub fn iter_points(routes: &[Vec<Point>]) -> impl Iterator<Item = Crossing> {
routes.iter().enumerate().flat_map(move |(i, a)| {
routes
.iter()
.enumerate()
.skip(i + 1)
.flat_map(move |(j, b)| {
a.windows(2).enumerate().flat_map(move |(sa, pa)| {
b.windows(2).enumerate().filter_map(move |(sb, pb)| {
let crossing = |h, v, at| Crossing {
at,
horizontal: h,
vertical: v,
};
crossing_point(pa[0], pa[1], pb[0], pb[1])
.map(|at| crossing((i, sa), (j, sb), at))
.or_else(|| {
crossing_point(pb[0], pb[1], pa[0], pa[1])
.map(|at| crossing((j, sb), (i, sa), at))
})
})
})
})
})
}