retrofire_core/math/
mat.rs

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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
#![allow(clippy::needless_range_loop)]

//! Matrices and linear transforms.

use core::array;
use core::fmt::{self, Debug, Formatter};
use core::marker::PhantomData;
use core::ops::Range;

use crate::render::{NdcToScreen, ViewToProj};

use super::space::{Linear, Proj4, Real};
use super::vec::{ProjVec4, Vec2, Vec2u, Vec3, Vector};

/// A linear transform from one space (or basis) to another.
///
/// This is a tag trait with no functionality in itself. It is used to
/// statically ensure that only compatible maps can be composed, and that
/// only compatible vectors can be transformed.
pub trait LinearMap {
    /// The source space, or domain, of `Self`.
    type Source;
    /// The destination space, or range, of `Self`.
    type Dest;
}

/// Composition of two `LinearMap`s, `Self` ∘ `Inner`.
/// If `Self` maps from `B` to `C`, and `Inner` maps from `A` to `B`,
/// `Self::Result` maps from `A` to `C`.
pub trait Compose<Inner: LinearMap>: LinearMap<Source = Inner::Dest> {
    /// The result of composing `Self` with `Inner`.
    type Result: LinearMap<Source = Inner::Source, Dest = Self::Dest>;
}

/// A change of basis in real vector space of dimension `DIM`.
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub struct RealToReal<const DIM: usize, SrcBasis = (), DstBasis = ()>(
    PhantomData<(SrcBasis, DstBasis)>,
);

/// Mapping from real to projective space.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct RealToProj<SrcBasis>(PhantomData<SrcBasis>);

/// A generic matrix type.
#[repr(transparent)]
#[derive(Copy, Eq, PartialEq)]
pub struct Matrix<Repr, Map>(pub Repr, PhantomData<Map>);

/// Type alias for a 3x3 float matrix.
pub type Mat3x3<Map = ()> = Matrix<[[f32; 3]; 3], Map>;
/// Type alias for a 4x4 float matrix.
pub type Mat4x4<Map = ()> = Matrix<[[f32; 4]; 4], Map>;

//
// Inherent impls
//

impl<Repr, Map> Matrix<Repr, Map> {
    /// Returns a matrix with the given elements.
    #[inline]
    pub const fn new(els: Repr) -> Self {
        Self(els, PhantomData)
    }

    /// Returns a matrix equal to `self` but with mapping `M`.
    ///
    /// This method can be used to coerce a matrix to a different
    /// mapping in case it is needed to make types match.
    #[inline]
    pub fn to<M>(&self) -> Matrix<Repr, M>
    where
        Repr: Clone,
    {
        Matrix::new(self.0.clone())
    }
}

impl<Sc, const N: usize, const M: usize, Map> Matrix<[[Sc; N]; M], Map>
where
    Sc: Copy,
    Map: LinearMap,
{
    /// Returns the row vector of `self` with index `i`.
    /// The returned vector is in space `Map::Source`.
    ///
    /// # Panics
    /// If `i >= M`.
    #[inline]
    pub fn row_vec(&self, i: usize) -> Vector<[Sc; N], Map::Source> {
        Vector::new(self.0[i])
    }
    /// Returns the column vector of `self` with index `i`.
    ///
    /// The returned vector is in space `Map::Dest`.
    ///
    /// # Panics
    /// If `i >= N`.
    #[inline]
    pub fn col_vec(&self, i: usize) -> Vector<[Sc; M], Map::Dest> {
        Vector::new(self.0.map(|row| row[i]))
    }
}
impl<Sc: Copy, const N: usize, const DIM: usize, S, D>
    Matrix<[[Sc; N]; N], RealToReal<DIM, S, D>>
{
    /// Returns `self` with its rows and columns swapped.
    pub fn transpose(self) -> Matrix<[[Sc; N]; N], RealToReal<DIM, D, S>> {
        const { assert!(N >= DIM, "map dimension >= matrix dimension") }
        array::from_fn(|j| array::from_fn(|i| self.0[i][j])).into()
    }
}

impl<const N: usize, Map> Matrix<[[f32; N]; N], Map> {
    /// Returns the `N`×`N` identity matrix.
    pub const fn identity() -> Self {
        let mut els = [[0.0; N]; N];
        let mut i = 0;
        while i < N {
            els[i][i] = 1.0;
            i += 1;
        }
        Self::new(els)
    }

    /// Returns whether every element of `self` is finite
    /// (ie. neither `Inf`, `-Inf`, or `NaN`).
    fn is_finite(&self) -> bool {
        self.0.iter().flatten().all(|e| e.is_finite())
    }
}

impl<M: LinearMap> Mat4x4<M> {
    /// Constructs a matrix from a set of basis vectors.
    pub const fn from_basis(i: Vec3, j: Vec3, k: Vec3) -> Self {
        Self::new([
            [i.0[0], i.0[1], i.0[2], 0.0],
            [j.0[0], j.0[1], j.0[2], 0.0],
            [k.0[0], k.0[1], k.0[2], 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ])
    }
}

impl<Sc, const N: usize, Map> Matrix<[[Sc; N]; N], Map>
where
    Sc: Linear<Scalar = Sc> + Copy,
    Map: LinearMap,
{
    /// Returns the composite transform of `self` and `other`.
    ///
    /// Computes the matrix product of `self` and `other` such that applying
    /// the resulting transformation is equivalent to first applying `other`
    /// and then `self`. More succinctly,
    /// ```text
    /// (𝗠 ∘ 𝗡)𝘃 = 𝗠(𝗡𝘃)
    /// ```
    /// for some matrices 𝗠 and 𝗡 and a vector 𝘃.
    #[must_use]
    pub fn compose<Inner: LinearMap>(
        &self,
        other: &Matrix<[[Sc; N]; N], Inner>,
    ) -> Matrix<[[Sc; N]; N], <Map as Compose<Inner>>::Result>
    where
        Map: Compose<Inner>,
    {
        let cols: [_; N] = array::from_fn(|i| other.col_vec(i));
        array::from_fn(|j| {
            let row = self.row_vec(j);
            array::from_fn(|i| row.dot(&cols[i]))
        })
        .into()
    }
    /// Returns the composite transform of `other` and `self`.
    ///
    /// Computes the matrix product of `self` and `other` such that applying
    /// the resulting matrix is equivalent to first applying `self` and then
    /// `other`. The call `self.then(other)` is thus equivalent to
    /// `other.compose(self)`.
    #[must_use]
    pub fn then<Outer: Compose<Map>>(
        &self,
        other: &Matrix<[[Sc; N]; N], Outer>,
    ) -> Matrix<[[Sc; N]; N], <Outer as Compose<Map>>::Result> {
        other.compose(self)
    }
}

impl<Src, Dst> Mat3x3<RealToReal<2, Src, Dst>> {
    /// Maps the real 2-vector 𝘃 from basis `Src` to basis `Dst`.
    ///
    /// Computes the matrix–vector multiplication 𝝡𝘃 where 𝘃 is interpreted as
    /// a column vector with an implicit 𝘃<sub>2</sub> component with value 1:
    ///
    /// ```text
    ///         / M00 ·  ·  \ / v0 \
    ///  Mv  =  |  ·  ·  ·  | | v1 |  =  ( v0' v1' 1 )
    ///         \  ·  · M22 / \  1 /
    /// ```
    #[must_use]
    pub fn apply(&self, v: &Vec2<Src>) -> Vec2<Dst> {
        let v = [v.x(), v.y(), 1.0].into();
        array::from_fn(|i| self.row_vec(i).dot(&v)).into()
    }
}

impl<Src, Dst> Mat4x4<RealToReal<3, Src, Dst>> {
    /// Maps the real 3-vector 𝘃 from basis `Src` to basis `Dst`.
    ///
    /// Computes the matrix–vector multiplication 𝝡𝘃 where 𝘃 is interpreted as
    /// a column vector with an implicit 𝘃<sub>3</sub> component with value 1:
    ///
    /// ```text
    ///         / M00 ·  ·  ·  \ / v0 \
    ///  Mv  =  |  ·  ·  ·  ·  | | v1 |  =  ( v0' v1' v2' 1 )
    ///         |  ·  ·  ·  ·  | | v2 |
    ///         \  ·  ·  · M33 / \  1 /
    /// ```
    #[must_use]
    pub fn apply(&self, v: &Vec3<Src>) -> Vec3<Dst> {
        let v = [v.x(), v.y(), v.z(), 1.0].into();
        array::from_fn(|i| self.row_vec(i).dot(&v)).into()
    }

    /// Returns the determinant of `self`.
    ///
    /// Given a matrix M,
    /// ```text
    ///         / a  b  c  d \
    ///  M  =   | e  f  g  h |
    ///         | i  j  k  l |
    ///         \ m  n  o  p /
    /// ```
    /// its determinant can be computed by recursively computing
    /// the determinants of sub-matrices on rows 1.. and multiplying
    /// them by the elements on row 0:
    /// ```text
    ///              | f g h |       | e g h |
    /// det(M) = a · | j k l | - b · | i k l |  + - ···
    ///              | n o p |       | m o p |
    /// ```
    pub fn determinant(&self) -> f32 {
        let [[a, b, c, d], r, s, t] = self.0;
        let det2 = |m, n| s[m] * t[n] - s[n] * t[m];
        let det3 =
            |j, k, l| r[j] * det2(k, l) - r[k] * det2(j, l) + r[l] * det2(j, k);

        a * det3(1, 2, 3) - b * det3(0, 2, 3) + c * det3(0, 1, 3)
            - d * det3(0, 1, 2)
    }

    /// Returns the inverse matrix of `self`.
    ///
    /// The inverse 𝝡<sup>-1</sup> of matrix 𝝡 is a matrix that, when
    /// composed with 𝝡, results in the identity matrix:
    ///
    /// 𝝡 ∘ 𝝡<sup>-1</sup> = 𝝡<sup>-1</sup> ∘ 𝝡 = 𝐈
    ///
    /// In other words, it applies the transform of 𝝡 in reverse.
    /// Given vectors 𝘃 and 𝘂,
    ///
    /// 𝝡𝘃 = 𝘂 ⇔ 𝝡<sup>-1</sup> 𝘂 = 𝘃.
    ///
    /// Only matrices with a nonzero determinant have a defined inverse.
    /// A matrix without an inverse is said to be singular.
    ///
    /// Note: This method uses naive Gauss–Jordan elimination and may
    /// suffer from imprecision or numerical instability in certain cases.
    ///
    /// # Panics
    /// If `self` is singular or near-singular:
    /// * Panics in debug mode.
    /// * Does not panic in release mode, but the result may be inaccurate
    /// or contain `Inf`s or `NaN`s.
    #[must_use]
    pub fn inverse(&self) -> Mat4x4<RealToReal<3, Dst, Src>> {
        use super::float::f32;
        if cfg!(debug_assertions) {
            let det = self.determinant();
            assert!(
                f32::abs(det) > f32::EPSILON,
                "a singular, near-singular, or non-finite matrix does not \
                 have a well-defined inverse (determinant = {det})"
            );
        }

        // Elementary row operation subtracting one row,
        // multiplied by a scalar, from another
        fn sub_row(m: &mut Mat4x4, from: usize, to: usize, mul: f32) {
            m.0[to] = (m.row_vec(to) - m.row_vec(from) * mul).0;
        }

        // Elementary row operation multiplying one row with a scalar
        fn mul_row(m: &mut Mat4x4, row: usize, mul: f32) {
            m.0[row] = (m.row_vec(row) * mul).0;
        }

        // Elementary row operation swapping two rows
        fn swap_rows(m: &mut Mat4x4, r: usize, s: usize) {
            m.0.swap(r, s);
        }

        // This algorithm attempts to reduce `this` to the identity matrix
        // by simultaneously applying elementary row operations to it and
        // another matrix `inv` which starts as the identity matrix. Once
        // `this` is reduced, the value of `inv` has become the inverse of
        // `this` and thus of `self`.

        let inv = &mut Mat4x4::identity();
        let this = &mut self.to();

        // Apply row operations to reduce the matrix to an upper echelon form
        for idx in 0..4 {
            let pivot = (idx..4)
                .max_by(|&r1, &r2| {
                    let v1 = f32::abs(this.0[r1][idx]);
                    let v2 = f32::abs(this.0[r2][idx]);
                    v1.partial_cmp(&v2).unwrap()
                })
                .unwrap();

            if this.0[pivot][idx] != 0.0 {
                swap_rows(this, idx, pivot);
                swap_rows(inv, idx, pivot);

                let div = 1.0 / this.0[idx][idx];
                for r in (idx + 1)..4 {
                    let x = this.0[r][idx] * div;
                    sub_row(this, idx, r, x);
                    sub_row(inv, idx, r, x);
                }
            }
        }
        // now in upper echelon form, back-substitute variables
        for &idx in &[3, 2, 1] {
            let diag = this.0[idx][idx];
            for r in 0..idx {
                let x = this.0[r][idx] / diag;

                sub_row(this, idx, r, x);
                sub_row(inv, idx, r, x);
            }
        }
        // normalize
        for r in 0..4 {
            let x = 1.0 / this.0[r][r];
            mul_row(this, r, x);
            mul_row(inv, r, x);
        }
        debug_assert!(inv.is_finite());
        inv.to()
    }
}

impl<Src> Mat4x4<RealToProj<Src>> {
    /// Maps the real 3-vector 𝘃 from basis 𝖡 to the projective 4-space.
    ///
    /// Computes the matrix–vector multiplication 𝝡𝘃 where 𝘃 is interpreted as
    /// a column vector with an implicit 𝘃<sub>3</sub> component with value 1:
    ///
    /// ```text
    ///         / M00  ·  · \ / v0 \
    ///  Mv  =  |    ·      | | v1 |  =  ( v0' v1' v2' v3' )
    ///         |      ·    | | v2 |
    ///         \ ·  ·  M33 / \  1 /
    /// ```
    #[must_use]
    pub fn apply(&self, v: &Vec3<Src>) -> ProjVec4 {
        let v = Vector::from([v.x(), v.y(), v.z(), 1.0]);
        [
            self.row_vec(0).dot(&v),
            self.row_vec(1).dot(&v),
            self.row_vec(2).dot(&v),
            self.row_vec(3).dot(&v),
        ]
        .into()
    }
}

//
// Local trait impls
//

impl<const DIM: usize, S, D> LinearMap for RealToReal<DIM, S, D> {
    type Source = Real<DIM, S>;
    type Dest = Real<DIM, D>;
}

impl<const DIM: usize, S, I, D> Compose<RealToReal<DIM, S, I>>
    for RealToReal<DIM, I, D>
{
    type Result = RealToReal<DIM, S, D>;
}

impl<S> LinearMap for RealToProj<S> {
    type Source = Real<3, S>;
    type Dest = Proj4;
}

impl<S, I> Compose<RealToReal<3, S, I>> for RealToProj<I> {
    type Result = RealToProj<S>;
}

/// Dummy `LinearMap` to help with generic code.
impl LinearMap for () {
    type Source = ();
    type Dest = ();
}

//
// Foreign trait impls
//

impl<R: Clone, M> Clone for Matrix<R, M> {
    fn clone(&self) -> Self {
        self.to()
    }
}

impl<const N: usize, Map> Default for Matrix<[[f32; N]; N], Map> {
    /// Returns the `N`×`N` identity matrix.
    fn default() -> Self {
        Self::identity()
    }
}

impl<S: Debug, Map: Debug + Default, const N: usize, const M: usize> Debug
    for Matrix<[[S; N]; M], Map>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Matrix<{:?}>[", Map::default())?;
        for i in 0..M {
            writeln!(f, "    {:6.2?}", self.0[i])?;
        }
        write!(f, "]")
    }
}

impl<const DIM: usize, F, T> Debug for RealToReal<DIM, F, T>
where
    F: Debug + Default,
    T: Debug + Default,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}→{:?}", F::default(), T::default())
    }
}

impl<Repr, M> From<Repr> for Matrix<Repr, M> {
    fn from(repr: Repr) -> Self {
        Self(repr, PhantomData)
    }
}

//
// Free functions
//

/// Returns a matrix applying a scaling by `s`.
///
/// Tip: use [`splat`][super::vec::splat] to scale uniformly:
/// ```
/// # use retrofire_core::math::{mat::scale, vec::splat};
/// let m = scale(splat(2.0));
/// assert_eq!(m.0[0][0], 2.0);
/// assert_eq!(m.0[1][1], 2.0);
/// assert_eq!(m.0[2][2], 2.0);
/// ```
pub const fn scale(s: Vec3) -> Mat4x4<RealToReal<3>> {
    let [x, y, z] = s.0;
    Matrix::new([
        [x, 0.0, 0.0, 0.0],
        [0.0, y, 0.0, 0.0],
        [0.0, 0.0, z, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ])
}

/// Returns a matrix applying a translation by `t`.
pub const fn translate(t: Vec3) -> Mat4x4<RealToReal<3>> {
    let [x, y, z] = t.0;
    Matrix::new([
        [1.0, 0.0, 0.0, x],
        [0.0, 1.0, 0.0, y],
        [0.0, 0.0, 1.0, z],
        [0.0, 0.0, 0.0, 1.0],
    ])
}

/// Returns a matrix applying a rotation such that the original y axis
/// is now parallel with `new_y` and the new z axis is orthogonal to
/// both `x` and `new_y`.
///
/// Returns an orthogonal basis. If `new_y` and `x` are unit vectors,
/// the result is orthonormal.
#[cfg(feature = "fp")]
pub fn orient_y(new_y: Vec3, x: Vec3) -> Mat4x4<RealToReal<3>> {
    orient(new_y, x.cross(&new_y).normalize())
}
/// Returns a matrix applying a rotation such that the original z axis
/// is now parallel with `new_z` and the new y axis is orthogonal to
/// both `new_z` and `x`.
///
/// Returns an orthogonal basis. If `new_z` and `x` are unit vectors,
/// the result is orthonormal.
#[cfg(feature = "fp")]
pub fn orient_z(new_z: Vec3, x: Vec3) -> Mat4x4<RealToReal<3>> {
    orient(new_z.cross(&x).normalize(), new_z)
}

#[cfg(feature = "fp")]
fn orient(new_y: Vec3, new_z: Vec3) -> Mat4x4<RealToReal<3>> {
    use crate::math::{space::Linear, ApproxEq};

    assert!(!new_y.approx_eq(&Vec3::zero()));
    assert!(!new_z.approx_eq(&Vec3::zero()));

    let new_x = new_y.cross(&new_z);
    Mat4x4::from_basis(new_x, new_y, new_z)
}

// TODO constify rotate_* functions once we have const trig functions

/// Returns a matrix applying a rotation by `a` about the x axis.
#[cfg(feature = "fp")]
pub fn rotate_x(a: super::angle::Angle) -> Mat4x4<RealToReal<3>> {
    let (sin, cos) = a.sin_cos();
    [
        [1.0, 0.0, 0.0, 0.0],
        [0.0, cos, sin, 0.0],
        [0.0, -sin, cos, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
    .into()
}
/// Returns a matrix applying a rotation by `a` about the y axis.
#[cfg(feature = "fp")]
pub fn rotate_y(a: super::angle::Angle) -> Mat4x4<RealToReal<3>> {
    let (sin, cos) = a.sin_cos();
    [
        [cos, 0.0, -sin, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [sin, 0.0, cos, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
    .into()
}
/// Returns a matrix applying a rotation of angle `a` about the z axis.
#[cfg(feature = "fp")]
pub fn rotate_z(a: super::angle::Angle) -> Mat4x4<RealToReal<3>> {
    let (sin, cos) = a.sin_cos();
    [
        [cos, sin, 0.0, 0.0],
        [-sin, cos, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
    .into()
}

/// Creates a perspective projection matrix.
///
/// # Parameters
/// * `focal_ratio`: Focal length/aperture ratio. Larger values mean
/// a smaller angle of view, with 1.0 corresponding to a horizontal
/// field of view of 90 degrees.
/// * `aspect_ratio`: Viewport width/height ratio. Larger values mean
/// a wider field of view.
/// * `near_far`: Depth range between the near and far clipping planes.
/// Objects outside this range are clipped or culled.
///
/// # Panics
/// * If any parameter value is nonpositive.
/// * If `near_far` is an empty range.
pub fn perspective(
    focal_ratio: f32,
    aspect_ratio: f32,
    near_far: Range<f32>,
) -> Mat4x4<ViewToProj> {
    let (near, far) = (near_far.start, near_far.end);

    assert!(focal_ratio > 0.0, "focal ratio must be positive");
    assert!(aspect_ratio > 0.0, "aspect ratio must be positive");
    assert!(near > 0.0, "near must be positive");
    assert!(!near_far.is_empty(), "far must be greater than near");

    let e00 = focal_ratio;
    let e11 = e00 * aspect_ratio;
    let e22 = (far + near) / (far - near);
    let e23 = 2.0 * far * near / (near - far);
    [
        [e00, 0.0, 0.0, 0.0],
        [0.0, e11, 0.0, 0.0],
        [0.0, 0.0, e22, e23],
        [0.0, 0.0, 1.0, 0.0],
    ]
    .into()
}

/// Creates an orthographic projection matrix.
///
/// # Parameters
/// * `lbn`: The left-bottom-near corner of the projection box.
/// * `rtf`: The right-bottom-far corner of the projection box.
pub fn orthographic(lbn: Vec3, rtf: Vec3) -> Mat4x4<ViewToProj> {
    let [dx, dy, dz] = (rtf - lbn).0;
    let [sx, sy, sz] = (rtf + lbn).0;
    [
        [2.0 / dx, 0.0, 0.0, -sx / dx],
        [0.0, 2.0 / dy, 0.0, -sy / dy],
        [0.0, 0.0, 2.0 / dz, -sz / dz],
        [0.0, 0.0, 0.0, 1.0],
    ]
    .into()
}

/// Creates a viewport transform matrix. A viewport matrix is used to
/// transform points from the NDC space to screen space for rasterization.
///
/// # Parameters
/// * `bounds`: the left-top and right-bottom coordinates of the viewport.
pub fn viewport(bounds: Range<Vec2u>) -> Mat4x4<NdcToScreen> {
    let Range { start, end } = bounds;
    let h = (end.x() - start.x()) as f32 / 2.0;
    let v = (end.y() - start.y()) as f32 / 2.0;
    [
        [h, 0.0, 0.0, h + start.x() as f32],
        [0.0, v, 0.0, v + start.y() as f32],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
    .into()
}

#[cfg(test)]
mod tests {
    use crate::assert_approx_eq;
    use crate::math::vec::{splat, vec2, vec3};

    #[cfg(feature = "fp")]
    use crate::math::angle::degs;

    use super::*;

    #[derive(Debug, Default, Eq, PartialEq)]
    struct Basis1;
    #[derive(Debug, Default, Eq, PartialEq)]
    struct Basis2;

    type Map<const N: usize = 3> = RealToReal<N, Basis1, Basis2>;
    type InvMap<const N: usize = 3> = RealToReal<N, Basis2, Basis1>;

    mod mat3x3 {
        use super::*;

        const MAT: Mat3x3<Map> = Matrix::new([
            [0.0, 1.0, 2.0], //
            [10.0, 11.0, 12.0],
            [20.0, 21.0, 22.0],
        ]);

        #[test]
        fn row_col_vecs() {
            assert_eq!(MAT.row_vec(2), vec3::<_, Basis1>(20.0, 21.0, 22.0));
            assert_eq!(MAT.col_vec(2), vec3::<_, Basis2>(2.0, 12.0, 22.0));
        }

        #[test]
        fn composition() {
            let t = Mat3x3::<Map<2>>::new([
                [1.0, 0.0, 2.0], //
                [0.0, 1.0, -3.0],
                [0.0, 0.0, 1.0],
            ]);
            let s = Mat3x3::<InvMap<2>>::new([
                [-1.0, 0.0, 0.0], //
                [0.0, 2.0, 0.0],
                [0.0, 0.0, 1.0],
            ]);

            let ts = t.then(&s);
            let st = s.then(&t);

            assert_eq!(ts, s.compose(&t));
            assert_eq!(st, t.compose(&s));

            assert_eq!(ts.apply(&splat(0.0)), vec2(-2.0, -6.0));
            assert_eq!(st.apply(&splat(0.0)), vec2(2.0, -3.0));
        }

        #[test]
        fn scaling() {
            let m = Mat3x3::<Map<2>>::new([
                [2.0, 0.0, 0.0], //
                [0.0, -3.0, 0.0],
                [0.0, 0.0, 1.0],
            ]);
            assert_eq!(m.apply(&vec2(1.0, 2.0)), vec2(2.0, -6.0));
        }

        #[test]
        fn translation() {
            let m = Mat3x3::<Map<2>>::new([
                [1.0, 0.0, 2.0], //
                [0.0, 1.0, -3.0],
                [0.0, 0.0, 1.0],
            ]);
            assert_eq!(m.apply(&vec2(1.0, 2.0)), vec2(3.0, -1.0));
        }

        #[test]
        fn matrix_debug() {
            assert_eq!(
                alloc::format!("{MAT:?}"),
                r#"Matrix<Basis1→Basis2>[
    [  0.00,   1.00,   2.00]
    [ 10.00,  11.00,  12.00]
    [ 20.00,  21.00,  22.00]
]"#
            );
        }
    }

    mod mat4x4 {
        use super::*;

        const MAT: Mat4x4<Map> = Matrix::new([
            [0.0, 1.0, 2.0, 3.0],
            [10.0, 11.0, 12.0, 13.0],
            [20.0, 21.0, 22.0, 23.0],
            [30.0, 31.0, 32.0, 33.0],
        ]);

        #[test]
        fn row_col_vecs() {
            assert_eq!(MAT.row_vec(1), [10.0, 11.0, 12.0, 13.0].into());
            assert_eq!(MAT.col_vec(3), [3.0, 13.0, 23.0, 33.0].into());
        }

        #[test]
        fn composition() {
            let t = translate(vec3(1.0, 2.0, 3.0)).to::<Map>();
            let s = scale(vec3(3.0, 2.0, 1.0)).to::<InvMap>();

            let ts = t.then(&s);
            let st = s.then(&t);

            assert_eq!(ts, s.compose(&t));
            assert_eq!(st, t.compose(&s));

            assert_eq!(ts.apply(&splat(0.0)), vec3::<_, Basis1>(3.0, 4.0, 3.0));
            assert_eq!(st.apply(&splat(0.0)), vec3::<_, Basis2>(1.0, 2.0, 3.0));
        }

        #[test]
        fn scaling_vec3() {
            let m = scale(vec3(1.0, -2.0, 3.0));
            let v = vec3(0.0, 4.0, -3.0);
            assert_eq!(m.apply(&v), vec3(0.0, -8.0, -9.0));
        }

        #[test]
        fn translation_vec3() {
            let m = translate(vec3(1.0, 2.0, 3.0));
            let v = vec3(0.0, 5.0, -3.0);
            assert_eq!(m.apply(&v), vec3(1.0, 7.0, 0.0));
        }

        #[cfg(feature = "fp")]
        #[test]
        fn rotation_x() {
            let m = rotate_x(degs(90.0));
            assert_eq!(m.apply(&splat(0.0)), splat(0.0));
            assert_approx_eq!(
                m.apply(&vec3(0.0, 0.0, 1.0)),
                vec3(0.0, 1.0, 0.0)
            );
        }

        #[cfg(feature = "fp")]
        #[test]
        fn rotation_y() {
            let m = rotate_y(degs(90.0));
            assert_eq!(m.apply(&splat(0.0)), splat(0.0));
            assert_approx_eq!(
                m.apply(&vec3(1.0, 0.0, 0.0)),
                vec3(0.0, 0.0, 1.0)
            );
        }

        #[cfg(feature = "fp")]
        #[test]
        fn rotation_z() {
            let m = rotate_z(degs(90.0));
            assert_eq!(m.apply(&splat(0.0)), splat(0.0));
            assert_approx_eq!(
                m.apply(&vec3(0.0, 1.0, 0.0)),
                vec3(1.0, 0.0, 0.0)
            );
        }

        #[test]
        fn matrix_debug() {
            assert_eq!(
                alloc::format!("{MAT:?}"),
                r#"Matrix<Basis1→Basis2>[
    [  0.00,   1.00,   2.00,   3.00]
    [ 10.00,  11.00,  12.00,  13.00]
    [ 20.00,  21.00,  22.00,  23.00]
    [ 30.00,  31.00,  32.00,  33.00]
]"#
            );
        }
    }

    #[test]
    fn transposition() {
        let m = Matrix::<_, Map>::new([
            [0.0, 1.0, 2.0], //
            [10.0, 11.0, 12.0],
            [20.0, 21.0, 22.0],
        ]);
        assert_eq!(
            m.transpose(),
            Matrix::<_, InvMap>::new([
                [0.0, 10.0, 20.0], //
                [1.0, 11.0, 21.0],
                [2.0, 12.0, 22.0],
            ])
        );
    }

    #[test]
    fn determinant_of_identity_is_one() {
        let id: Mat4x4<Map> = Mat4x4::identity();
        assert_eq!(id.determinant(), 1.0);
    }

    #[test]
    fn determinant_of_scaling_is_product_of_diagonal() {
        let scale: Mat4x4<_> = scale(vec3(2.0, 3.0, 4.0));
        assert_eq!(scale.determinant(), 24.0);
    }

    #[cfg(feature = "fp")]
    #[test]
    fn determinant_of_rotation_is_one() {
        let rot = rotate_x(degs(73.0)).then(&rotate_y(degs(-106.0)));
        assert_approx_eq!(rot.determinant(), 1.0);
    }

    #[cfg(feature = "fp")]
    #[test]
    fn mat_times_mat_inverse_is_identity() {
        let m = translate(vec3(1.0e3, -2.0e2, 0.0))
            .then(&scale(vec3(0.5, 100.0, 42.0)))
            .to::<Map>();

        let m_inv: Mat4x4<InvMap> = m.inverse();

        assert_eq!(
            m.compose(&m_inv),
            Mat4x4::<RealToReal<3, Basis2, Basis2>>::identity()
        );
        assert_eq!(
            m_inv.compose(&m),
            Mat4x4::<RealToReal<3, Basis1, Basis1>>::identity()
        );
    }

    #[test]
    fn inverse_reverts_transform() {
        let m: Mat4x4<Map> = scale(vec3(1.0, 2.0, 0.5))
            .then(&translate(vec3(-2.0, 3.0, 0.0)))
            .to();
        let m_inv: Mat4x4<InvMap> = m.inverse();

        let v1: Vec3<Basis1> = vec3(1.0, -2.0, 3.0);
        let v2: Vec3<Basis2> = vec3(2.0, 0.0, -2.0);

        assert_eq!(m_inv.apply(&m.apply(&v1)), v1);
        assert_eq!(m.apply(&m_inv.apply(&v2)), v2);
    }

    #[test]
    fn orthographic_box_maps_to_unit_cube() {
        let lbn = vec3(-20.0, 0.0, 0.01);
        let rtf = vec3(100.0, 50.0, 100.0);

        let m = orthographic(lbn, rtf);

        assert_approx_eq!(m.apply(&lbn.to()), [-1.0, -1.0, -1.0, 1.0].into());
        assert_approx_eq!(m.apply(&rtf.to()), splat(1.0));
    }

    #[test]
    fn perspective_frustum_maps_to_unit_cube() {
        let left_bot_near = vec3(-0.125, -0.0625, 0.1);
        let right_top_far = vec3(125.0, 62.5, 100.0);

        let m = perspective(0.8, 2.0, 0.1..100.0);

        let lbn = m.apply(&left_bot_near);
        assert_approx_eq!(lbn / lbn.w(), [-1.0, -1.0, -1.0, 1.0].into());

        let rtf = m.apply(&right_top_far);
        assert_approx_eq!(rtf / rtf.w(), splat(1.0));
    }
}