use crate::GeometryError;
use crate::topology::de9im::{IntersectionMatrix, Operand};
use crate::topology::label::Dimension;
use crate::types::{
Geometry, GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point,
Polygon,
};
mod sealed {
pub struct View<'a>(pub(crate) super::Borrowed<'a>);
pub trait Sealed {
#[doc(hidden)]
fn view(&self) -> View<'_>;
}
}
#[derive(Clone, Copy)]
pub(crate) enum Borrowed<'a> {
Point(&'a Point),
MultiPoint(&'a MultiPoint),
LineString(&'a LineString),
MultiLineString(&'a MultiLineString),
Polygon(&'a Polygon),
MultiPolygon(&'a MultiPolygon),
GeometryCollection(&'a GeometryCollection),
}
impl<'a> Borrowed<'a> {
pub(crate) fn from_geometry(g: &'a Geometry) -> Self {
match g {
Geometry::Point(p) => Self::Point(p),
Geometry::MultiPoint(m) => Self::MultiPoint(m),
Geometry::LineString(l) => Self::LineString(l),
Geometry::MultiLineString(m) => Self::MultiLineString(m),
Geometry::Polygon(p) => Self::Polygon(p),
Geometry::MultiPolygon(m) => Self::MultiPolygon(m),
Geometry::GeometryCollection(c) => Self::GeometryCollection(c),
}
}
fn operand(self) -> Result<Operand<'a>, GeometryError> {
Ok(match self {
Self::Point(p) => Operand::point(p),
Self::MultiPoint(m) => Operand::multi_point(m),
Self::LineString(l) => Operand::line_string(l),
Self::MultiLineString(m) => Operand::multi_line_string(m),
Self::Polygon(p) => Operand::polygon(p),
Self::MultiPolygon(m) => Operand::multi_polygon(m),
Self::GeometryCollection(gc) => {
return crate::topology::collection::collection_operand(gc);
}
})
}
}
pub trait Relatable: sealed::Sealed {}
macro_rules! relatable {
($($ty:ty => $variant:ident),* $(,)?) => {$(
impl sealed::Sealed for $ty {
fn view(&self) -> sealed::View<'_> {
sealed::View(Borrowed::$variant(self))
}
}
impl Relatable for $ty {}
)*};
}
relatable! {
Point => Point,
MultiPoint => MultiPoint,
LineString => LineString,
MultiLineString => MultiLineString,
Polygon => Polygon,
MultiPolygon => MultiPolygon,
GeometryCollection => GeometryCollection,
}
impl sealed::Sealed for Geometry {
fn view(&self) -> sealed::View<'_> {
sealed::View(Borrowed::from_geometry(self))
}
}
impl Relatable for Geometry {}
impl<T: Relatable + ?Sized> sealed::Sealed for &T {
fn view(&self) -> sealed::View<'_> {
(**self).view()
}
}
impl<T: Relatable + ?Sized> Relatable for &T {}
pub(crate) fn borrowed(g: &impl Relatable) -> Borrowed<'_> {
g.view().0
}
#[must_use]
pub fn dimension(g: &impl Relatable) -> Dimension {
match g.view().0 {
Borrowed::GeometryCollection(c) => c.dimension(),
b => b.operand().map_or(Dimension::Empty, |o| o.dimension()),
}
}
pub use crate::topology::line_analysis::locate;
pub fn relate(a: &impl Relatable, b: &impl Relatable) -> Result<Relation, GeometryError> {
let (oa, ob) = (a.view().0.operand()?, b.view().0.operand()?);
let m = IntersectionMatrix::compute_operands(&oa, &ob);
Ok(Relation::from_matrix(&m, oa.dimension(), ob.dimension()))
}
pub fn intersects(a: &impl Relatable, b: &impl Relatable) -> Result<bool, GeometryError> {
if let Some(v) = point_meets(a.view().0, b.view().0) {
return Ok(v);
}
let (oa, ob) = (a.view().0.operand()?, b.view().0.operand()?);
if let (Operand::Area(x), Operand::Area(y)) = (&oa, &ob) {
use crate::topology::areal::AreaOperand;
let (wx, wy) = crate::topology::de9im::windowed_pair(x, y);
return Ok(crate::topology::polygon_analysis::areas_intersect(
wx.as_ref().map_or(x as &dyn AreaOperand, |w| w),
wy.as_ref().map_or(y as &dyn AreaOperand, |w| w),
));
}
let m = IntersectionMatrix::compute_operands(&oa, &ob);
Ok(Relation::from_matrix(&m, oa.dimension(), ob.dimension()).intersects())
}
fn point_meets(a: Borrowed<'_>, b: Borrowed<'_>) -> Option<bool> {
use crate::exact::kernel::on_segment;
use crate::topology::areal::{AreaOperand, Areal};
use crate::topology::label::Location;
let (p, other) = match (a, b) {
(Borrowed::Point(p), o) | (o, Borrowed::Point(p)) => (p.coord(), o),
_ => return None,
};
let on_line = |l: &LineString| {
l.coords()
.as_slice()
.windows(2)
.any(|w| on_segment(p, w[0], w[1]))
};
match other {
Borrowed::LineString(l) => Some(on_line(l)),
Borrowed::MultiLineString(m) => Some(m.line_strings().iter().any(on_line)),
Borrowed::Polygon(q) => Some(Areal::single(q).locate(p) != Location::Exterior),
Borrowed::MultiPolygon(m) if !m.is_empty() => {
Some(Areal::multi(m).locate(p) != Location::Exterior)
}
_ => None,
}
}
pub fn disjoint(a: &impl Relatable, b: &impl Relatable) -> Result<bool, GeometryError> {
Ok(!intersects(a, b)?)
}
macro_rules! predicate_fns {
($($(#[doc = $doc:literal])* $name:ident),* $(,)?) => {$(
$(#[doc = $doc])*
///
/// # Errors
///
/// As [`relate`]: a collection operand whose polygonal leaves
/// overlap.
pub fn $name(a: &impl Relatable, b: &impl Relatable) -> Result<bool, GeometryError> {
Ok(relate(a, b)?.$name())
}
)*};
}
predicate_fns! {
equals,
touches,
crosses,
within,
contains,
overlaps,
covers,
covered_by,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Relation {
matrix: IntersectionMatrix,
dim_a: Dimension,
dim_b: Dimension,
}
impl Relation {
#[must_use]
pub fn from_matrix(m: &IntersectionMatrix, dim_a: Dimension, dim_b: Dimension) -> Self {
Self {
matrix: *m,
dim_a,
dim_b,
}
}
#[must_use]
pub fn matrix(&self) -> IntersectionMatrix {
self.matrix
}
#[must_use]
pub fn equals(&self) -> bool {
self.matrix.equals()
}
#[must_use]
pub fn disjoint(&self) -> bool {
self.matrix.disjoint()
}
#[must_use]
pub fn intersects(&self) -> bool {
self.matrix.intersects()
}
#[must_use]
pub fn touches(&self) -> bool {
self.matrix.touches()
}
#[must_use]
pub fn crosses(&self) -> bool {
self.matrix.crosses(self.dim_a, self.dim_b)
}
#[must_use]
pub fn within(&self) -> bool {
self.matrix.within()
}
#[must_use]
pub fn contains(&self) -> bool {
self.matrix.contains()
}
#[must_use]
pub fn overlaps(&self) -> bool {
self.matrix.overlaps(self.dim_a, self.dim_b)
}
#[must_use]
pub fn covers(&self) -> bool {
self.matrix.covers()
}
#[must_use]
pub fn covered_by(&self) -> bool {
self.matrix.covered_by()
}
}
impl IntersectionMatrix {
#[must_use]
pub fn equals(&self) -> bool {
let all_empty = self.cells()[..8].iter().all(|&d| d == Dimension::Empty);
if all_empty {
return true;
}
self.interior_interior != Dimension::Empty
&& self.interior_exterior == Dimension::Empty
&& self.boundary_exterior == Dimension::Empty
&& self.exterior_interior == Dimension::Empty
&& self.exterior_boundary == Dimension::Empty
}
#[must_use]
pub fn disjoint(&self) -> bool {
self.interior_interior == Dimension::Empty
&& self.interior_boundary == Dimension::Empty
&& self.boundary_interior == Dimension::Empty
&& self.boundary_boundary == Dimension::Empty
}
#[must_use]
pub fn intersects(&self) -> bool {
!self.disjoint()
}
#[must_use]
pub fn touches(&self) -> bool {
self.interior_interior == Dimension::Empty
&& (self.interior_boundary != Dimension::Empty
|| self.boundary_interior != Dimension::Empty
|| self.boundary_boundary != Dimension::Empty)
}
#[must_use]
pub fn within(&self) -> bool {
self.interior_interior != Dimension::Empty
&& self.interior_exterior == Dimension::Empty
&& self.boundary_exterior == Dimension::Empty
}
#[must_use]
pub fn contains(&self) -> bool {
self.interior_interior != Dimension::Empty
&& self.exterior_interior == Dimension::Empty
&& self.exterior_boundary == Dimension::Empty
}
#[must_use]
pub fn covers(&self) -> bool {
self.intersects()
&& self.exterior_interior == Dimension::Empty
&& self.exterior_boundary == Dimension::Empty
}
#[must_use]
pub fn covered_by(&self) -> bool {
self.intersects()
&& self.interior_exterior == Dimension::Empty
&& self.boundary_exterior == Dimension::Empty
}
#[must_use]
pub fn crosses(&self, dim_a: Dimension, dim_b: Dimension) -> bool {
if dim_a == Dimension::Empty || dim_b == Dimension::Empty {
return false;
}
let t = |d: Dimension| d != Dimension::Empty;
if dim_a < dim_b {
t(self.interior_interior) && t(self.interior_exterior)
} else if dim_a > dim_b {
t(self.interior_interior) && t(self.exterior_interior)
} else if dim_a == Dimension::Line {
self.interior_interior == Dimension::Point
} else {
false
}
}
#[must_use]
pub fn overlaps(&self, dim_a: Dimension, dim_b: Dimension) -> bool {
if dim_a != dim_b || dim_a == Dimension::Empty {
return false;
}
let t = |d: Dimension| d != Dimension::Empty;
self.interior_interior == dim_a && t(self.interior_exterior) && t(self.exterior_interior)
}
}
#[cfg(test)]
mod fast_path_tests;
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::types::{Coord2d, CoordSeq, LinearRing};
const DIMS: [Dimension; 4] = [
Dimension::Empty,
Dimension::Point,
Dimension::Line,
Dimension::Area,
];
fn every_matrix() -> impl Iterator<Item = IntersectionMatrix> {
(0..4usize.pow(9)).map(|mut k| {
let mut c = [Dimension::Empty; 9];
for cell in &mut c {
*cell = DIMS[k % 4];
k /= 4;
}
IntersectionMatrix {
interior_interior: c[0],
interior_boundary: c[1],
interior_exterior: c[2],
boundary_interior: c[3],
boundary_boundary: c[4],
boundary_exterior: c[5],
exterior_interior: c[6],
exterior_boundary: c[7],
exterior_exterior: c[8],
}
})
}
#[test]
fn predicates_relate_as_defined_on_every_matrix() {
for m in every_matrix() {
let t = m.swap_ab();
assert_eq!(m.covered_by(), t.covers(), "{m}");
assert_eq!(m.within(), t.contains(), "{m}");
assert_eq!(m.disjoint(), !m.intersects(), "{m}");
assert_eq!(m.equals(), t.equals(), "{m}");
assert_eq!(m.touches(), t.touches(), "{m}");
if m.contains() {
assert!(m.covers(), "{m}");
}
for da in DIMS {
for db in DIMS {
assert_eq!(m.crosses(da, db), t.crosses(db, da), "{m} {da:?} {db:?}");
assert_eq!(m.overlaps(da, db), t.overlaps(db, da), "{m} {da:?} {db:?}");
}
}
}
}
fn square(x: f64) -> Polygon {
let c = |a: f64, b: f64| Coord2d::new(a, b);
let ring = LinearRing::new(CoordSeq::new(vec![
c(x, 0.0),
c(x + 2.0, 0.0),
c(x + 2.0, 2.0),
c(x, 2.0),
]))
.unwrap();
Polygon::new_simple(ring).unwrap()
}
#[test]
fn every_operand_form_gives_the_same_relation() {
let (a, b) = (square(0.0), square(1.0));
let (ga, gb) = (Geometry::Polygon(a.clone()), Geometry::Polygon(b.clone()));
let r = relate(&a, &b).unwrap();
assert_eq!(r, relate(&ga, &gb).unwrap());
assert_eq!(r, relate(&&a, &gb).unwrap());
assert_eq!(r, relate(&ga, &&&b).unwrap());
assert_eq!(r.matrix(), IntersectionMatrix::compute(&a, &b));
assert!(r.overlaps() && r.intersects() && !r.touches() && !r.covers());
assert_eq!(overlaps(&a, &b), Ok(true));
assert_eq!(dimension(&a), Dimension::Area);
assert_eq!(dimension(&MultiPolygon::empty()), Dimension::Empty);
}
#[test]
fn a_relation_reads_crosses_and_overlaps_by_its_dimensions() {
let m = IntersectionMatrix::from_pattern("1F1FF0102").unwrap();
let lines = Relation::from_matrix(&m, Dimension::Line, Dimension::Line);
let areas = Relation::from_matrix(&m, Dimension::Area, Dimension::Area);
assert!(lines.overlaps() && !areas.overlaps());
assert_eq!(lines.matrix(), m);
}
}