1use crate::error::{GeolithError, Result};
9
10const WGS84_A: f64 = 6_378_137.0;
12
13const WGS84_INV_F: f64 = 298.257_223_563;
15
16const UTM_K0: f64 = 0.9996;
18
19const UTM_FALSE_EASTING: f64 = 500_000.0;
21
22const UTM_FALSE_NORTHING_SOUTH: f64 = 10_000_000.0;
24
25#[non_exhaustive]
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Crs {
29 Wgs84,
31 WebMercator,
33 Utm {
35 zone: u8,
37 north: bool,
39 },
40}
41
42impl Crs {
43 pub fn from_epsg(code: u32) -> Result<Self> {
54 match code {
55 4326 => Ok(Self::Wgs84),
56 3857 | 900_913 | 3785 => Ok(Self::WebMercator),
57 32_601..=32_660 => Ok(Self::Utm {
58 zone: (code - 32_600) as u8,
59 north: true,
60 }),
61 32_701..=32_760 => Ok(Self::Utm {
62 zone: (code - 32_700) as u8,
63 north: false,
64 }),
65 25_828..=25_838 => Ok(Self::Utm {
66 zone: (code - 25_800) as u8,
67 north: true,
68 }),
69 7_791..=7_793 => Ok(Self::Utm {
70 zone: (code - 7_759) as u8,
71 north: true,
72 }),
73 26_901..=26_923 => Ok(Self::Utm {
74 zone: (code - 26_900) as u8,
75 north: true,
76 }),
77 other => Err(GeolithError::Crs(format!(
78 "unsupported EPSG:{other} — supported: 4326, 3857, UTM zones \
79 (326xx/327xx WGS84, 258xx ETRS89, 7791-7793 RDN2008, 269xx NAD83)"
80 ))),
81 }
82 }
83
84 #[must_use]
86 pub fn epsg(&self) -> u32 {
87 match *self {
88 Self::Wgs84 => 4326,
89 Self::WebMercator => 3857,
90 Self::Utm { zone, north } => {
91 let base = if north { 32_600 } else { 32_700 };
92 base + u32::from(zone)
93 }
94 }
95 }
96
97 #[must_use]
99 pub fn to_wgs84(&self, x: f64, y: f64) -> (f64, f64) {
100 match *self {
101 Self::Wgs84 => (x, y),
102 Self::WebMercator => web_mercator_to_wgs84(x, y),
103 Self::Utm { zone, north } => utm_to_wgs84(x, y, zone, north),
104 }
105 }
106
107 #[must_use]
109 pub fn from_wgs84(&self, lon: f64, lat: f64) -> (f64, f64) {
110 match *self {
111 Self::Wgs84 => (lon, lat),
112 Self::WebMercator => wgs84_to_web_mercator(lon, lat),
113 Self::Utm { zone, north } => wgs84_to_utm(lon, lat, zone, north),
114 }
115 }
116}
117
118#[must_use]
120fn e_squared() -> f64 {
121 let f = 1.0 / WGS84_INV_F;
122 f * (2.0 - f)
123}
124
125#[must_use]
127fn web_mercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
128 let lon = (x / WGS84_A).to_degrees();
129 let lat = ((y / WGS84_A).exp().atan() * 2.0 - std::f64::consts::FRAC_PI_2).to_degrees();
130 (lon, lat)
131}
132
133#[must_use]
135fn wgs84_to_web_mercator(lon: f64, lat: f64) -> (f64, f64) {
136 let x = lon.to_radians() * WGS84_A;
137 let clamped = lat.clamp(-89.999_999, 89.999_999).to_radians();
138 let y = (std::f64::consts::FRAC_PI_4 + clamped / 2.0).tan().ln() * WGS84_A;
139 (x, y)
140}
141
142#[must_use]
144fn utm_central_meridian(zone: u8) -> f64 {
145 f64::from(zone) * 6.0 - 183.0
146}
147
148#[must_use]
150fn utm_to_wgs84(easting: f64, northing: f64, zone: u8, north: bool) -> (f64, f64) {
151 let e2 = e_squared();
152 let ep2 = e2 / (1.0 - e2);
153
154 let x = easting - UTM_FALSE_EASTING;
155 let y = if north {
156 northing
157 } else {
158 northing - UTM_FALSE_NORTHING_SOUTH
159 };
160
161 let m = y / UTM_K0;
162 let mu = m / (WGS84_A * (1.0 - e2 / 4.0 - 3.0 * e2 * e2 / 64.0 - 5.0 * e2.powi(3) / 256.0));
163
164 let sqrt_1_e2 = (1.0 - e2).sqrt();
165 let e1 = (1.0 - sqrt_1_e2) / (1.0 + sqrt_1_e2);
166
167 let phi1 = mu
168 + (3.0 * e1 / 2.0 - 27.0 * e1.powi(3) / 32.0) * (2.0 * mu).sin()
169 + (21.0 * e1 * e1 / 16.0 - 55.0 * e1.powi(4) / 32.0) * (4.0 * mu).sin()
170 + (151.0 * e1.powi(3) / 96.0) * (6.0 * mu).sin()
171 + (1097.0 * e1.powi(4) / 512.0) * (8.0 * mu).sin();
172
173 let (sin_phi1, cos_phi1) = phi1.sin_cos();
174 let tan_phi1 = sin_phi1 / cos_phi1;
175
176 let c1 = ep2 * cos_phi1 * cos_phi1;
177 let t1 = tan_phi1 * tan_phi1;
178 let denom = 1.0 - e2 * sin_phi1 * sin_phi1;
179 let n1 = WGS84_A / denom.sqrt();
180 let r1 = WGS84_A * (1.0 - e2) / denom.powf(1.5);
181 let d = x / (n1 * UTM_K0);
182
183 let d2 = d * d;
184 let d4 = d2 * d2;
185 let d6 = d4 * d2;
186
187 let lat = phi1
188 - (n1 * tan_phi1 / r1)
189 * (d2 / 2.0 - (5.0 + 3.0 * t1 + 10.0 * c1 - 4.0 * c1 * c1 - 9.0 * ep2) * d4 / 24.0
190 + (61.0 + 90.0 * t1 + 298.0 * c1 + 45.0 * t1 * t1 - 252.0 * ep2 - 3.0 * c1 * c1)
191 * d6
192 / 720.0);
193
194 let lon = utm_central_meridian(zone).to_radians()
195 + (d - (1.0 + 2.0 * t1 + c1) * d2 * d / 6.0
196 + (5.0 - 2.0 * c1 + 28.0 * t1 - 3.0 * c1 * c1 + 8.0 * ep2 + 24.0 * t1 * t1) * d4 * d
197 / 120.0)
198 / cos_phi1;
199
200 (lon.to_degrees(), lat.to_degrees())
201}
202
203#[must_use]
205fn wgs84_to_utm(lon: f64, lat: f64, zone: u8, north: bool) -> (f64, f64) {
206 let e2 = e_squared();
207 let ep2 = e2 / (1.0 - e2);
208
209 let phi = lat.to_radians();
210 let lambda = lon.to_radians();
211 let lambda0 = utm_central_meridian(zone).to_radians();
212
213 let (sin_phi, cos_phi) = phi.sin_cos();
214 let tan_phi = sin_phi / cos_phi;
215
216 let n = WGS84_A / (1.0 - e2 * sin_phi * sin_phi).sqrt();
217 let t = tan_phi * tan_phi;
218 let c = ep2 * cos_phi * cos_phi;
219 let a_term = cos_phi * (lambda - lambda0);
220
221 let m = WGS84_A
222 * ((1.0 - e2 / 4.0 - 3.0 * e2 * e2 / 64.0 - 5.0 * e2.powi(3) / 256.0) * phi
223 - (3.0 * e2 / 8.0 + 3.0 * e2 * e2 / 32.0 + 45.0 * e2.powi(3) / 1024.0)
224 * (2.0 * phi).sin()
225 + (15.0 * e2 * e2 / 256.0 + 45.0 * e2.powi(3) / 1024.0) * (4.0 * phi).sin()
226 - (35.0 * e2.powi(3) / 3072.0) * (6.0 * phi).sin());
227
228 let a2 = a_term * a_term;
229 let a3 = a2 * a_term;
230 let a4 = a2 * a2;
231 let a5 = a4 * a_term;
232 let a6 = a4 * a2;
233
234 let easting = UTM_K0
235 * n
236 * (a_term
237 + (1.0 - t + c) * a3 / 6.0
238 + (5.0 - 18.0 * t + t * t + 72.0 * c - 58.0 * ep2) * a5 / 120.0)
239 + UTM_FALSE_EASTING;
240
241 let mut northing = UTM_K0
242 * (m + n
243 * tan_phi
244 * (a2 / 2.0
245 + (5.0 - t + 9.0 * c + 4.0 * c * c) * a4 / 24.0
246 + (61.0 - 58.0 * t + t * t + 600.0 * c - 330.0 * ep2) * a6 / 720.0));
247
248 if !north {
249 northing += UTM_FALSE_NORTHING_SOUTH;
250 }
251
252 (easting, northing)
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn epsg_roundtrip_for_supported_codes() {
261 for code in [4326_u32, 3857, 32_632, 32_701, 32_760] {
262 let crs = Crs::from_epsg(code).expect("supported code");
263 assert_eq!(crs.epsg(), code);
264 }
265 }
266
267 #[test]
268 fn epsg_aliases_map_to_web_mercator() {
269 assert_eq!(
270 Crs::from_epsg(900_913).expect("alias"),
271 Crs::WebMercator,
272 "900913 is the legacy Web Mercator alias"
273 );
274 assert_eq!(Crs::from_epsg(3785).expect("alias"), Crs::WebMercator);
275 }
276
277 #[test]
278 fn unsupported_epsg_is_rejected() {
279 let err = Crs::from_epsg(27_700).expect_err("OSGB is unsupported");
280 assert!(matches!(err, GeolithError::Crs(_)));
281 }
282
283 #[test]
286 fn utm_compatible_datums_map_to_wgs84_zones() {
287 assert_eq!(
288 Crs::from_epsg(7_791).expect("RDN2008 32N"),
289 Crs::Utm {
290 zone: 32,
291 north: true
292 }
293 );
294 assert_eq!(
295 Crs::from_epsg(25_832).expect("ETRS89 32N"),
296 Crs::Utm {
297 zone: 32,
298 north: true
299 }
300 );
301 assert_eq!(
302 Crs::from_epsg(26_910).expect("NAD83 10N"),
303 Crs::Utm {
304 zone: 10,
305 north: true
306 }
307 );
308 assert!(
309 Crs::from_epsg(7_794).is_err(),
310 "RDN2008 / Italy zone is not a UTM zone and must be rejected"
311 );
312 }
313
314 #[test]
315 fn wgs84_is_identity() {
316 let crs = Crs::Wgs84;
317 let (lon, lat) = crs.to_wgs84(7.9797, 45.9756);
318 assert!((lon - 7.9797).abs() < 1e-12);
319 assert!((lat - 45.9756).abs() < 1e-12);
320 }
321
322 #[test]
323 fn web_mercator_roundtrip() {
324 let crs = Crs::WebMercator;
325 let (x, y) = crs.from_wgs84(7.9797, 45.9756);
326 let (lon, lat) = crs.to_wgs84(x, y);
327 assert!((lon - 7.9797).abs() < 1e-9, "lon roundtrip: {lon}");
328 assert!((lat - 45.9756).abs() < 1e-9, "lat roundtrip: {lat}");
329 }
330
331 #[test]
332 fn web_mercator_origin_is_zero() {
333 let (x, y) = Crs::WebMercator.from_wgs84(0.0, 0.0);
334 assert!(x.abs() < 1e-9);
335 assert!(y.abs() < 1e-9);
336 }
337
338 #[test]
341 fn utm_north_roundtrip_belvedere() {
342 let crs = Crs::Utm {
343 zone: 32,
344 north: true,
345 };
346 let (lon0, lat0) = (7.9097, 45.9256);
347 let (e, n) = crs.from_wgs84(lon0, lat0);
348
349 assert!(
350 (400_000.0..=600_000.0).contains(&e),
351 "easting near central meridian: {e}"
352 );
353 assert!(
354 (5_000_000.0..=5_200_000.0).contains(&n),
355 "northing for 45.9N: {n}"
356 );
357
358 let (lon, lat) = crs.to_wgs84(e, n);
359 assert!((lon - lon0).abs() < 1e-7, "lon roundtrip: {lon}");
360 assert!((lat - lat0).abs() < 1e-7, "lat roundtrip: {lat}");
361 }
362
363 #[test]
364 fn utm_central_meridian_matches_zone_definition() {
365 assert!((utm_central_meridian(1) + 177.0).abs() < 1e-12);
366 assert!((utm_central_meridian(31) - 3.0).abs() < 1e-12);
367 assert!((utm_central_meridian(60) - 177.0).abs() < 1e-12);
368 }
369
370 #[test]
371 fn utm_central_meridian_has_false_easting_exactly() {
372 let crs = Crs::Utm {
373 zone: 32,
374 north: true,
375 };
376 let (e, _) = crs.from_wgs84(utm_central_meridian(32), 45.0);
377 assert!(
378 (e - UTM_FALSE_EASTING).abs() < 1e-6,
379 "central meridian maps to false easting: {e}"
380 );
381 }
382
383 #[test]
384 fn utm_south_roundtrip_applies_false_northing() {
385 let crs = Crs::Utm {
386 zone: 55,
387 north: false,
388 };
389 let (lon0, lat0) = (147.0, -42.0);
390 let (e, n) = crs.from_wgs84(lon0, lat0);
391 assert!(
392 n > 5_000_000.0,
393 "southern northing carries the false offset: {n}"
394 );
395 let (lon, lat) = crs.to_wgs84(e, n);
396 assert!((lon - lon0).abs() < 1e-7, "lon roundtrip: {lon}");
397 assert!((lat - lat0).abs() < 1e-7, "lat roundtrip: {lat}");
398 }
399
400 #[test]
401 fn utm_equator_northing_is_zero_in_north() {
402 let crs = Crs::Utm {
403 zone: 32,
404 north: true,
405 };
406 let (_, n) = crs.from_wgs84(9.0, 0.0);
407 assert!(n.abs() < 1e-6, "equator northing in north zone: {n}");
408 }
409}