use crate::types::{Coord2d, Envelope};
fn to_rect(e: &Envelope) -> situs::Rect {
let (min, max) = (e.min(), e.max());
situs::Rect::new(min.x, min.y, max.x, max.y)
.expect("an Envelope satisfies Rect's invariants: finite, min <= max")
}
fn edge_rect(a: Coord2d, b: Coord2d) -> situs::Rect {
let (min_x, max_x) = if b.x < a.x { (b.x, a.x) } else { (a.x, b.x) };
let (min_y, max_y) = if b.y < a.y { (b.y, a.y) } else { (a.y, b.y) };
situs::Rect::new(min_x, min_y, max_x, max_y)
.expect("an edge of a validated ring has finite endpoints, so its box is a Rect")
}
fn from_rect(r: &situs::Rect) -> Envelope {
Envelope::new(
Coord2d::new(r.min_x(), r.min_y()),
Coord2d::new(r.max_x(), r.max_y()),
)
.expect("a Rect satisfies Envelope's invariants: finite, min <= max")
}
#[derive(Clone, Debug)]
pub(crate) struct BoxIndex {
inner: situs::Index,
}
impl BoxIndex {
pub(super) fn from_envelopes(entries: &[(Envelope, u32)]) -> Self {
let entries: Vec<(situs::Rect, u32)> =
entries.iter().map(|(e, id)| (to_rect(e), *id)).collect();
Self {
inner: situs::Index::bulk_load(entries),
}
}
pub(crate) fn from_edges(entries: &[((Coord2d, Coord2d), u32)]) -> Self {
let entries: Vec<(situs::Rect, u32)> = entries
.iter()
.map(|((a, b), id)| (edge_rect(*a, *b), *id))
.collect();
Self {
inner: situs::Index::bulk_load(entries),
}
}
pub(crate) fn candidates(&self, window: &Envelope, visit: impl FnMut(u32)) {
self.inner.query(&to_rect(window), visit);
}
pub(crate) fn try_candidates<B>(
&self,
window: &Envelope,
visit: impl FnMut(u32) -> core::ops::ControlFlow<B>,
) -> core::ops::ControlFlow<B> {
self.inner.try_query(&to_rect(window), visit)
}
pub(crate) fn self_join(&self, visit: impl FnMut(u32, u32)) {
self.inner.self_join(visit);
}
pub(crate) fn from_boxes(entries: &[(Envelope, u32)]) -> Self {
Self::from_envelopes(entries)
}
pub(super) fn len(&self) -> usize {
self.inner.len()
}
pub(super) fn bounds(&self) -> Option<Envelope> {
self.inner.bounds().map(|r| from_rect(&r))
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct SegmentIndex {
inner: situs::DynamicIndex,
}
impl SegmentIndex {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn insert(&mut self, a: Coord2d, b: Coord2d, id: u32) {
self.inner.insert(edge_rect(a, b), id);
}
pub(crate) fn remove(&mut self, a: Coord2d, b: Coord2d, id: u32) -> bool {
self.inner.remove(&edge_rect(a, b), id)
}
pub(crate) fn candidates(&self, lo: Coord2d, hi: Coord2d, visit: impl FnMut(u32)) {
self.inner.query(&edge_rect(lo, hi), visit);
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.inner.len()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::float_cmp)]
mod tests {
use super::*;
use crate::error::GeometryError;
use proptest::prelude::*;
fn c(x: f64, y: f64) -> Coord2d {
Coord2d::new(x, y)
}
fn same_verdict(a: f64, b: f64, x: f64, y: f64) {
let rect = situs::Rect::new(a, b, x, y);
let env = Envelope::new(c(a, b), c(x, y));
match (rect, env) {
(Ok(r), Ok(e)) => {
assert_eq!(to_rect(&e), r);
assert_eq!(from_rect(&r), e);
}
(Err(situs::RectError::NonFinite), Err(GeometryError::NonFiniteCoordinate { .. }))
| (Err(situs::RectError::Inverted), Err(GeometryError::InvertedEnvelope)) => {}
(r, e) => {
panic!("Rect::new gave {r:?} but Envelope::new gave {e:?} for ({a}, {b}, {x}, {y})")
}
}
}
#[test]
fn fixed_bounds_get_the_same_verdict() {
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
same_verdict(bad, 0.0, 1.0, 1.0);
same_verdict(0.0, bad, 1.0, 1.0);
same_verdict(0.0, 0.0, bad, 1.0);
same_verdict(0.0, 0.0, 1.0, bad);
same_verdict(bad, 5.0, 0.0, 0.0);
}
same_verdict(1.0, 0.0, 0.0, 1.0);
same_verdict(0.0, 1.0, 1.0, 0.0);
same_verdict(2.0, 3.0, 2.0, 3.0);
same_verdict(-0.0, 0.0, 0.0, -0.0);
}
#[test]
fn edge_rect_is_the_endpoints_box_in_either_order() {
let r = edge_rect(c(3.0, -1.0), c(-2.0, 4.0));
assert_eq!(
(r.min_x(), r.min_y(), r.max_x(), r.max_y()),
(-2.0, -1.0, 3.0, 4.0)
);
assert_eq!(edge_rect(c(-2.0, 4.0), c(3.0, -1.0)), r);
let p = edge_rect(c(1.0, 1.0), c(1.0, 1.0));
assert_eq!((p.min_x(), p.max_x()), (1.0, 1.0));
}
fn bound() -> impl Strategy<Value = f64> {
prop_oneof![
6 => (-20i32..=20).prop_map(|v| f64::from(v) * 0.5),
2 => prop::num::f64::ANY,
1 => prop_oneof![Just(f64::NAN), Just(f64::INFINITY), Just(f64::NEG_INFINITY), Just(-0.0)],
]
}
fn bound_finite() -> impl Strategy<Value = f64> {
(-12i32..=12).prop_map(|v| f64::from(v) * 0.5)
}
fn envelope() -> impl Strategy<Value = Envelope> {
(bound(), bound(), bound(), bound()).prop_filter_map("finite", |(a, b, x, y)| {
let (lo_x, hi_x) = if a <= x { (a, x) } else { (x, a) };
let (lo_y, hi_y) = if b <= y { (b, y) } else { (y, b) };
Envelope::new(c(lo_x, lo_y), c(hi_x, hi_y)).ok()
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(20_000))]
#[test]
fn new_agrees(a in bound(), b in bound(), x in bound(), y in bound()) {
same_verdict(a, b, x, y);
}
#[test]
fn intersects_agrees(e in envelope(), f in envelope()) {
let (r, s) = (to_rect(&e), to_rect(&f));
prop_assert_eq!(r.intersects(&s), e.intersects(&f));
prop_assert_eq!(r.contains_rect(&s), e.contains_envelope(&f));
prop_assert_eq!(from_rect(&r.union(&s)).contains_envelope(&e), true);
}
#[test]
fn contains_agrees(e in envelope(), x in bound(), y in bound()) {
prop_assert_eq!(to_rect(&e).contains_point(x, y), e.contains_coord(c(x, y)));
}
#[test]
fn segment_index_tracks_inserts_and_removals(
segs in prop::collection::vec((bound_finite(), bound_finite(), bound_finite(), bound_finite()), 1..60),
removals in prop::collection::vec(any::<prop::sample::Index>(), 0..60),
windows in prop::collection::vec((bound_finite(), bound_finite(), bound_finite(), bound_finite()), 1..8),
) {
let mut index = SegmentIndex::new();
let mut live: Vec<(Coord2d, Coord2d, u32)> = Vec::new();
for (k, &(a, b, x, y)) in segs.iter().enumerate() {
let id = u32::try_from(k).unwrap();
index.insert(c(a, b), c(x, y), id);
live.push((c(a, b), c(x, y), id));
}
for r in &removals {
if live.is_empty() {
break;
}
let (a, b, id) = live.swap_remove(r.index(live.len()));
prop_assert!(index.remove(a, b, id));
prop_assert!(!index.remove(a, b, id));
}
prop_assert_eq!(index.len(), live.len());
for &(a, b, x, y) in &windows {
let window = edge_rect(c(a, b), c(x, y));
let mut got = Vec::new();
index.candidates(c(a, b), c(x, y), |id| got.push(id));
got.sort_unstable();
let mut want: Vec<u32> = live
.iter()
.filter(|(p, q, _)| edge_rect(*p, *q).intersects(&window))
.map(|&(_, _, id)| id)
.collect();
want.sort_unstable();
prop_assert_eq!(got, want);
}
}
#[test]
fn round_trip_is_exact(e in envelope()) {
let back = from_rect(&to_rect(&e));
prop_assert_eq!(back.min().x.to_bits(), e.min().x.to_bits());
prop_assert_eq!(back.min().y.to_bits(), e.min().y.to_bits());
prop_assert_eq!(back.max().x.to_bits(), e.max().x.to_bits());
prop_assert_eq!(back.max().y.to_bits(), e.max().y.to_bits());
}
}
}