Skip to main content

geometry_algorithm/
distance.rs

1//! User-facing `distance` / `distance_with` / `comparable_distance`
2//! entry points.
3//!
4//! Mirrors the three free-function overloads Boost.Geometry users
5//! reach for:
6//!
7//! * `boost::geometry::distance(g1, g2)` — strategy-less, picks the
8//!   default strategy for the coordinate-system pair. See
9//!   `boost/geometry/algorithms/distance.hpp` and the dispatch
10//!   plumbing in
11//!   `boost/geometry/algorithms/detail/distance/interface.hpp`.
12//! * `boost::geometry::distance(g1, g2, strategy)` — explicit-strategy
13//!   companion, same file.
14//! * `boost::geometry::comparable_distance(g1, g2)` — the
15//!   "skip the sqrt" form, from
16//!   `boost/geometry/algorithms/comparable_distance.hpp`.
17//!
18//! The strategy trait, default-strategy projection, and
19//! reverse-dispatch wrapper all live in `geometry-strategy::distance`
20//! (T21/T22). T23 is the thin layer that turns them into ordinary
21//! Rust functions.
22
23use geometry_cs::CoordinateSystem;
24use geometry_strategy::distance::{DefaultDistance, DefaultDistanceStrategy, DistanceStrategy};
25use geometry_trait::{Geometry, Point};
26
27/// Shorthand for the CS family of `G`'s point type. Used purely to
28/// keep the `where` clauses on the three free functions readable;
29/// matches the family projection spelled out long-form in the
30/// definition of
31/// [`geometry_strategy::distance::DefaultDistanceStrategy`].
32type Family<G> = <<<G as Geometry>::Point as Point>::Cs as CoordinateSystem>::Family;
33
34/// Distance between two geometries using the default strategy for
35/// their coordinate-system pair.
36///
37/// Mirrors the no-strategy overload of `boost::geometry::distance(g1, g2)`
38/// from `boost/geometry/algorithms/distance.hpp` and the dispatch
39/// in `boost/geometry/algorithms/detail/distance/interface.hpp`. The
40/// default strategy is resolved via
41/// [`DefaultDistanceStrategy`], which is the Rust analogue of Boost's
42/// `boost::geometry::strategy::distance::services::default_strategy<…>::type`.
43#[inline]
44pub fn distance<A, B>(
45    a: &A,
46    b: &B,
47) -> <DefaultDistanceStrategy<A, B> as DistanceStrategy<A, B>>::Out
48where
49    A: Geometry,
50    B: Geometry,
51    Family<A>: DefaultDistance<Family<B>>,
52    DefaultDistanceStrategy<A, B>: DistanceStrategy<A, B> + Default,
53{
54    DefaultDistanceStrategy::<A, B>::default().distance(a, b)
55}
56
57/// Distance between two geometries using an explicit strategy.
58///
59/// Mirrors the with-strategy overload
60/// `boost::geometry::distance(g1, g2, strategy)` from
61/// `boost/geometry/algorithms/distance.hpp` and the dispatch
62/// in `boost/geometry/algorithms/detail/distance/interface.hpp`.
63///
64/// The C++ overload is spelled the same as the strategy-less one and
65/// disambiguated by SFINAE on the strategy concept; on the Rust side
66/// the two overloads become two distinct names ([`distance`] and
67/// `distance_with`) so the strategy argument never clashes with the
68/// strategy-less form during type inference.
69///
70/// Taking the strategy by value (rather than by reference, as Boost
71/// does with `Strategy const&` at
72/// `boost/geometry/algorithms/detail/distance/interface.hpp:68`)
73/// keeps the call site free of an `&` everyone would forget. Concrete
74/// strategies are zero-sized or pointer-sized configuration objects
75/// (`Pythagoras`, `Haversine`, `Andoyer { spheroid }`), so passing
76/// them by value monomorphises into nothing.
77#[inline]
78#[allow(
79    clippy::needless_pass_by_value,
80    reason = "Strategies are ZST/small Copy configuration objects; by-value matches the user-facing call shape."
81)]
82pub fn distance_with<A, B, S>(a: &A, b: &B, strategy: S) -> S::Out
83where
84    A: Geometry,
85    B: Geometry,
86    S: DistanceStrategy<A, B>,
87{
88    strategy.distance(a, b)
89}
90
91/// Comparable distance — equivalent ordering, cheaper math.
92///
93/// Mirrors `boost::geometry::comparable_distance(g1, g2)` from
94/// `boost/geometry/algorithms/comparable_distance.hpp`. The result
95/// preserves the ordering of [`distance`] but skips work the ordering
96/// does not need (e.g. the final `sqrt` for Pythagoras). The
97/// comparable companion of the default strategy is selected via
98/// [`DistanceStrategy::Comparable`], the Rust analogue of Boost's
99/// `boost::geometry::strategy::distance::services::comparable_type<…>::type`.
100#[inline]
101pub fn comparable_distance<A, B>(
102    a: &A,
103    b: &B,
104) -> <<DefaultDistanceStrategy<A, B> as DistanceStrategy<A, B>>::Comparable as DistanceStrategy<
105    A,
106    B,
107>>::Out
108where
109    A: Geometry,
110    B: Geometry,
111    Family<A>: DefaultDistance<Family<B>>,
112    DefaultDistanceStrategy<A, B>: DistanceStrategy<A, B> + Default,
113{
114    DefaultDistanceStrategy::<A, B>::default()
115        .comparable()
116        .distance(a, b)
117}
118
119#[cfg(test)]
120mod tests {
121    //! Canonical 3-4-5 triangle, exercised through every entry point.
122    //! Reference value matches `geometry/test/strategies/pythagoras.cpp`
123    //! (lines 50-66) and `doc/quickstart.qbk` (Cartesian distance
124    //! example).
125
126    use super::{comparable_distance, distance, distance_with};
127    use geometry_cs::Cartesian;
128    use geometry_model::Point2D;
129    use geometry_strategy::cartesian::Pythagoras;
130
131    // 3² + 4² = 25 exactly and √25 = 5 exactly in IEEE-754; `assert_eq!`
132    // is the spec's chosen shape (T23 spec, `Tests` block). The
133    // pedantic `float_cmp` warning does not apply to integer-valued
134    // floats from finite arithmetic on small integers.
135    #[allow(clippy::float_cmp, reason = "3-4-5 is exact in IEEE-754 f64.")]
136    #[test]
137    fn cartesian_quickstart_3_4_5() {
138        let a = Point2D::<f64, Cartesian>::new(0.0, 0.0);
139        let b = Point2D::<f64, Cartesian>::new(3.0, 4.0);
140        assert_eq!(distance(&a, &b), 5.0);
141        assert_eq!(distance_with(&a, &b, Pythagoras), 5.0);
142        assert_eq!(comparable_distance(&a, &b), 25.0);
143    }
144
145    /// The 1D squared-difference walk: |7 − 2| = 5, squared = 25.
146    /// Exercises the `DIM == 1` dispatch arm of the Pythagoras kernel.
147    #[test]
148    fn one_dimensional_distance() {
149        type P1 = geometry_model::Point<f64, 1, Cartesian>;
150        let a = P1::new(2.0);
151        let b = P1::new(7.0);
152        assert!((distance(&a, &b) - 5.0).abs() < 1e-12);
153        assert!((comparable_distance(&a, &b) - 25.0).abs() < 1e-12);
154    }
155
156    /// The 4D walk (`MAX_DIM`): unit steps on each of four axes give
157    /// squared distance 4 and real distance 2. Exercises the `DIM == 4`
158    /// dispatch arm.
159    #[test]
160    fn four_dimensional_distance() {
161        use geometry_trait::PointMut as _;
162        type P4 = geometry_model::Point<f64, 4, Cartesian>;
163        let o = P4::default();
164        let mut p = P4::default();
165        p.set::<0>(1.0);
166        p.set::<1>(1.0);
167        p.set::<2>(1.0);
168        p.set::<3>(1.0);
169        assert!((comparable_distance(&o, &p) - 4.0).abs() < 1e-12);
170        assert!((distance(&o, &p) - 2.0).abs() < 1e-12);
171    }
172
173    /// A 3D point-to-segment distance exercises the `DIM == 3` dispatch
174    /// arms of the projected-point kernel. The point `(3, 4, 0)`
175    /// projects onto the z-axis segment `(0,0,0)-(0,0,10)` at the start
176    /// endpoint, so the distance is `sqrt(3² + 4²) = 5`.
177    #[test]
178    fn three_dimensional_point_to_segment() {
179        use geometry_model::{Point3D, Segment};
180        use geometry_strategy::PointToSegment;
181        type P3 = Point3D<f64, Cartesian>;
182        let p = P3::new(3.0, 4.0, 0.0);
183        let s = Segment::new(P3::new(0.0, 0.0, 0.0), P3::new(0.0, 0.0, 10.0));
184        let d = distance_with(&p, &s, PointToSegment::<Pythagoras>::default());
185        assert!((d - 5.0).abs() < 1e-12, "got {d}");
186    }
187
188    /// The north pole reached from two distinct longitudes is one
189    /// physical point (distance 0) for every geodesic strategy. The
190    /// differing longitudes bypass the coordinate-equality
191    /// short-circuit, so the in-formula degenerate guards report it.
192    #[cfg(feature = "std")]
193    #[test]
194    fn geodesic_coincident_poles_at_different_longitudes_are_zero() {
195        use geometry_adapt::{Adapt, WithCs};
196        use geometry_cs::{Degree, Geographic};
197        use geometry_strategy::geographic::{Andoyer, Thomas, Vincenty};
198
199        type Gg = WithCs<Adapt<[f64; 2]>, Geographic<Degree>>;
200        let deg = |lon: f64, lat: f64| -> Gg { WithCs::new(Adapt([lon, lat])) };
201
202        let a = deg(0.0, 90.0);
203        let b = deg(180.0, 90.0);
204        assert!(distance_with(&a, &b, Andoyer::WGS84).abs() < 1e-3);
205        assert!(distance_with(&a, &b, Thomas::WGS84).abs() < 1e-6);
206        assert!(distance_with(&a, &b, Vincenty::WGS84).abs() < 1e-3);
207    }
208
209    /// Thomas: a line whose *second* endpoint sits exactly on a pole
210    /// exercises the `lat2 == ±π/2` reduced-latitude short-circuit.
211    /// `(1, 80) → (0, 90)` ≈ 1116.825795 km.
212    #[cfg(feature = "std")]
213    #[test]
214    fn thomas_second_endpoint_at_pole() {
215        use geometry_adapt::{Adapt, WithCs};
216        use geometry_cs::{Degree, Geographic};
217        use geometry_strategy::geographic::Thomas;
218
219        type Gg = WithCs<Adapt<[f64; 2]>, Geographic<Degree>>;
220        let deg = |lon: f64, lat: f64| -> Gg { WithCs::new(Adapt([lon, lat])) };
221
222        let d = distance_with(&deg(1.0, 80.0), &deg(0.0, 90.0), Thomas::WGS84);
223        assert!(
224            (d / 1000.0 - 1_116.825_795).abs() < 0.012,
225            "{} km",
226            d / 1000.0
227        );
228    }
229
230    /// Vincenty: a pair straddling the antimeridian normalises Δλ into
231    /// `(-π, π]` in both directions; both describe the same 20°
232    /// equatorial arc (≈ 2 226 km on WGS84).
233    #[cfg(feature = "std")]
234    #[test]
235    fn vincenty_antimeridian_longitude_is_normalised_both_ways() {
236        use geometry_adapt::{Adapt, WithCs};
237        use geometry_cs::{Degree, Geographic};
238        use geometry_strategy::geographic::Vincenty;
239
240        type Gg = WithCs<Adapt<[f64; 2]>, Geographic<Degree>>;
241        let deg = |lon: f64, lat: f64| -> Gg { WithCs::new(Adapt([lon, lat])) };
242
243        let east = distance_with(&deg(170.0, 0.0), &deg(-170.0, 0.0), Vincenty::WGS84);
244        let west = distance_with(&deg(-170.0, 0.0), &deg(170.0, 0.0), Vincenty::WGS84);
245        assert!((east - west).abs() < 1e-6, "{east} vs {west}");
246        assert!(
247            (east / 1000.0 - 2_226.0).abs() < 5.0,
248            "{} km",
249            east / 1000.0
250        );
251    }
252}