s2rst 0.4.0

A Rust port of Google's S2 spherical geometry library — points, regions, shapes, and a hierarchical cell index on the sphere.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2026 Torgeir Børresen <tb@starkad.no>
// Rust port of Google's S2 Geometry library — a derivative work, modified from
// the upstream Apache-2.0 source(s) below (Copyright Google Inc.). See LICENSE.
//   - C++:  google/s2geometry
//   - Go:   golang/geo
//   - Java: google/s2-geometry-library-java

//! Point containment queries using a [`ShapeIndex`].
//!
//! [`ContainsPointQuery`] determines whether one or more shapes in a
//! [`ShapeIndex`] contain a given point. Shape boundaries may be modeled
//! as Open, `SemiOpen`, or Closed.
//!
//! Corresponds to C++ `s2contains_point_query.h`, Go `s2/contains_point_query.go`.

#![expect(clippy::cast_sign_loss, reason = "EdgeId (i32) used as Vec indices")]
use std::ops::ControlFlow;

use crate::s2::Point;
use crate::s2::edge_crosser::EdgeCrosser;
use crate::s2::edge_crossings::{Crossing, vertex_crossing};
use crate::s2::shape::{Dimension, Shape, ShapeEdge, ShapeEdgeId, ShapeId};
use crate::s2::shape_index::{ClippedShape, ShapeIndex, ShapeIndexIterator};

/// Controls whether shapes contain their vertices.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VertexModel {
    /// No shapes contain their vertices. `contains` returns true only if the
    /// point is in the interior of some polygon.
    Open,
    /// Polygon containment is defined such that if several polygons tile the
    /// region around a vertex, exactly one contains that vertex. Points and
    /// polylines still do not contain any vertices.
    #[default]
    SemiOpen,
    /// All shapes contain their vertices (including points and polylines).
    Closed,
}

/// Determines whether shapes in a [`ShapeIndex`] contain a given point.
///
/// This type is not thread-safe (it caches an iterator internally). For
/// concurrent queries, create one per thread or use separate instances.
///
/// # Examples
///
/// ```
/// use s2rst::s2::contains_point_query::{ContainsPointQuery, VertexModel};
/// use s2rst::s2::shape_index::ShapeIndex;
/// use s2rst::s2::lax_loop::LaxLoop;
/// use s2rst::s2::LatLng;
///
/// let mut index = ShapeIndex::new();
/// index.add(Box::new(LaxLoop::new(vec![
///     LatLng::from_degrees(0.0, 0.0).to_point(),
///     LatLng::from_degrees(0.0, 10.0).to_point(),
///     LatLng::from_degrees(10.0, 10.0).to_point(),
///     LatLng::from_degrees(10.0, 0.0).to_point(),
/// ])));
/// index.build();
///
/// let mut query = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
/// assert!(query.contains(LatLng::from_degrees(5.0, 5.0).to_point()));
/// assert!(!query.contains(LatLng::from_degrees(20.0, 20.0).to_point()));
/// ```
#[derive(Debug)]
pub struct ContainsPointQuery<'a> {
    model: VertexModel,
    index: &'a ShapeIndex,
    iter: ShapeIndexIterator<'a>,
}

impl<'a> ContainsPointQuery<'a> {
    /// Creates a new query for the given index and vertex model.
    #[inline]
    pub fn new(index: &'a ShapeIndex, model: VertexModel) -> Self {
        ContainsPointQuery {
            model,
            index,
            iter: index.iter(),
        }
    }

    /// Reports whether any shape in the index contains the point `p`.
    #[inline]
    pub fn contains(&mut self, p: Point) -> bool {
        if !self.iter.locate_point(p) {
            return false;
        }
        let Some(cell) = self.iter.index_cell() else {
            return false;
        };
        let center = self.iter.center();
        for clipped in &cell.shapes {
            if self.shape_contains_impl(clipped, center, p) {
                return true;
            }
        }
        false
    }

    /// Reports whether the shape with the given `shape_id` contains `p`.
    #[inline]
    pub fn shape_contains(&mut self, shape_id: impl Into<ShapeId>, p: Point) -> bool {
        let shape_id = shape_id.into();
        if !self.iter.locate_point(p) {
            return false;
        }
        let Some(cell) = self.iter.index_cell() else {
            return false;
        };
        let center = self.iter.center();
        match cell.find_by_shape_id(shape_id) {
            Some(clipped) => self.shape_contains_impl(clipped, center, p),
            None => false,
        }
    }

    /// Returns references to all shapes in the index that contain `p`.
    ///
    /// This is a convenience wrapper that collects shape IDs via
    /// [`containing_shape_ids`](Self::containing_shape_ids) and then looks
    /// up each shape in the index. Matches C++ `GetContainingShapes`.
    pub fn containing_shapes(&mut self, p: Point) -> Vec<&'a dyn Shape> {
        let ids = self.containing_shape_ids(p);
        ids.into_iter()
            .filter_map(|id| self.index.shape(id))
            .collect()
    }

    /// Returns a list of shape IDs for all shapes containing `p`.
    pub fn containing_shape_ids(&mut self, p: Point) -> Vec<ShapeId> {
        let mut ids = Vec::new();
        let _ = self.visit_containing_shapes(p, |shape_id, _shape| {
            ids.push(shape_id);
            ControlFlow::Continue(())
        });
        ids
    }

    /// Visits all shapes containing `p`. The callback receives the shape ID
    /// and shape reference. Return `ControlFlow::Break(())` to stop early.
    pub fn visit_containing_shapes<F>(&mut self, p: Point, mut f: F) -> ControlFlow<()>
    where
        F: FnMut(ShapeId, &dyn Shape) -> ControlFlow<()>,
    {
        if !self.iter.locate_point(p) {
            return ControlFlow::Continue(());
        }
        let Some(cell) = self.iter.index_cell() else {
            return ControlFlow::Continue(());
        };
        let center = self.iter.center();
        for clipped in &cell.shapes {
            if self.shape_contains_impl(clipped, center, p)
                && let Some(shape) = self.index.shape(clipped.shape_id)
            {
                f(clipped.shape_id, shape)?;
            }
        }
        ControlFlow::Continue(())
    }

    /// Returns a reference to the underlying index.
    pub fn index(&self) -> &'a ShapeIndex {
        self.index
    }

    /// Visits all edges in the index that are incident to the point `p`
    /// (i.e., `p` is one of the edge endpoints), terminating early if the
    /// visitor returns `ControlFlow::Break(())`. Each edge is visited at
    /// most once.
    pub fn visit_incident_edges<F>(&mut self, p: Point, mut visitor: F) -> ControlFlow<()>
    where
        F: FnMut(&ShapeEdge) -> ControlFlow<()>,
    {
        if !self.iter.locate_point(p) {
            return ControlFlow::Continue(());
        }
        let Some(cell) = self.iter.index_cell() else {
            return ControlFlow::Continue(());
        };
        for clipped in &cell.shapes {
            let num_edges = clipped.num_edges();
            if num_edges == 0 {
                continue;
            }
            let Some(shape) = self.index.shape(clipped.shape_id) else {
                continue;
            };
            for &edge_id in &clipped.edges {
                let edge = shape.edge(edge_id as usize);
                if edge.v0 == p || edge.v1 == p {
                    visitor(&ShapeEdge::new(
                        ShapeEdgeId::new(clipped.shape_id, edge_id),
                        edge,
                    ))?;
                }
            }
        }
        ControlFlow::Continue(())
    }

    /// Internal containment test for a clipped shape.
    ///
    /// Tests whether `clipped` contains `p`, using `center` as the cell center
    /// from which edge crossings are counted.
    pub(crate) fn shape_contains_impl(
        &self,
        clipped: &ClippedShape,
        center: Point,
        p: Point,
    ) -> bool {
        let mut inside = clipped.contains_center;
        let num_edges = clipped.num_edges();
        if num_edges == 0 {
            return inside;
        }

        let Some(shape) = self.index.shape(clipped.shape_id) else {
            return false;
        };

        if shape.dimension() != Dimension::Polygon {
            // Points and polylines: only contained with Closed model.
            if self.model != VertexModel::Closed {
                return false;
            }
            for &edge_id in &clipped.edges {
                let edge = shape.edge(edge_id as usize);
                if edge.v0 == p || edge.v1 == p {
                    return true;
                }
            }
            return false;
        }

        // Polygon (dimension 2): count edge crossings from cell center to p.
        let mut crosser = EdgeCrosser::new(center, p);
        for &edge_id in &clipped.edges {
            let edge = shape.edge(edge_id as usize);
            let sign = crosser.crossing_sign(edge.v0, edge.v1);
            match sign {
                Crossing::DoNotCross => {}
                Crossing::Cross => {
                    inside = !inside;
                }
                Crossing::MaybeCross => {
                    // For Open and Closed models, check if p is a vertex.
                    if self.model != VertexModel::SemiOpen && (edge.v0 == p || edge.v1 == p) {
                        return self.model == VertexModel::Closed;
                    }
                    if vertex_crossing(crosser.a, crosser.b, edge.v0, edge.v1) {
                        inside = !inside;
                    }
                }
            }
        }

        inside
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::s2::LatLng;
    use crate::s2::shape::{Chain, ChainPosition, Edge, ReferencePoint};

    /// A simple point-set shape for testing.
    #[derive(Debug)]
    struct PointVectorShape {
        points: Vec<Point>,
    }

    impl Shape for PointVectorShape {
        fn num_edges(&self) -> usize {
            self.points.len()
        }
        fn edge(&self, id: usize) -> Edge {
            Edge::new(self.points[id], self.points[id])
        }
        fn reference_point(&self) -> ReferencePoint {
            ReferencePoint::default()
        }
        fn num_chains(&self) -> usize {
            self.points.len()
        }
        fn chain(&self, chain_id: usize) -> Chain {
            Chain::new(chain_id, 1)
        }
        fn chain_edge(&self, chain_id: usize, _offset: usize) -> Edge {
            self.edge(chain_id)
        }
        fn chain_position(&self, edge_id: usize) -> ChainPosition {
            ChainPosition::new(edge_id, 0)
        }
        fn dimension(&self) -> Dimension {
            Dimension::Point
        }
    }

    fn p(lat: f64, lng: f64) -> Point {
        LatLng::from_degrees(lat, lng).to_point()
    }

    #[test]
    fn test_contains_point_empty_index() {
        let mut index = ShapeIndex::new();
        index.build();
        let mut query = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
        assert!(!query.contains(p(0.0, 0.0)));
    }

    #[test]
    fn test_contains_point_closed_model() {
        let mut index = ShapeIndex::new();
        let target = p(10.0, 20.0);
        index.add(Box::new(PointVectorShape {
            points: vec![target],
        }));
        index.build();

        // Open model: points don't contain vertices.
        let mut q_open = ContainsPointQuery::new(&index, VertexModel::Open);
        assert!(!q_open.contains(target));

        // Closed model: points contain vertices.
        let mut q_closed = ContainsPointQuery::new(&index, VertexModel::Closed);
        assert!(q_closed.contains(target));
    }

    #[test]
    fn test_containing_shape_ids() {
        let mut index = ShapeIndex::new();
        let target = p(10.0, 20.0);
        let id0 = index.add(Box::new(PointVectorShape {
            points: vec![target],
        }));
        let _id1 = index.add(Box::new(PointVectorShape {
            points: vec![p(30.0, 40.0)],
        }));
        index.build();

        let mut q = ContainsPointQuery::new(&index, VertexModel::Closed);
        let ids = q.containing_shape_ids(target);
        assert_eq!(ids, vec![id0]);
    }

    #[test]
    fn test_shape_contains() {
        let mut index = ShapeIndex::new();
        let target = p(10.0, 20.0);
        let id = index.add(Box::new(PointVectorShape {
            points: vec![target],
        }));
        index.build();

        let mut q = ContainsPointQuery::new(&index, VertexModel::Closed);
        assert!(q.shape_contains(id, target));
    }

    #[test]
    fn test_no_match() {
        let mut index = ShapeIndex::new();
        index.add(Box::new(PointVectorShape {
            points: vec![p(10.0, 20.0)],
        }));
        index.build();

        let mut q = ContainsPointQuery::new(&index, VertexModel::Closed);
        // A distant point should not be contained.
        assert!(!q.contains(p(-80.0, -170.0)));
    }

    #[test]
    fn test_contains_point_vertex_model() {
        use crate::s2::lax_loop::LaxLoop;

        // Build a polygon (LaxLoop, dimension 2) as a triangle and add it
        // to a ShapeIndex. Then test containment for a point exactly on a
        // vertex, a point in the interior, and a point outside.
        let v0 = p(0.0, 0.0);
        let v1 = p(0.0, 10.0);
        let v2 = p(10.0, 5.0);
        let shape = LaxLoop::new(vec![v0, v1, v2]);

        let mut index = ShapeIndex::new();
        index.add(Box::new(shape));
        index.build();

        // An interior point of the triangle.
        let interior = p(3.0, 5.0);

        // SemiOpen model: interior point should be contained, vertex may or may not be.
        let mut q_semi = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
        assert!(
            q_semi.contains(interior),
            "SemiOpen: interior point should be contained"
        );

        // Closed model: vertex v0 should be contained, as should the interior.
        let mut q_closed = ContainsPointQuery::new(&index, VertexModel::Closed);
        assert!(
            q_closed.contains(interior),
            "Closed: interior point should be contained"
        );
        // With the Closed model, the vertex itself is contained if it's
        // recognized as on the boundary. Since v0 is a vertex of a
        // dimension-2 shape, the MaybeCross path returns Closed==true.
        assert!(
            q_closed.contains(v0),
            "Closed: vertex v0 should be contained"
        );

        // Open model: the vertex itself should NOT be contained.
        let mut q_open = ContainsPointQuery::new(&index, VertexModel::Open);
        assert!(
            !q_open.contains(v0),
            "Open: vertex v0 should not be contained"
        );
        // But the interior point should still be contained.
        assert!(
            q_open.contains(interior),
            "Open: interior point should be contained"
        );

        // A point well outside should not be contained in any model.
        let outside = p(-50.0, -50.0);
        let mut q_any = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
        assert!(
            !q_any.contains(outside),
            "point well outside should not be contained"
        );
    }

    #[test]
    fn test_containing_shapes() {
        // Create an index with a LaxPolygon containing the test point
        // and another that does not.

        use crate::s2::text_format;
        let lp1 = text_format::make_lax_polygon("0:0, 0:10, 10:10, 10:0");
        let lp2 = text_format::make_lax_polygon("20:20, 20:30, 30:30, 30:20");
        let mut index = ShapeIndex::new();
        index.add(Box::new(lp1));
        index.add(Box::new(lp2));
        index.build();

        let interior_point = p(5.0, 5.0);
        let mut query = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
        let shapes = query.containing_shapes(interior_point);
        assert_eq!(
            shapes.len(),
            1,
            "exactly one shape should contain the point"
        );

        // A point outside both polygons.
        let outside = p(-5.0, -5.0);
        let shapes2 = query.containing_shapes(outside);
        assert!(shapes2.is_empty(), "no shapes should contain outside point");
    }

    #[test]
    fn test_containing_shapes_matches_ids() {
        // Verify that containing_shapes returns the same shapes as
        // containing_shape_ids.
        use crate::s2::text_format;
        let lp = text_format::make_lax_polygon("0:0, 0:10, 10:10, 10:0");
        let mut index = ShapeIndex::new();
        index.add(Box::new(lp));
        index.build();

        let pt = p(5.0, 5.0);
        let mut query = ContainsPointQuery::new(&index, VertexModel::SemiOpen);
        let ids = query.containing_shape_ids(pt);
        let shapes = query.containing_shapes(pt);
        assert_eq!(ids.len(), shapes.len());
        assert!(!ids.is_empty(), "point should be contained");
        for (id, shape) in ids.iter().zip(shapes.iter()) {
            assert_eq!(index.shape(*id).unwrap().num_edges(), shape.num_edges());
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_vertex_model_roundtrip() {
        for vm in [
            VertexModel::Open,
            VertexModel::SemiOpen,
            VertexModel::Closed,
        ] {
            let json = serde_json::to_string(&vm).unwrap();
            let back: VertexModel = serde_json::from_str(&json).unwrap();
            assert_eq!(vm, back);
        }
    }
}