spatio-types 0.2.3

Core spatial and temporal data types for the Spatio database
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
use crate::geo::Point;
use serde::{Deserialize, Serialize};
use std::time::SystemTime;

/// A 3D geographic point with x, y (longitude/latitude) and z (altitude/elevation).
///
/// This type represents a point in 3D space, typically used for altitude-aware
/// geospatial applications like drone tracking, aviation, or multi-floor buildings.
///
/// # Examples
///
/// ```
/// use spatio_types::point::Point3d;
/// use spatio_types::geo::Point;
///
/// // Create a 3D point for a drone at 100 meters altitude
/// let drone_position = Point3d::new(-74.0060, 40.7128, 100.0);
/// assert_eq!(drone_position.altitude(), 100.0);
///
/// // Calculate 3D distance to another point
/// let other = Point3d::new(-74.0070, 40.7138, 150.0);
/// let distance = drone_position.distance_3d(&other);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Point3d {
    /// The 2D geographic point (longitude/latitude or x/y)
    pub point: Point,
    /// The altitude/elevation/z-coordinate (in meters typically)
    pub z: f64,
}

impl Point3d {
    /// Create a new 3D point from x, y, and z coordinates.
    ///
    /// # Arguments
    ///
    /// * `x` - Longitude or x-coordinate
    /// * `y` - Latitude or y-coordinate
    /// * `z` - Altitude/elevation in meters
    ///
    /// # Examples
    ///
    /// ```
    /// use spatio_types::point::Point3d;
    ///
    /// let point = Point3d::new(-74.0060, 40.7128, 100.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn new(x: f64, y: f64, z: f64) -> Self {
        Self {
            point: Point::new(x, y),
            z,
        }
    }

    /// Create a 3D point from a 2D point and altitude.
    #[inline]
    #[must_use]
    pub fn from_point_and_altitude(point: Point, z: f64) -> Self {
        Self { point, z }
    }

    /// Get the x coordinate (longitude).
    #[inline]
    pub fn x(&self) -> f64 {
        self.point.x()
    }

    /// Get the y coordinate (latitude).
    #[inline]
    pub fn y(&self) -> f64 {
        self.point.y()
    }

    /// Get the z coordinate (altitude/elevation).
    #[inline]
    pub fn z(&self) -> f64 {
        self.z
    }

    /// Get the altitude (alias for z()).
    #[inline]
    pub fn altitude(&self) -> f64 {
        self.z
    }

    /// Get a reference to the underlying 2D point.
    #[inline]
    pub fn point_2d(&self) -> &Point {
        &self.point
    }

    /// Project this 3D point to 2D by discarding the z coordinate.
    #[inline]
    #[must_use]
    pub fn to_2d(&self) -> Point {
        self.point
    }

    /// Calculate the planar (Cartesian) Euclidean distance to another 3D point.
    ///
    /// This treats `x`, `y` and `z` as Cartesian coordinates in the same unit and
    /// applies the Pythagorean theorem. It is only meaningful when all three axes
    /// share a unit (e.g. a projected/local coordinate system in metres).
    ///
    /// For geographic longitude/latitude inputs the `x`/`y` axes are in degrees
    /// while `z` is in metres, so the result is not a physical distance — use
    /// [`Point3d::haversine_3d`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use spatio_types::point::Point3d;
    ///
    /// let p1 = Point3d::new(0.0, 0.0, 0.0);
    /// let p2 = Point3d::new(3.0, 4.0, 12.0);
    /// let distance = p1.distance_3d(&p2);
    /// assert_eq!(distance, 13.0); // 3-4-5 triangle extended to 3D
    /// ```
    #[inline]
    #[must_use]
    pub fn distance_3d(&self, other: &Point3d) -> f64 {
        let dx = self.x() - other.x();
        let dy = self.y() - other.y();
        let dz = self.z - other.z;
        (dx * dx + dy * dy + dz * dz).sqrt()
    }

    /// Calculate all distance components at once (horizontal, altitude, 3D).
    ///
    /// Computes the horizontal haversine distance once and derives the altitude
    /// difference and combined 3D distance from it, so callers needing all three
    /// avoid recomputing the haversine term per component.
    ///
    /// # Returns
    ///
    /// Tuple of (horizontal_distance, altitude_difference, distance_3d) in meters.
    ///
    /// # Examples
    ///
    /// ```
    /// use spatio_types::point::Point3d;
    ///
    /// let p1 = Point3d::new(-74.0060, 40.7128, 0.0);
    /// let p2 = Point3d::new(-74.0070, 40.7138, 100.0);
    /// let (h_dist, alt_diff, dist_3d) = p1.haversine_distances(&p2);
    /// ```
    pub fn haversine_distances(&self, other: &Point3d) -> (f64, f64, f64) {
        let horizontal_distance = self.point.haversine_distance(&other.point);
        let altitude_diff = (self.z - other.z).abs();
        let distance_3d = (horizontal_distance.powi(2) + altitude_diff.powi(2)).sqrt();

        (horizontal_distance, altitude_diff, distance_3d)
    }

    /// Calculate the haversine distance combined with altitude difference.
    ///
    /// This uses the haversine formula for the horizontal distance (considering Earth's curvature)
    /// and combines it with the altitude difference using the Pythagorean theorem.
    ///
    /// # Returns
    ///
    /// Distance in meters.
    ///
    /// # Examples
    ///
    /// ```
    /// use spatio_types::point::Point3d;
    ///
    /// let p1 = Point3d::new(-74.0060, 40.7128, 0.0);    // NYC sea level
    /// let p2 = Point3d::new(-74.0070, 40.7138, 100.0);  // Nearby, 100m up
    /// let distance = p1.haversine_3d(&p2);
    /// ```
    #[inline]
    pub fn haversine_3d(&self, other: &Point3d) -> f64 {
        let (_, _, dist_3d) = self.haversine_distances(other);
        dist_3d
    }

    /// Calculate the haversine distance on the 2D plane (ignoring altitude).
    ///
    /// # Returns
    ///
    /// Distance in meters.
    #[inline]
    pub fn haversine_2d(&self, other: &Point3d) -> f64 {
        self.point.haversine_distance(&other.point)
    }

    /// Get the altitude difference to another point.
    #[inline]
    pub fn altitude_difference(&self, other: &Point3d) -> f64 {
        (self.z - other.z).abs()
    }

    /// Convert to GeoJSON string representation.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "geojson")]
    /// # {
    /// use spatio_types::point::Point3d;
    ///
    /// let point = Point3d::new(-74.0060, 40.7128, 100.0);
    /// let json = point.to_geojson().unwrap();
    /// assert!(json.contains("Point"));
    /// # }
    /// ```
    #[cfg(feature = "geojson")]
    pub fn to_geojson(&self) -> Result<String, crate::geo::GeoJsonError> {
        use geojson::{Geometry, Value};

        let geom = Geometry::new(Value::Point(vec![self.x(), self.y(), self.z()]));
        serde_json::to_string(&geom).map_err(|e| {
            crate::geo::GeoJsonError::Serialization(format!("Failed to serialize 3D point: {}", e))
        })
    }

    /// Parse from GeoJSON string. Defaults altitude to 0.0 if not present.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "geojson")]
    /// # {
    /// use spatio_types::point::Point3d;
    ///
    /// let json = r#"{"type":"Point","coordinates":[-74.006,40.7128,100.0]}"#;
    /// let point = Point3d::from_geojson(json).unwrap();
    /// assert_eq!(point.x(), -74.006);
    /// assert_eq!(point.z(), 100.0);
    /// # }
    /// ```
    #[cfg(feature = "geojson")]
    pub fn from_geojson(geojson: &str) -> Result<Self, crate::geo::GeoJsonError> {
        use geojson::{Geometry, Value};

        let geom: Geometry = serde_json::from_str(geojson).map_err(|e| {
            crate::geo::GeoJsonError::Deserialization(format!("Failed to parse GeoJSON: {}", e))
        })?;

        match geom.value {
            Value::Point(coords) => {
                if coords.len() < 2 {
                    return Err(crate::geo::GeoJsonError::InvalidCoordinates(
                        "Point must have at least 2 coordinates".to_string(),
                    ));
                }
                let z = coords.get(2).copied().unwrap_or(0.0);
                if !(coords[0].is_finite() && coords[1].is_finite() && z.is_finite()) {
                    return Err(crate::geo::GeoJsonError::InvalidCoordinates(
                        "Point coordinates must be finite".to_string(),
                    ));
                }
                Ok(Point3d::new(coords[0], coords[1], z))
            }
            _ => Err(crate::geo::GeoJsonError::InvalidGeometry(
                "GeoJSON geometry is not a Point".to_string(),
            )),
        }
    }
}

/// A geographic point with an associated timestamp.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemporalPoint {
    pub point: Point,
    pub timestamp: SystemTime,
}

impl TemporalPoint {
    pub fn new(point: Point, timestamp: SystemTime) -> Self {
        Self { point, timestamp }
    }

    pub fn point(&self) -> &Point {
        &self.point
    }

    pub fn timestamp(&self) -> &SystemTime {
        &self.timestamp
    }
}

/// A geographic point with an associated altitude and timestamp.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TemporalPoint3D {
    pub point: Point,
    pub altitude: f64,
    pub timestamp: SystemTime,
}

impl TemporalPoint3D {
    pub fn new(point: Point, altitude: f64, timestamp: SystemTime) -> Self {
        Self {
            point,
            altitude,
            timestamp,
        }
    }

    pub fn point(&self) -> &Point {
        &self.point
    }

    pub fn altitude(&self) -> f64 {
        self.altitude
    }

    pub fn timestamp(&self) -> &SystemTime {
        &self.timestamp
    }

    /// Convert to a 3D point.
    pub fn to_point_3d(&self) -> Point3d {
        Point3d::from_point_and_altitude(self.point, self.altitude)
    }

    /// Calculate 3D haversine distance to another temporal 3D point.
    pub fn distance_to(&self, other: &TemporalPoint3D) -> f64 {
        self.to_point_3d().haversine_3d(&other.to_point_3d())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_point3d_creation() {
        let p = Point3d::new(-74.0, 40.7, 100.0);
        assert_eq!(p.x(), -74.0);
        assert_eq!(p.y(), 40.7);
        assert_eq!(p.z(), 100.0);
        assert_eq!(p.altitude(), 100.0);
    }

    #[test]
    fn test_point3d_distance_3d() {
        let p1 = Point3d::new(0.0, 0.0, 0.0);
        let p2 = Point3d::new(3.0, 4.0, 12.0);
        let distance = p1.distance_3d(&p2);
        assert_eq!(distance, 13.0);
    }

    #[test]
    fn test_point3d_altitude_difference() {
        let p1 = Point3d::new(-74.0, 40.7, 50.0);
        let p2 = Point3d::new(-74.0, 40.7, 150.0);
        assert_eq!(p1.altitude_difference(&p2), 100.0);
    }

    #[test]
    fn test_point3d_to_2d() {
        let p = Point3d::new(-74.0, 40.7, 100.0);
        let p2d = p.to_2d();
        assert_eq!(p2d.x(), -74.0);
        assert_eq!(p2d.y(), 40.7);
    }

    #[test]
    fn test_haversine_3d() {
        // Two points at same location but different altitudes
        let p1 = Point3d::new(-74.0, 40.7, 0.0);
        let p2 = Point3d::new(-74.0, 40.7, 100.0);
        let distance = p1.haversine_3d(&p2);
        // Should be approximately 100 meters (just the altitude difference)
        assert!((distance - 100.0).abs() < 0.1);
    }

    #[test]
    fn test_haversine_distances() {
        let p1 = Point3d::new(-74.0060, 40.7128, 0.0);
        let p2 = Point3d::new(-74.0070, 40.7138, 100.0);
        let (h_dist, alt_diff, dist_3d) = p1.haversine_distances(&p2);

        // Verify altitude difference is correct
        assert_eq!(alt_diff, 100.0);

        // Verify 3D distance is correct
        assert!((dist_3d - (h_dist * h_dist + alt_diff * alt_diff).sqrt()).abs() < 0.1);

        // Verify it matches individual calls
        assert!((h_dist - p1.haversine_2d(&p2)).abs() < 0.1);
        assert!((dist_3d - p1.haversine_3d(&p2)).abs() < 0.1);
    }

    #[test]
    fn test_temporal_point3d_to_point3d() {
        let temporal = TemporalPoint3D::new(Point::new(-74.0, 40.7), 100.0, SystemTime::now());
        let p3d = temporal.to_point_3d();
        assert_eq!(p3d.x(), -74.0);
        assert_eq!(p3d.y(), 40.7);
        assert_eq!(p3d.altitude(), 100.0);
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_point3d_geojson_roundtrip() {
        let original = Point3d::new(-74.0060, 40.7128, 100.0);
        let json = original.to_geojson().unwrap();
        let parsed = Point3d::from_geojson(&json).unwrap();

        assert!((original.x() - parsed.x()).abs() < 1e-10);
        assert!((original.y() - parsed.y()).abs() < 1e-10);
        assert!((original.z() - parsed.z()).abs() < 1e-10);
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_point3d_from_geojson_defaults_z() {
        let json = r#"{"type":"Point","coordinates":[-74.006,40.7128]}"#;
        let point = Point3d::from_geojson(json).unwrap();
        assert_eq!(point.z(), 0.0);
    }
}