use crate::GeometryError;
use crate::exact::kernel::{edge_crosses_ray, on_segment, orient, segments_properly_cross};
use crate::index::SegmentIndex;
use crate::ops::simplify::{check_tolerance, segment_distance};
use crate::ops::validate::validity_issues;
use crate::predicates::Relatable;
use crate::types::{
Coord2d, CoordSeq, Geometry, GeometryCollection, LineString, LinearRing, MaybeVouched,
MultiLineString, MultiPolygon, Polygon, Unvouched, UnvouchedReason,
};
use arithmetica::Sign;
#[cfg(test)]
mod tests;
pub trait TopologySimplifiable: sealed::Sealed + Relatable + Clone {}
impl TopologySimplifiable for LineString {}
impl TopologySimplifiable for MultiLineString {}
impl TopologySimplifiable for Polygon {}
impl TopologySimplifiable for MultiPolygon {}
impl TopologySimplifiable for GeometryCollection {}
pub fn simplify_preserve_topology<G: TopologySimplifiable>(
g: &G,
tolerance: f64,
) -> Result<G, GeometryError> {
simplify_preserve_topology_unvouched(g, tolerance)?.vouched()
}
pub fn simplify_preserve_topology_unvouched<G: TopologySimplifiable>(
g: &G,
tolerance: f64,
) -> Result<MaybeVouched<G>, GeometryError> {
check_tolerance(tolerance)?;
let input_issue = validity_issues(g).first().map(|i| i.issue);
let out = if tolerance == 0.0 {
g.clone()
} else {
simplify_raw(g, tolerance)?
};
Ok(match input_issue {
Some(issue) => {
MaybeVouched::Unvouched(Unvouched::new(out, UnvouchedReason::InvalidInput { issue }))
}
None => vouch(out),
})
}
fn vouch<G: Relatable>(out: G) -> MaybeVouched<G> {
match validity_issues(&out).first().map(|i| i.issue) {
None => MaybeVouched::Vouched(out),
Some(issue) => MaybeVouched::Unvouched(Unvouched::new(
out,
UnvouchedReason::InvalidResult { issue },
)),
}
}
fn simplify_raw<G: TopologySimplifiable>(g: &G, tolerance: f64) -> Result<G, GeometryError> {
let mut flat = sealed::Flat::default();
g.flatten(&mut flat);
let kept = Simplifier::new(&flat, tolerance)?.run();
g.rebuild(&mut sealed::Kept::new(kept))
}
pub(super) mod sealed {
use super::{
Coord2d, CoordSeq, Geometry, GeometryCollection, GeometryError, LineString, LinearRing,
MultiLineString, MultiPolygon, Polygon,
};
#[derive(Clone, Copy, Debug)]
pub struct Chain {
pub(in crate::ops) start: usize,
pub(in crate::ops) len: usize,
pub(in crate::ops) closed: bool,
}
#[derive(Debug, Default)]
pub struct Flat {
pub(in crate::ops) verts: Vec<Coord2d>,
pub(in crate::ops) chains: Vec<Chain>,
pub(in crate::ops) points: Vec<Coord2d>,
}
impl Flat {
fn push(&mut self, coords: &[Coord2d], closed: bool) {
self.chains.push(Chain {
start: self.verts.len(),
len: coords.len(),
closed,
});
self.verts.extend_from_slice(coords);
}
fn ring(&mut self, r: &LinearRing) {
self.push(r.coords().as_slice(), true);
}
fn line(&mut self, l: &LineString) {
self.push(l.coords().as_slice(), false);
}
fn polygon(&mut self, p: &Polygon) {
self.ring(p.exterior());
for h in p.holes() {
self.ring(h);
}
}
fn geometry(&mut self, g: &Geometry) {
match g {
Geometry::Point(p) => self.points.push(p.coord()),
Geometry::MultiPoint(m) => self.points.extend(m.points().iter().map(|p| p.coord())),
Geometry::LineString(l) => self.line(l),
Geometry::MultiLineString(m) => m.line_strings().iter().for_each(|l| self.line(l)),
Geometry::Polygon(p) => self.polygon(p),
Geometry::MultiPolygon(m) => m.polygons().iter().for_each(|p| self.polygon(p)),
Geometry::GeometryCollection(c) => {
c.geometries().iter().for_each(|e| self.geometry(e));
}
}
}
}
pub struct Kept {
chains: std::vec::IntoIter<Vec<Coord2d>>,
}
impl Kept {
pub(in crate::ops) fn new(chains: Vec<Vec<Coord2d>>) -> Self {
Self {
chains: chains.into_iter(),
}
}
fn next(&mut self) -> CoordSeq {
CoordSeq::new(self.chains.next().unwrap_or_default())
}
fn ring(&mut self) -> Result<LinearRing, GeometryError> {
LinearRing::new(self.next())
}
fn line(&mut self) -> Result<LineString, GeometryError> {
LineString::new(self.next())
}
fn polygon(&mut self, p: &Polygon) -> Result<Polygon, GeometryError> {
let exterior = self.ring()?;
let holes = p
.holes()
.iter()
.map(|_| self.ring())
.collect::<Result<Vec<_>, _>>()?;
Polygon::new(exterior, holes)
}
fn geometry(&mut self, g: &Geometry) -> Result<Geometry, GeometryError> {
Ok(match g {
Geometry::Point(_) | Geometry::MultiPoint(_) => g.clone(),
Geometry::LineString(_) => Geometry::LineString(self.line()?),
Geometry::MultiLineString(m) => Geometry::MultiLineString(self.lines(m)?),
Geometry::Polygon(p) => Geometry::Polygon(self.polygon(p)?),
Geometry::MultiPolygon(m) => Geometry::MultiPolygon(self.polygons(m)?),
Geometry::GeometryCollection(c) => {
Geometry::GeometryCollection(self.collection(c)?)
}
})
}
fn lines(&mut self, m: &MultiLineString) -> Result<MultiLineString, GeometryError> {
let lines = m
.line_strings()
.iter()
.map(|_| self.line())
.collect::<Result<Vec<_>, _>>()?;
Ok(MultiLineString::new(lines))
}
fn polygons(&mut self, m: &MultiPolygon) -> Result<MultiPolygon, GeometryError> {
let parts = m
.polygons()
.iter()
.map(|p| self.polygon(p))
.collect::<Result<Vec<_>, _>>()?;
MultiPolygon::new(parts)
}
fn collection(
&mut self,
c: &GeometryCollection,
) -> Result<GeometryCollection, GeometryError> {
let elements = c
.geometries()
.iter()
.map(|e| self.geometry(e))
.collect::<Result<Vec<_>, _>>()?;
GeometryCollection::new(elements)
}
}
pub trait Sealed: Sized {
fn flatten(&self, flat: &mut Flat);
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError>;
}
impl Sealed for LineString {
fn flatten(&self, flat: &mut Flat) {
flat.line(self);
}
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError> {
kept.line()
}
}
impl Sealed for MultiLineString {
fn flatten(&self, flat: &mut Flat) {
self.line_strings().iter().for_each(|l| flat.line(l));
}
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError> {
kept.lines(self)
}
}
impl Sealed for Polygon {
fn flatten(&self, flat: &mut Flat) {
flat.polygon(self);
}
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError> {
kept.polygon(self)
}
}
impl Sealed for MultiPolygon {
fn flatten(&self, flat: &mut Flat) {
self.polygons().iter().for_each(|p| flat.polygon(p));
}
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError> {
kept.polygons(self)
}
}
impl Sealed for GeometryCollection {
fn flatten(&self, flat: &mut Flat) {
self.geometries().iter().for_each(|g| flat.geometry(g));
}
fn rebuild(&self, kept: &mut Kept) -> Result<Self, GeometryError> {
kept.collection(self)
}
}
}
const END: u32 = u32::MAX;
#[derive(Clone, Copy, Debug)]
pub(in crate::ops) enum Obstacle {
Segment(Coord2d, Coord2d),
Point(Coord2d),
}
struct Simplifier<'a> {
verts: &'a [Coord2d],
chains: &'a [sealed::Chain],
points: &'a [Coord2d],
tolerance: f64,
next: Vec<u32>,
alive: Vec<bool>,
fixed: Vec<bool>,
index: SegmentIndex,
in_run: Vec<bool>,
}
pub(in crate::ops) struct Run {
pub(in crate::ops) ids: Vec<u32>,
pub(in crate::ops) pts: Vec<Coord2d>,
pub(in crate::ops) lo: Coord2d,
pub(in crate::ops) hi: Coord2d,
}
impl Run {
fn vi(&self) -> Coord2d {
self.pts[0]
}
fn vj(&self) -> Coord2d {
self.pts[self.pts.len() - 1]
}
fn allowed(&self, p: Coord2d) -> bool {
p == self.vi() || p == self.vj()
}
fn segments(&self) -> impl Iterator<Item = (Coord2d, Coord2d)> + '_ {
self.pts.windows(2).map(|w| (w[0], w[1]))
}
fn contains_box(&self, p: Coord2d) -> bool {
p.x >= self.lo.x && p.x <= self.hi.x && p.y >= self.lo.y && p.y <= self.hi.y
}
}
fn boxes_meet((a, b): (Coord2d, Coord2d), (c, d): (Coord2d, Coord2d)) -> bool {
a.x.min(b.x) <= c.x.max(d.x)
&& c.x.min(d.x) <= a.x.max(b.x)
&& a.y.min(b.y) <= c.y.max(d.y)
&& c.y.min(d.y) <= a.y.max(b.y)
}
#[allow(clippy::float_cmp)] fn collinear_overlap(a: Coord2d, b: Coord2d, p: Coord2d, q: Coord2d) -> bool {
if orient(p, q, a) != Sign::Zero || orient(p, q, b) != Sign::Zero {
return false;
}
let along = |c: Coord2d| if p.x == q.x { c.y } else { c.x };
let (s0, s1) = (along(a).min(along(b)), along(a).max(along(b)));
let (t0, t1) = (along(p).min(along(q)), along(p).max(along(q)));
s0.max(t0) < s1.min(t1)
}
fn meets_outside(
(a, b): (Coord2d, Coord2d),
(p, q): (Coord2d, Coord2d),
allowed: impl Fn(Coord2d) -> bool,
) -> bool {
segments_properly_cross(a, b, p, q)
|| (on_segment(a, p, q) && !allowed(a))
|| (on_segment(b, p, q) && !allowed(b))
|| (on_segment(p, a, b) && !allowed(p))
|| (on_segment(q, a, b) && !allowed(q))
|| collinear_overlap(a, b, p, q)
}
impl<'a> Simplifier<'a> {
fn new(flat: &'a sealed::Flat, tolerance: f64) -> Result<Self, GeometryError> {
let count = flat.verts.len() + flat.points.len();
if u32::try_from(count).map_or(true, |n| n == u32::MAX) {
return Err(GeometryError::TooManyEntries { count });
}
let n = flat.verts.len();
let mut s = Self {
verts: &flat.verts,
chains: &flat.chains,
points: &flat.points,
tolerance,
next: vec![END; n],
alive: vec![true; n],
fixed: vec![false; n],
index: SegmentIndex::new(),
in_run: vec![false; n],
};
s.link_and_index();
s.fix_vertices();
Ok(s)
}
fn id(i: usize) -> u32 {
u32::try_from(i).unwrap_or(END)
}
fn at(&self, id: u32) -> Coord2d {
self.verts[id as usize]
}
fn link_and_index(&mut self) {
for ch in self.chains {
for k in 0..ch.len {
let here = ch.start + k;
let succ = if k + 1 < ch.len {
Some(here + 1)
} else if ch.closed {
Some(ch.start)
} else {
None
};
if let Some(t) = succ {
self.next[here] = Self::id(t);
self.index
.insert(self.verts[here], self.verts[t], Self::id(here));
}
}
}
let n = self.verts.len();
for (k, &p) in self.points.iter().enumerate() {
self.index.insert(p, p, Self::id(n + k));
}
}
fn obstacle(&self, id: u32) -> Obstacle {
let n = self.verts.len();
let i = id as usize;
if i < n {
Obstacle::Segment(self.verts[i], self.at(self.next[i]))
} else {
Obstacle::Point(self.points[i - n])
}
}
fn fix_vertices(&mut self) {
for ch in self.chains {
if !ch.closed {
self.fixed[ch.start] = true;
self.fixed[ch.start + ch.len - 1] = true;
}
}
self.fix_repeated();
self.fix_on_segment();
}
fn fix_repeated(&mut self) {
let n = self.verts.len();
let coord = |k: usize| {
if k < n {
self.verts[k]
} else {
self.points[k - n]
}
};
let mut order: Vec<usize> = (0..n + self.points.len()).collect();
order.sort_by(|&i, &j| {
let (p, q) = (coord(i), coord(j));
p.x.partial_cmp(&q.x)
.unwrap_or(core::cmp::Ordering::Equal)
.then(p.y.partial_cmp(&q.y).unwrap_or(core::cmp::Ordering::Equal))
});
let mut start = 0;
while start < order.len() {
let mut end = start + 1;
while end < order.len() && coord(order[end]) == coord(order[start]) {
end += 1;
}
if end - start > 1 {
for &k in &order[start..end] {
if k < n {
self.fixed[k] = true;
}
}
}
start = end;
}
}
fn fix_on_segment(&mut self) {
for i in 0..self.verts.len() {
let p = self.verts[i];
let mut hit = false;
self.index.candidates(p, p, |id| {
if let Obstacle::Segment(a, b) = self.obstacle(id) {
hit |= p != a && p != b && on_segment(p, a, b);
}
});
self.fixed[i] |= hit;
}
}
fn run(mut self) -> Vec<Vec<Coord2d>> {
for c in 0..self.chains.len() {
let ch = self.chains[c];
let mut anchors: Vec<usize> =
(0..ch.len).filter(|&k| self.fixed[ch.start + k]).collect();
if ch.closed {
if anchors.is_empty() {
anchors.push(0);
}
for (k, &lo) in anchors.iter().enumerate() {
let hi = anchors.get(k + 1).copied().unwrap_or(anchors[0] + ch.len);
self.simplify_run(ch, lo, hi);
}
} else {
for w in anchors.windows(2) {
self.simplify_run(ch, w[0], w[1]);
}
}
}
self.chains
.iter()
.map(|ch| {
(ch.start..ch.start + ch.len)
.filter(|&g| self.alive[g])
.map(|g| self.verts[g])
.collect()
})
.collect()
}
fn gid(ch: sealed::Chain, k: usize) -> usize {
ch.start + k % ch.len
}
fn simplify_run(&mut self, ch: sealed::Chain, lo: usize, hi: usize) {
let mut stack = vec![(lo, hi)];
while let Some((lo, hi)) = stack.pop() {
if hi < lo + 2 {
continue;
}
let (a, b) = (self.verts[Self::gid(ch, lo)], self.verts[Self::gid(ch, hi)]);
let (split, within) = self.farthest(ch, lo, hi, a, b);
if within && a != b {
let run = self.make_run(ch, lo, hi);
if self.accept(&run) {
self.commit(&run);
continue;
}
}
stack.push((split, hi));
stack.push((lo, split));
}
}
fn farthest(
&self,
ch: sealed::Chain,
lo: usize,
hi: usize,
a: Coord2d,
b: Coord2d,
) -> (usize, bool) {
let mut best: Option<(usize, f64)> = None;
for k in lo + 1..hi {
match segment_distance(self.verts[Self::gid(ch, k)], a, b) {
None => return (k, false),
Some(d) => {
if best.is_none_or(|(_, bd)| d > bd) {
best = Some((k, d));
}
}
}
}
best.map_or((lo + 1, false), |(k, d)| (k, d <= self.tolerance))
}
fn make_run(&self, ch: sealed::Chain, lo: usize, hi: usize) -> Run {
let ids: Vec<u32> = (lo..=hi).map(|k| Self::id(Self::gid(ch, k))).collect();
let pts: Vec<Coord2d> = ids.iter().map(|&i| self.at(i)).collect();
let mut lo_c = pts[0];
let mut hi_c = pts[0];
for p in &pts {
lo_c = Coord2d::new(lo_c.x.min(p.x), lo_c.y.min(p.y));
hi_c = Coord2d::new(hi_c.x.max(p.x), hi_c.y.max(p.y));
}
Run {
ids,
pts,
lo: lo_c,
hi: hi_c,
}
}
fn accept(&mut self, run: &Run) -> bool {
if run_touches_itself(run) {
return false;
}
let m = run.ids.len() - 1;
for &id in &run.ids[..m] {
self.in_run[id as usize] = true;
}
let mut candidates = Vec::new();
self.index
.candidates(run.lo, run.hi, |id| candidates.push(id));
let ok = candidates.iter().all(|&id| {
(id as usize) < self.in_run.len() && self.in_run[id as usize]
|| clear_of(run, self.obstacle(id))
});
for &id in &run.ids[..m] {
self.in_run[id as usize] = false;
}
ok
}
fn commit(&mut self, run: &Run) {
let m = run.ids.len() - 1;
for k in 0..m {
let removed = self.index.remove(run.pts[k], run.pts[k + 1], run.ids[k]);
debug_assert!(removed, "a current segment is in the index");
}
for &id in &run.ids[1..m] {
self.alive[id as usize] = false;
}
self.next[run.ids[0] as usize] = run.ids[m];
self.index.insert(run.vi(), run.vj(), run.ids[0]);
}
}
pub(in crate::ops) fn clear_of(run: &Run, o: Obstacle) -> bool {
match o {
Obstacle::Point(p) => run.allowed(p) || point_clear(run, p),
Obstacle::Segment(a, b) => {
!chord_meets(run, (a, b))
&& !run_meets(run, (a, b))
&& [a, b]
.iter()
.all(|&e| run.allowed(e) || !inside_region(run, e))
}
}
}
fn chord_meets(run: &Run, s: (Coord2d, Coord2d)) -> bool {
let c = (run.vi(), run.vj());
boxes_meet(s, c) && meets_outside(s, c, |p| run.allowed(p))
}
fn run_meets(run: &Run, s: (Coord2d, Coord2d)) -> bool {
run.segments()
.any(|r| boxes_meet(s, r) && meets_outside(s, r, |p| run.allowed(p)))
}
fn inside_region(run: &Run, p: Coord2d) -> bool {
if !run.contains_box(p) {
return false;
}
let mut inside = edge_crosses_ray(run.vj(), run.vi(), p);
for (a, b) in run.segments() {
if edge_crosses_ray(a, b, p) {
inside = !inside;
}
}
inside
}
fn point_clear(run: &Run, p: Coord2d) -> bool {
!on_segment(p, run.vi(), run.vj())
&& !run.segments().any(|(a, b)| on_segment(p, a, b))
&& !inside_region(run, p)
}
pub(in crate::ops) fn run_touches_itself(run: &Run) -> bool {
let s: Vec<(Coord2d, Coord2d)> = run.segments().collect();
for i in 0..s.len() {
if i + 1 < s.len() {
let ((a, b), (_, c)) = (s[i], s[i + 1]);
if on_segment(c, a, b) || on_segment(a, b, c) {
return true;
}
}
for j in i + 2..s.len() {
if boxes_meet(s[i], s[j]) && meets_outside(s[i], s[j], |_| false) {
return true;
}
}
}
false
}