use crate::exact::kernel::orient;
use crate::types::{Coord2d, CoordSeq, LineString, Lineal, MultiLineString};
use arithmetica::Sign;
#[derive(Clone, Debug, PartialEq)]
pub struct SharedPaths {
pub same_direction: MultiLineString,
pub opposite_direction: MultiLineString,
}
#[allow(clippy::float_cmp)]
fn along(a: Coord2d, b: Coord2d) -> fn(Coord2d) -> f64 {
if a.x == b.x { |c| c.y } else { |c| c.x }
}
#[derive(Clone, Copy)]
struct Piece {
seg: usize,
from: Coord2d,
to: Coord2d,
at_start: bool,
at_end: bool,
}
#[allow(clippy::float_cmp)]
fn segment_pieces(seg: usize, p: Coord2d, q: Coord2d, b: &[LineString]) -> [Vec<Piece>; 2] {
let k = along(p, q);
let a_up = k(q) > k(p);
let mut iv: [Vec<(Coord2d, Coord2d)>; 2] = [Vec::new(), Vec::new()];
let (a_lo, a_hi) = if a_up { (p, q) } else { (q, p) };
for l in b {
for w in l.coords().as_slice().windows(2) {
let (r, s) = (w[0], w[1]);
if orient(p, q, r) != Sign::Zero || orient(p, q, s) != Sign::Zero {
continue;
}
let b_up = k(s) > k(r);
let (b_lo, b_hi) = if b_up { (r, s) } else { (s, r) };
let lo = if k(b_lo) > k(a_lo) { b_lo } else { a_lo };
let hi = if k(b_hi) < k(a_hi) { b_hi } else { a_hi };
if k(lo) < k(hi) {
iv[usize::from(a_up != b_up)].push((lo, hi));
}
}
}
iv.map(|mut v| {
v.sort_by(|x, y| k(x.0).total_cmp(&k(y.0)));
let mut merged: Vec<(Coord2d, Coord2d)> = Vec::new();
for (lo, hi) in v {
match merged.last_mut() {
Some(last) if k(lo) <= k(last.1) => {
if k(hi) > k(last.1) {
last.1 = hi;
}
}
_ => merged.push((lo, hi)),
}
}
if !a_up {
merged.reverse();
}
merged
.into_iter()
.map(|(lo, hi)| {
let (from, to) = if a_up { (lo, hi) } else { (hi, lo) };
Piece {
seg,
from,
to,
at_start: k(from) == k(p),
at_end: k(to) == k(q),
}
})
.collect()
})
}
fn join(pieces: &[Piece], out: &mut Vec<LineString>) {
let mut cur: Vec<Coord2d> = Vec::new();
let mut last: Option<Piece> = None;
for &pc in pieces {
let continues = last.is_some_and(|l| l.at_end && pc.at_start && pc.seg == l.seg + 1);
if !continues && !cur.is_empty() {
out.push(LineString::from_valid(CoordSeq::new(core::mem::take(
&mut cur,
))));
}
if cur.is_empty() {
cur.push(pc.from);
}
cur.push(pc.to);
last = Some(pc);
}
if !cur.is_empty() {
out.push(LineString::from_valid(CoordSeq::new(cur)));
}
}
#[must_use]
pub fn shared_paths(a: &impl Lineal, b: &impl Lineal) -> SharedPaths {
let bl = b.components();
let mut same = Vec::new();
let mut opposite = Vec::new();
for l in a.components() {
let mut classes: [Vec<Piece>; 2] = [Vec::new(), Vec::new()];
for (i, w) in l.coords().as_slice().windows(2).enumerate() {
let [s, o] = segment_pieces(i, w[0], w[1], bl);
classes[0].extend(s);
classes[1].extend(o);
}
join(&classes[0], &mut same);
join(&classes[1], &mut opposite);
}
SharedPaths {
same_direction: MultiLineString::new(same),
opposite_direction: MultiLineString::new(opposite),
}
}