s2json_core/geometry/
bbox.rs

1use core::cmp::Ordering;
2
3use crate::*;
4use alloc::fmt;
5use serde::{
6    de::{self, SeqAccess, Visitor},
7    ser::SerializeTuple,
8    Deserialize, Deserializer, Serialize, Serializer,
9};
10
11trait Bounded {
12    fn min_value() -> Self;
13    fn max_value() -> Self;
14}
15macro_rules! impl_bounded {
16    ($($t:ty),*) => {
17        $(
18            impl Bounded for $t {
19                fn min_value() -> Self {
20                    <$t>::MIN
21                }
22                fn max_value() -> Self {
23                    <$t>::MAX
24                }
25            }
26        )*
27    };
28}
29
30// Implement for common numeric types
31impl_bounded!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, isize, usize, f32, f64);
32
33/// A BBOX is defined in lon-lat space and helps with zooming motion to
34/// see the entire line or polygon
35/// The order is (left, bottom, right, top)
36/// If WM, then the projection is lon-lat
37/// If S2, then the projection is s-t
38#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
39pub struct BBox<T = f64> {
40    /// left most longitude (WM) or S (S2)
41    pub left: T,
42    /// bottom most latitude (WM) or T (S2)
43    pub bottom: T,
44    /// right most longitude (WM) or T (S2)
45    pub right: T,
46    /// top most latitude (WM) or S (S2)
47    pub top: T,
48}
49impl<T> From<BBox<T>> for MValue
50where
51    T: Into<ValueType>,
52{
53    fn from(bbox: BBox<T>) -> MValue {
54        MValue::from([
55            ("left".into(), bbox.left.into()),
56            ("bottom".into(), bbox.bottom.into()),
57            ("right".into(), bbox.right.into()),
58            ("top".into(), bbox.top.into()),
59        ])
60    }
61}
62impl<T> From<&BBox<T>> for MValue
63where
64    T: Copy + Into<ValueType>,
65{
66    fn from(bbox: &BBox<T>) -> MValue {
67        MValue::from([
68            ("left".into(), bbox.left.into()),
69            ("bottom".into(), bbox.bottom.into()),
70            ("right".into(), bbox.right.into()),
71            ("top".into(), bbox.top.into()),
72        ])
73    }
74}
75impl<T> From<MValue> for BBox<T>
76where
77    T: From<ValueType>,
78{
79    fn from(mvalue: MValue) -> Self {
80        BBox {
81            left: mvalue.get("left").unwrap().clone().into(),
82            bottom: mvalue.get("bottom").unwrap().clone().into(),
83            right: mvalue.get("right").unwrap().clone().into(),
84            top: mvalue.get("top").unwrap().clone().into(),
85        }
86    }
87}
88impl<T> From<&MValue> for BBox<T>
89where
90    T: From<ValueType>,
91{
92    fn from(mvalue: &MValue) -> Self {
93        BBox {
94            left: mvalue.get("left").unwrap().clone().into(),
95            bottom: mvalue.get("bottom").unwrap().clone().into(),
96            right: mvalue.get("right").unwrap().clone().into(),
97            top: mvalue.get("top").unwrap().clone().into(),
98        }
99    }
100}
101impl<T> MValueCompatible for BBox<T>
102where
103    ValueType: From<T>,
104    T: From<ValueType> + Default + Bounded + Copy,
105{
106}
107impl<T> Default for BBox<T>
108where
109    T: Default + Bounded + Copy,
110{
111    fn default() -> Self {
112        BBox::new(T::max_value(), T::max_value(), T::min_value(), T::min_value())
113    }
114}
115impl<T> BBox<T> {
116    /// Creates a new BBox
117    pub fn new(left: T, bottom: T, right: T, top: T) -> Self
118    where
119        T: Copy,
120    {
121        BBox { left, bottom, right, top }
122    }
123
124    /// Checks if a point is within the BBox
125    pub fn point_overlap<M: Clone>(&self, point: VectorPoint<M>) -> bool
126    where
127        T: Into<f64> + Copy, // Ensures that comparison operators work for type T
128    {
129        point.x >= self.left.into()
130            && point.x <= self.right.into()
131            && point.y >= self.bottom.into()
132            && point.y <= self.top.into()
133    }
134
135    /// Merges another bounding box with this one
136    pub fn merge(&self, other: &Self) -> Self
137    where
138        T: PartialOrd + Copy,
139    {
140        let mut new_bbox = *self;
141        new_bbox.left = if new_bbox.left < other.left { new_bbox.left } else { other.left };
142        new_bbox.bottom =
143            if new_bbox.bottom < other.bottom { new_bbox.bottom } else { other.bottom };
144        new_bbox.right = if new_bbox.right > other.right { new_bbox.right } else { other.right };
145        new_bbox.top = if new_bbox.top > other.top { new_bbox.top } else { other.top };
146
147        new_bbox
148    }
149
150    /// Merges in place another bounding box with this one
151    pub fn merge_in_place(&mut self, other: &Self)
152    where
153        T: PartialOrd + Copy,
154    {
155        self.left = if self.left < other.left { self.left } else { other.left };
156        self.bottom = if self.bottom < other.bottom { self.bottom } else { other.bottom };
157        self.right = if self.right > other.right { self.right } else { other.right };
158        self.top = if self.top > other.top { self.top } else { other.top };
159    }
160
161    /// Checks if another bounding box overlaps with this one and returns the overlap
162    pub fn overlap(&self, other: &BBox<T>) -> Option<BBox<T>>
163    where
164        T: PartialOrd + Copy,
165    {
166        if self.left > other.right
167            || self.right < other.left
168            || self.bottom > other.top
169            || self.top < other.bottom
170        {
171            None
172        } else {
173            let left = if self.left > other.left { self.left } else { other.left };
174            let bottom = if self.bottom > other.bottom { self.bottom } else { other.bottom };
175            let right = if self.right < other.right { self.right } else { other.right };
176            let top = if self.top < other.top { self.top } else { other.top };
177
178            Some(BBox { left, bottom, right, top })
179        }
180    }
181
182    /// Clips the bounding box along an axis
183    pub fn clip(&self, axis: Axis, k1: T, k2: T) -> BBox<T>
184    where
185        T: PartialOrd + Copy,
186    {
187        let mut new_bbox = *self;
188        if axis == Axis::X {
189            new_bbox.left = if new_bbox.left > k1 { new_bbox.left } else { k1 };
190            new_bbox.right = if new_bbox.right < k2 { new_bbox.right } else { k2 };
191        } else {
192            new_bbox.bottom = if new_bbox.bottom > k1 { new_bbox.bottom } else { k1 };
193            new_bbox.top = if new_bbox.top < k2 { new_bbox.top } else { k2 };
194        }
195
196        new_bbox
197    }
198}
199impl BBox<f64> {
200    /// Creates a new BBox from a point
201    pub fn from_point<M: Clone>(point: &VectorPoint<M>) -> Self {
202        BBox::new(point.x, point.y, point.x, point.y)
203    }
204
205    /// Creates a new BBox from a linestring
206    pub fn from_linestring<M: Clone>(line: &VectorLineString<M>) -> Self {
207        let mut bbox = BBox::from_point(&line[0]);
208        for point in line {
209            bbox.extend_from_point(point);
210        }
211        bbox
212    }
213
214    /// Creates a new BBox from a multi-linestring
215    pub fn from_multi_linestring<M: Clone>(lines: &VectorMultiLineString<M>) -> Self {
216        let mut bbox = BBox::from_point(&lines[0][0]);
217        for line in lines {
218            for point in line {
219                bbox.extend_from_point(point);
220            }
221        }
222        bbox
223    }
224
225    /// Creates a new BBox from a polygon
226    pub fn from_polygon<M: Clone>(polygon: &VectorPolygon<M>) -> Self {
227        BBox::<f64>::from_multi_linestring(polygon)
228    }
229
230    /// Creates a new BBox from a multi-polygon
231    pub fn from_multi_polygon<M: Clone>(polygons: &VectorMultiPolygon<M>) -> Self {
232        let mut bbox = BBox::from_point(&polygons[0][0][0]);
233        for polygon in polygons {
234            for line in polygon {
235                for point in line {
236                    bbox.extend_from_point(point);
237                }
238            }
239        }
240        bbox
241    }
242
243    /// Extends the bounding box with a point
244    pub fn extend_from_point<M: Clone>(&mut self, point: &VectorPoint<M>) {
245        self.merge_in_place(&BBox::from_point(point));
246    }
247
248    /// Creates a new BBox from zoom-uv coordinates
249    pub fn from_uv_zoom(u: f64, v: f64, zoom: u8) -> Self {
250        let division_factor = 2. / (1 << zoom) as f64;
251
252        BBox {
253            left: division_factor * u - 1.0,
254            bottom: division_factor * v - 1.0,
255            right: division_factor * (u + 1.0) - 1.0,
256            top: division_factor * (v + 1.0) - 1.0,
257        }
258    }
259
260    /// Creates a new BBox from zoom-st coordinates
261    pub fn from_st_zoom(s: f64, t: f64, zoom: u8) -> Self {
262        let division_factor = (2. / (1 << zoom) as f64) * 0.5;
263
264        BBox {
265            left: division_factor * s,
266            bottom: division_factor * t,
267            right: division_factor * (s + 1.),
268            top: division_factor * (t + 1.),
269        }
270    }
271}
272impl<T> Serialize for BBox<T>
273where
274    T: Serialize + Copy,
275{
276    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
277    where
278        S: Serializer,
279    {
280        let mut seq = serializer.serialize_tuple(4)?;
281        seq.serialize_element(&self.left)?;
282        seq.serialize_element(&self.bottom)?;
283        seq.serialize_element(&self.right)?;
284        seq.serialize_element(&self.top)?;
285        seq.end()
286    }
287}
288impl<'de, T> Deserialize<'de> for BBox<T>
289where
290    T: Deserialize<'de> + Copy,
291{
292    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
293    where
294        D: Deserializer<'de>,
295    {
296        struct BBoxVisitor<T> {
297            marker: core::marker::PhantomData<T>,
298        }
299
300        impl<'de, T> Visitor<'de> for BBoxVisitor<T>
301        where
302            T: Deserialize<'de> + Copy,
303        {
304            type Value = BBox<T>;
305
306            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
307                formatter.write_str("a sequence of four numbers")
308            }
309
310            fn visit_seq<V>(self, mut seq: V) -> Result<BBox<T>, V::Error>
311            where
312                V: SeqAccess<'de>,
313            {
314                let left =
315                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
316                let bottom =
317                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
318                let right =
319                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(2, &self))?;
320                let top = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(3, &self))?;
321                Ok(BBox { left, bottom, right, top })
322            }
323        }
324
325        deserializer.deserialize_tuple(4, BBoxVisitor { marker: core::marker::PhantomData })
326    }
327}
328
329/// A BBOX is defined in lon-lat space and helps with zooming motion to
330/// see the entire 3D line or polygon
331#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
332pub struct BBox3D<T = f64> {
333    /// left most longitude (WM) or S (S2)
334    pub left: T,
335    /// bottom most latitude (WM) or T (S2)
336    pub bottom: T,
337    /// right most longitude (WM) or T (S2)
338    pub right: T,
339    /// top most latitude (WM) or S (S2)
340    pub top: T,
341    /// near most height (WM) or T (S2)
342    /// generic height is relative to the surface of the earth in meters
343    pub near: T,
344    /// far most height (WM) or T (S2)
345    /// generic height is relative to the surface of the earth in meters
346    pub far: T,
347}
348impl<T> BBox3D<T> {
349    /// Creates a new BBox3D
350    pub fn new(left: T, bottom: T, right: T, top: T, near: T, far: T) -> Self
351    where
352        T: Copy,
353    {
354        BBox3D { left, bottom, right, top, near, far }
355    }
356
357    /// Checks if a point is within the BBox
358    pub fn point_overlap<M: Clone>(&self, point: VectorPoint<M>) -> bool
359    where
360        T: Into<f64> + Copy, // Ensures that comparison operators work for type T
361    {
362        let z = point.z.unwrap_or_default();
363        point.x >= self.left.into()
364            && point.x <= self.right.into()
365            && point.y >= self.bottom.into()
366            && point.y <= self.top.into()
367            && z >= self.near.into()
368            && z <= self.far.into()
369    }
370
371    /// Merges another bounding box with this one
372    pub fn merge(&self, other: &BBox3D<T>) -> BBox3D<T>
373    where
374        T: PartialOrd + Copy,
375    {
376        let mut new_bbox = *self;
377        new_bbox.left = if new_bbox.left < other.left { new_bbox.left } else { other.left };
378        new_bbox.bottom =
379            if new_bbox.bottom < other.bottom { new_bbox.bottom } else { other.bottom };
380        new_bbox.right = if new_bbox.right > other.right { new_bbox.right } else { other.right };
381        new_bbox.top = if new_bbox.top > other.top { new_bbox.top } else { other.top };
382        new_bbox.near = if new_bbox.near < other.near { new_bbox.near } else { other.near };
383        new_bbox.far = if new_bbox.far > other.far { new_bbox.far } else { other.far };
384
385        new_bbox
386    }
387
388    /// Merges in place another bounding box with this one
389    pub fn merge_in_place(&mut self, other: &Self)
390    where
391        T: PartialOrd + Copy,
392    {
393        self.left = if self.left < other.left { self.left } else { other.left };
394        self.bottom = if self.bottom < other.bottom { self.bottom } else { other.bottom };
395        self.right = if self.right > other.right { self.right } else { other.right };
396        self.top = if self.top > other.top { self.top } else { other.top };
397        self.near = if self.near < other.near { self.near } else { other.near };
398        self.far = if self.far > other.far { self.far } else { other.far };
399    }
400
401    /// Checks if another bounding box overlaps with this one and returns the overlap
402    pub fn overlap(&self, other: &BBox3D<T>) -> Option<BBox3D<T>>
403    where
404        T: PartialOrd + Copy,
405    {
406        if self.left > other.right
407            || self.right < other.left
408            || self.bottom > other.top
409            || self.top < other.bottom
410            || self.near > other.far
411            || self.far < other.near
412        {
413            None
414        } else {
415            let left = if self.left > other.left { self.left } else { other.left };
416            let bottom = if self.bottom > other.bottom { self.bottom } else { other.bottom };
417            let right = if self.right < other.right { self.right } else { other.right };
418            let top = if self.top < other.top { self.top } else { other.top };
419
420            let near = if self.near > other.near { self.near } else { other.near };
421            let far = if self.far < other.far { self.far } else { other.far };
422
423            Some(BBox3D { left, bottom, right, top, near, far })
424        }
425    }
426
427    /// Clips the bounding box along an axis
428    pub fn clip(&self, axis: Axis, k1: T, k2: T) -> BBox3D<T>
429    where
430        T: PartialOrd + Copy,
431    {
432        let mut new_bbox = *self;
433        if axis == Axis::X {
434            new_bbox.left = if new_bbox.left > k1 { new_bbox.left } else { k1 };
435            new_bbox.right = if new_bbox.right < k2 { new_bbox.right } else { k2 };
436        } else {
437            new_bbox.bottom = if new_bbox.bottom > k1 { new_bbox.bottom } else { k1 };
438            new_bbox.top = if new_bbox.top < k2 { new_bbox.top } else { k2 };
439        }
440
441        new_bbox
442    }
443}
444impl<T> Serialize for BBox3D<T>
445where
446    T: Serialize + Copy,
447{
448    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
449    where
450        S: Serializer,
451    {
452        let mut seq = serializer.serialize_tuple(6)?;
453        seq.serialize_element(&self.left)?;
454        seq.serialize_element(&self.bottom)?;
455        seq.serialize_element(&self.right)?;
456        seq.serialize_element(&self.top)?;
457        seq.serialize_element(&self.near)?;
458        seq.serialize_element(&self.far)?;
459        seq.end()
460    }
461}
462impl Default for BBox3D<f64> {
463    fn default() -> Self {
464        BBox3D::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN, f64::MAX, f64::MIN)
465    }
466}
467impl BBox3D<f64> {
468    /// Creates a new BBox3D from a point
469    pub fn from_point<M: Clone>(point: &VectorPoint<M>) -> Self {
470        BBox3D::new(
471            point.x,
472            point.y,
473            point.x,
474            point.y,
475            point.z.unwrap_or(f64::MAX),
476            point.z.unwrap_or(f64::MIN),
477        )
478    }
479
480    /// Creates a new BBox from a linestring
481    pub fn from_linestring<M: Clone>(line: &VectorLineString<M>) -> Self {
482        let mut bbox = BBox3D::from_point(&line[0]);
483        for point in line {
484            bbox.extend_from_point(point);
485        }
486        bbox
487    }
488
489    /// Creates a new BBox from a multi-linestring
490    pub fn from_multi_linestring<M: Clone>(lines: &VectorMultiLineString<M>) -> Self {
491        let mut bbox = BBox3D::from_point(&lines[0][0]);
492        for line in lines {
493            for point in line {
494                bbox.extend_from_point(point);
495            }
496        }
497        bbox
498    }
499
500    /// Creates a new BBox from a polygon
501    pub fn from_polygon<M: Clone>(polygon: &VectorPolygon<M>) -> Self {
502        BBox3D::<f64>::from_multi_linestring(polygon)
503    }
504
505    /// Creates a new BBox from a multi-polygon
506    pub fn from_multi_polygon<M: Clone>(polygons: &VectorMultiPolygon<M>) -> Self {
507        let mut bbox = BBox3D::from_point(&polygons[0][0][0]);
508        for polygon in polygons {
509            for line in polygon {
510                for point in line {
511                    bbox.extend_from_point(point);
512                }
513            }
514        }
515        bbox
516    }
517
518    /// Creates a new BBox3D from a BBox
519    pub fn from_bbox(bbox: &BBox) -> Self {
520        BBox3D::new(bbox.left, bbox.bottom, bbox.right, bbox.top, 0., 0.)
521    }
522
523    /// Extends the bounding box with a point
524    pub fn extend_from_point<M: Clone>(&mut self, point: &VectorPoint<M>) {
525        self.merge_in_place(&BBox3D::from_point(point));
526    }
527
528    /// Creates a new BBox3D from zoom-uv coordinates
529    pub fn from_uv_zoom(u: f64, v: f64, zoom: u8) -> Self {
530        let division_factor = 2. / (1 << zoom) as f64;
531
532        BBox3D {
533            left: division_factor * u - 1.0,
534            bottom: division_factor * v - 1.0,
535            right: division_factor * (u + 1.0) - 1.0,
536            top: division_factor * (v + 1.0) - 1.0,
537            near: f64::MAX,
538            far: f64::MIN,
539        }
540    }
541
542    /// Creates a new BBox from zoom-st coordinates
543    pub fn from_st_zoom(s: f64, t: f64, zoom: u8) -> Self {
544        let division_factor = (2. / (1 << zoom) as f64) * 0.5;
545
546        BBox3D {
547            left: division_factor * s,
548            bottom: division_factor * t,
549            right: division_factor * (s + 1.),
550            top: division_factor * (t + 1.),
551            near: f64::MAX,
552            far: f64::MIN,
553        }
554    }
555}
556impl From<BBox> for BBox3D<f64> {
557    fn from(bbox: BBox) -> Self {
558        BBox3D::from_bbox(&bbox)
559    }
560}
561impl<'de, T> Deserialize<'de> for BBox3D<T>
562where
563    T: Deserialize<'de> + Copy,
564{
565    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
566    where
567        D: Deserializer<'de>,
568    {
569        struct BBox3DVisitor<T> {
570            marker: core::marker::PhantomData<T>,
571        }
572
573        impl<'de, T> Visitor<'de> for BBox3DVisitor<T>
574        where
575            T: Deserialize<'de> + Copy,
576        {
577            type Value = BBox3D<T>;
578
579            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
580                formatter.write_str("a sequence of six numbers")
581            }
582
583            fn visit_seq<V>(self, mut seq: V) -> Result<BBox3D<T>, V::Error>
584            where
585                V: SeqAccess<'de>,
586            {
587                let left =
588                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
589                let bottom =
590                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
591                let right =
592                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(2, &self))?;
593                let top = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(3, &self))?;
594                let near =
595                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(4, &self))?;
596                let far = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(5, &self))?;
597                Ok(BBox3D { left, bottom, right, top, near, far })
598            }
599        }
600
601        deserializer.deserialize_tuple(6, BBox3DVisitor { marker: core::marker::PhantomData })
602    }
603}
604
605/// BBox or BBox3D
606#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
607pub enum BBOX {
608    /// 2D bounding box
609    BBox(BBox),
610    /// 3D bounding box
611    BBox3D(BBox3D),
612}
613impl Default for BBOX {
614    fn default() -> Self {
615        BBOX::BBox(BBox::default())
616    }
617}
618impl Eq for BBOX {}
619impl PartialOrd for BBOX {
620    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
621        Some(self.cmp(other))
622    }
623}
624impl Ord for BBOX {
625    fn cmp(&self, other: &Self) -> Ordering {
626        match (self, other) {
627            (BBOX::BBox(a), BBOX::BBox(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
628            (BBOX::BBox3D(a), BBOX::BBox3D(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
629            // Ensure that BBox and BBox3D are ordered correctly
630            (BBOX::BBox(_), BBOX::BBox3D(_)) => Ordering::Less,
631            (BBOX::BBox3D(_), BBOX::BBox(_)) => Ordering::Greater,
632        }
633    }
634}