proj-core 0.4.0

Pure-Rust coordinate transformation library with no C dependencies
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use crate::datum::Datum;
use crate::error::{Error, Result};

/// A coordinate system's projected linear unit.
///
/// The stored value is the conversion factor from one native unit to meters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinearUnit {
    meters_per_unit: f64,
}

impl LinearUnit {
    /// Metre-based projected coordinates.
    pub const fn metre() -> Self {
        Self {
            meters_per_unit: 1.0,
        }
    }

    /// Alias for [`LinearUnit::metre`].
    pub const fn meter() -> Self {
        Self::metre()
    }

    /// Kilometer-based projected coordinates.
    pub const fn kilometre() -> Self {
        Self {
            meters_per_unit: 1000.0,
        }
    }

    /// Alias for [`LinearUnit::kilometre`].
    pub const fn kilometer() -> Self {
        Self::kilometre()
    }

    /// International foot-based projected coordinates.
    pub const fn foot() -> Self {
        Self {
            meters_per_unit: 0.3048,
        }
    }

    /// US survey foot-based projected coordinates.
    pub const fn us_survey_foot() -> Self {
        Self {
            meters_per_unit: 0.3048006096012192,
        }
    }

    /// Construct a custom projected linear unit from its meter conversion factor.
    pub fn from_meters_per_unit(meters_per_unit: f64) -> Result<Self> {
        if !meters_per_unit.is_finite() || meters_per_unit <= 0.0 {
            return Err(Error::InvalidDefinition(
                "linear unit conversion factor must be a finite positive number".into(),
            ));
        }

        Ok(Self { meters_per_unit })
    }

    /// Return the number of meters represented by one native projected unit.
    pub const fn meters_per_unit(self) -> f64 {
        self.meters_per_unit
    }

    /// Convert a native projected coordinate value into meters.
    pub const fn to_meters(self, value: f64) -> f64 {
        value * self.meters_per_unit
    }

    /// Convert a meter value into the native projected unit.
    pub const fn from_meters(self, value: f64) -> f64 {
        value / self.meters_per_unit
    }
}

/// A Coordinate Reference System definition.
#[derive(Debug, Clone)]
pub enum CrsDef {
    /// Geographic CRS (lon/lat in degrees).
    Geographic(GeographicCrsDef),
    /// Projected CRS (easting/northing in the CRS's native linear unit).
    Projected(ProjectedCrsDef),
}

impl CrsDef {
    /// Get the datum for this CRS.
    pub fn datum(&self) -> &Datum {
        match self {
            CrsDef::Geographic(g) => g.datum(),
            CrsDef::Projected(p) => p.datum(),
        }
    }

    /// Get the EPSG code for this CRS.
    pub fn epsg(&self) -> u32 {
        match self {
            CrsDef::Geographic(g) => g.epsg(),
            CrsDef::Projected(p) => p.epsg(),
        }
    }

    /// Get the CRS name.
    pub fn name(&self) -> &str {
        match self {
            CrsDef::Geographic(g) => g.name(),
            CrsDef::Projected(p) => p.name(),
        }
    }

    /// Returns true if this is a geographic CRS.
    pub fn is_geographic(&self) -> bool {
        matches!(self, CrsDef::Geographic(_))
    }

    /// Returns true if this is a projected CRS.
    pub fn is_projected(&self) -> bool {
        matches!(self, CrsDef::Projected(_))
    }

    /// Returns the geographic CRS EPSG code used for operation selection, when known.
    pub fn base_geographic_crs_epsg(&self) -> Option<u32> {
        match self {
            CrsDef::Geographic(g) if g.epsg() != 0 => Some(g.epsg()),
            CrsDef::Projected(p) if p.base_geographic_crs_epsg() != 0 => {
                Some(p.base_geographic_crs_epsg())
            }
            _ => None,
        }
    }

    /// Returns true when two CRS definitions map to the same internal semantics.
    pub fn semantically_equivalent(&self, other: &Self) -> bool {
        match (self, other) {
            (CrsDef::Geographic(a), CrsDef::Geographic(b)) => a.datum().same_datum(b.datum()),
            (CrsDef::Projected(a), CrsDef::Projected(b)) => {
                a.datum().same_datum(b.datum())
                    && approx_eq(a.linear_unit_to_meter(), b.linear_unit_to_meter())
                    && projection_methods_equivalent(&a.method(), &b.method())
            }
            _ => false,
        }
    }
}

/// Definition of a geographic CRS (longitude, latitude in degrees).
#[derive(Debug, Clone)]
pub struct GeographicCrsDef {
    epsg: u32,
    datum: Datum,
    name: &'static str,
}

impl GeographicCrsDef {
    pub const fn new(epsg: u32, datum: Datum, name: &'static str) -> Self {
        Self { epsg, datum, name }
    }

    pub const fn epsg(&self) -> u32 {
        self.epsg
    }

    pub const fn datum(&self) -> &Datum {
        &self.datum
    }

    pub const fn name(&self) -> &'static str {
        self.name
    }
}

/// Definition of a projected CRS (easting, northing in the CRS's native linear unit).
#[derive(Debug, Clone)]
pub struct ProjectedCrsDef {
    epsg: u32,
    base_geographic_crs_epsg: u32,
    datum: Datum,
    method: ProjectionMethod,
    linear_unit: LinearUnit,
    name: &'static str,
}

impl ProjectedCrsDef {
    pub const fn new(
        epsg: u32,
        datum: Datum,
        method: ProjectionMethod,
        linear_unit: LinearUnit,
        name: &'static str,
    ) -> Self {
        Self::new_with_base_geographic_crs(epsg, 0, datum, method, linear_unit, name)
    }

    pub const fn new_with_base_geographic_crs(
        epsg: u32,
        base_geographic_crs_epsg: u32,
        datum: Datum,
        method: ProjectionMethod,
        linear_unit: LinearUnit,
        name: &'static str,
    ) -> Self {
        Self {
            epsg,
            base_geographic_crs_epsg,
            datum,
            method,
            linear_unit,
            name,
        }
    }

    pub const fn epsg(&self) -> u32 {
        self.epsg
    }

    pub const fn datum(&self) -> &Datum {
        &self.datum
    }

    pub const fn base_geographic_crs_epsg(&self) -> u32 {
        self.base_geographic_crs_epsg
    }

    pub const fn method(&self) -> ProjectionMethod {
        self.method
    }

    pub const fn linear_unit(&self) -> LinearUnit {
        self.linear_unit
    }

    pub const fn linear_unit_to_meter(&self) -> f64 {
        self.linear_unit.meters_per_unit()
    }

    pub const fn name(&self) -> &'static str {
        self.name
    }
}

/// All supported projection methods with their parameters.
///
/// Angle parameters are stored in **degrees**. Conversion to radians happens
/// at projection construction time (once), not per-transform.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProjectionMethod {
    /// Web Mercator (EPSG:3857) — spherical Mercator on WGS84 semi-major axis.
    WebMercator,

    /// Transverse Mercator (includes UTM zones).
    TransverseMercator {
        /// Central meridian (degrees).
        lon0: f64,
        /// Latitude of origin (degrees).
        lat0: f64,
        /// Scale factor on central meridian.
        k0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Polar Stereographic.
    PolarStereographic {
        /// Central meridian / straight vertical longitude (degrees).
        lon0: f64,
        /// Latitude of true scale (degrees). Determines the hemisphere.
        lat_ts: f64,
        /// Scale factor (used when lat_ts = ±90°, otherwise derived from lat_ts).
        k0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Lambert Conformal Conic (1SP or 2SP).
    LambertConformalConic {
        /// Central meridian (degrees).
        lon0: f64,
        /// Latitude of origin (degrees).
        lat0: f64,
        /// First standard parallel (degrees).
        lat1: f64,
        /// Second standard parallel (degrees). Set equal to lat1 for 1SP variant.
        lat2: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Albers Equal Area Conic.
    AlbersEqualArea {
        /// Central meridian (degrees).
        lon0: f64,
        /// Latitude of origin (degrees).
        lat0: f64,
        /// First standard parallel (degrees).
        lat1: f64,
        /// Second standard parallel (degrees).
        lat2: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Lambert Azimuthal Equal Area.
    LambertAzimuthalEqualArea {
        /// Longitude of natural origin (degrees).
        lon0: f64,
        /// Latitude of natural origin (degrees).
        lat0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Lambert Azimuthal Equal Area (spherical).
    LambertAzimuthalEqualAreaSpherical {
        /// Longitude of natural origin (degrees).
        lon0: f64,
        /// Latitude of natural origin (degrees).
        lat0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// EPSG Oblique Stereographic (Roussilhe / double stereographic).
    ObliqueStereographic {
        /// Longitude of natural origin (degrees).
        lon0: f64,
        /// Latitude of natural origin (degrees).
        lat0: f64,
        /// Scale factor at natural origin.
        k0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Hotine Oblique Mercator / Rectified Skew Orthomorphic.
    HotineObliqueMercator {
        /// Latitude of projection centre (degrees).
        latc: f64,
        /// Longitude of projection centre (degrees).
        lonc: f64,
        /// Azimuth of central line at projection centre (degrees clockwise from north).
        azimuth: f64,
        /// Angle from rectified to skew grid (degrees).
        rectified_grid_angle: f64,
        /// Scale factor at projection centre.
        k0: f64,
        /// False easting or easting at projection centre (meters).
        false_easting: f64,
        /// False northing or northing at projection centre (meters).
        false_northing: f64,
        /// EPSG variant B offsets the natural origin to the projection centre.
        variant_b: bool,
    },

    /// Cassini-Soldner.
    CassiniSoldner {
        /// Longitude of natural origin (degrees).
        lon0: f64,
        /// Latitude of natural origin (degrees).
        lat0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Standard Mercator (ellipsoidal, distinct from Web Mercator).
    Mercator {
        /// Central meridian (degrees).
        lon0: f64,
        /// Latitude of true scale (degrees). 0 for 1SP variant.
        lat_ts: f64,
        /// Scale factor (for 1SP when lat_ts = 0).
        k0: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },

    /// Equidistant Cylindrical / Plate Carrée.
    EquidistantCylindrical {
        /// Central meridian (degrees).
        lon0: f64,
        /// Latitude of true scale (degrees).
        lat_ts: f64,
        /// False easting (meters).
        false_easting: f64,
        /// False northing (meters).
        false_northing: f64,
    },
}

fn projection_methods_equivalent(a: &ProjectionMethod, b: &ProjectionMethod) -> bool {
    match (a, b) {
        (ProjectionMethod::WebMercator, ProjectionMethod::WebMercator) => true,
        (
            ProjectionMethod::TransverseMercator {
                lon0: a_lon0,
                lat0: a_lat0,
                k0: a_k0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::TransverseMercator {
                lon0: b_lon0,
                lat0: b_lat0,
                k0: b_k0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_k0, *b_k0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::PolarStereographic {
                lon0: a_lon0,
                lat_ts: a_lat_ts,
                k0: a_k0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::PolarStereographic {
                lon0: b_lon0,
                lat_ts: b_lat_ts,
                k0: b_k0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat_ts, *b_lat_ts)
                && approx_eq(*a_k0, *b_k0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::LambertConformalConic {
                lon0: a_lon0,
                lat0: a_lat0,
                lat1: a_lat1,
                lat2: a_lat2,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::LambertConformalConic {
                lon0: b_lon0,
                lat0: b_lat0,
                lat1: b_lat1,
                lat2: b_lat2,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_lat1, *b_lat1)
                && approx_eq(*a_lat2, *b_lat2)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::AlbersEqualArea {
                lon0: a_lon0,
                lat0: a_lat0,
                lat1: a_lat1,
                lat2: a_lat2,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::AlbersEqualArea {
                lon0: b_lon0,
                lat0: b_lat0,
                lat1: b_lat1,
                lat2: b_lat2,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_lat1, *b_lat1)
                && approx_eq(*a_lat2, *b_lat2)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::LambertAzimuthalEqualArea {
                lon0: a_lon0,
                lat0: a_lat0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::LambertAzimuthalEqualArea {
                lon0: b_lon0,
                lat0: b_lat0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::LambertAzimuthalEqualAreaSpherical {
                lon0: a_lon0,
                lat0: a_lat0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::LambertAzimuthalEqualAreaSpherical {
                lon0: b_lon0,
                lat0: b_lat0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::ObliqueStereographic {
                lon0: a_lon0,
                lat0: a_lat0,
                k0: a_k0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::ObliqueStereographic {
                lon0: b_lon0,
                lat0: b_lat0,
                k0: b_k0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_k0, *b_k0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::HotineObliqueMercator {
                latc: a_latc,
                lonc: a_lonc,
                azimuth: a_azimuth,
                rectified_grid_angle: a_rectified_grid_angle,
                k0: a_k0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
                variant_b: a_variant_b,
            },
            ProjectionMethod::HotineObliqueMercator {
                latc: b_latc,
                lonc: b_lonc,
                azimuth: b_azimuth,
                rectified_grid_angle: b_rectified_grid_angle,
                k0: b_k0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
                variant_b: b_variant_b,
            },
        ) => {
            a_variant_b == b_variant_b
                && approx_eq(*a_latc, *b_latc)
                && approx_eq(*a_lonc, *b_lonc)
                && approx_eq(*a_azimuth, *b_azimuth)
                && approx_eq(*a_rectified_grid_angle, *b_rectified_grid_angle)
                && approx_eq(*a_k0, *b_k0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::CassiniSoldner {
                lon0: a_lon0,
                lat0: a_lat0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::CassiniSoldner {
                lon0: b_lon0,
                lat0: b_lat0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat0, *b_lat0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::Mercator {
                lon0: a_lon0,
                lat_ts: a_lat_ts,
                k0: a_k0,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::Mercator {
                lon0: b_lon0,
                lat_ts: b_lat_ts,
                k0: b_k0,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat_ts, *b_lat_ts)
                && approx_eq(*a_k0, *b_k0)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        (
            ProjectionMethod::EquidistantCylindrical {
                lon0: a_lon0,
                lat_ts: a_lat_ts,
                false_easting: a_false_easting,
                false_northing: a_false_northing,
            },
            ProjectionMethod::EquidistantCylindrical {
                lon0: b_lon0,
                lat_ts: b_lat_ts,
                false_easting: b_false_easting,
                false_northing: b_false_northing,
            },
        ) => {
            approx_eq(*a_lon0, *b_lon0)
                && approx_eq(*a_lat_ts, *b_lat_ts)
                && approx_eq(*a_false_easting, *b_false_easting)
                && approx_eq(*a_false_northing, *b_false_northing)
        }
        _ => false,
    }
}

fn approx_eq(a: f64, b: f64) -> bool {
    (a - b).abs() < 1e-12
}

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

    #[test]
    fn geographic_crs_is_geographic() {
        let crs = CrsDef::Geographic(GeographicCrsDef::new(4326, datum::WGS84, "WGS 84"));
        assert!(crs.is_geographic());
        assert!(!crs.is_projected());
        assert_eq!(crs.epsg(), 4326);
    }

    #[test]
    fn projected_crs_is_projected() {
        let crs = CrsDef::Projected(ProjectedCrsDef::new(
            3857,
            datum::WGS84,
            ProjectionMethod::WebMercator,
            LinearUnit::metre(),
            "WGS 84 / Pseudo-Mercator",
        ));
        assert!(crs.is_projected());
        assert!(!crs.is_geographic());
        assert_eq!(crs.epsg(), 3857);
    }

    #[test]
    fn linear_unit_validates_positive_finite_conversion() {
        assert!(LinearUnit::from_meters_per_unit(0.3048).is_ok());
        assert!(LinearUnit::from_meters_per_unit(0.0).is_err());
        assert!(LinearUnit::from_meters_per_unit(f64::NAN).is_err());
    }
}