Skip to main content

nodedb_spatial/
operations.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Geometry construction and transformation operations.
4//!
5//! ST_Buffer, ST_Envelope, ST_Union — produce new geometries from existing ones.
6
7use nodedb_types::geometry::Geometry;
8use nodedb_types::{BoundingBox, geometry_bbox};
9
10/// ST_Buffer(geom, distance_meters) → Polygon.
11///
12/// Expands geometry by distance using equirectangular approximation.
13/// - Point → 32-sided circle polygon
14/// - LineString → buffered corridor (parallel offset + end caps)
15/// - Polygon → expanded polygon (vertex offset outward)
16///
17/// Meter-to-degree conversion: `Δlng = meters / (111320 * cos(lat))`,
18/// `Δlat = meters / 110540`. Accurate to <0.5% for ±70° latitude.
19pub fn st_buffer(geom: &Geometry, distance_meters: f64, segments: usize) -> Geometry {
20    let segments = segments.max(4);
21
22    match geom {
23        Geometry::Point { coordinates } => {
24            buffer_point(coordinates[0], coordinates[1], distance_meters, segments)
25        }
26        Geometry::LineString { coordinates } => {
27            buffer_linestring(coordinates, distance_meters, segments)
28        }
29        Geometry::Polygon { coordinates } => buffer_polygon(coordinates, distance_meters, segments),
30        // Multi* types: buffer each component and collect.
31        Geometry::MultiPoint { coordinates } => {
32            let polys: Vec<Vec<Vec<[f64; 2]>>> = coordinates
33                .iter()
34                .map(|pt| {
35                    if let Geometry::Polygon { coordinates: rings } =
36                        buffer_point(pt[0], pt[1], distance_meters, segments)
37                    {
38                        rings
39                    } else {
40                        vec![]
41                    }
42                })
43                .collect();
44            Geometry::MultiPolygon { coordinates: polys }
45        }
46        _ => {
47            // For unsupported types, fall back to buffering the bbox.
48            let bb = geometry_bbox(geom).expand_meters(distance_meters);
49            bbox_to_polygon(&bb)
50        }
51    }
52}
53
54/// ST_Envelope(geom) → Polygon — bounding box as a polygon.
55pub fn st_envelope(geom: &Geometry) -> Geometry {
56    let bb = geometry_bbox(geom);
57    bbox_to_polygon(&bb)
58}
59
60/// ST_Union(a, b) → Geometry — merge two geometries.
61///
62/// For this version, collects into appropriate Multi* type or
63/// GeometryCollection. True polygon clipping (Weiler-Atherton) is
64/// deferred — this handles the common cases correctly.
65pub fn st_union(a: &Geometry, b: &Geometry) -> Geometry {
66    match (a, b) {
67        // Point + Point → MultiPoint
68        (Geometry::Point { coordinates: ca }, Geometry::Point { coordinates: cb }) => {
69            Geometry::MultiPoint {
70                coordinates: vec![*ca, *cb],
71            }
72        }
73        // LineString + LineString → MultiLineString
74        (Geometry::LineString { coordinates: la }, Geometry::LineString { coordinates: lb }) => {
75            Geometry::MultiLineString {
76                coordinates: vec![la.clone(), lb.clone()],
77            }
78        }
79        // Polygon + Polygon → MultiPolygon
80        (Geometry::Polygon { coordinates: ra }, Geometry::Polygon { coordinates: rb }) => {
81            Geometry::MultiPolygon {
82                coordinates: vec![ra.clone(), rb.clone()],
83            }
84        }
85        // Same-type Multi* + element → extend
86        (Geometry::MultiPoint { coordinates: pts }, Geometry::Point { coordinates: pt }) => {
87            let mut coords = pts.clone();
88            coords.push(*pt);
89            Geometry::MultiPoint {
90                coordinates: coords,
91            }
92        }
93        (Geometry::Point { coordinates: pt }, Geometry::MultiPoint { coordinates: pts }) => {
94            let mut coords = vec![*pt];
95            coords.extend_from_slice(pts);
96            Geometry::MultiPoint {
97                coordinates: coords,
98            }
99        }
100        // Everything else → GeometryCollection
101        _ => Geometry::GeometryCollection {
102            geometries: vec![a.clone(), b.clone()],
103        },
104    }
105}
106
107// ── Buffer helpers ──
108
109/// Buffer a point into an approximate circle polygon.
110fn buffer_point(lng: f64, lat: f64, meters: f64, segments: usize) -> Geometry {
111    let dlat = meters / 110_540.0;
112    let dlng = meters / (111_320.0 * lat.to_radians().cos().max(0.001));
113
114    let mut ring = Vec::with_capacity(segments + 1);
115    for i in 0..segments {
116        let angle = 2.0 * std::f64::consts::PI * (i as f64) / (segments as f64);
117        ring.push([lng + dlng * angle.cos(), lat + dlat * angle.sin()]);
118    }
119    // Close the ring.
120    ring.push(ring[0]);
121
122    Geometry::Polygon {
123        coordinates: vec![ring],
124    }
125}
126
127/// Buffer a linestring by creating a corridor (parallel offset on both sides + end caps).
128fn buffer_linestring(line: &[[f64; 2]], meters: f64, segments: usize) -> Geometry {
129    if line.is_empty() {
130        return Geometry::Polygon {
131            coordinates: vec![vec![]],
132        };
133    }
134    if line.len() == 1 {
135        return buffer_point(line[0][0], line[0][1], meters, segments);
136    }
137
138    // Build the offset polygon: left side forward, right side backward, with
139    // semicircular end caps.
140    let mut left_side = Vec::new();
141    let mut right_side = Vec::new();
142
143    for i in 0..line.len() - 1 {
144        let (nl, nr) = offset_segment(line[i], line[i + 1], meters);
145        left_side.push(nl.0);
146        left_side.push(nl.1);
147        right_side.push(nr.0);
148        right_side.push(nr.1);
149    }
150
151    // Build polygon: left side forward → end cap → right side backward → start cap.
152    let mut ring = Vec::new();
153    ring.extend_from_slice(&left_side);
154
155    // End cap (semicircle around last point).
156    let last = line[line.len() - 1];
157    let cap_segments = segments / 2;
158    let end_dir = direction(line[line.len() - 2], last);
159    for i in 0..=cap_segments {
160        let angle = end_dir - std::f64::consts::FRAC_PI_2
161            + std::f64::consts::PI * (i as f64) / (cap_segments as f64);
162        let dlat = meters / 110_540.0;
163        let dlng = meters / (111_320.0 * last[1].to_radians().cos().max(0.001));
164        ring.push([last[0] + dlng * angle.cos(), last[1] + dlat * angle.sin()]);
165    }
166
167    // Right side backward.
168    for pt in right_side.iter().rev() {
169        ring.push(*pt);
170    }
171
172    // Start cap (semicircle around first point).
173    let first = line[0];
174    let start_dir = direction(first, line[1]);
175    for i in 0..=cap_segments {
176        let angle = start_dir
177            + std::f64::consts::FRAC_PI_2
178            + std::f64::consts::PI * (i as f64) / (cap_segments as f64);
179        let dlat = meters / 110_540.0;
180        let dlng = meters / (111_320.0 * first[1].to_radians().cos().max(0.001));
181        ring.push([first[0] + dlng * angle.cos(), first[1] + dlat * angle.sin()]);
182    }
183
184    // Close.
185    if let Some(&first_pt) = ring.first() {
186        ring.push(first_pt);
187    }
188
189    Geometry::Polygon {
190        coordinates: vec![ring],
191    }
192}
193
194/// Buffer a polygon by offsetting each vertex outward.
195fn buffer_polygon(rings: &[Vec<[f64; 2]>], meters: f64, _segments: usize) -> Geometry {
196    let mut new_rings = Vec::with_capacity(rings.len());
197
198    for (ring_idx, ring) in rings.iter().enumerate() {
199        if ring.len() < 3 {
200            new_rings.push(ring.clone());
201            continue;
202        }
203        let is_exterior = ring_idx == 0;
204        // For exterior: expand outward. For holes: shrink inward.
205        let sign = if is_exterior { 1.0 } else { -1.0 };
206        let offset_m = meters * sign;
207
208        let mut new_ring = Vec::with_capacity(ring.len());
209        let n = if ring.first() == ring.last() {
210            ring.len() - 1
211        } else {
212            ring.len()
213        };
214
215        for i in 0..n {
216            let prev = ring[(i + n - 1) % n];
217            let curr = ring[i];
218            let next = ring[(i + 1) % n];
219
220            // Bisector direction (average of the two edge normals).
221            let n1 = edge_outward_normal(prev, curr);
222            let n2 = edge_outward_normal(curr, next);
223            let bisect = [(n1[0] + n2[0]) / 2.0, (n1[1] + n2[1]) / 2.0];
224            let len = (bisect[0] * bisect[0] + bisect[1] * bisect[1])
225                .sqrt()
226                .max(1e-12);
227            let unit = [bisect[0] / len, bisect[1] / len];
228
229            let dlat = offset_m / 110_540.0;
230            let dlng = offset_m / (111_320.0 * curr[1].to_radians().cos().max(0.001));
231
232            new_ring.push([curr[0] + unit[0] * dlng, curr[1] + unit[1] * dlat]);
233        }
234
235        // Close.
236        if let Some(&first_pt) = new_ring.first() {
237            new_ring.push(first_pt);
238        }
239        new_rings.push(new_ring);
240    }
241
242    Geometry::Polygon {
243        coordinates: new_rings,
244    }
245}
246
247/// Compute offset segments (left and right parallel lines at `meters` distance).
248/// A pair of offset segments: (left_segment, right_segment).
249type OffsetPair = (([f64; 2], [f64; 2]), ([f64; 2], [f64; 2]));
250
251fn offset_segment(a: [f64; 2], b: [f64; 2], meters: f64) -> OffsetPair {
252    let normal = edge_outward_normal(a, b);
253    let dlat = meters / 110_540.0;
254    let mid_lat = ((a[1] + b[1]) / 2.0).to_radians().cos().max(0.001);
255    let dlng = meters / (111_320.0 * mid_lat);
256
257    let left = (
258        [a[0] + normal[0] * dlng, a[1] + normal[1] * dlat],
259        [b[0] + normal[0] * dlng, b[1] + normal[1] * dlat],
260    );
261    let right = (
262        [a[0] - normal[0] * dlng, a[1] - normal[1] * dlat],
263        [b[0] - normal[0] * dlng, b[1] - normal[1] * dlat],
264    );
265    (left, right)
266}
267
268/// Outward-pointing unit normal for an edge (a→b).
269///
270/// For CCW rings (standard exterior), the outward direction is the right
271/// normal (dy, -dx). This is correct because CCW traversal has the
272/// interior on the left.
273fn edge_outward_normal(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
274    let dx = b[0] - a[0];
275    let dy = b[1] - a[1];
276    let len = (dx * dx + dy * dy).sqrt().max(1e-12);
277    // Right normal: (dy, -dx) normalized — outward for CCW rings.
278    [dy / len, -dx / len]
279}
280
281/// Direction angle (radians) from a to b.
282fn direction(a: [f64; 2], b: [f64; 2]) -> f64 {
283    (b[1] - a[1]).atan2(b[0] - a[0])
284}
285
286/// Convert a BoundingBox to a Polygon.
287fn bbox_to_polygon(bb: &BoundingBox) -> Geometry {
288    Geometry::Polygon {
289        coordinates: vec![vec![
290            [bb.min_lng, bb.min_lat],
291            [bb.max_lng, bb.min_lat],
292            [bb.max_lng, bb.max_lat],
293            [bb.min_lng, bb.max_lat],
294            [bb.min_lng, bb.min_lat],
295        ]],
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    #[test]
304    fn buffer_point_circle() {
305        let circle = st_buffer(&Geometry::point(0.0, 0.0), 1000.0, 32);
306        if let Geometry::Polygon { coordinates } = &circle {
307            assert_eq!(coordinates.len(), 1);
308            // 32 segments + 1 closing point.
309            assert_eq!(coordinates[0].len(), 33);
310            // All points should be roughly 1000m from center.
311            for pt in &coordinates[0][..32] {
312                let d = nodedb_types::geometry::haversine_distance(0.0, 0.0, pt[0], pt[1]);
313                assert!((d - 1000.0).abs() < 50.0, "d={d}");
314            }
315        } else {
316            panic!("expected Polygon");
317        }
318    }
319
320    #[test]
321    fn buffer_point_4_segments() {
322        let circle = st_buffer(&Geometry::point(10.0, 50.0), 500.0, 4);
323        if let Geometry::Polygon { coordinates } = &circle {
324            assert_eq!(coordinates[0].len(), 5); // 4 + close
325        } else {
326            panic!("expected Polygon");
327        }
328    }
329
330    #[test]
331    fn envelope_polygon() {
332        let poly = Geometry::polygon(vec![vec![[1.0, 2.0], [5.0, 2.0], [3.0, 8.0], [1.0, 2.0]]]);
333        let env = st_envelope(&poly);
334        if let Geometry::Polygon { coordinates } = &env {
335            let ring = &coordinates[0];
336            assert_eq!(ring[0], [1.0, 2.0]); // min_lng, min_lat
337            assert_eq!(ring[2], [5.0, 8.0]); // max_lng, max_lat
338        } else {
339            panic!("expected Polygon");
340        }
341    }
342
343    #[test]
344    fn envelope_point() {
345        let env = st_envelope(&Geometry::point(5.0, 10.0));
346        if let Geometry::Polygon { coordinates } = &env {
347            // Zero-area bbox → degenerate polygon.
348            assert_eq!(coordinates[0][0], [5.0, 10.0]);
349            assert_eq!(coordinates[0][2], [5.0, 10.0]);
350        } else {
351            panic!("expected Polygon");
352        }
353    }
354
355    #[test]
356    fn union_points() {
357        let a = Geometry::point(1.0, 2.0);
358        let b = Geometry::point(3.0, 4.0);
359        let u = st_union(&a, &b);
360        if let Geometry::MultiPoint { coordinates } = &u {
361            assert_eq!(coordinates.len(), 2);
362        } else {
363            panic!("expected MultiPoint, got {:?}", u.geometry_type());
364        }
365    }
366
367    #[test]
368    fn union_polygons() {
369        let a = Geometry::polygon(vec![vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]]);
370        let b = Geometry::polygon(vec![vec![[2.0, 2.0], [3.0, 2.0], [3.0, 3.0], [2.0, 2.0]]]);
371        let u = st_union(&a, &b);
372        if let Geometry::MultiPolygon { coordinates } = &u {
373            assert_eq!(coordinates.len(), 2);
374        } else {
375            panic!("expected MultiPolygon");
376        }
377    }
378
379    #[test]
380    fn union_mixed_types() {
381        let a = Geometry::point(1.0, 2.0);
382        let b = Geometry::polygon(vec![vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]]);
383        let u = st_union(&a, &b);
384        if let Geometry::GeometryCollection { geometries } = &u {
385            assert_eq!(geometries.len(), 2);
386        } else {
387            panic!("expected GeometryCollection");
388        }
389    }
390
391    #[test]
392    fn buffer_linestring_corridor() {
393        let line = Geometry::line_string(vec![[0.0, 0.0], [0.1, 0.0]]);
394        let buf = st_buffer(&line, 1000.0, 16);
395        if let Geometry::Polygon { coordinates } = &buf {
396            assert!(!coordinates[0].is_empty());
397            // Should have more points than a simple rectangle due to end caps.
398            assert!(coordinates[0].len() > 10);
399        } else {
400            panic!("expected Polygon");
401        }
402    }
403
404    #[test]
405    fn buffer_polygon_expands() {
406        let poly = Geometry::polygon(vec![vec![
407            [0.0, 0.0],
408            [1.0, 0.0],
409            [1.0, 1.0],
410            [0.0, 1.0],
411            [0.0, 0.0],
412        ]]);
413        let buf = st_buffer(&poly, 1000.0, 32);
414        if let Geometry::Polygon { .. } = &buf {
415            let orig_bb = geometry_bbox(&poly);
416            let buf_bb = geometry_bbox(&buf);
417            // Buffered should be larger.
418            assert!(buf_bb.min_lng < orig_bb.min_lng);
419            assert!(buf_bb.max_lng > orig_bb.max_lng);
420            assert!(buf_bb.min_lat < orig_bb.min_lat);
421            assert!(buf_bb.max_lat > orig_bb.max_lat);
422        } else {
423            panic!("expected Polygon");
424        }
425    }
426}