ferravex_math/
segments.rs

1//! Checked closest witnesses for finite 2D and 3D segments.
2//!
3//! Inputs reuse [`Vec2`] and [`Vec3`]. Coordinates are promoted **before**
4//! subtraction. Parameters, witness coordinates and distance are f64: even the
5//! separation of opposite `f32::MAX` points is representable. Witness arrays
6//! retain the computed precision rather than rounding to the engine's f32
7//! vectors; `Vec3::from_array(hit.first.map(|x| x as f32))` is an explicit
8//! presentation conversion. Distance is the Euclidean distance between the
9//! returned arrays, not a separate calculation from rounded f32 witnesses.
10//!
11//! Parameters are clamped to `0..=1`. Exactly coincident endpoints define a
12//! point segment with parameter zero; short nonzero segments are not discarded.
13//! Pair queries examine the four endpoint projections and, for nonparallel
14//! lines, their interior closest pair. Equal computed squared separations
15//! choose the lexicographically lowest `(first_parameter, second_parameter)`.
16//! Comparisons subtract squared separations componentwise before summing, so a
17//! large identical component does not hide improvements on another axis.
18//! Thus parallel overlap selects its earliest point on the first segment;
19//! reversing or swapping segments can change the selected witness in a tie.
20//! Parallel means an exactly zero f64 cross product; no angle epsilon changes
21//! near-parallel crossings into parallel lines. Cross products avoid the
22//! cancellation of `dot(u,u) * dot(v,v) - dot(u,v).powi(2)` near parallelism.
23//!
24//! These are ordinary floating-point queries, not exact geometric predicates.
25//! Ill-conditioned inputs and coordinates spanning widely different scales
26//! still lose precision in f64. No cross-platform bitwise result is promised.
27//! All queries use bounded stack storage, constant work, no heap allocation,
28//! and no retained state. A rejected query cannot affect a later one. There is
29//! no capacity, clock, reset, collision sweep, or route-progress state.
30//!
31//! # Runnable aim, tether and gate recipe
32//!
33//! A game can use distance to choose aim proximity, report a stretched tether,
34//! or measure proximity between a movement segment and a track gate. These
35//! geometric observations do not establish swept shape contact or a valid lap.
36//!
37//! ```rust
38//! use ferravex_math::{Vec2, Vec3, vec2, vec3};
39//! use ferravex_math::segments::{
40//!     ClosestPoints, SegmentError, closest_point_segment2, closest_point_segment3,
41//!     closest_segments2, closest_segments3,
42//! };
43//!
44//! fn main() -> Result<(), SegmentError> {
45//!     let aim: ClosestPoints<2> = closest_point_segment2(
46//!         vec2(4., 1.), Vec2::ZERO, vec2(10., 0.),
47//!     )?;
48//!     assert!(aim.distance <= 1.5); // target is within authored aim radius
49//!     assert_eq!(aim.second, [4., 0.]);
50//!
51//!     let tether = closest_point_segment3(
52//!         vec3(3., 4., 2.), Vec3::ZERO, vec3(6., 0., 0.),
53//!     )?;
54//!     assert!(tether.distance > 4.); // compare in the same world units
55//!     let attachment = Vec3::from_array(tether.second.map(|x| x as f32));
56//!     assert_eq!(attachment, vec3(3., 0., 0.));
57//!
58//!     let gate = closest_segments2(
59//!         vec2(-2., 0.), vec2(2., 0.), vec2(0., -1.), vec2(0., 1.),
60//!     )?;
61//!     assert_eq!(gate.distance, 0.);
62//!     assert_eq!(gate.first_parameter, 0.5);
63//!     // The game still owns gate ordering, direction, and accepted-event feedback.
64//!     let elevated_gate = closest_segments3(
65//!         vec3(-2., 0., 2.), vec3(2., 0., 2.),
66//!         vec3(0., -1., 0.), vec3(0., 1., 0.),
67//!     )?;
68//!     assert_eq!(elevated_gate.distance, 2.);
69//!     Ok(())
70//! }
71//! ```
72
73use crate::{Vec2, Vec3};
74
75/// A query rejected NaN or an infinite input coordinate.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum SegmentError {
79    /// Every coordinate of every supplied point must be finite.
80    NonFiniteInput,
81}
82
83impl std::fmt::Display for SegmentError {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.write_str("segment query coordinates must be finite")
86    }
87}
88
89impl std::error::Error for SegmentError {}
90
91/// Two closest witnesses, with finite f64 coordinates and distance.
92///
93/// Query functions return `N = 2` or `N = 3`. For a point query, `first` is the
94/// supplied point and `first_parameter` is zero. Otherwise both parameters
95/// describe their respective ordered start/end inputs. See the module recipe.
96#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct ClosestPoints<const N: usize> {
98    /// Point on the first segment (or the query point).
99    pub first: [f64; N],
100    /// Point on the second segment.
101    pub second: [f64; N],
102    /// Fraction along the first segment, in `0..=1`.
103    pub first_parameter: f64,
104    /// Fraction along the second segment, in `0..=1`.
105    pub second_parameter: f64,
106    /// Euclidean distance between `first` and `second`, in input world units.
107    pub distance: f64,
108}
109
110/// Projects a finite point onto an ordered 2D segment, including its endpoints.
111/// A zero-length segment returns its start at parameter zero.
112///
113/// ```
114/// use ferravex_math::{Vec2, vec2};
115/// use ferravex_math::segments::closest_point_segment2;
116/// let hit = closest_point_segment2(vec2(3., 4.), Vec2::ZERO, Vec2::X)?;
117/// assert_eq!(hit.second, [1., 0.]);
118/// assert_eq!(hit.second_parameter, 1.);
119/// assert_eq!(hit.distance, 20_f64.sqrt());
120/// # Ok::<(), ferravex_math::segments::SegmentError>(())
121/// ```
122pub fn closest_point_segment2(
123    point: Vec2,
124    start: Vec2,
125    end: Vec2,
126) -> Result<ClosestPoints<2>, SegmentError> {
127    point_segment(point.to_array(), start.to_array(), end.to_array())
128}
129
130/// Projects a finite point onto an ordered 3D segment. See the module's f64
131/// witness policy; nonfinite inputs are errors, not fallback points.
132///
133/// ```
134/// use ferravex_math::{Vec3, vec3};
135/// use ferravex_math::segments::closest_point_segment3;
136/// let hit = closest_point_segment3(vec3(0., 2., 3.), Vec3::ZERO, Vec3::Z * 6.)?;
137/// assert_eq!(hit.second, [0., 0., 3.]);
138/// assert_eq!(hit.second_parameter, 0.5);
139/// assert_eq!(hit.distance, 2.);
140/// # Ok::<(), ferravex_math::segments::SegmentError>(())
141/// ```
142pub fn closest_point_segment3(
143    point: Vec3,
144    start: Vec3,
145    end: Vec3,
146) -> Result<ClosestPoints<3>, SegmentError> {
147    point_segment(point.to_array(), start.to_array(), end.to_array())
148}
149
150/// Finds closest points on two finite ordered 2D segments, including crossings,
151/// parallel overlap and point segments. Equal computed squared separations prefer the
152/// lowest first parameter, then the lowest second parameter.
153///
154/// ```
155/// use ferravex_math::{Vec2, vec2};
156/// use ferravex_math::segments::closest_segments2;
157/// let hit = closest_segments2(Vec2::ZERO, Vec2::X * 4., vec2(2., 0.), vec2(6., 0.))?;
158/// assert_eq!((hit.first_parameter, hit.second_parameter), (0.5, 0.));
159/// assert_eq!(hit.first, hit.second);
160/// assert_eq!(hit.distance, 0.);
161/// # Ok::<(), ferravex_math::segments::SegmentError>(())
162/// ```
163pub fn closest_segments2(
164    first_start: Vec2,
165    first_end: Vec2,
166    second_start: Vec2,
167    second_end: Vec2,
168) -> Result<ClosestPoints<2>, SegmentError> {
169    segment_pair(
170        first_start.to_array(),
171        first_end.to_array(),
172        second_start.to_array(),
173        second_end.to_array(),
174    )
175}
176
177/// Finds closest points on two finite ordered 3D segments, including skew and
178/// point segments. No normalization or minimum-length threshold is required.
179///
180/// ```
181/// use ferravex_math::vec3;
182/// use ferravex_math::segments::closest_segments3;
183/// let hit = closest_segments3(
184///     vec3(-1., 0., 0.), vec3(1., 0., 0.),
185///     vec3(0., -1., 3.), vec3(0., 1., 3.),
186/// )?;
187/// assert_eq!(hit.first, [0., 0., 0.]);
188/// assert_eq!(hit.second, [0., 0., 3.]);
189/// assert_eq!(hit.distance, 3.);
190/// # Ok::<(), ferravex_math::segments::SegmentError>(())
191/// ```
192pub fn closest_segments3(
193    first_start: Vec3,
194    first_end: Vec3,
195    second_start: Vec3,
196    second_end: Vec3,
197) -> Result<ClosestPoints<3>, SegmentError> {
198    segment_pair(
199        first_start.to_array(),
200        first_end.to_array(),
201        second_start.to_array(),
202        second_end.to_array(),
203    )
204}
205
206fn finite<const N: usize>(point: [f32; N]) -> Result<[f64; N], SegmentError> {
207    if point.iter().all(|x| x.is_finite()) {
208        Ok(point.map(f64::from))
209    } else {
210        Err(SegmentError::NonFiniteInput)
211    }
212}
213
214fn sub<const N: usize>(a: [f64; N], b: [f64; N]) -> [f64; N] {
215    std::array::from_fn(|i| a[i] - b[i])
216}
217
218fn dot<const N: usize>(a: [f64; N], b: [f64; N]) -> f64 {
219    (0..N).map(|i| a[i] * b[i]).sum()
220}
221
222fn interpolate<const N: usize>(a: [f64; N], b: [f64; N], t: f64) -> [f64; N] {
223    if t == 0. {
224        a
225    } else if t == 1. {
226        b
227    } else {
228        std::array::from_fn(|i| a[i] * (1. - t) + b[i] * t)
229    }
230}
231
232fn project<const N: usize>(point: [f64; N], a: [f64; N], b: [f64; N]) -> f64 {
233    let delta = sub(b, a);
234    let length_squared = dot(delta, delta);
235    if length_squared == 0. {
236        return 0.;
237    }
238    let t = dot(sub(point, a), delta) / length_squared;
239    if t <= 0. { 0. } else { t.min(1.) }
240}
241
242fn witnesses<const N: usize>(
243    a: [f64; N],
244    b: [f64; N],
245    c: [f64; N],
246    d: [f64; N],
247    s: f64,
248    t: f64,
249) -> ClosestPoints<N> {
250    let first = interpolate(a, b, s);
251    let second = interpolate(c, d, t);
252    let offset = sub(first, second);
253    ClosestPoints {
254        first,
255        second,
256        first_parameter: s,
257        second_parameter: t,
258        // Hypot keeps tiny nonzero separation even when squaring it underflows.
259        distance: offset.into_iter().fold(0., f64::hypot),
260    }
261}
262
263fn point_segment<const N: usize>(
264    point: [f32; N],
265    a: [f32; N],
266    b: [f32; N],
267) -> Result<ClosestPoints<N>, SegmentError> {
268    let (point, a, b) = (finite(point)?, finite(a)?, finite(b)?);
269    Ok(witnesses(point, point, a, b, 0., project(point, a, b)))
270}
271
272// Compare norms without first rounding away small differences under an equal
273// large component. Neumaier summation also retains residuals when components
274// of the difference have opposite signs. This is still f64, not an exact test.
275fn squared_difference<const N: usize>(a: &ClosestPoints<N>, b: &ClosestPoints<N>) -> f64 {
276    let (mut sum, mut correction) = (0_f64, 0_f64);
277    for i in 0..N {
278        let x = a.first[i] - a.second[i];
279        let y = b.first[i] - b.second[i];
280        let term = (x - y) * (x + y);
281        let next = sum + term;
282        correction += if sum.abs() >= term.abs() {
283            (sum - next) + term
284        } else {
285            (term - next) + sum
286        };
287        sum = next;
288    }
289    sum + correction
290}
291
292// Compensate the rounded second product when taking a 2x2 determinant.
293fn determinant(a: f64, b: f64, c: f64, d: f64) -> f64 {
294    let cd = c * d;
295    a.mul_add(b, -cd) + (-c).mul_add(d, cd)
296}
297
298fn segment_pair<const N: usize>(
299    a: [f32; N],
300    b: [f32; N],
301    c: [f32; N],
302    d: [f32; N],
303) -> Result<ClosestPoints<N>, SegmentError> {
304    let (a, b, c, d) = (finite(a)?, finite(b)?, finite(c)?, finite(d)?);
305    let u = sub(b, a);
306    let v = sub(d, c);
307    if dot(u, u) == 0. {
308        return Ok(witnesses(a, b, c, d, 0., project(a, c, d)));
309    }
310    if dot(v, v) == 0. {
311        return Ok(witnesses(a, b, c, d, project(c, a, b), 0.));
312    }
313
314    // Every constrained minimum lies on a boundary or is a stationary point
315    // of the two infinite lines. Enumerating boundaries avoids division by a
316    // small Gram determinant for parallel/endpoint cases.
317    let candidates = [
318        (0., project(a, c, d)),
319        (1., project(b, c, d)),
320        (project(c, a, b), 0.),
321        (project(d, a, b), 1.),
322    ];
323    let mut best = witnesses(a, b, c, d, candidates[0].0, candidates[0].1);
324    let mut consider = |s, t| {
325        let candidate = witnesses(a, b, c, d, s, t);
326        let difference = squared_difference(&candidate, &best);
327        if difference < 0.
328            || (difference == 0. && (s, t) < (best.first_parameter, best.second_parameter))
329        {
330            best = candidate;
331        }
332    };
333    for (s, t) in candidates.into_iter().skip(1) {
334        consider(s, t);
335    }
336
337    // Wedge products work in either dimension. In 3D these are the components
338    // of cross(u,v), cross(c-a,v), and cross(c-a,u), with a shared sign per axis.
339    // Their dot ratios give the unconstrained closest-line parameters without
340    // subtracting almost equal squared dot products.
341    let w = sub(c, a);
342    let (mut denominator, mut s_numerator, mut t_numerator) = (0., 0., 0.);
343    for i in 0..N {
344        for j in i + 1..N {
345            let n = determinant(u[i], v[j], u[j], v[i]);
346            denominator += n * n;
347            s_numerator += determinant(w[i], v[j], w[j], v[i]) * n;
348            t_numerator += determinant(w[i], u[j], w[j], u[i]) * n;
349        }
350    }
351    if denominator > 0. {
352        let (s, t) = (s_numerator / denominator, t_numerator / denominator);
353        if (0. ..=1.).contains(&s) && (0. ..=1.).contains(&t) {
354            // Canonicalize negative zero in the public parameters.
355            consider(if s == 0. { 0. } else { s }, if t == 0. { 0. } else { t });
356        }
357    }
358    Ok(best)
359}