affn 0.6.0

Affine geometry primitives: strongly-typed coordinate systems, reference frames, and centers for scientific computing.
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
//! # Cartesian Direction (Unit Vectors)
//!
//! This module defines [`Direction<F>`], a **dimensionless unit vector** representing
//! orientation in 3D space.
//!
//! ## Mathematical Model
//!
//! A direction is a unit-length vector representing pure orientation without magnitude:
//!
//! - **Frame-dependent**: Orientation is relative to a reference frame `F`
//! - **Center-independent**: Directions are translation-invariant (free vectors)
//! - **Dimensionless**: No length unit; magnitude is always 1
//!
//! ## Key Properties
//!
//! 1. **Immutable normalization**: All constructors produce unit vectors
//! 2. **No translation**: Directions cannot be "moved" to a different origin
//! 3. **Rotation-only transforms**: Frame transformations are the only valid spatial ops
//!
//! ## Supported Operations
//!
//! | Operation | Result | Meaning |
//! |-----------|--------|---------|
//! | `Direction * Length` | `Vector` | Scale direction to displacement |
//! | `normalize(Vector)` | `Direction` | Extract orientation from displacement |
//! | `Position.direction()` | `Direction` | Unit vector from center to position |
//!
//! ## Forbidden Operations (do not compile)
//!
//! - `Direction + Direction` — Adding unit vectors is geometrically invalid
//! - `Direction + Vector` — Translating a direction is meaningless
//! - Center transformations on Direction — Directions have no center
//!
//! ## Example
//!
//! ```rust
//! use affn::cartesian::Direction;
//! use affn::frames::ReferenceFrame;
//!
//! #[derive(Debug, Copy, Clone)]
//! struct WorldFrame;
//! impl ReferenceFrame for WorldFrame {
//!     fn frame_name() -> &'static str { "WorldFrame" }
//! }
//!
//! // Create a normalized direction
//! let dir = Direction::<WorldFrame>::new(1.0, 2.0, 2.0);
//! assert!((dir.x() - 1.0/3.0).abs() < 1e-12);
//! assert!((dir.y() - 2.0/3.0).abs() < 1e-12);
//! assert!((dir.z() - 2.0/3.0).abs() < 1e-12);
//!
//! // Scale to create a Vector
//! use qtty::*;
//! let vec = dir.scale(10.0 * M);
//! ```

use super::vector::Displacement;
use super::xyz::XYZ;
use crate::centers::ReferenceCenter;
use crate::frames::ReferenceFrame;
use qtty::{LengthUnit, Quantity};

use std::marker::PhantomData;
use std::ops::Mul;

/// A unit vector representing orientation in 3D space.
///
/// Directions are frame-dependent but center-independent (free vectors).
/// The internal storage is a `Vector3<f64>` with magnitude 1 (dimensionless).
///
/// # Type Parameters
/// - `F`: The reference frame (e.g., `ICRS`, `EclipticMeanJ2000`, `Equatorial`)
///
/// # Invariants
///
/// All public constructors ensure the direction is normalized. For unchecked
/// construction, use [`from_xyz_unchecked`](Self::from_xyz_unchecked).
///
/// # Zero-Cost Abstraction
///
/// This type is `#[repr(transparent)]` over `XYZ<f64>`, ensuring no runtime
/// overhead compared to raw `Vector3<f64>`.
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct Direction<F: ReferenceFrame> {
    pub(in crate::cartesian) xyz: XYZ<f64>,
    _frame: PhantomData<F>,
}

// =============================================================================
// Constructors (Normalizing)
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Creates a direction from components, normalizing to unit length.
    ///
    /// # Panics
    /// Panics if the input vector has zero magnitude (cannot normalize a zero vector).
    /// Use [`Direction::try_new`] for fallible construction when the input may be zero.
    ///
    /// # Example
    /// ```rust
    /// use affn::cartesian::Direction;
    /// use affn::frames::ReferenceFrame;
    ///
    /// #[derive(Debug, Copy, Clone)]
    /// struct WorldFrame;
    /// impl ReferenceFrame for WorldFrame {
    ///     fn frame_name() -> &'static str { "WorldFrame" }
    /// }
    ///
    /// let dir = Direction::<WorldFrame>::new(3.0, 4.0, 0.0);
    /// assert!((dir.x() - 0.6).abs() < 1e-12);
    /// assert!((dir.y() - 0.8).abs() < 1e-12);
    /// ```
    #[inline]
    #[must_use]
    pub fn new(x: f64, y: f64, z: f64) -> Self {
        Self::try_new(x, y, z).expect("Cannot create Direction from zero vector")
    }

    /// Attempts to create a direction, returning `None` if the input is zero.
    #[inline]
    #[must_use]
    pub fn try_new(x: f64, y: f64, z: f64) -> Option<Self> {
        XYZ::new(x, y, z)
            .try_normalize()
            .map(Self::from_xyz_unchecked)
    }

    /// Creates a direction from components (alias for `new`).
    ///
    /// Provided for API symmetry with earlier versions.
    #[inline]
    pub fn normalize(x: f64, y: f64, z: f64) -> Self {
        Self::new(x, y, z)
    }

    /// Creates a direction from a nalgebra Vector3, normalizing.
    #[inline]
    pub fn from_vec3(vec: nalgebra::Vector3<f64>) -> Self {
        Self::new(vec.x, vec.y, vec.z)
    }
}

// =============================================================================
// Unchecked Constructors (for internal use)
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Creates a direction from pre-normalized XYZ storage.
    ///
    /// # Safety
    /// The caller must ensure `xyz` is already a unit vector (magnitude ≈ 1).
    /// No normalization is performed.
    #[inline]
    pub(crate) fn from_xyz_unchecked(xyz: XYZ<f64>) -> Self {
        Self {
            xyz,
            _frame: PhantomData,
        }
    }

    /// Creates a direction from raw components without normalization.
    ///
    /// # Safety
    /// The caller must ensure the components form a unit vector.
    #[inline]
    pub fn new_unchecked(x: f64, y: f64, z: f64) -> Self {
        Self::from_xyz_unchecked(XYZ::new(x, y, z))
    }
}

// =============================================================================
// Component Access
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Returns the x-component.
    #[inline]
    pub fn x(&self) -> f64 {
        self.xyz.x()
    }

    /// Returns the y-component.
    #[inline]
    pub fn y(&self) -> f64 {
        self.xyz.y()
    }

    /// Returns the z-component.
    #[inline]
    pub fn z(&self) -> f64 {
        self.xyz.z()
    }

    /// Returns the underlying nalgebra Vector3.
    #[inline]
    pub fn as_vec3(&self) -> nalgebra::Vector3<f64> {
        *self.xyz.as_vec3()
    }

    /// Reinterprets this direction as belonging to a different reference frame.
    ///
    /// This is a **zero-cost** operation: the unit-vector components are
    /// preserved unchanged; only the compile-time frame tag is replaced.
    ///
    /// Use after applying a mathematical rotation whose result still carries
    /// the original frame tag.
    #[inline]
    pub fn reinterpret_frame<F2: ReferenceFrame>(self) -> Direction<F2> {
        Direction::new_unchecked(self.x(), self.y(), self.z())
    }
}

// =============================================================================
// Scaling: Direction * Length -> Vector
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Scales the direction by a length to produce a displacement vector.
    ///
    /// # Example
    /// ```rust
    /// use affn::cartesian::Direction;
    /// use affn::frames::ReferenceFrame;
    /// use qtty::*;
    ///
    /// #[derive(Debug, Copy, Clone)]
    /// struct WorldFrame;
    /// impl ReferenceFrame for WorldFrame {
    ///     fn frame_name() -> &'static str { "WorldFrame" }
    /// }
    ///
    /// let dir = Direction::<WorldFrame>::new(1.0, 0.0, 0.0);
    /// let vec = dir.scale(5.0 * M);
    /// assert!((vec.x().value() - 5.0).abs() < 1e-12);
    /// ```
    #[inline]
    pub fn scale<U: LengthUnit>(&self, magnitude: Quantity<U>) -> Displacement<F, U> {
        Displacement::new(
            magnitude * self.x(),
            magnitude * self.y(),
            magnitude * self.z(),
        )
    }

    /// Creates a position at the given distance from the origin in this direction.
    ///
    /// For centers with `Params = ()`, this is a convenience method.
    #[inline]
    pub fn position<C, U>(&self, magnitude: Quantity<U>) -> super::Position<C, F, U>
    where
        C: ReferenceCenter<Params = ()>,
        U: LengthUnit,
    {
        super::Position::new(
            magnitude * self.x(),
            magnitude * self.y(),
            magnitude * self.z(),
        )
    }

    /// Creates a position with explicit center parameters.
    #[inline]
    pub fn position_with_params<C, U>(
        &self,
        center_params: C::Params,
        magnitude: Quantity<U>,
    ) -> super::Position<C, F, U>
    where
        C: ReferenceCenter,
        U: LengthUnit,
    {
        super::Position::new_with_params(
            center_params,
            magnitude * self.x(),
            magnitude * self.y(),
            magnitude * self.z(),
        )
    }
}

// =============================================================================
// Operator: Direction * Quantity<U> -> Vector
// =============================================================================

impl<F: ReferenceFrame, U: LengthUnit> Mul<Quantity<U>> for Direction<F> {
    type Output = Displacement<F, U>;

    #[inline]
    fn mul(self, magnitude: Quantity<U>) -> Self::Output {
        self.scale(magnitude)
    }
}

impl<F: ReferenceFrame, U: LengthUnit> Mul<Direction<F>> for Quantity<U> {
    type Output = Displacement<F, U>;

    #[inline]
    fn mul(self, dir: Direction<F>) -> Self::Output {
        dir.scale(self)
    }
}

// =============================================================================
// Geometric Operations
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Computes the dot product with another direction.
    ///
    /// Returns cosine of the angle between directions (range: -1 to 1).
    #[inline]
    pub fn dot(&self, other: &Self) -> f64 {
        self.xyz.dot(&other.xyz)
    }

    /// Computes the cross product with another direction.
    ///
    /// The result is normalized if non-zero (perpendicular directions).
    #[inline]
    pub fn cross(&self, other: &Self) -> Option<Self> {
        self.xyz
            .cross(&other.xyz)
            .try_normalize()
            .map(Self::from_xyz_unchecked)
    }

    /// Negates the direction (points in opposite direction).
    #[inline]
    pub fn negate(&self) -> Self {
        Self::from_xyz_unchecked(self.xyz.neg())
    }

    /// Returns the angle between this direction and another, in radians.
    #[inline]
    pub fn angle_to(&self, other: &Self) -> f64 {
        // Clamp to handle floating-point errors at extremes
        self.dot(other).clamp(-1.0, 1.0).acos()
    }
}

// =============================================================================
// Spherical Conversion
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Converts this Cartesian direction to spherical coordinates.
    ///
    /// Returns a spherical direction with polar (latitude) and azimuth (longitude)
    /// angles in degrees. Angles are canonicalized to:
    /// - polar in `[-90°, +90°]`
    /// - azimuth in `[0°, 360°)`
    pub fn to_spherical(&self) -> crate::spherical::Direction<F> {
        let (polar, azimuth) = crate::spherical::xyz_to_polar_azimuth(self.x(), self.y(), self.z());
        crate::spherical::Direction::<F>::new_raw(polar, azimuth)
    }
}

// =============================================================================
// Display
// =============================================================================

impl<F: ReferenceFrame> Direction<F> {
    /// Returns a formatted string representation.
    pub fn display(&self) -> String {
        format!("{self}")
    }
}

impl<F: ReferenceFrame> std::fmt::Display for Direction<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Frame: {}, X: ", F::frame_name())?;
        std::fmt::Display::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::Display::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::Display::fmt(&self.z(), f)
    }
}

impl<F: ReferenceFrame> std::fmt::LowerExp for Direction<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Frame: {}, X: ", F::frame_name())?;
        std::fmt::LowerExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::LowerExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::LowerExp::fmt(&self.z(), f)
    }
}

impl<F: ReferenceFrame> std::fmt::UpperExp for Direction<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Frame: {}, X: ", F::frame_name())?;
        std::fmt::UpperExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::UpperExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::UpperExp::fmt(&self.z(), f)
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    // Import the derive
    use crate::DeriveReferenceCenter as ReferenceCenter;
    use crate::DeriveReferenceFrame as ReferenceFrame;
    use qtty::*;

    // Define test-specific frame
    #[derive(Debug, Copy, Clone, ReferenceFrame)]
    struct TestFrame;
    #[derive(Debug, Copy, Clone, ReferenceCenter)]
    struct TestCenter;

    #[derive(Clone, Debug, Default, PartialEq)]
    struct TestParams {
        tag: i32,
    }

    #[derive(Debug, Copy, Clone, ReferenceCenter)]
    #[center(params = TestParams)]
    struct ParamCenter;

    #[test]
    fn test_direction_normalization() {
        let dir = Direction::<TestFrame>::new(3.0, 4.0, 0.0);
        let norm = (dir.x() * dir.x() + dir.y() * dir.y() + dir.z() * dir.z()).sqrt();
        assert!((norm - 1.0).abs() < 1e-12);
        assert!((dir.x() - 0.6).abs() < 1e-12);
        assert!((dir.y() - 0.8).abs() < 1e-12);
    }

    #[test]
    fn test_direction_scale() {
        let dir = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let vec = dir.scale(Quantity::<Meter>::new(5.0));
        assert!((vec.x().value() - 5.0).abs() < 1e-12);
        assert!(vec.y().value().abs() < 1e-12);
        assert!(vec.z().value().abs() < 1e-12);
    }

    #[test]
    fn test_direction_dot_product() {
        let a = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let b = Direction::<TestFrame>::new(0.0, 1.0, 0.0);
        // Perpendicular directions have dot product 0
        assert!(a.dot(&b).abs() < 1e-12);

        // Same direction has dot product 1
        assert!((a.dot(&a) - 1.0).abs() < 1e-12);

        // Opposite directions have dot product -1
        assert!((a.dot(&a.negate()) + 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_direction_cross_product() {
        let x = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let y = Direction::<TestFrame>::new(0.0, 1.0, 0.0);
        let z = x.cross(&y).expect("perpendicular directions");
        assert!(z.x().abs() < 1e-12);
        assert!(z.y().abs() < 1e-12);
        assert!((z.z() - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_direction_try_new_zero() {
        assert!(Direction::<TestFrame>::try_new(0.0, 0.0, 0.0).is_none());
    }

    #[test]
    fn test_direction_angle() {
        let a = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let b = Direction::<TestFrame>::new(0.0, 1.0, 0.0);
        let angle = a.angle_to(&b);
        assert!((angle - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
    }

    #[test]
    fn test_direction_helpers_and_accessors() {
        let dir = Direction::<TestFrame>::normalize(0.0, 3.0, 4.0);
        let vec3 = dir.as_vec3();
        assert!((vec3.x - 0.0).abs() < 1e-12);
        assert!((vec3.y - 0.6).abs() < 1e-12);
        assert!((vec3.z - 0.8).abs() < 1e-12);

        let from_vec3 = Direction::<TestFrame>::from_vec3(nalgebra::Vector3::new(0.0, 3.0, 4.0));
        assert!((from_vec3.y() - 0.6).abs() < 1e-12);
        assert!((from_vec3.z() - 0.8).abs() < 1e-12);

        let unchecked = Direction::<TestFrame>::new_unchecked(1.0, 0.0, 0.0);
        assert!((unchecked.x() - 1.0).abs() < 1e-12);
        assert!(unchecked.y().abs() < 1e-12);

        let spherical = unchecked.to_spherical();
        assert!((spherical.polar.value()).abs() < 1e-12);
        assert!((spherical.azimuth.value()).abs() < 1e-12);
    }

    #[test]
    fn test_direction_position_helpers() {
        let dir = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let pos = dir.position::<TestCenter, Meter>(2.0 * M);
        assert!((pos.x().value() - 2.0).abs() < 1e-12);
        assert!(pos.y().value().abs() < 1e-12);

        let params = TestParams { tag: 7 };
        let pos_params = dir.position_with_params::<ParamCenter, Meter>(params.clone(), 3.0 * M);
        assert_eq!(pos_params.center_params(), &params);
        assert!((pos_params.x().value() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_direction_scaling_operator_left() {
        let dir = Direction::<TestFrame>::new(0.0, 1.0, 0.0);
        let disp: Displacement<TestFrame, Meter> = 4.0 * M * dir;
        assert!((disp.y().value() - 4.0).abs() < 1e-12);
        assert!(disp.x().value().abs() < 1e-12);
    }

    #[test]
    fn test_direction_display() {
        let dir = Direction::<TestFrame>::new(1.0, 0.0, 0.0);
        let text = dir.display();
        assert!(text.contains("Frame: TestFrame"));
        assert!(text.contains("X: 1"));

        let text_prec = format!("{:.3}", dir);
        let expected_x = format!("{:.3}", dir.x());
        assert!(text_prec.contains(&format!("X: {expected_x}")));

        let text_exp = format!("{:.2e}", dir);
        let expected_y = format!("{:.2e}", dir.y());
        assert!(text_exp.contains(&format!("Y: {expected_y}")));
    }

    #[test]
    fn direction_has_xyz_layout() {
        assert_eq!(
            core::mem::size_of::<Direction<TestFrame>>(),
            core::mem::size_of::<XYZ<f64>>()
        );
        assert_eq!(
            core::mem::align_of::<Direction<TestFrame>>(),
            core::mem::align_of::<XYZ<f64>>()
        );
    }
}