use std::cmp::Ordering;
use arithmetica::rational::{RationalCoord2d, rational_compare_along};
use crate::GeometryError;
use crate::exact::kernel::on_segment;
use crate::topology::areal::{AreaOperand, Window, inside_part_off_boundary, on_part_boundary};
use crate::topology::de9im::{IntersectionMatrix, Operand};
use crate::topology::label::{Dimension, Location};
use crate::topology::line_analysis::{
EventAt, LineSet, collinear_overlap, proper_crossing, segment_events,
};
use crate::topology::polygon_analysis::polygons_matrix;
use crate::types::{
Coord2d, Geometry, GeometryCollection, LineString, LinearRing, Polygon,
first_overlapping_parts_ref,
};
pub(crate) struct GcParts<'a> {
pub(crate) area: Option<ArealParts<'a>>,
pub(crate) lines: Option<LineSet<'a>>,
pub(crate) pts: Vec<Coord2d>,
}
pub(crate) struct ArealParts<'a> {
parts: Vec<&'a Polygon>,
}
impl ArealParts<'_> {
fn rings(&self) -> impl Iterator<Item = &crate::types::LinearRing> + '_ {
self.parts
.iter()
.flat_map(|p| core::iter::once(p.exterior()).chain(p.holes().iter()))
}
}
impl AreaOperand for ArealParts<'_> {
fn for_edges_near(&self, _w: &Window, f: &mut dyn FnMut(Coord2d, Coord2d) -> bool) {
for ring in self.rings() {
for (a, b) in ring.edges() {
if !f(a, b) {
return;
}
}
}
}
fn for_vertices_near(&self, _w: &Window, f: &mut dyn FnMut(Coord2d) -> bool) {
for v in self.rings().flat_map(|r| r.coords().as_slice()) {
if !f(*v) {
return;
}
}
}
fn for_edges_with_ref_near(
&self,
_w: &Window,
f: &mut dyn FnMut(usize, usize, Coord2d, Coord2d) -> bool,
) {
for (part, p) in self.parts.iter().enumerate() {
let rings = core::iter::once(p.exterior()).chain(p.holes().iter());
for (ring, r) in rings.enumerate() {
for (a, b) in r.edges() {
if !f(part, ring, a, b) {
return;
}
}
}
}
}
fn has_edge_outside(&self, _w: &Window) -> bool {
false
}
fn locate(&self, p: Coord2d) -> Location {
if self.parts.iter().any(|q| on_part_boundary(p, q)) {
Location::Boundary
} else if self.parts.iter().any(|q| inside_part_off_boundary(p, q)) {
Location::Interior
} else {
Location::Exterior
}
}
fn envelope(&self) -> Option<(f64, f64, f64, f64)> {
crate::types::bbox_fold(self.parts.iter().map(|p| p.exterior().bbox()))
}
}
pub(crate) fn collection_operand(gc: &GeometryCollection) -> Result<Operand<'_>, GeometryError> {
let mut polys: Vec<&Polygon> = Vec::new();
let mut poly_paths: Vec<Vec<usize>> = Vec::new();
let mut lines: Vec<&LineString> = Vec::new();
let mut pts: Vec<Coord2d> = Vec::new();
let mut stack = vec![gc.geometries().iter().enumerate()];
let mut path: Vec<usize> = Vec::new();
while let Some(top) = stack.last_mut() {
let Some((k, g)) = top.next() else {
stack.pop();
path.pop();
continue;
};
path.push(k);
match g {
Geometry::Polygon(p) => {
polys.push(p);
poly_paths.push(path.clone());
}
Geometry::MultiPolygon(m) => {
for (part, p) in m.polygons().iter().enumerate() {
polys.push(p);
let mut leaf = path.clone();
leaf.push(part);
poly_paths.push(leaf);
}
}
Geometry::LineString(l) => lines.push(l),
Geometry::MultiLineString(m) => lines.extend(m.line_strings()),
Geometry::Point(p) => pts.push(p.coord()),
Geometry::MultiPoint(m) => pts.extend(m.points().iter().map(|p| p.coord())),
Geometry::GeometryCollection(inner) => {
stack.push(inner.geometries().iter().enumerate());
continue; }
}
path.pop();
}
if let Some((first, second)) = first_overlapping_parts_ref(&polys) {
return Err(GeometryError::CollectionElementsOverlap {
first: poly_paths[first].clone(),
second: poly_paths[second].clone(),
});
}
Ok(if polys.is_empty() && lines.is_empty() {
Operand::Points(pts)
} else if polys.is_empty() && pts.is_empty() {
Operand::Lines(LineSet::new(lines))
} else {
Operand::Collection(GcParts {
area: (!polys.is_empty()).then_some(ArealParts { parts: polys }),
lines: (!lines.is_empty()).then(|| LineSet::new(lines)),
pts,
})
})
}
pub(crate) fn collection_boundary(
gc: &GeometryCollection,
) -> Result<(Vec<&LinearRing>, Vec<Coord2d>), GeometryError> {
Ok(match collection_operand(gc)? {
Operand::Lines(l) => (Vec::new(), l.boundary().to_vec()),
Operand::Collection(parts) => {
let rings: Vec<&LinearRing> = parts.area.as_ref().map_or_else(Vec::new, |a| {
a.parts
.iter()
.flat_map(|p| core::iter::once(p.exterior()).chain(p.holes().iter()))
.collect()
});
let pts = parts.lines.as_ref().map_or_else(Vec::new, |l| {
l.boundary()
.iter()
.copied()
.filter(|&x| {
parts
.area
.as_ref()
.is_none_or(|a| a.locate(x) == Location::Exterior)
})
.collect()
});
(rings, pts)
}
_ => (Vec::new(), Vec::new()),
})
}
pub(crate) struct Strata<'s> {
area: Option<&'s dyn AreaOperand>,
lines: Option<&'s LineSet<'s>>,
pts: &'s [Coord2d],
}
impl<'s> Strata<'s> {
pub(crate) fn of(op: &'s Operand<'s>) -> Self {
match op {
Operand::Points(p) => Self {
area: None,
lines: None,
pts: p,
},
Operand::Lines(l) => Self {
area: None,
lines: Some(l),
pts: &[],
},
Operand::Area(a) => Self {
area: Some(a),
lines: None,
pts: &[],
},
Operand::Collection(gc) => Self::of_parts(gc),
}
}
pub(crate) fn of_parts(gc: &'s GcParts<'s>) -> Self {
Self {
area: gc.area.as_ref().map(|a| a as &dyn AreaOperand),
lines: gc.lines.as_ref(),
pts: &gc.pts,
}
}
pub(crate) fn of_area(a: &'s dyn AreaOperand) -> Self {
Self {
area: Some(a),
lines: None,
pts: &[],
}
}
fn mod2(&self) -> &[Coord2d] {
self.lines.map_or(&[], |l| l.boundary())
}
}
fn gc_locate(x: Coord2d, s: &Strata<'_>) -> Location {
if let Some(a) = s.area {
match a.locate(x) {
Location::Interior => return Location::Interior,
Location::Boundary => return Location::Boundary,
Location::Exterior => {}
}
}
if let Some(l) = s.lines
&& l.contains(x)
{
return if l.boundary().contains(&x) {
Location::Boundary
} else {
Location::Interior
};
}
if s.pts.contains(&x) {
return Location::Interior;
}
Location::Exterior
}
enum Classifier<'c> {
Areal(&'c dyn AreaOperand),
Lineal(&'c LineSet<'c>),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Lab {
Loc(Location),
On(bool),
}
impl Lab {
fn initial(c: &Classifier<'_>) -> Self {
match c {
Classifier::Areal(_) => Lab::Loc(Location::Exterior),
Classifier::Lineal(_) => Lab::On(false),
}
}
}
#[derive(Clone, Copy)]
enum Pos {
At(Coord2d),
Cross(Coord2d, Coord2d),
}
struct Ev {
which: usize,
pos: Pos,
point: Lab,
ahead: Option<Lab>,
}
fn param(pos: &Pos, p: Coord2d, q: Coord2d) -> Option<RationalCoord2d> {
match *pos {
Pos::At(x) => RationalCoord2d::from_f64([x.x, x.y]).ok(),
Pos::Cross(a, b) => RationalCoord2d::from_segment_intersection(
[p.x, p.y],
[q.x, q.y],
[a.x, a.y],
[b.x, b.y],
)
.ok()
.flatten(),
}
}
fn classifier_events(which: usize, c: &Classifier<'_>, p: Coord2d, q: Coord2d) -> Vec<Ev> {
match c {
Classifier::Areal(a) => segment_events(p, q, *a)
.into_iter()
.map(|ev| {
let (pos, point) = match ev.at {
EventAt::Point(x) => (Pos::At(x), Lab::Loc(a.locate(x))),
EventAt::Crossing { a: ea, b: eb } => {
(Pos::Cross(ea, eb), Lab::Loc(Location::Boundary))
}
};
Ev {
which,
pos,
point,
ahead: Some(Lab::Loc(ev.ahead)),
}
})
.collect(),
Classifier::Lineal(l) => lineal_events(which, l, p, q),
}
}
#[allow(clippy::float_cmp)]
fn lineal_events(which: usize, l: &LineSet<'_>, p: Coord2d, q: Coord2d) -> Vec<Ev> {
let along = |c: Coord2d| if p.x == q.x { c.y } else { c.x };
let forward = along(q) > along(p);
let pm = |c: Coord2d| if forward { along(c) } else { -along(c) };
let mut toggles: Vec<(f64, Coord2d, i32)> = Vec::new();
let mut out = Vec::new();
for (c, d) in l.segments() {
if collinear_overlap(p, q, c, d) {
let (lo, hi) = if pm(c) <= pm(d) { (c, d) } else { (d, c) };
let lo = if pm(lo) < pm(p) { p } else { lo };
let hi = if pm(hi) > pm(q) { q } else { hi };
if pm(lo) < pm(hi) {
toggles.push((pm(lo), lo, 1));
toggles.push((pm(hi), hi, -1));
}
} else if proper_crossing(p, q, c, d) {
out.push(Ev {
which,
pos: Pos::Cross(c, d),
point: Lab::On(true),
ahead: None,
});
}
for v in [c, d] {
if v != p && v != q && on_segment(v, p, q) {
out.push(Ev {
which,
pos: Pos::At(v),
point: Lab::On(true),
ahead: None,
});
}
}
}
toggles.sort_by(|a, b| a.0.total_cmp(&b.0).then(b.2.cmp(&a.2)));
let mut depth = 0;
for (_, at, delta) in toggles {
let was = depth > 0;
depth += delta;
let now = depth > 0;
if was != now {
out.push(Ev {
which,
pos: Pos::At(at),
point: Lab::On(true),
ahead: Some(Lab::On(now)),
});
}
}
out
}
enum WalkItem {
Point(Option<Coord2d>, Vec<Lab>),
Stretch(Vec<Lab>),
}
fn walk_segment(p: Coord2d, q: Coord2d, cls: &[Classifier<'_>]) -> Vec<WalkItem> {
let mut cur: Vec<Lab> = cls.iter().map(Lab::initial).collect();
let mut out = Vec::new();
if cls.is_empty() {
out.push(WalkItem::Stretch(cur));
return out;
}
let mut evs: Vec<Ev> = Vec::new();
for (i, c) in cls.iter().enumerate() {
evs.extend(classifier_events(i, c, p, q));
}
let params: Vec<Option<RationalCoord2d>> = evs.iter().map(|e| param(&e.pos, p, q)).collect();
let q_param = param(&Pos::At(q), p, q);
let cmp = |x: &Option<RationalCoord2d>, y: &Option<RationalCoord2d>| -> Ordering {
match (x, y) {
(Some(a), Some(b)) => {
rational_compare_along([p.x, p.y], [q.x, q.y], a, b).unwrap_or(Ordering::Equal)
}
_ => Ordering::Equal,
}
};
let mut order: Vec<usize> = (0..evs.len()).collect();
order.sort_by(|&i, &j| cmp(¶ms[i], ¶ms[j]));
let p_param = param(&Pos::At(p), p, q);
if order
.first()
.is_none_or(|&f| cmp(¶ms[f], &p_param) != Ordering::Equal)
{
out.push(WalkItem::Stretch(cur.clone()));
}
let mut k = 0;
while k < order.len() {
let mut j = k + 1;
while j < order.len() && cmp(¶ms[order[k]], ¶ms[order[j]]) == Ordering::Equal {
j += 1;
}
let mut at_point = cur.clone();
let mut coord: Option<Coord2d> = None;
for &e in &order[k..j] {
at_point[evs[e].which] = evs[e].point;
if let Pos::At(x) = evs[e].pos {
coord = Some(x);
}
}
out.push(WalkItem::Point(coord, at_point));
for &e in &order[k..j] {
if let Some(ahead) = evs[e].ahead {
cur[evs[e].which] = ahead;
}
}
if j < order.len() || cmp(¶ms[order[k]], &q_param) != Ordering::Equal {
out.push(WalkItem::Stretch(cur.clone()));
}
k = j;
}
out
}
const I: usize = 0;
const B: usize = 1;
const E: usize = 2;
struct Acc {
cells: [[Dimension; 3]; 3],
swap: bool,
}
impl Acc {
fn new() -> Self {
let mut cells = [[Dimension::Empty; 3]; 3];
cells[E][E] = Dimension::Area;
Self { cells, swap: false }
}
fn raise(&mut self, row: usize, col: usize, d: Dimension) {
let (r, c) = if self.swap { (col, row) } else { (row, col) };
if d > self.cells[r][c] {
self.cells[r][c] = d;
}
}
fn row_of(loc: Location) -> usize {
match loc {
Location::Interior => I,
Location::Boundary => B,
Location::Exterior => E,
}
}
fn matrix(&self) -> IntersectionMatrix {
let c = &self.cells;
IntersectionMatrix {
interior_interior: c[I][I],
interior_boundary: c[I][B],
interior_exterior: c[I][E],
boundary_interior: c[B][I],
boundary_boundary: c[B][B],
boundary_exterior: c[B][E],
exterior_interior: c[E][I],
exterior_boundary: c[E][B],
exterior_exterior: c[E][E],
}
}
}
fn col_of(area_lab: Option<Lab>, line_lab: Option<Lab>) -> usize {
match area_lab {
Some(Lab::Loc(Location::Interior)) => return I,
Some(Lab::Loc(Location::Boundary)) => return B,
_ => {}
}
if line_lab == Some(Lab::On(true)) {
return I;
}
E
}
fn lineal_contributions(a: &Strata<'_>, b: &Strata<'_>, acc: &mut Acc) {
let Some(l) = a.lines else { return };
let mut cls: Vec<Classifier<'_>> = Vec::new();
cls.push(Classifier::Lineal(l));
let mask = a.area.map(|ar| {
cls.push(Classifier::Areal(ar));
cls.len() - 1
});
let tgt_a = b.area.map(|ar| {
cls.push(Classifier::Areal(ar));
cls.len() - 1
});
let tgt_l = b.lines.map(|ln| {
cls.push(Classifier::Lineal(ln));
cls.len() - 1
});
let masked = |labels: &[Lab]| {
mask.is_some_and(|m| matches!(labels[m], Lab::Loc(Location::Interior | Location::Boundary)))
};
let candidate = |x: Coord2d, acc: &mut Acc| {
if a.area.is_some_and(|ar| ar.locate(x) != Location::Exterior) {
return; }
let row = if a.mod2().contains(&x) { B } else { I };
acc.raise(row, Acc::row_of(gc_locate(x, b)), Dimension::Point);
};
for (p, q) in l.segments() {
candidate(p, acc);
candidate(q, acc);
for item in walk_segment(p, q, &cls) {
match item {
WalkItem::Point(Some(x), _) => candidate(x, acc),
WalkItem::Point(None, labels) => {
if !masked(&labels) {
let col = col_of(tgt_a.map(|i| labels[i]), tgt_l.map(|i| labels[i]));
acc.raise(I, col, Dimension::Point);
}
}
WalkItem::Stretch(labels) => {
if !masked(&labels) {
let col = col_of(tgt_a.map(|i| labels[i]), tgt_l.map(|i| labels[i]));
acc.raise(I, col, Dimension::Line);
}
}
}
}
}
}
fn boundary_contributions(a: &Strata<'_>, b: &Strata<'_>, acc: &mut Acc) {
let Some(ar) = a.area else { return };
let mut cls: Vec<Classifier<'_>> = Vec::new();
let tgt_a = b.area.map(|x| {
cls.push(Classifier::Areal(x));
cls.len() - 1
});
let tgt_l = b.lines.map(|x| {
cls.push(Classifier::Lineal(x));
cls.len() - 1
});
let mut edges: Vec<(Coord2d, Coord2d)> = Vec::new();
ar.for_edges_near(&ar.all_window(), &mut |p, q| {
edges.push((p, q));
true
});
for (p, q) in edges {
for item in walk_segment(p, q, &cls) {
if let WalkItem::Stretch(labels) = item {
let col = col_of(tgt_a.map(|i| labels[i]), tgt_l.map(|i| labels[i]));
acc.raise(B, col, Dimension::Line);
}
}
}
}
fn point_contributions(a: &Strata<'_>, b: &Strata<'_>, acc: &mut Acc) {
let on_own_lines = |x: Coord2d| a.lines.is_some_and(|l| l.contains(x));
let in_own_area = |x: Coord2d| a.area.is_some_and(|ar| ar.locate(x) != Location::Exterior);
for &x in a.pts {
if in_own_area(x) || on_own_lines(x) {
continue; }
acc.raise(I, Acc::row_of(gc_locate(x, b)), Dimension::Point);
}
for &x in a.mod2() {
if in_own_area(x) {
continue; }
acc.raise(B, Acc::row_of(gc_locate(x, b)), Dimension::Point);
}
}
pub(crate) fn merged_matrix(a: &Strata<'_>, b: &Strata<'_>) -> IntersectionMatrix {
let mut acc = Acc::new();
match (a.area, b.area) {
(Some(aa), Some(ba)) => {
let m = polygons_matrix(aa, ba);
for (row, col, d) in [
(I, I, m.interior_interior),
(I, B, m.interior_boundary),
(B, I, m.boundary_interior),
(B, B, m.boundary_boundary),
(I, E, m.interior_exterior),
(E, I, m.exterior_interior),
] {
acc.raise(row, col, d);
}
}
(Some(_), None) => acc.raise(I, E, Dimension::Area),
(None, Some(_)) => acc.raise(E, I, Dimension::Area),
(None, None) => {}
}
lineal_contributions(a, b, &mut acc);
boundary_contributions(a, b, &mut acc);
point_contributions(a, b, &mut acc);
acc.swap = true;
lineal_contributions(b, a, &mut acc);
boundary_contributions(b, a, &mut acc);
point_contributions(b, a, &mut acc);
acc.matrix()
}
pub(crate) fn parts_dimension(gc: &GcParts<'_>) -> Dimension {
if gc.area.is_some() {
Dimension::Area
} else if gc.lines.is_some() {
Dimension::Line
} else if gc.pts.is_empty() {
Dimension::Empty
} else {
Dimension::Point
}
}