Skip to main content

unit_sphere/
lib.rs

1// Copyright (c) 2024-2026 Ken Barker
2
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation the
6// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7// sell copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21//! # unit-sphere
22//!
23//! [![crates.io](https://img.shields.io/crates/v/unit-sphere.svg)](https://crates.io/crates/unit-sphere)
24//! [![docs.io](https://docs.rs/unit-sphere/badge.svg)](https://docs.rs/unit-sphere/)
25//! [![License](https://img.shields.io/badge/License-MIT-blue)](https://opensource.org/license/mit/)
26//! [![Rust](https://github.com/kenba/unit-sphere-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/kenba/unit-sphere-rs/actions)
27//! [![codecov](https://codecov.io/gh/kenba/unit-sphere-rs/graph/badge.svg?token=G1H1XINERW)](https://codecov.io/gh/kenba/unit-sphere-rs)
28//!
29//! A library for performing geometric calculations on the surface of a sphere.
30//!
31//! The library uses a combination of spherical trigonometry and vector geometry
32//! to perform [great-circle navigation](https://en.wikipedia.org/wiki/Great-circle_navigation)
33//! on the surface of a unit sphere, see *Figure 1*.
34//!
35//! ![great circle arc](https://via-technology.aero/img/navigation/sphere/great_circle_arc.svg)\
36//! *Figure 1 A Great Circle Arc*
37//!
38//! A [great circle](https://en.wikipedia.org/wiki/Great_circle) is the
39//! shortest path between positions on the surface of a sphere.
40//! It is the spherical equivalent of a straight line in planar geometry.
41//!
42//! ## Spherical trigonometry
43//!
44//! A great circle path between positions may be found using
45//! [spherical trigonometry](https://en.wikipedia.org/wiki/Spherical_trigonometry).
46//!
47//! The [course](https://en.wikipedia.org/wiki/Great-circle_navigation#Course)
48//! (initial azimuth) of a great circle can be calculated from the
49//! latitudes and longitudes of the start and end points.
50//! While great circle distance can also be calculated from the latitudes and
51//! longitudes of the start and end points using the
52//! [haversine formula](https://en.wikipedia.org/wiki/Haversine_formula).
53//! The resulting distance in `Radians` can be converted to the required units by
54//! multiplying the distance by the Earth radius measured in the required units.
55//!
56//! ## Vector geometry
57//!
58//! Points on the surface of a sphere and great circle poles may be represented
59//! by 3D [vectors](https://www.movable-type.co.uk/scripts/latlong-vectors.html).\
60//! Many calculations are simpler and quicker using vectors than spherical trigonometry.
61//!
62//! ![Spherical Vector Coordinates](https://via-technology.aero/img/navigation/sphere/ecef_coordinates.svg)\
63//! *Figure 2 Spherical Vector Coordinates*
64//!
65//! For example, the across track distance of a point from a great circle can
66//! be calculated from the [dot product](https://en.wikipedia.org/wiki/Dot_product)
67//! of the point and the great circle pole vectors.
68//! While intersection points of great circles can simply be calculated from
69//! the [cross product](https://en.wikipedia.org/wiki/Cross_product) of their
70//! pole vectors.
71//!
72//! ## Design
73//!
74//! The `great_circle` module performs spherical trigonometric calculations
75//! and the `vector` module performs vector geometry calculations.
76//! See: [spherical vector geometry](https://via-technology.aero/navigation/spherical-vector-geometry/).
77//!
78//! The software uses types: `Angle`, `Degrees` and `Radians` from the
79//! [angle-sc](https://crates.io/crates/angle-sc) crate.
80//!
81//! The library is declared [no_std](https://docs.rust-embedded.org/book/intro/no-std.html)
82//! so it can be used in embedded applications.
83//!
84//! ## Example
85//!
86//! The following example calculates the intersection between two Great Circle `Arc`s
87//! it is taken from Charles Karney's original solution to
88//! [Intersection between two geodesic lines](https://sourceforge.net/p/geographiclib/discussion/1026621/thread/21aaff9f/#fe0a).
89//!
90//! ```rust
91//! use unit_sphere::{Arc, Degrees, LatLong, calculate_intersection_point};
92//! use angle_sc::is_within_tolerance;
93//!
94//! let istanbul = LatLong::new(Degrees(42.0), Degrees(29.0));
95//! let washington = LatLong::new(Degrees(39.0), Degrees(-77.0));
96//! let reyjavik = LatLong::new(Degrees(64.0), Degrees(-22.0));
97//! let accra = LatLong::new(Degrees(6.0), Degrees(0.0));
98//!
99//! let arc_0 = Arc::try_from((&istanbul, &washington)).unwrap();
100//! let arc_1 = Arc::try_from((&reyjavik, &accra)).unwrap();
101//!
102//! let intersection_point = calculate_intersection_point(&arc_0, &arc_1).unwrap();
103//! let lat_long = LatLong::from(&intersection_point);
104//! // Geodesic intersection latitude is 54.7170296089477
105//! assert!(is_within_tolerance(54.72, lat_long.lat().0, 0.05));
106//! // Geodesic intersection longitude is -14.56385574430775
107//! assert!(is_within_tolerance(-14.56, lat_long.lon().0, 0.02));
108//! ```
109
110#![cfg_attr(not(test), no_std)]
111
112extern crate angle_sc;
113extern crate nalgebra as na;
114
115pub mod great_circle;
116pub mod vector;
117
118pub use angle_sc::{Angle, Degrees, Radians, Validate};
119pub use na::Vector3;
120use num_traits::{Float, float::FloatConst};
121use thiserror::Error;
122
123pub const NINETY: f64 = 90.0;
124
125/// Test whether a latitude in degrees is a valid latitude.
126///
127/// I.e. whether it lies in the range: -90.0 <= degrees <= 90.0
128#[allow(clippy::missing_panics_doc)]
129#[must_use]
130pub fn is_valid_latitude<T: Float>(degrees: T) -> bool {
131    let ninety = T::from(NINETY).expect("Could not convert constant to Float");
132    (-ninety..=ninety).contains(&degrees)
133}
134
135/// Test whether a longitude in degrees is a valid longitude.
136///
137/// I.e. whether it lies in the range: -180.0 <= degrees <= 180.0
138#[allow(clippy::missing_panics_doc)]
139#[must_use]
140pub fn is_valid_longitude<T: Float>(degrees: T) -> bool {
141    let one_eighty =
142        T::from(angle_sc::ONE_HUNDRED_AND_EIGHTY).expect("Could not convert constant to Float");
143    (-one_eighty..=one_eighty).contains(&degrees)
144}
145
146/// A position as a latitude and longitude pair of `Degrees`.
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub struct LatLong<T: Float> {
149    lat: Degrees<T>,
150    lon: Degrees<T>,
151}
152
153impl<T: Float> Validate for LatLong<T> {
154    /// Test whether a `LatLong` is valid.
155    ///
156    /// I.e. whether the latitude lies in the range: -90.0 <= lat <= 90.0
157    /// and the longitude lies in the range: -180.0 <= lon <= 180.0
158    fn is_valid(&self) -> bool {
159        is_valid_latitude(self.lat.0) && is_valid_longitude(self.lon.0)
160    }
161}
162
163impl<T: Float> LatLong<T> {
164    #[must_use]
165    pub const fn new(lat: Degrees<T>, lon: Degrees<T>) -> Self {
166        Self { lat, lon }
167    }
168
169    #[must_use]
170    pub const fn lat(&self) -> Degrees<T> {
171        self.lat
172    }
173
174    #[must_use]
175    pub const fn lon(&self) -> Degrees<T> {
176        self.lon
177    }
178
179    /// Determine whether the `LatLong` is South of  a.
180    ///
181    /// It compares the latitude of the two points.
182    /// * `a` - the other `LatLong`.
183    ///
184    /// returns true if South of a, false otherwise.
185    #[must_use]
186    pub fn is_south_of(&self, a: &Self) -> bool {
187        self.lat.0 < a.lat.0
188    }
189
190    /// Determine whether the `LatLong` is West of `LatLong` a.
191    ///
192    /// It compares the longitude difference of the two points.
193    /// * `a`, `b` - the points.
194    ///
195    /// returns true if a is West of b, false otherwise.
196    #[must_use]
197    pub fn is_west_of(&self, a: &Self) -> bool {
198        (a.lon() - self.lon).0 < T::zero()
199    }
200}
201
202/// A Error type for an invalid `LatLong`.
203#[derive(Error, Debug, Eq, PartialEq)]
204pub enum LatLongError<T> {
205    #[error("invalid latitude value: `{0}`")]
206    Latitude(T),
207    #[error("invalid longitude value: `{0}`")]
208    Longitude(T),
209}
210
211impl<T> TryFrom<(T, T)> for LatLong<T>
212where
213    T: Float,
214{
215    type Error = LatLongError<T>;
216
217    /// Attempt to convert a pair of f64 values in latitude, longitude order.
218    ///
219    /// return a valid `LatLong` or a `LatLongError`.
220    fn try_from(lat_long: (T, T)) -> Result<Self, Self::Error> {
221        if !is_valid_latitude(lat_long.0) {
222            Err(LatLongError::Latitude(lat_long.0))
223        } else if !is_valid_longitude(lat_long.1) {
224            Err(LatLongError::Longitude(lat_long.1))
225        } else {
226            Ok(Self::new(
227                Degrees::<T>(lat_long.0),
228                Degrees::<T>(lat_long.1),
229            ))
230        }
231    }
232}
233
234/// Calculate the azimuth and distance along the great circle of point b from
235/// point a.
236/// * `a`, `b` - the start and end positions
237///
238/// returns the great-circle azimuth relative to North and distance of point b
239/// from point a.
240#[must_use]
241pub fn calculate_azimuth_and_distance<T>(a: &LatLong<T>, b: &LatLong<T>) -> (Angle<T>, Radians<T>)
242where
243    T: Float + FloatConst,
244    f64: From<T>,
245{
246    let a_lat = Angle::from(a.lat);
247    let b_lat = Angle::from(b.lat);
248    let delta_long = Angle::from((b.lon, a.lon));
249    (
250        great_circle::calculate_gc_azimuth(a_lat, b_lat, delta_long),
251        great_circle::calculate_gc_distance(a_lat, b_lat, delta_long),
252    )
253}
254
255/// Calculate the distance along the great circle of point b from point a.
256///
257/// See: [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula).
258/// This function is less accurate than `calculate_azimuth_and_distance`.
259/// * `a`, `b` - the start and end positions
260///
261/// returns the great-circle distance of point b from point a in `Radians`.
262#[must_use]
263pub fn haversine_distance<T>(a: &LatLong<T>, b: &LatLong<T>) -> Radians<T>
264where
265    T: Float + FloatConst,
266    f64: From<T>,
267{
268    let a_lat = Angle::from(a.lat);
269    let b_lat = Angle::from(b.lat);
270    let delta_lat = Angle::from((b.lat, a.lat));
271    let delta_long = Angle::from(b.lon - a.lon);
272    great_circle::calculate_haversine_distance(a_lat, b_lat, delta_long, delta_lat)
273}
274
275impl<T> From<&LatLong<T>> for Vector3<T>
276where
277    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
278    f64: From<T>,
279{
280    /// Convert a `LatLong` to a point on the unit sphere.
281    ///
282    /// @pre |lat| <= 90.0 degrees.
283    /// * `lat` - the latitude.
284    /// * `lon` - the longitude.
285    ///
286    /// returns a `Vector3` of the point on the unit sphere.
287    fn from(a: &LatLong<T>) -> Self {
288        vector::to_point(Angle::from(a.lat), Angle::from(a.lon))
289    }
290}
291
292impl<T> From<&Vector3<T>> for LatLong<T>
293where
294    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
295    f64: From<T>,
296{
297    /// Convert a point to a `LatLong`
298    fn from(value: &Vector3<T>) -> Self {
299        Self::new(
300            Degrees::from(vector::latitude(value)),
301            Degrees::from(vector::longitude(value)),
302        )
303    }
304}
305
306/// An `Arc` of a Great Circle on a unit sphere.
307#[derive(Clone, Copy, Debug, Eq, PartialEq)]
308pub struct Arc<T: Float + FloatConst> {
309    /// The start point of the `Arc`.
310    a: Vector3<T>,
311    /// The right hand pole of the Great Circle of the `Arc`.
312    pole: Vector3<T>,
313    /// The length of the `Arc`.
314    length: Radians<T>,
315    /// The half width of the `Arc`.
316    half_width: Radians<T>,
317}
318
319impl<T> Validate for Arc<T>
320where
321    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
322{
323    /// Test whether an `Arc` is valid.
324    ///
325    /// I.e. both a and pole are on the unit sphere and are orthogonal and
326    /// both length and `half_width` are not negative.
327    fn is_valid(&self) -> bool {
328        vector::is_unit(&self.a)
329            && vector::is_unit(&self.pole)
330            && vector::are_orthogonal(&self.a, &self.pole)
331            && !self.length.0.is_sign_negative()
332            && !self.half_width.0.is_sign_negative()
333    }
334}
335
336impl<T> Arc<T>
337where
338    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
339    f64: From<T>,
340{
341    /// Construct an `Arc`
342    ///
343    /// * `a` - the start point of the `Arc`.
344    /// * `pole` - the right hand pole of the Great Circle of the `Arc`.
345    /// * `length` - the length of the `Arc`.
346    /// * `half_width` - the half width of the `Arc`.
347    #[must_use]
348    pub const fn new(
349        a: Vector3<T>,
350        pole: Vector3<T>,
351        length: Radians<T>,
352        half_width: Radians<T>,
353    ) -> Self {
354        Self {
355            a,
356            pole,
357            length,
358            half_width,
359        }
360    }
361
362    /// Construct an `Arc`
363    ///
364    /// * `a` - the start position
365    /// * `azimuth` - the azimuth at a.
366    /// * `length` - the length of the `Arc`.
367    #[must_use]
368    pub fn from_lat_lon_azi_length(a: &LatLong<T>, azimuth: Angle<T>, length: Radians<T>) -> Self {
369        Self::new(
370            Vector3::from(a),
371            vector::calculate_pole(Angle::from(a.lat()), Angle::from(a.lon()), azimuth),
372            length,
373            Radians(T::zero()),
374        )
375    }
376
377    /// Construct an `Arc` from the start and end positions.
378    ///
379    /// Note: if the points are the same or antipodal, the pole will be invalid.
380    /// * `a`, `b` - the start and end positions
381    #[must_use]
382    pub fn between_positions(a: &LatLong<T>, b: &LatLong<T>) -> Self {
383        let min_value = T::epsilon() + T::epsilon();
384
385        let (azimuth, length) = calculate_azimuth_and_distance(a, b);
386        let a_lat = Angle::from(a.lat());
387        // if a is at the North or South pole
388        if a_lat.cos().0 < min_value {
389            // use b's longitude
390            Self::from_lat_lon_azi_length(&LatLong::new(a.lat(), b.lon()), azimuth, length)
391        } else {
392            Self::from_lat_lon_azi_length(a, azimuth, length)
393        }
394    }
395
396    /// Set the `half_width` of an `Arc`.
397    ///
398    /// * `half_width` - the half width of the `Arc`.
399    #[must_use]
400    pub const fn set_half_width(&mut self, half_width: Radians<T>) -> &mut Self {
401        self.half_width = half_width;
402        self
403    }
404
405    /// The start point of the `Arc`.
406    #[must_use]
407    pub const fn a(&self) -> Vector3<T> {
408        self.a
409    }
410
411    /// The right hand pole of the Great Circle at the start point of the `Arc`.
412    #[must_use]
413    pub const fn pole(&self) -> Vector3<T> {
414        self.pole
415    }
416
417    /// The length of the `Arc`.
418    #[must_use]
419    pub const fn length(&self) -> Radians<T> {
420        self.length
421    }
422
423    /// The half width of the `Arc`.
424    #[must_use]
425    pub const fn half_width(&self) -> Radians<T> {
426        self.half_width
427    }
428
429    /// The azimuth at the start point.
430    #[must_use]
431    pub fn azimuth(&self) -> Angle<T> {
432        vector::calculate_azimuth(&self.a, &self.pole)
433    }
434
435    /// The direction vector of the `Arc` at the start point.
436    #[must_use]
437    pub fn direction(&self) -> Vector3<T> {
438        vector::direction(&self.a, &self.pole)
439    }
440
441    /// A position vector at distance along the `Arc`.
442    #[must_use]
443    pub fn position(&self, distance: Radians<T>) -> Vector3<T> {
444        vector::position(&self.a, &self.direction(), Angle::from(distance))
445    }
446
447    /// The end point of the `Arc`.
448    #[must_use]
449    pub fn b(&self) -> Vector3<T> {
450        self.position(self.length)
451    }
452
453    /// The mid point of the `Arc`.
454    #[must_use]
455    pub fn mid_point(&self) -> Vector3<T> {
456        self.position(self.length.half())
457    }
458
459    /// The position of a perpendicular point at distance from the `Arc`.
460    ///
461    /// * `point` a point on the `Arc`'s great circle.
462    /// * `distance` the perpendicular distance from the `Arc`'s great circle.
463    ///
464    /// returns the point at perpendicular distance from point.
465    #[must_use]
466    pub fn perp_position(&self, point: &Vector3<T>, distance: Radians<T>) -> Vector3<T> {
467        vector::position(point, &self.pole, Angle::from(distance))
468    }
469
470    /// The position of a point at angle from the `Arc` start, at `Arc` length.
471    ///
472    /// * `angle` the angle from the `Arc` start.
473    ///
474    /// returns the point at angle from the `Arc` start, at `Arc` length.
475    #[must_use]
476    pub fn angle_position(&self, angle: Angle<T>) -> Vector3<T> {
477        vector::rotate_position(&self.a, &self.pole, angle, Angle::from(self.length))
478    }
479
480    /// The `Arc` at the end of an `Arc`, just the point if `half_width` is zero.
481    ///
482    /// @param `at_b` if true the `Arc` at b, else the `Arc` at a.
483    ///
484    /// @return the end `Arc` at a or b.
485    #[must_use]
486    pub fn end_arc(&self, at_b: bool) -> Self {
487        let min_value = T::epsilon() + T::epsilon();
488
489        let p = if at_b { self.b() } else { self.a };
490        let pole = vector::direction(&p, &self.pole);
491        if self.half_width.0 < min_value {
492            Self::new(p, pole, Radians::default(), Radians::default())
493        } else {
494            let a = self.perp_position(&p, self.half_width);
495            Self::new(
496                a,
497                pole,
498                self.half_width + self.half_width,
499                Radians::default(),
500            )
501        }
502    }
503
504    /// Calculate great-circle along and across track distances of point from
505    /// the `Arc`.
506    ///
507    /// * `point` - the point.
508    ///
509    /// returns the along and across track distances of the point in Radians.
510    #[must_use]
511    pub fn calculate_atd_and_xtd(&self, point: &Vector3<T>) -> (Radians<T>, Radians<T>) {
512        vector::calculate_atd_and_xtd(&self.a, &self.pole(), point)
513    }
514
515    /// Calculate the shortest great-circle distance of a point from the `Arc`.
516    ///
517    /// * `point` - the point.
518    ///
519    /// returns the shortest distance of a point from the `Arc` in Radians.
520    #[must_use]
521    pub fn shortest_distance(&self, point: &Vector3<T>) -> Radians<T> {
522        let min_value = T::epsilon() + T::epsilon();
523        let two = T::one() + T::one();
524
525        let (atd, xtd) = self.calculate_atd_and_xtd(point);
526        if (-min_value <= atd.0) && (atd.0 <= self.length.0 + two * min_value) {
527            // point is alongside the arc
528            xtd.abs()
529        } else {
530            // adjust atd to measure the distance from the centre of the Arc to the point
531            let atd_centre = atd - self.length.half();
532            let p = if atd_centre.0.is_sign_negative() {
533                self.a
534            } else {
535                self.b()
536            };
537            great_circle::e2gc_distance(vector::distance(&p, point))
538        }
539    }
540}
541
542/// A Error type for an invalid `Arc`.
543#[derive(Error, Debug, Eq, PartialEq)]
544pub enum ArcError<T> {
545    #[error("positions are too close: `{0}`")]
546    PositionsTooClose(T),
547    #[error("positions are too far apart: `{0}`")]
548    PositionsTooFar(T),
549}
550
551impl<T> TryFrom<(&LatLong<T>, &LatLong<T>)> for Arc<T>
552where
553    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
554    f64: From<T>,
555{
556    type Error = ArcError<T>;
557
558    /// Construct an `Arc` from a pair of positions.
559    ///
560    /// * `params` - the start and end positions
561    #[allow(clippy::missing_panics_doc)]
562    fn try_from(params: (&LatLong<T>, &LatLong<T>)) -> Result<Self, Self::Error> {
563        let min_angle_multiple = T::from(16384).expect("Could not convert constant to Float");
564        let min_sin_angle = min_angle_multiple * T::epsilon();
565        let min_sq_norm = min_sin_angle * min_sin_angle;
566
567        // Convert positions to vectors
568        let a = Vector3::<T>::from(params.0);
569        let b = Vector3::<T>::from(params.1);
570        // Calculate the great circle pole
571        vector::normalise(&a.cross(&b), min_sq_norm).map_or_else(
572            || {
573                let sq_d = vector::sq_distance(&a, &b);
574                if sq_d < T::one() {
575                    Err(ArcError::PositionsTooClose(sq_d))
576                } else {
577                    Err(ArcError::PositionsTooFar(sq_d))
578                }
579            },
580            |pole| {
581                Ok(Self::new(
582                    a,
583                    pole,
584                    great_circle::e2gc_distance(vector::distance(&a, &b)),
585                    Radians::default(),
586                ))
587            },
588        )
589    }
590}
591
592/// Calculate the great-circle distances along a pair of `Arc`s to their
593/// closest intersection point or their coincident arc distances if the
594/// `Arc`s are on coincident Great Circles.
595///
596/// * `arc_0`, `arc_1` the `Arc`s.
597///
598/// returns the distances along the first `Arc` and second `Arc` to the intersection
599/// point or to their coincident arc distances if the `Arc`s do not intersect.
600#[allow(clippy::missing_panics_doc)]
601#[must_use]
602pub fn calculate_intersection_distances<T>(
603    arc_0: &Arc<T>,
604    arc_1: &Arc<T>,
605) -> (Radians<T>, Radians<T>)
606where
607    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
608    f64: From<T>,
609{
610    let min_angle_multiple = T::from(16384).expect("Could not convert constant to Float");
611    let min_sin_angle = min_angle_multiple * T::epsilon();
612    let min_sq_norm = min_sin_angle * min_sin_angle;
613
614    let (distance_0, distance_1, _angle) =
615        vector::intersection::calculate_arc_reference_distances_and_angle(
616            &arc_0.mid_point(),
617            &arc_0.pole(),
618            &arc_1.mid_point(),
619            &arc_1.pole(),
620            min_sq_norm,
621        );
622    (
623        distance_0 + arc_0.length().half(),
624        distance_1 + arc_1.length().half(),
625    )
626}
627
628/// Calculate whether a pair of `Arc`s intersect and (if so) where.
629///
630/// * `arc_0`, `arc_1` the `Arc`s.
631///
632/// returns the distance along the first `Arc` to the second `Arc` or None if they
633/// don't intersect.
634///
635/// # Examples
636/// ```
637/// use unit_sphere::{Arc, Degrees, LatLong, calculate_intersection_point};
638/// use angle_sc::is_within_tolerance;
639///
640/// let istanbul = LatLong::new(Degrees(42.0), Degrees(29.0));
641/// let washington = LatLong::new(Degrees(39.0), Degrees(-77.0));
642/// let reyjavik = LatLong::new(Degrees(64.0), Degrees(-22.0));
643/// let accra = LatLong::new(Degrees(6.0), Degrees(0.0));
644///
645/// let arc_0 = Arc::try_from((&istanbul, &washington)).unwrap();
646/// let arc_1 = Arc::try_from((&reyjavik, &accra)).unwrap();
647///
648/// // Calculate the intersection point position
649/// let intersection_point = calculate_intersection_point(&arc_0, &arc_1).unwrap();
650/// let lat_long = LatLong::from(&intersection_point);
651///
652/// // The expected latitude and longitude are from:
653/// // <https://sourceforge.net/p/geographiclib/discussion/1026621/thread/21aaff9f/#fe0a>
654///
655/// // Geodesic intersection latitude is 54.7170296089477
656/// assert!(is_within_tolerance(54.72, lat_long.lat().0, 0.05));
657/// // Geodesic intersection longitude is -14.56385574430775
658/// assert!(is_within_tolerance(-14.56, lat_long.lon().0, 0.02));
659/// ```
660#[allow(clippy::missing_panics_doc)]
661#[must_use]
662pub fn calculate_intersection_point<T>(arc_0: &Arc<T>, arc_1: &Arc<T>) -> Option<Vector3<T>>
663where
664    T: Float + FloatConst + na::Scalar + na::ComplexField<RealField = T>,
665    f64: From<T>,
666{
667    let min_value = T::epsilon() + T::epsilon();
668
669    let min_angle_multiple = T::from(16384).expect("Could not convert constant to Float");
670    let min_sin_angle = min_angle_multiple * T::epsilon();
671    let min_sq_norm = min_sin_angle * min_sin_angle;
672
673    let (point, angle) = vector::intersection::calculate_reference_point_and_angle(
674        &arc_0.mid_point(),
675        &arc_0.pole(),
676        &arc_1.mid_point(),
677        &arc_1.pole(),
678        min_sq_norm,
679    );
680
681    // calculate distances to the intersection or centroid from arc mid points
682    let distance_0 = vector::calculate_great_circle_atd(&arc_0.mid_point(), &arc_0.pole(), &point);
683    let distance_1 = vector::calculate_great_circle_atd(&arc_1.mid_point(), &arc_1.pole(), &point);
684
685    let arcs_are_coincident = angle.sin().0 == T::zero();
686    let arcs_intersect_or_overlap = if arcs_are_coincident {
687        // do coincident arcs overlap?
688        distance_0.abs() + distance_1.abs()
689            <= arc_0.length().half() + arc_1.length().half() + Radians(min_value)
690    } else {
691        // do great circles intersect inside both arcs
692        (distance_0.abs() <= arc_0.length().half() + Radians(min_value))
693            && distance_1.abs() <= (arc_1.length().half() + Radians(min_value))
694    };
695
696    if arcs_intersect_or_overlap {
697        Some(point)
698    } else {
699        None
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706    use angle_sc::{Degrees, is_within_tolerance};
707
708    #[test]
709    fn test_is_valid_latitude() {
710        // value < -90
711        assert!(!is_valid_latitude(-90.0001));
712        // value = -90
713        assert!(is_valid_latitude(-90.0));
714        // value = 90
715        assert!(is_valid_latitude(90.0));
716        // value > 90
717        assert!(!is_valid_latitude(90.0001));
718    }
719
720    #[test]
721    fn test_is_valid_longitude() {
722        // value < -180
723        assert!(!is_valid_longitude(-180.0001));
724        // value = -180
725        assert!(is_valid_longitude(-180.0));
726        // value = 180
727        assert!(is_valid_longitude(180.0));
728        // value > 180
729        assert!(!is_valid_longitude(180.0001));
730    }
731
732    #[test]
733    fn test_latlong_traits() {
734        let a = LatLong::try_from((0.0, 90.0)).unwrap();
735
736        assert!(a.is_valid());
737
738        let a_clone = a.clone();
739        assert!(a_clone == a);
740
741        assert_eq!(Degrees(0.0), a.lat());
742        assert_eq!(Degrees(90.0), a.lon());
743
744        assert!(!a.is_south_of(&a));
745        assert!(!a.is_west_of(&a));
746
747        let b = LatLong::try_from((-10.0, -91.0)).unwrap();
748        assert!(b.is_south_of(&a));
749        assert!(b.is_west_of(&a));
750
751        println!("LatLong: {:?}", a);
752
753        let invalid_lat = LatLong::try_from((91.0, 0.0));
754        assert_eq!(Err(LatLongError::Latitude(91.0)), invalid_lat);
755        println!("invalid_lat: {:?}", invalid_lat);
756
757        let invalid_lon = LatLong::try_from((0.0, 181.0));
758        assert_eq!(Err(LatLongError::Longitude(181.0)), invalid_lon);
759        println!("invalid_lon: {:?}", invalid_lon);
760    }
761
762    #[test]
763    fn test_vector3d_traits() {
764        let a = LatLong::try_from((0.0, 90.0)).unwrap();
765        let point = Vector3::from(&a);
766
767        assert_eq!(0.0, point.x);
768        assert_eq!(1.0, point.y);
769        assert_eq!(0.0, point.z);
770
771        assert_eq!(Degrees(0.0), Degrees::from(vector::latitude(&point)));
772        assert_eq!(Degrees(90.0), Degrees::from(vector::longitude(&point)));
773
774        let result = LatLong::from(&point);
775        assert_eq!(a, result);
776    }
777
778    #[test]
779    fn test_great_circle_90n_0n_0e() {
780        let a = LatLong::new(Degrees(90.0), Degrees(0.0));
781        let b = LatLong::new(Degrees(0.0), Degrees(0.0));
782        let (azimuth, dist) = calculate_azimuth_and_distance(&a, &b);
783
784        assert!(is_within_tolerance(
785            core::f64::consts::FRAC_PI_2,
786            dist.0,
787            f64::EPSILON
788        ));
789        assert_eq!(180.0, Degrees::from(azimuth).0);
790
791        let dist = haversine_distance(&a, &b);
792        assert!(is_within_tolerance(
793            core::f64::consts::FRAC_PI_2,
794            dist.0,
795            f64::EPSILON
796        ));
797    }
798
799    #[test]
800    fn test_great_circle_90s_0n_50e() {
801        let a = LatLong::new(Degrees(-90.0), Degrees(0.0));
802        let b = LatLong::new(Degrees(0.0), Degrees(50.0));
803        let (azimuth, dist) = calculate_azimuth_and_distance(&a, &b);
804
805        assert!(is_within_tolerance(
806            core::f64::consts::FRAC_PI_2,
807            dist.0,
808            f64::EPSILON
809        ));
810        assert_eq!(0.0, Degrees::from(azimuth).0);
811
812        let dist = haversine_distance(&a, &b);
813        assert!(is_within_tolerance(
814            core::f64::consts::FRAC_PI_2,
815            dist.0,
816            f64::EPSILON
817        ));
818    }
819
820    #[test]
821    fn test_great_circle_0n_60e_0n_60w() {
822        let a = LatLong::new(Degrees(0.0), Degrees(60.0));
823        let b = LatLong::new(Degrees(0.0), Degrees(-60.0));
824        let (azimuth, dist) = calculate_azimuth_and_distance(&a, &b);
825
826        assert!(is_within_tolerance(
827            2.0 * core::f64::consts::FRAC_PI_3,
828            dist.0,
829            2.0 * f64::EPSILON
830        ));
831        assert_eq!(-90.0, Degrees::from(azimuth).0);
832
833        let dist = haversine_distance(&a, &b);
834        assert!(is_within_tolerance(
835            2.0 * core::f64::consts::FRAC_PI_3,
836            dist.0,
837            2.0 * f64::EPSILON
838        ));
839    }
840
841    #[test]
842    fn test_arc() {
843        // Greenwich equator
844        let g_eq = LatLong::new(Degrees(0.0), Degrees(0.0));
845
846        // 90 degrees East on the equator
847        let e_eq = LatLong::new(Degrees(0.0), Degrees(90.0));
848
849        let mut arc = Arc::between_positions(&g_eq, &e_eq);
850        let arc = arc.set_half_width(Radians(0.01));
851        assert!(arc.is_valid());
852        assert_eq!(Radians(0.01), arc.half_width());
853
854        assert_eq!(Vector3::from(&g_eq), arc.a());
855        assert_eq!(Vector3::new(0.0, 0.0, 1.0), arc.pole());
856        assert!(is_within_tolerance(
857            core::f64::consts::FRAC_PI_2,
858            arc.length().0,
859            f64::EPSILON
860        ));
861        assert_eq!(Angle::from(Degrees(90.0)), arc.azimuth());
862        let b = Vector3::from(&e_eq);
863        assert!(is_within_tolerance(
864            0.0,
865            vector::distance(&b, &arc.b()),
866            f64::EPSILON
867        ));
868
869        let mid_point = arc.mid_point();
870        assert_eq!(0.0, mid_point.z);
871        assert!(is_within_tolerance(
872            45.0,
873            Degrees::from(vector::longitude(&mid_point)).0,
874            32.0 * f64::EPSILON
875        ));
876
877        let start_arc = arc.end_arc(false);
878        assert_eq!(0.02, start_arc.length().0);
879
880        let start_arc_a = start_arc.a();
881        assert_eq!(start_arc_a, arc.perp_position(&arc.a(), Radians(0.01)));
882
883        let angle_90 = Angle::from(Degrees(90.0));
884        let pole_0 = Vector3::new(0.0, 0.0, 1.0);
885        assert!(vector::distance(&pole_0, &arc.angle_position(angle_90)) <= f64::EPSILON);
886
887        let end_arc = arc.end_arc(true);
888        assert_eq!(0.02, end_arc.length().0);
889
890        let end_arc_a = end_arc.a();
891        assert_eq!(end_arc_a, arc.perp_position(&arc.b(), Radians(0.01)));
892    }
893
894    #[test]
895    fn test_north_and_south_poles() {
896        let north_pole = LatLong::new(Degrees(90.0), Degrees(0.0));
897        let south_pole = LatLong::new(Degrees(-90.0), Degrees(0.0));
898
899        let (azimuth, distance) = calculate_azimuth_and_distance(&south_pole, &north_pole);
900        assert_eq!(0.0, Degrees::from(azimuth).0);
901        assert_eq!(core::f64::consts::PI, distance.0);
902
903        let (azimuth, distance) = calculate_azimuth_and_distance(&north_pole, &south_pole);
904        assert_eq!(180.0, Degrees::from(azimuth).0);
905        assert_eq!(core::f64::consts::PI, distance.0);
906
907        // 90 degrees East on the equator
908        let e_eq = LatLong::new(Degrees(0.0), Degrees(50.0));
909
910        let arc = Arc::between_positions(&north_pole, &e_eq);
911        assert!(is_within_tolerance(
912            e_eq.lat().0,
913            LatLong::from(&arc.b()).lat().abs().0,
914            1e-13
915        ));
916        assert!(is_within_tolerance(
917            e_eq.lon().0,
918            LatLong::from(&arc.b()).lon().0,
919            50.0 * f64::EPSILON
920        ));
921
922        let arc = Arc::between_positions(&south_pole, &e_eq);
923        assert!(is_within_tolerance(
924            e_eq.lat().0,
925            LatLong::from(&arc.b()).lat().abs().0,
926            1e-13
927        ));
928        assert!(is_within_tolerance(
929            e_eq.lon().0,
930            LatLong::from(&arc.b()).lon().0,
931            50.0 * f64::EPSILON
932        ));
933
934        let w_eq = LatLong::new(Degrees(0.0), Degrees(-140.0));
935
936        let arc = Arc::between_positions(&north_pole, &w_eq);
937        assert!(is_within_tolerance(
938            w_eq.lat().0,
939            LatLong::from(&arc.b()).lat().abs().0,
940            1e-13
941        ));
942        assert!(is_within_tolerance(
943            w_eq.lon().0,
944            LatLong::from(&arc.b()).lon().0,
945            256.0 * f64::EPSILON
946        ));
947
948        let arc = Arc::between_positions(&south_pole, &w_eq);
949        assert!(is_within_tolerance(
950            w_eq.lat().0,
951            LatLong::from(&arc.b()).lat().abs().0,
952            1e-13
953        ));
954        assert!(is_within_tolerance(
955            w_eq.lon().0,
956            LatLong::from(&arc.b()).lon().0,
957            256.0 * f64::EPSILON
958        ));
959
960        let invalid_arc = Arc::try_from((&north_pole, &north_pole));
961        assert_eq!(Err(ArcError::PositionsTooClose(0.0)), invalid_arc);
962        println!("invalid_arc: {:?}", invalid_arc);
963
964        let arc = Arc::between_positions(&north_pole, &north_pole);
965        assert_eq!(north_pole, LatLong::from(&arc.b()));
966
967        let invalid_arc = Arc::try_from((&north_pole, &south_pole));
968        assert_eq!(Err(ArcError::PositionsTooFar(4.0)), invalid_arc);
969        println!("invalid_arc: {:?}", invalid_arc);
970
971        let arc = Arc::between_positions(&north_pole, &south_pole);
972        assert_eq!(south_pole, LatLong::from(&arc.b()));
973
974        let arc = Arc::between_positions(&south_pole, &north_pole);
975        assert_eq!(north_pole, LatLong::from(&arc.b()));
976
977        let arc = Arc::between_positions(&south_pole, &south_pole);
978        assert_eq!(south_pole, LatLong::from(&arc.b()));
979    }
980
981    #[test]
982    fn test_arc_atd_and_xtd() {
983        // Greenwich equator
984        let g_eq = LatLong::new(Degrees(0.0), Degrees(0.0));
985
986        // 90 degrees East on the equator
987        let e_eq = LatLong::new(Degrees(0.0), Degrees(90.0));
988
989        let arc = Arc::try_from((&g_eq, &e_eq)).unwrap();
990        assert!(arc.is_valid());
991
992        let start_arc = arc.end_arc(false);
993        assert_eq!(0.0, start_arc.length().0);
994
995        let start_arc_a = start_arc.a();
996        assert_eq!(arc.a(), start_arc_a);
997
998        let longitude = Degrees(1.0);
999
1000        // Test across track distance
1001        // Accuracy drops off outside of this range
1002        for lat in -83..84 {
1003            let lat = f64::from(lat);
1004            let latitude = Degrees(lat);
1005            let latlong = LatLong::new(latitude, longitude);
1006            let point = Vector3::from(&latlong);
1007
1008            let expected = (lat).to_radians();
1009            let (atd, xtd) = arc.calculate_atd_and_xtd(&point);
1010            assert!(is_within_tolerance(1_f64.to_radians(), atd.0, f64::EPSILON));
1011            assert!(is_within_tolerance(expected, xtd.0, 2.0 * f64::EPSILON));
1012
1013            let d = arc.shortest_distance(&point);
1014            assert!(is_within_tolerance(expected.abs(), d.0, 2.0 * f64::EPSILON));
1015        }
1016
1017        let point = Vector3::from(&g_eq);
1018        let d = arc.shortest_distance(&point);
1019        assert_eq!(0.0, d.0);
1020
1021        let point = Vector3::from(&e_eq);
1022        let d = arc.shortest_distance(&point);
1023        assert_eq!(0.0, d.0);
1024
1025        let latlong = LatLong::new(Degrees(0.0), Degrees(-1.0));
1026        let point = Vector3::from(&latlong);
1027        let d = arc.shortest_distance(&point);
1028        assert!(is_within_tolerance(1_f64.to_radians(), d.0, f64::EPSILON));
1029
1030        let point = -point;
1031        let d = arc.shortest_distance(&point);
1032        assert!(is_within_tolerance(89_f64.to_radians(), d.0, f64::EPSILON));
1033
1034        // a point closer to the end of the arc than the start
1035        let latlong = LatLong::new(Degrees(0.0), Degrees(-160.0));
1036        let point = Vector3::from(&latlong);
1037        let d = arc.shortest_distance(&point);
1038        // shortest distance is from the end of the arc to the point
1039        assert_eq!(
1040            great_circle::e2gc_distance(vector::distance(&arc.b(), &point)),
1041            d
1042        );
1043    }
1044
1045    #[test]
1046    fn test_arc_intersection_point() {
1047        // Karney's example:
1048        // Istanbul, Washington, Reyjavik and Accra
1049        // from: <https://sourceforge.net/p/geographiclib/discussion/1026621/thread/21aaff9f/#fe0a>
1050        let istanbul = LatLong::new(Degrees(42.0), Degrees(29.0));
1051        let washington = LatLong::new(Degrees(39.0), Degrees(-77.0));
1052        let reyjavik = LatLong::new(Degrees(64.0), Degrees(-22.0));
1053        let accra = LatLong::new(Degrees(6.0), Degrees(0.0));
1054
1055        let arc_0 = Arc::try_from((&istanbul, &washington)).unwrap();
1056        let arc_1 = Arc::try_from((&reyjavik, &accra)).unwrap();
1057
1058        let intersection_point = calculate_intersection_point(&arc_0, &arc_1).unwrap();
1059        let lat_long = LatLong::from(&intersection_point);
1060        // Geodesic intersection latitude is 54.7170296089477
1061        assert!(is_within_tolerance(54.72, lat_long.lat().0, 0.05));
1062        // Geodesic intersection longitude is -14.56385574430775
1063        assert!(is_within_tolerance(-14.56, lat_long.lon().0, 0.02));
1064
1065        // Switch arcs
1066        let intersection_point = calculate_intersection_point(&arc_1, &arc_0).unwrap();
1067        let lat_long = LatLong::from(&intersection_point);
1068        // Geodesic intersection latitude is 54.7170296089477
1069        assert!(is_within_tolerance(54.72, lat_long.lat().0, 0.05));
1070        // Geodesic intersection longitude is -14.56385574430775
1071        assert!(is_within_tolerance(-14.56, lat_long.lon().0, 0.02));
1072    }
1073
1074    #[test]
1075    fn test_arc_intersection_same_great_circles() {
1076        let south_pole_1 = LatLong::new(Degrees(-88.0), Degrees(-180.0));
1077        let south_pole_2 = LatLong::new(Degrees(-87.0), Degrees(0.0));
1078
1079        let arc_0 = Arc::try_from((&south_pole_1, &south_pole_2)).unwrap();
1080
1081        let intersection_lengths = calculate_intersection_distances(&arc_0, &arc_0);
1082        assert_eq!(arc_0.length().half(), intersection_lengths.0);
1083        assert_eq!(arc_0.length().half(), intersection_lengths.1);
1084
1085        let intersection_point = calculate_intersection_point(&arc_0, &arc_0).unwrap();
1086        assert!(is_within_tolerance(
1087            arc_0.length().half().0,
1088            great_circle::e2gc_distance(vector::distance(&arc_0.a(), &intersection_point)).0,
1089            f64::EPSILON
1090        ));
1091
1092        let south_pole_3 = LatLong::new(Degrees(-85.0), Degrees(0.0));
1093        let south_pole_4 = LatLong::new(Degrees(-86.0), Degrees(0.0));
1094        let arc_1 = Arc::try_from((&south_pole_3, &south_pole_4)).unwrap();
1095        let intersection_point = calculate_intersection_point(&arc_0, &arc_1);
1096        assert!(intersection_point.is_none());
1097    }
1098}