euclid/
transform3d.rs

1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10#![cfg_attr(feature = "cargo-clippy", allow(just_underscores_and_digits))]
11
12use super::{UnknownUnit, Angle};
13use crate::approxeq::ApproxEq;
14use crate::homogen::HomogeneousVector;
15#[cfg(feature = "mint")]
16use mint;
17use crate::trig::Trig;
18use crate::point::{Point2D, point2, Point3D, point3};
19use crate::vector::{Vector2D, Vector3D, vec2, vec3};
20use crate::rect::Rect;
21use crate::box2d::Box2D;
22use crate::box3d::Box3D;
23use crate::transform2d::Transform2D;
24use crate::scale::Scale;
25use crate::num::{One, Zero};
26use core::ops::{Add, Mul, Sub, Div, Neg};
27use core::marker::PhantomData;
28use core::fmt;
29use core::cmp::{Eq, PartialEq};
30use core::hash::{Hash};
31use num_traits::NumCast;
32#[cfg(feature = "serde")]
33use serde::{Deserialize, Serialize};
34
35/// A 3d transform stored as a column-major 4 by 4 matrix.
36///
37/// Transforms can be parametrized over the source and destination units, to describe a
38/// transformation from a space to another.
39/// For example, `Transform3D<f32, WorldSpace, ScreenSpace>::transform_point3d`
40/// takes a `Point3D<f32, WorldSpace>` and returns a `Point3D<f32, ScreenSpace>`.
41///
42/// Transforms expose a set of convenience methods for pre- and post-transformations.
43/// Pre-transformations (`pre_*` methods) correspond to adding an operation that is
44/// applied before the rest of the transformation, while post-transformations (`then_*`
45/// methods) add an operation that is applied after.
46///
47/// When translating Transform3D into general matrix representations, consider that the
48/// representation follows the column major notation with column vectors.
49///
50/// ```text
51///  |x'|   | m11 m12 m13 m14 |   |x|
52///  |y'|   | m21 m22 m23 m24 |   |y|
53///  |z'| = | m31 m32 m33 m34 | x |y|
54///  |w |   | m41 m42 m43 m44 |   |1|
55/// ```
56///
57/// The translation terms are m41, m42 and m43.
58#[repr(C)]
59#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60#[cfg_attr(
61    feature = "serde",
62    serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))
63)]
64pub struct Transform3D<T, Src, Dst> {
65    pub m11: T, pub m12: T, pub m13: T, pub m14: T,
66    pub m21: T, pub m22: T, pub m23: T, pub m24: T,
67    pub m31: T, pub m32: T, pub m33: T, pub m34: T,
68    pub m41: T, pub m42: T, pub m43: T, pub m44: T,
69    #[doc(hidden)]
70    pub _unit: PhantomData<(Src, Dst)>,
71}
72
73impl<T: Copy, Src, Dst> Copy for Transform3D<T, Src, Dst> {}
74
75impl<T: Clone, Src, Dst> Clone for Transform3D<T, Src, Dst> {
76    fn clone(&self) -> Self {
77        Transform3D {
78            m11: self.m11.clone(),
79            m12: self.m12.clone(),
80            m13: self.m13.clone(),
81            m14: self.m14.clone(),
82            m21: self.m21.clone(),
83            m22: self.m22.clone(),
84            m23: self.m23.clone(),
85            m24: self.m24.clone(),
86            m31: self.m31.clone(),
87            m32: self.m32.clone(),
88            m33: self.m33.clone(),
89            m34: self.m34.clone(),
90            m41: self.m41.clone(),
91            m42: self.m42.clone(),
92            m43: self.m43.clone(),
93            m44: self.m44.clone(),
94            _unit: PhantomData,
95        }
96    }
97}
98
99impl<T, Src, Dst> Eq for Transform3D<T, Src, Dst> where T: Eq {}
100
101impl<T, Src, Dst> PartialEq for Transform3D<T, Src, Dst>
102    where T: PartialEq
103{
104    fn eq(&self, other: &Self) -> bool {
105        self.m11 == other.m11 &&
106            self.m12 == other.m12 &&
107            self.m13 == other.m13 &&
108            self.m14 == other.m14 &&
109            self.m21 == other.m21 &&
110            self.m22 == other.m22 &&
111            self.m23 == other.m23 &&
112            self.m24 == other.m24 &&
113            self.m31 == other.m31 &&
114            self.m32 == other.m32 &&
115            self.m33 == other.m33 &&
116            self.m34 == other.m34 &&
117            self.m41 == other.m41 &&
118            self.m42 == other.m42 &&
119            self.m43 == other.m43 &&
120            self.m44 == other.m44
121    }
122}
123
124impl<T, Src, Dst> Hash for Transform3D<T, Src, Dst>
125    where T: Hash
126{
127    fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
128        self.m11.hash(h);
129        self.m12.hash(h);
130        self.m13.hash(h);
131        self.m14.hash(h);
132        self.m21.hash(h);
133        self.m22.hash(h);
134        self.m23.hash(h);
135        self.m24.hash(h);
136        self.m31.hash(h);
137        self.m32.hash(h);
138        self.m33.hash(h);
139        self.m34.hash(h);
140        self.m41.hash(h);
141        self.m42.hash(h);
142        self.m43.hash(h);
143        self.m44.hash(h);
144    }
145}
146
147
148impl<T, Src, Dst> Transform3D<T, Src, Dst> {
149    /// Create a transform specifying all of it's component as a 4 by 4 matrix.
150    ///
151    /// Components are specified following column-major-column-vector matrix notation.
152    /// For example, the translation terms m41, m42, m43 are the 13rd, 14th and 15th parameters.
153    ///
154    /// ```
155    /// use euclid::default::Transform3D;
156    /// let tx = 1.0;
157    /// let ty = 2.0;
158    /// let tz = 3.0;
159    /// let translation = Transform3D::new(
160    ///   1.0, 0.0, 0.0, 0.0,
161    ///   0.0, 1.0, 0.0, 0.0,
162    ///   0.0, 0.0, 1.0, 0.0,
163    ///   tx,  ty,  tz,  1.0,
164    /// );
165    /// ```
166    #[inline]
167    #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
168    pub const fn new(
169        m11: T, m12: T, m13: T, m14: T,
170        m21: T, m22: T, m23: T, m24: T,
171        m31: T, m32: T, m33: T, m34: T,
172        m41: T, m42: T, m43: T, m44: T,
173    ) -> Self {
174        Transform3D {
175            m11, m12, m13, m14,
176            m21, m22, m23, m24,
177            m31, m32, m33, m34,
178            m41, m42, m43, m44,
179            _unit: PhantomData,
180        }
181    }
182
183    /// Create a transform representing a 2d transformation from the components
184    /// of a 2 by 3 matrix transformation.
185    ///
186    /// Components follow the column-major-column-vector notation (m41 and m42
187    /// representating the translation terms).
188    ///
189    /// ```text
190    /// m11  m12   0   0
191    /// m21  m22   0   0
192    ///   0    0   1   0
193    /// m41  m42   0   1
194    /// ```
195    #[inline]
196    pub fn new_2d(m11: T, m12: T, m21: T, m22: T, m41: T, m42: T) -> Self
197    where
198        T: Zero + One,
199    {
200        let _0 = || T::zero();
201        let _1 = || T::one();
202
203        Self::new(
204            m11,  m12,  _0(), _0(),
205            m21,  m22,  _0(), _0(),
206            _0(), _0(), _1(), _0(),
207            m41,  m42,  _0(), _1()
208       )
209    }
210
211
212    /// Returns `true` if this transform can be represented with a `Transform2D`.
213    ///
214    /// See <https://drafts.csswg.org/css-transforms/#2d-transform>
215    #[inline]
216    pub fn is_2d(&self) -> bool
217    where
218        T: Zero + One + PartialEq,
219    {
220        let (_0, _1): (T, T) = (Zero::zero(), One::one());
221        self.m31 == _0 && self.m32 == _0 &&
222        self.m13 == _0 && self.m23 == _0 &&
223        self.m43 == _0 && self.m14 == _0 &&
224        self.m24 == _0 && self.m34 == _0 &&
225        self.m33 == _1 && self.m44 == _1
226    }
227}
228
229impl<T: Copy, Src, Dst> Transform3D<T, Src, Dst> {
230    /// Returns an array containing this transform's terms.
231    ///
232    /// The terms are laid out in the same order as they are
233    /// specified in `Transform3D::new`, that is following the
234    /// column-major-column-vector matrix notation.
235    ///
236    /// For example the translation terms are found on the
237    /// 13th, 14th and 15th slots of the array.
238    #[inline]
239    pub fn to_array(&self) -> [T; 16] {
240        [
241            self.m11, self.m12, self.m13, self.m14,
242            self.m21, self.m22, self.m23, self.m24,
243            self.m31, self.m32, self.m33, self.m34,
244            self.m41, self.m42, self.m43, self.m44
245        ]
246    }
247
248    /// Returns an array containing this transform's terms transposed.
249    ///
250    /// The terms are laid out in transposed order from the same order of
251    /// `Transform3D::new` and `Transform3D::to_array`, that is following
252    /// the row-major-column-vector matrix notation.
253    ///
254    /// For example the translation terms are found at indices 3, 7 and 11
255    /// of the array.
256    #[inline]
257    pub fn to_array_transposed(&self) -> [T; 16] {
258        [
259            self.m11, self.m21, self.m31, self.m41,
260            self.m12, self.m22, self.m32, self.m42,
261            self.m13, self.m23, self.m33, self.m43,
262            self.m14, self.m24, self.m34, self.m44
263        ]
264    }
265
266    /// Equivalent to `to_array` with elements packed four at a time
267    /// in an array of arrays.
268    #[inline]
269    pub fn to_arrays(&self) -> [[T; 4]; 4] {
270        [
271            [self.m11, self.m12, self.m13, self.m14],
272            [self.m21, self.m22, self.m23, self.m24],
273            [self.m31, self.m32, self.m33, self.m34],
274            [self.m41, self.m42, self.m43, self.m44]
275        ]
276    }
277
278    /// Equivalent to `to_array_transposed` with elements packed
279    /// four at a time in an array of arrays.
280    #[inline]
281    pub fn to_arrays_transposed(&self) -> [[T; 4]; 4] {
282        [
283            [self.m11, self.m21, self.m31, self.m41],
284            [self.m12, self.m22, self.m32, self.m42],
285            [self.m13, self.m23, self.m33, self.m43],
286            [self.m14, self.m24, self.m34, self.m44]
287        ]
288    }
289
290    /// Create a transform providing its components via an array
291    /// of 16 elements instead of as individual parameters.
292    ///
293    /// The order of the components corresponds to the
294    /// column-major-column-vector matrix notation (the same order
295    /// as `Transform3D::new`).
296    #[inline]
297    pub fn from_array(array: [T; 16]) -> Self {
298        Self::new(
299            array[0],  array[1],  array[2],  array[3],
300            array[4],  array[5],  array[6],  array[7],
301            array[8],  array[9],  array[10], array[11],
302            array[12], array[13], array[14], array[15],
303        )
304    }
305
306    /// Equivalent to `from_array` with elements packed four at a time
307    /// in an array of arrays.
308    ///
309    /// The order of the components corresponds to the
310    /// column-major-column-vector matrix notation (the same order
311    /// as `Transform3D::new`).
312    #[inline]
313    pub fn from_arrays(array: [[T; 4]; 4]) -> Self {
314        Self::new(
315            array[0][0], array[0][1], array[0][2], array[0][3],
316            array[1][0], array[1][1], array[1][2], array[1][3],
317            array[2][0], array[2][1], array[2][2], array[2][3],
318            array[3][0], array[3][1], array[3][2], array[3][3],
319        )
320    }
321
322    /// Tag a unitless value with units.
323    #[inline]
324    pub fn from_untyped(m: &Transform3D<T, UnknownUnit, UnknownUnit>) -> Self {
325        Transform3D::new(
326            m.m11, m.m12, m.m13, m.m14,
327            m.m21, m.m22, m.m23, m.m24,
328            m.m31, m.m32, m.m33, m.m34,
329            m.m41, m.m42, m.m43, m.m44,
330        )
331    }
332
333    /// Drop the units, preserving only the numeric value.
334    #[inline]
335    pub fn to_untyped(&self) -> Transform3D<T, UnknownUnit, UnknownUnit> {
336        Transform3D::new(
337            self.m11, self.m12, self.m13, self.m14,
338            self.m21, self.m22, self.m23, self.m24,
339            self.m31, self.m32, self.m33, self.m34,
340            self.m41, self.m42, self.m43, self.m44,
341        )
342    }
343
344    /// Returns the same transform with a different source unit.
345    #[inline]
346    pub fn with_source<NewSrc>(&self) -> Transform3D<T, NewSrc, Dst> {
347        Transform3D::new(
348            self.m11, self.m12, self.m13, self.m14,
349            self.m21, self.m22, self.m23, self.m24,
350            self.m31, self.m32, self.m33, self.m34,
351            self.m41, self.m42, self.m43, self.m44,
352        )
353    }
354
355    /// Returns the same transform with a different destination unit.
356    #[inline]
357    pub fn with_destination<NewDst>(&self) -> Transform3D<T, Src, NewDst> {
358        Transform3D::new(
359            self.m11, self.m12, self.m13, self.m14,
360            self.m21, self.m22, self.m23, self.m24,
361            self.m31, self.m32, self.m33, self.m34,
362            self.m41, self.m42, self.m43, self.m44,
363        )
364    }
365
366    /// Create a 2D transform picking the relevant terms from this transform.
367    ///
368    /// This method assumes that self represents a 2d transformation, callers
369    /// should check that [`self.is_2d()`] returns `true` beforehand.
370    ///
371    /// [`self.is_2d()`]: #method.is_2d
372    pub fn to_2d(&self) -> Transform2D<T, Src, Dst> {
373        Transform2D::new(
374            self.m11, self.m12,
375            self.m21, self.m22,
376            self.m41, self.m42
377        )
378    }
379}
380
381impl <T, Src, Dst> Transform3D<T, Src, Dst>
382where
383    T: Zero + One,
384{
385    /// Creates an identity matrix:
386    ///
387    /// ```text
388    /// 1 0 0 0
389    /// 0 1 0 0
390    /// 0 0 1 0
391    /// 0 0 0 1
392    /// ```
393    #[inline]
394    pub fn identity() -> Self {
395        Self::translation(T::zero(), T::zero(), T::zero())
396    }
397
398    /// Intentional not public, because it checks for exact equivalence
399    /// while most consumers will probably want some sort of approximate
400    /// equivalence to deal with floating-point errors.
401    #[inline]
402    fn is_identity(&self) -> bool
403    where
404        T: PartialEq,
405    {
406        *self == Self::identity()
407    }
408
409    /// Create a 2d skew transform.
410    ///
411    /// See <https://drafts.csswg.org/css-transforms/#funcdef-skew>
412    pub fn skew(alpha: Angle<T>, beta: Angle<T>) -> Self
413    where
414        T: Trig,
415    {
416        let _0 = || T::zero();
417        let _1 = || T::one();
418        let (sx, sy) = (beta.radians.tan(), alpha.radians.tan());
419
420        Self::new(
421            _1(), sx,   _0(), _0(),
422            sy,   _1(), _0(), _0(),
423            _0(), _0(), _1(), _0(),
424            _0(), _0(), _0(), _1(),
425        )
426    }
427
428    /// Create a simple perspective transform, projecting to the plane `z = -d`.
429    ///
430    /// ```text
431    /// 1   0   0   0
432    /// 0   1   0   0
433    /// 0   0   1 -1/d
434    /// 0   0   0   1
435    /// ```
436    ///
437    /// See <https://drafts.csswg.org/css-transforms-2/#PerspectiveDefined>.
438    pub fn perspective(d: T) -> Self
439    where
440        T: Neg<Output = T> + Div<Output = T>,
441    {
442        let _0 = || T::zero();
443        let _1 = || T::one();
444
445        Self::new(
446            _1(), _0(), _0(),  _0(),
447            _0(), _1(), _0(),  _0(),
448            _0(), _0(), _1(), -_1() / d,
449            _0(), _0(), _0(),  _1(),
450        )
451    }
452}
453
454
455/// Methods for combining generic transformations
456impl <T, Src, Dst> Transform3D<T, Src, Dst>
457where
458    T: Copy + Add<Output = T> + Mul<Output = T>,
459{
460    /// Returns the multiplication of the two matrices such that mat's transformation
461    /// applies after self's transformation.
462    ///
463    /// Assuming row vectors, this is equivalent to self * mat
464    #[must_use]
465    pub fn then<NewDst>(&self, other: &Transform3D<T, Dst, NewDst>) -> Transform3D<T, Src, NewDst> {
466        Transform3D::new(
467            self.m11 * other.m11  +  self.m12 * other.m21  +  self.m13 * other.m31  +  self.m14 * other.m41,
468            self.m11 * other.m12  +  self.m12 * other.m22  +  self.m13 * other.m32  +  self.m14 * other.m42,
469            self.m11 * other.m13  +  self.m12 * other.m23  +  self.m13 * other.m33  +  self.m14 * other.m43,
470            self.m11 * other.m14  +  self.m12 * other.m24  +  self.m13 * other.m34  +  self.m14 * other.m44,
471
472            self.m21 * other.m11  +  self.m22 * other.m21  +  self.m23 * other.m31  +  self.m24 * other.m41,
473            self.m21 * other.m12  +  self.m22 * other.m22  +  self.m23 * other.m32  +  self.m24 * other.m42,
474            self.m21 * other.m13  +  self.m22 * other.m23  +  self.m23 * other.m33  +  self.m24 * other.m43,
475            self.m21 * other.m14  +  self.m22 * other.m24  +  self.m23 * other.m34  +  self.m24 * other.m44,
476
477            self.m31 * other.m11  +  self.m32 * other.m21  +  self.m33 * other.m31  +  self.m34 * other.m41,
478            self.m31 * other.m12  +  self.m32 * other.m22  +  self.m33 * other.m32  +  self.m34 * other.m42,
479            self.m31 * other.m13  +  self.m32 * other.m23  +  self.m33 * other.m33  +  self.m34 * other.m43,
480            self.m31 * other.m14  +  self.m32 * other.m24  +  self.m33 * other.m34  +  self.m34 * other.m44,
481
482            self.m41 * other.m11  +  self.m42 * other.m21  +  self.m43 * other.m31  +  self.m44 * other.m41,
483            self.m41 * other.m12  +  self.m42 * other.m22  +  self.m43 * other.m32  +  self.m44 * other.m42,
484            self.m41 * other.m13  +  self.m42 * other.m23  +  self.m43 * other.m33  +  self.m44 * other.m43,
485            self.m41 * other.m14  +  self.m42 * other.m24  +  self.m43 * other.m34  +  self.m44 * other.m44,
486        )
487    }
488}
489
490/// Methods for creating and combining translation transformations
491impl <T, Src, Dst> Transform3D<T, Src, Dst>
492where
493    T: Zero + One,
494{
495    /// Create a 3d translation transform:
496    ///
497    /// ```text
498    /// 1 0 0 0
499    /// 0 1 0 0
500    /// 0 0 1 0
501    /// x y z 1
502    /// ```
503    #[inline]
504    pub fn translation(x: T, y: T, z: T) -> Self {
505        let _0 = || T::zero();
506        let _1 = || T::one();
507
508        Self::new(
509            _1(), _0(), _0(), _0(),
510            _0(), _1(), _0(), _0(),
511            _0(), _0(), _1(), _0(),
512             x,    y,    z,   _1(),
513        )
514    }
515
516    /// Returns a transform with a translation applied before self's transformation.
517    #[must_use]
518    pub fn pre_translate(&self, v: Vector3D<T, Src>) -> Self
519    where
520        T: Copy + Add<Output = T> + Mul<Output = T>,
521    {
522        Transform3D::translation(v.x, v.y, v.z).then(self)
523    }
524
525    /// Returns a transform with a translation applied after self's transformation.
526    #[must_use]
527    pub fn then_translate(&self, v: Vector3D<T, Dst>) -> Self
528    where
529        T: Copy + Add<Output = T> + Mul<Output = T>,
530    {
531        self.then(&Transform3D::translation(v.x, v.y, v.z))
532    }
533}
534
535/// Methods for creating and combining rotation transformations
536impl<T, Src, Dst> Transform3D<T, Src, Dst>
537where
538    T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Zero + One + Trig,
539{
540    /// Create a 3d rotation transform from an angle / axis.
541    /// The supplied axis must be normalized.
542    pub fn rotation(x: T, y: T, z: T, theta: Angle<T>) -> Self {
543        let (_0, _1): (T, T) = (Zero::zero(), One::one());
544        let _2 = _1 + _1;
545
546        let xx = x * x;
547        let yy = y * y;
548        let zz = z * z;
549
550        let half_theta = theta.get() / _2;
551        let sc = half_theta.sin() * half_theta.cos();
552        let sq = half_theta.sin() * half_theta.sin();
553
554        Transform3D::new(
555            _1 - _2 * (yy + zz) * sq,
556            _2 * (x * y * sq + z * sc),
557            _2 * (x * z * sq - y * sc),
558            _0,
559
560
561            _2 * (x * y * sq - z * sc),
562            _1 - _2 * (xx + zz) * sq,
563            _2 * (y * z * sq + x * sc),
564            _0,
565
566            _2 * (x * z * sq + y * sc),
567            _2 * (y * z * sq - x * sc),
568            _1 - _2 * (xx + yy) * sq,
569            _0,
570
571            _0,
572            _0,
573            _0,
574            _1
575        )
576    }
577
578    /// Returns a transform with a rotation applied after self's transformation.
579    #[must_use]
580    pub fn then_rotate(&self, x: T, y: T, z: T, theta: Angle<T>) -> Self {
581        self.then(&Transform3D::rotation(x, y, z, theta))
582    }
583
584    /// Returns a transform with a rotation applied before self's transformation.
585    #[must_use]
586    pub fn pre_rotate(&self, x: T, y: T, z: T, theta: Angle<T>) -> Self {
587        Transform3D::rotation(x, y, z, theta).then(self)
588    }
589}
590
591/// Methods for creating and combining scale transformations
592impl<T, Src, Dst> Transform3D<T, Src, Dst>
593where
594    T: Zero + One,
595{
596    /// Create a 3d scale transform:
597    ///
598    /// ```text
599    /// x 0 0 0
600    /// 0 y 0 0
601    /// 0 0 z 0
602    /// 0 0 0 1
603    /// ```
604    #[inline]
605    pub fn scale(x: T, y: T, z: T) -> Self {
606        let _0 = || T::zero();
607        let _1 = || T::one();
608
609        Self::new(
610             x,   _0(), _0(), _0(),
611            _0(),  y,   _0(), _0(),
612            _0(), _0(),  z,   _0(),
613            _0(), _0(), _0(), _1(),
614        )
615    }
616
617    /// Returns a transform with a scale applied before self's transformation.
618    #[must_use]
619    pub fn pre_scale(&self, x: T, y: T, z: T) -> Self
620    where
621        T: Copy + Add<Output = T> + Mul<Output = T>,
622    {
623        Transform3D::new(
624            self.m11 * x, self.m12 * x, self.m13 * x, self.m14 * x,
625            self.m21 * y, self.m22 * y, self.m23 * y, self.m24 * y,
626            self.m31 * z, self.m32 * z, self.m33 * z, self.m34 * z,
627            self.m41    , self.m42,     self.m43,     self.m44
628        )
629    }
630
631    /// Returns a transform with a scale applied after self's transformation.
632    #[must_use]
633    pub fn then_scale(&self, x: T, y: T, z: T) -> Self
634    where
635        T: Copy + Add<Output = T> + Mul<Output = T>,
636    {
637        self.then(&Transform3D::scale(x, y, z))
638    }
639}
640
641/// Methods for apply transformations to objects
642impl<T, Src, Dst> Transform3D<T, Src, Dst>
643where
644    T: Copy + Add<Output = T> + Mul<Output = T>,
645{
646    /// Returns the homogeneous vector corresponding to the transformed 2d point.
647    ///
648    /// The input point must be use the unit Src, and the returned point has the unit Dst.
649    #[inline]
650    pub fn transform_point2d_homogeneous(
651        &self, p: Point2D<T, Src>
652    ) -> HomogeneousVector<T, Dst> {
653        let x = p.x * self.m11 + p.y * self.m21 + self.m41;
654        let y = p.x * self.m12 + p.y * self.m22 + self.m42;
655        let z = p.x * self.m13 + p.y * self.m23 + self.m43;
656        let w = p.x * self.m14 + p.y * self.m24 + self.m44;
657
658        HomogeneousVector::new(x, y, z, w)
659    }
660
661    /// Returns the given 2d point transformed by this transform, if the transform makes sense,
662    /// or `None` otherwise.
663    ///
664    /// The input point must be use the unit Src, and the returned point has the unit Dst.
665    #[inline]
666    pub fn transform_point2d(&self, p: Point2D<T, Src>) -> Option<Point2D<T, Dst>>
667    where
668        T: Div<Output = T> + Zero + PartialOrd,
669    {
670        //Note: could use `transform_point2d_homogeneous()` but it would waste the calculus of `z`
671        let w = p.x * self.m14 + p.y * self.m24 + self.m44;
672        if w > T::zero() {
673            let x = p.x * self.m11 + p.y * self.m21 + self.m41;
674            let y = p.x * self.m12 + p.y * self.m22 + self.m42;
675
676            Some(Point2D::new(x / w, y / w))
677        } else {
678            None
679        }
680    }
681
682    /// Returns the given 2d vector transformed by this matrix.
683    ///
684    /// The input point must be use the unit Src, and the returned point has the unit Dst.
685    #[inline]
686    pub fn transform_vector2d(&self, v: Vector2D<T, Src>) -> Vector2D<T, Dst> {
687        vec2(
688            v.x * self.m11 + v.y * self.m21,
689            v.x * self.m12 + v.y * self.m22,
690        )
691    }
692
693    /// Returns the homogeneous vector corresponding to the transformed 3d point.
694    ///
695    /// The input point must be use the unit Src, and the returned point has the unit Dst.
696    #[inline]
697    pub fn transform_point3d_homogeneous(
698        &self, p: Point3D<T, Src>
699    ) -> HomogeneousVector<T, Dst> {
700        let x = p.x * self.m11 + p.y * self.m21 + p.z * self.m31 + self.m41;
701        let y = p.x * self.m12 + p.y * self.m22 + p.z * self.m32 + self.m42;
702        let z = p.x * self.m13 + p.y * self.m23 + p.z * self.m33 + self.m43;
703        let w = p.x * self.m14 + p.y * self.m24 + p.z * self.m34 + self.m44;
704
705        HomogeneousVector::new(x, y, z, w)
706    }
707
708    /// Returns the given 3d point transformed by this transform, if the transform makes sense,
709    /// or `None` otherwise.
710    ///
711    /// The input point must be use the unit Src, and the returned point has the unit Dst.
712    #[inline]
713    pub fn transform_point3d(&self, p: Point3D<T, Src>) -> Option<Point3D<T, Dst>>
714    where
715        T: Div<Output = T> + Zero + PartialOrd,
716    {
717        self.transform_point3d_homogeneous(p).to_point3d()
718    }
719
720    /// Returns the given 3d vector transformed by this matrix.
721    ///
722    /// The input point must be use the unit Src, and the returned point has the unit Dst.
723    #[inline]
724    pub fn transform_vector3d(&self, v: Vector3D<T, Src>) -> Vector3D<T, Dst> {
725        vec3(
726            v.x * self.m11 + v.y * self.m21 + v.z * self.m31,
727            v.x * self.m12 + v.y * self.m22 + v.z * self.m32,
728            v.x * self.m13 + v.y * self.m23 + v.z * self.m33,
729        )
730    }
731
732    /// Returns a rectangle that encompasses the result of transforming the given rectangle by this
733    /// transform, if the transform makes sense for it, or `None` otherwise.
734    pub fn outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Option<Rect<T, Dst>>
735    where
736        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
737    {
738        let min = rect.min();
739        let max = rect.max();
740        Some(Rect::from_points(&[
741            self.transform_point2d(min)?,
742            self.transform_point2d(max)?,
743            self.transform_point2d(point2(max.x, min.y))?,
744            self.transform_point2d(point2(min.x, max.y))?,
745        ]))
746    }
747
748    /// Returns a 2d box that encompasses the result of transforming the given box by this
749    /// transform, if the transform makes sense for it, or `None` otherwise.
750    pub fn outer_transformed_box2d(&self, b: &Box2D<T, Src>) -> Option<Box2D<T, Dst>>
751    where
752        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
753    {
754        Some(Box2D::from_points(&[
755            self.transform_point2d(b.min)?,
756            self.transform_point2d(b.max)?,
757            self.transform_point2d(point2(b.max.x, b.min.y))?,
758            self.transform_point2d(point2(b.min.x, b.max.y))?,
759        ]))
760    }
761
762    /// Returns a 3d box that encompasses the result of transforming the given box by this
763    /// transform, if the transform makes sense for it, or `None` otherwise.
764    pub fn outer_transformed_box3d(&self, b: &Box3D<T, Src>) -> Option<Box3D<T, Dst>>
765    where
766        T: Sub<Output = T> + Div<Output = T> + Zero + PartialOrd,
767    {
768        Some(Box3D::from_points(&[
769            self.transform_point3d(point3(b.min.x, b.min.y, b.min.z))?,
770            self.transform_point3d(point3(b.min.x, b.min.y, b.max.z))?,
771            self.transform_point3d(point3(b.min.x, b.max.y, b.min.z))?,
772            self.transform_point3d(point3(b.min.x, b.max.y, b.max.z))?,
773            self.transform_point3d(point3(b.max.x, b.min.y, b.min.z))?,
774            self.transform_point3d(point3(b.max.x, b.min.y, b.max.z))?,
775            self.transform_point3d(point3(b.max.x, b.max.y, b.min.z))?,
776            self.transform_point3d(point3(b.max.x, b.max.y, b.max.z))?,
777        ]))
778    }
779}
780
781
782impl <T, Src, Dst> Transform3D<T, Src, Dst>
783where T: Copy +
784         Add<T, Output=T> +
785         Sub<T, Output=T> +
786         Mul<T, Output=T> +
787         Div<T, Output=T> +
788         Neg<Output=T> +
789         PartialOrd +
790         One + Zero {
791
792    /// Create an orthogonal projection transform.
793    pub fn ortho(left: T, right: T,
794                 bottom: T, top: T,
795                 near: T, far: T) -> Self {
796        let tx = -((right + left) / (right - left));
797        let ty = -((top + bottom) / (top - bottom));
798        let tz = -((far + near) / (far - near));
799
800        let (_0, _1): (T, T) = (Zero::zero(), One::one());
801        let _2 = _1 + _1;
802        Transform3D::new(
803            _2 / (right - left), _0                 , _0                , _0,
804            _0                 , _2 / (top - bottom), _0                , _0,
805            _0                 , _0                 , -_2 / (far - near), _0,
806            tx                 , ty                 , tz                , _1
807        )
808    }
809
810    /// Check whether shapes on the XY plane with Z pointing towards the
811    /// screen transformed by this matrix would be facing back.
812    pub fn is_backface_visible(&self) -> bool {
813        // inverse().m33 < 0;
814        let det = self.determinant();
815        let m33 = self.m12 * self.m24 * self.m41 - self.m14 * self.m22 * self.m41 +
816                  self.m14 * self.m21 * self.m42 - self.m11 * self.m24 * self.m42 -
817                  self.m12 * self.m21 * self.m44 + self.m11 * self.m22 * self.m44;
818        let _0: T = Zero::zero();
819        (m33 * det) < _0
820    }
821
822    /// Returns whether it is possible to compute the inverse transform.
823    #[inline]
824    pub fn is_invertible(&self) -> bool {
825        self.determinant() != Zero::zero()
826    }
827
828    /// Returns the inverse transform if possible.
829    pub fn inverse(&self) -> Option<Transform3D<T, Dst, Src>> {
830        let det = self.determinant();
831
832        if det == Zero::zero() {
833            return None;
834        }
835
836        // todo(gw): this could be made faster by special casing
837        // for simpler transform types.
838        let m = Transform3D::new(
839            self.m23*self.m34*self.m42 - self.m24*self.m33*self.m42 +
840            self.m24*self.m32*self.m43 - self.m22*self.m34*self.m43 -
841            self.m23*self.m32*self.m44 + self.m22*self.m33*self.m44,
842
843            self.m14*self.m33*self.m42 - self.m13*self.m34*self.m42 -
844            self.m14*self.m32*self.m43 + self.m12*self.m34*self.m43 +
845            self.m13*self.m32*self.m44 - self.m12*self.m33*self.m44,
846
847            self.m13*self.m24*self.m42 - self.m14*self.m23*self.m42 +
848            self.m14*self.m22*self.m43 - self.m12*self.m24*self.m43 -
849            self.m13*self.m22*self.m44 + self.m12*self.m23*self.m44,
850
851            self.m14*self.m23*self.m32 - self.m13*self.m24*self.m32 -
852            self.m14*self.m22*self.m33 + self.m12*self.m24*self.m33 +
853            self.m13*self.m22*self.m34 - self.m12*self.m23*self.m34,
854
855            self.m24*self.m33*self.m41 - self.m23*self.m34*self.m41 -
856            self.m24*self.m31*self.m43 + self.m21*self.m34*self.m43 +
857            self.m23*self.m31*self.m44 - self.m21*self.m33*self.m44,
858
859            self.m13*self.m34*self.m41 - self.m14*self.m33*self.m41 +
860            self.m14*self.m31*self.m43 - self.m11*self.m34*self.m43 -
861            self.m13*self.m31*self.m44 + self.m11*self.m33*self.m44,
862
863            self.m14*self.m23*self.m41 - self.m13*self.m24*self.m41 -
864            self.m14*self.m21*self.m43 + self.m11*self.m24*self.m43 +
865            self.m13*self.m21*self.m44 - self.m11*self.m23*self.m44,
866
867            self.m13*self.m24*self.m31 - self.m14*self.m23*self.m31 +
868            self.m14*self.m21*self.m33 - self.m11*self.m24*self.m33 -
869            self.m13*self.m21*self.m34 + self.m11*self.m23*self.m34,
870
871            self.m22*self.m34*self.m41 - self.m24*self.m32*self.m41 +
872            self.m24*self.m31*self.m42 - self.m21*self.m34*self.m42 -
873            self.m22*self.m31*self.m44 + self.m21*self.m32*self.m44,
874
875            self.m14*self.m32*self.m41 - self.m12*self.m34*self.m41 -
876            self.m14*self.m31*self.m42 + self.m11*self.m34*self.m42 +
877            self.m12*self.m31*self.m44 - self.m11*self.m32*self.m44,
878
879            self.m12*self.m24*self.m41 - self.m14*self.m22*self.m41 +
880            self.m14*self.m21*self.m42 - self.m11*self.m24*self.m42 -
881            self.m12*self.m21*self.m44 + self.m11*self.m22*self.m44,
882
883            self.m14*self.m22*self.m31 - self.m12*self.m24*self.m31 -
884            self.m14*self.m21*self.m32 + self.m11*self.m24*self.m32 +
885            self.m12*self.m21*self.m34 - self.m11*self.m22*self.m34,
886
887            self.m23*self.m32*self.m41 - self.m22*self.m33*self.m41 -
888            self.m23*self.m31*self.m42 + self.m21*self.m33*self.m42 +
889            self.m22*self.m31*self.m43 - self.m21*self.m32*self.m43,
890
891            self.m12*self.m33*self.m41 - self.m13*self.m32*self.m41 +
892            self.m13*self.m31*self.m42 - self.m11*self.m33*self.m42 -
893            self.m12*self.m31*self.m43 + self.m11*self.m32*self.m43,
894
895            self.m13*self.m22*self.m41 - self.m12*self.m23*self.m41 -
896            self.m13*self.m21*self.m42 + self.m11*self.m23*self.m42 +
897            self.m12*self.m21*self.m43 - self.m11*self.m22*self.m43,
898
899            self.m12*self.m23*self.m31 - self.m13*self.m22*self.m31 +
900            self.m13*self.m21*self.m32 - self.m11*self.m23*self.m32 -
901            self.m12*self.m21*self.m33 + self.m11*self.m22*self.m33
902        );
903
904        let _1: T = One::one();
905        Some(m.mul_s(_1 / det))
906    }
907
908    /// Compute the determinant of the transform.
909    pub fn determinant(&self) -> T {
910        self.m14 * self.m23 * self.m32 * self.m41 -
911        self.m13 * self.m24 * self.m32 * self.m41 -
912        self.m14 * self.m22 * self.m33 * self.m41 +
913        self.m12 * self.m24 * self.m33 * self.m41 +
914        self.m13 * self.m22 * self.m34 * self.m41 -
915        self.m12 * self.m23 * self.m34 * self.m41 -
916        self.m14 * self.m23 * self.m31 * self.m42 +
917        self.m13 * self.m24 * self.m31 * self.m42 +
918        self.m14 * self.m21 * self.m33 * self.m42 -
919        self.m11 * self.m24 * self.m33 * self.m42 -
920        self.m13 * self.m21 * self.m34 * self.m42 +
921        self.m11 * self.m23 * self.m34 * self.m42 +
922        self.m14 * self.m22 * self.m31 * self.m43 -
923        self.m12 * self.m24 * self.m31 * self.m43 -
924        self.m14 * self.m21 * self.m32 * self.m43 +
925        self.m11 * self.m24 * self.m32 * self.m43 +
926        self.m12 * self.m21 * self.m34 * self.m43 -
927        self.m11 * self.m22 * self.m34 * self.m43 -
928        self.m13 * self.m22 * self.m31 * self.m44 +
929        self.m12 * self.m23 * self.m31 * self.m44 +
930        self.m13 * self.m21 * self.m32 * self.m44 -
931        self.m11 * self.m23 * self.m32 * self.m44 -
932        self.m12 * self.m21 * self.m33 * self.m44 +
933        self.m11 * self.m22 * self.m33 * self.m44
934    }
935
936    /// Multiplies all of the transform's component by a scalar and returns the result.
937    #[must_use]
938    pub fn mul_s(&self, x: T) -> Self {
939        Transform3D::new(
940            self.m11 * x, self.m12 * x, self.m13 * x, self.m14 * x,
941            self.m21 * x, self.m22 * x, self.m23 * x, self.m24 * x,
942            self.m31 * x, self.m32 * x, self.m33 * x, self.m34 * x,
943            self.m41 * x, self.m42 * x, self.m43 * x, self.m44 * x
944        )
945    }
946
947    /// Convenience function to create a scale transform from a `Scale`.
948    pub fn from_scale(scale: Scale<T, Src, Dst>) -> Self {
949        Transform3D::scale(scale.get(), scale.get(), scale.get())
950    }
951}
952
953impl <T, Src, Dst> Transform3D<T, Src, Dst>
954where
955    T: Copy + Mul<Output = T> + Div<Output = T> + Zero + One + PartialEq,
956{
957    /// Returns a projection of this transform in 2d space.
958    pub fn project_to_2d(&self) -> Self {
959        let (_0, _1): (T, T) = (Zero::zero(), One::one());
960
961        let mut result = self.clone();
962
963        result.m31 = _0;
964        result.m32 = _0;
965        result.m13 = _0;
966        result.m23 = _0;
967        result.m33 = _1;
968        result.m43 = _0;
969        result.m34 = _0;
970
971        // Try to normalize perspective when possible to convert to a 2d matrix.
972        // Some matrices, such as those derived from perspective transforms, can
973        // modify m44 from 1, while leaving the rest of the fourth column
974        // (m14, m24) at 0. In this case, after resetting the third row and
975        // third column above, the value of m44 functions only to scale the
976        // coordinate transform divide by W. The matrix can be converted to
977        // a true 2D matrix by normalizing out the scaling effect of m44 on
978        // the remaining components ahead of time.
979        if self.m14 == _0 && self.m24 == _0 && self.m44 != _0 && self.m44 != _1 {
980           let scale = _1 / self.m44;
981           result.m11 = result.m11 * scale;
982           result.m12 = result.m12 * scale;
983           result.m21 = result.m21 * scale;
984           result.m22 = result.m22 * scale;
985           result.m41 = result.m41 * scale;
986           result.m42 = result.m42 * scale;
987           result.m44 = _1;
988        }
989
990        result
991    }
992}
993
994impl<T: NumCast + Copy, Src, Dst> Transform3D<T, Src, Dst> {
995    /// Cast from one numeric representation to another, preserving the units.
996    #[inline]
997    pub fn cast<NewT: NumCast>(&self) -> Transform3D<NewT, Src, Dst> {
998        self.try_cast().unwrap()
999    }
1000
1001    /// Fallible cast from one numeric representation to another, preserving the units.
1002    pub fn try_cast<NewT: NumCast>(&self) -> Option<Transform3D<NewT, Src, Dst>> {
1003        match (NumCast::from(self.m11), NumCast::from(self.m12),
1004               NumCast::from(self.m13), NumCast::from(self.m14),
1005               NumCast::from(self.m21), NumCast::from(self.m22),
1006               NumCast::from(self.m23), NumCast::from(self.m24),
1007               NumCast::from(self.m31), NumCast::from(self.m32),
1008               NumCast::from(self.m33), NumCast::from(self.m34),
1009               NumCast::from(self.m41), NumCast::from(self.m42),
1010               NumCast::from(self.m43), NumCast::from(self.m44)) {
1011            (Some(m11), Some(m12), Some(m13), Some(m14),
1012             Some(m21), Some(m22), Some(m23), Some(m24),
1013             Some(m31), Some(m32), Some(m33), Some(m34),
1014             Some(m41), Some(m42), Some(m43), Some(m44)) => {
1015                Some(Transform3D::new(m11, m12, m13, m14,
1016                                                 m21, m22, m23, m24,
1017                                                 m31, m32, m33, m34,
1018                                                 m41, m42, m43, m44))
1019            },
1020            _ => None
1021        }
1022    }
1023}
1024
1025impl<T: ApproxEq<T>, Src, Dst> Transform3D<T, Src, Dst> {
1026    /// Returns true is this transform is approximately equal to the other one, using
1027    /// T's default epsilon value.
1028    ///
1029    /// The same as [`ApproxEq::approx_eq()`] but available without importing trait.
1030    ///
1031    /// [`ApproxEq::approx_eq()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq
1032    #[inline]
1033    pub fn approx_eq(&self, other: &Self) -> bool {
1034        <Self as ApproxEq<T>>::approx_eq(&self, &other)
1035    }
1036
1037    /// Returns true is this transform is approximately equal to the other one, using
1038    /// a provided epsilon value.
1039    ///
1040    /// The same as [`ApproxEq::approx_eq_eps()`] but available without importing trait.
1041    ///
1042    /// [`ApproxEq::approx_eq_eps()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq_eps
1043    #[inline]
1044    pub fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
1045        <Self as ApproxEq<T>>::approx_eq_eps(&self, &other, &eps)
1046    }
1047}
1048
1049
1050impl<T: ApproxEq<T>, Src, Dst> ApproxEq<T> for Transform3D<T, Src, Dst> {
1051    #[inline]
1052    fn approx_epsilon() -> T { T::approx_epsilon() }
1053
1054    fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
1055        self.m11.approx_eq_eps(&other.m11, eps) && self.m12.approx_eq_eps(&other.m12, eps) &&
1056        self.m13.approx_eq_eps(&other.m13, eps) && self.m14.approx_eq_eps(&other.m14, eps) &&
1057        self.m21.approx_eq_eps(&other.m21, eps) && self.m22.approx_eq_eps(&other.m22, eps) &&
1058        self.m23.approx_eq_eps(&other.m23, eps) && self.m24.approx_eq_eps(&other.m24, eps) &&
1059        self.m31.approx_eq_eps(&other.m31, eps) && self.m32.approx_eq_eps(&other.m32, eps) &&
1060        self.m33.approx_eq_eps(&other.m33, eps) && self.m34.approx_eq_eps(&other.m34, eps) &&
1061        self.m41.approx_eq_eps(&other.m41, eps) && self.m42.approx_eq_eps(&other.m42, eps) &&
1062        self.m43.approx_eq_eps(&other.m43, eps) && self.m44.approx_eq_eps(&other.m44, eps)
1063    }
1064}
1065
1066impl <T, Src, Dst> Default for Transform3D<T, Src, Dst>
1067    where T: Zero + One
1068{
1069    /// Returns the [identity transform](#method.identity).
1070    fn default() -> Self {
1071        Self::identity()
1072    }
1073}
1074
1075impl<T, Src, Dst> fmt::Debug for Transform3D<T, Src, Dst>
1076where T: Copy + fmt::Debug +
1077         PartialEq +
1078         One + Zero {
1079    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1080        if self.is_identity() {
1081            write!(f, "[I]")
1082        } else {
1083            self.to_array().fmt(f)
1084        }
1085    }
1086}
1087
1088#[cfg(feature = "mint")]
1089impl<T, Src, Dst> From<mint::RowMatrix4<T>> for Transform3D<T, Src, Dst> {
1090    fn from(m: mint::RowMatrix4<T>) -> Self {
1091        Transform3D {
1092            m11: m.x.x, m12: m.x.y, m13: m.x.z, m14: m.x.w,
1093            m21: m.y.x, m22: m.y.y, m23: m.y.z, m24: m.y.w,
1094            m31: m.z.x, m32: m.z.y, m33: m.z.z, m34: m.z.w,
1095            m41: m.w.x, m42: m.w.y, m43: m.w.z, m44: m.w.w,
1096            _unit: PhantomData,
1097        }
1098    }
1099}
1100#[cfg(feature = "mint")]
1101impl<T, Src, Dst> Into<mint::RowMatrix4<T>> for Transform3D<T, Src, Dst> {
1102    fn into(self) -> mint::RowMatrix4<T> {
1103        mint::RowMatrix4 {
1104            x: mint::Vector4 { x: self.m11, y: self.m12, z: self.m13, w: self.m14 },
1105            y: mint::Vector4 { x: self.m21, y: self.m22, z: self.m23, w: self.m24 },
1106            z: mint::Vector4 { x: self.m31, y: self.m32, z: self.m33, w: self.m34 },
1107            w: mint::Vector4 { x: self.m41, y: self.m42, z: self.m43, w: self.m44 },
1108        }
1109    }
1110}
1111
1112
1113#[cfg(test)]
1114mod tests {
1115    use crate::approxeq::ApproxEq;
1116    use super::*;
1117    use crate::{point2, point3};
1118    use crate::default;
1119
1120    use core::f32::consts::{FRAC_PI_2, PI};
1121
1122    type Mf32 = default::Transform3D<f32>;
1123
1124    // For convenience.
1125    fn rad(v: f32) -> Angle<f32> { Angle::radians(v) }
1126
1127    #[test]
1128    pub fn test_translation() {
1129        let t1 = Mf32::translation(1.0, 2.0, 3.0);
1130        let t2 = Mf32::identity().pre_translate(vec3(1.0, 2.0, 3.0));
1131        let t3 = Mf32::identity().then_translate(vec3(1.0, 2.0, 3.0));
1132        assert_eq!(t1, t2);
1133        assert_eq!(t1, t3);
1134
1135        assert_eq!(t1.transform_point3d(point3(1.0, 1.0, 1.0)), Some(point3(2.0, 3.0, 4.0)));
1136        assert_eq!(t1.transform_point2d(point2(1.0, 1.0)), Some(point2(2.0, 3.0)));
1137
1138        assert_eq!(t1.then(&t1), Mf32::translation(2.0, 4.0, 6.0));
1139
1140        assert!(!t1.is_2d());
1141        assert_eq!(Mf32::translation(1.0, 2.0, 3.0).to_2d(), Transform2D::translation(1.0, 2.0));
1142    }
1143
1144    #[test]
1145    pub fn test_rotation() {
1146        let r1 = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1147        let r2 = Mf32::identity().pre_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1148        let r3 = Mf32::identity().then_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1149        assert_eq!(r1, r2);
1150        assert_eq!(r1, r3);
1151
1152        assert!(r1.transform_point3d(point3(1.0, 2.0, 3.0)).unwrap().approx_eq(&point3(-2.0, 1.0, 3.0)));
1153        assert!(r1.transform_point2d(point2(1.0, 2.0)).unwrap().approx_eq(&point2(-2.0, 1.0)));
1154
1155        assert!(r1.then(&r1).approx_eq(&Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2*2.0))));
1156
1157        assert!(r1.is_2d());
1158        assert!(r1.to_2d().approx_eq(&Transform2D::rotation(rad(FRAC_PI_2))));
1159    }
1160
1161    #[test]
1162    pub fn test_scale() {
1163        let s1 = Mf32::scale(2.0, 3.0, 4.0);
1164        let s2 = Mf32::identity().pre_scale(2.0, 3.0, 4.0);
1165        let s3 = Mf32::identity().then_scale(2.0, 3.0, 4.0);
1166        assert_eq!(s1, s2);
1167        assert_eq!(s1, s3);
1168
1169        assert!(s1.transform_point3d(point3(2.0, 2.0, 2.0)).unwrap().approx_eq(&point3(4.0, 6.0, 8.0)));
1170        assert!(s1.transform_point2d(point2(2.0, 2.0)).unwrap().approx_eq(&point2(4.0, 6.0)));
1171
1172        assert_eq!(s1.then(&s1), Mf32::scale(4.0, 9.0, 16.0));
1173
1174        assert!(!s1.is_2d());
1175        assert_eq!(Mf32::scale(2.0, 3.0, 0.0).to_2d(), Transform2D::scale(2.0, 3.0));
1176    }
1177
1178
1179    #[test]
1180    pub fn test_pre_then_scale() {
1181        let m = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2)).then_translate(vec3(6.0, 7.0, 8.0));
1182        let s = Mf32::scale(2.0, 3.0, 4.0);
1183        assert_eq!(m.then(&s), m.then_scale(2.0, 3.0, 4.0));
1184    }
1185
1186
1187    #[test]
1188    pub fn test_ortho() {
1189        let (left, right, bottom, top) = (0.0f32, 1.0f32, 0.1f32, 1.0f32);
1190        let (near, far) = (-1.0f32, 1.0f32);
1191        let result = Mf32::ortho(left, right, bottom, top, near, far);
1192        let expected = Mf32::new(
1193             2.0,  0.0,         0.0, 0.0,
1194             0.0,  2.22222222,  0.0, 0.0,
1195             0.0,  0.0,        -1.0, 0.0,
1196            -1.0, -1.22222222, -0.0, 1.0
1197        );
1198        assert!(result.approx_eq(&expected));
1199    }
1200
1201    #[test]
1202    pub fn test_is_2d() {
1203        assert!(Mf32::identity().is_2d());
1204        assert!(Mf32::rotation(0.0, 0.0, 1.0, rad(0.7854)).is_2d());
1205        assert!(!Mf32::rotation(0.0, 1.0, 0.0, rad(0.7854)).is_2d());
1206    }
1207
1208    #[test]
1209    pub fn test_new_2d() {
1210        let m1 = Mf32::new_2d(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
1211        let m2 = Mf32::new(
1212            1.0, 2.0, 0.0, 0.0,
1213            3.0, 4.0, 0.0, 0.0,
1214            0.0, 0.0, 1.0, 0.0,
1215            5.0, 6.0, 0.0, 1.0
1216        );
1217        assert_eq!(m1, m2);
1218    }
1219
1220    #[test]
1221    pub fn test_inverse_simple() {
1222        let m1 = Mf32::identity();
1223        let m2 = m1.inverse().unwrap();
1224        assert!(m1.approx_eq(&m2));
1225    }
1226
1227    #[test]
1228    pub fn test_inverse_scale() {
1229        let m1 = Mf32::scale(1.5, 0.3, 2.1);
1230        let m2 = m1.inverse().unwrap();
1231        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1232        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1233    }
1234
1235    #[test]
1236    pub fn test_inverse_translate() {
1237        let m1 = Mf32::translation(-132.0, 0.3, 493.0);
1238        let m2 = m1.inverse().unwrap();
1239        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1240        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1241    }
1242
1243    #[test]
1244    pub fn test_inverse_rotate() {
1245        let m1 = Mf32::rotation(0.0, 1.0, 0.0, rad(1.57));
1246        let m2 = m1.inverse().unwrap();
1247        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1248        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1249    }
1250
1251    #[test]
1252    pub fn test_inverse_transform_point_2d() {
1253        let m1 = Mf32::translation(100.0, 200.0, 0.0);
1254        let m2 = m1.inverse().unwrap();
1255        assert!(m1.then(&m2).approx_eq(&Mf32::identity()));
1256        assert!(m2.then(&m1).approx_eq(&Mf32::identity()));
1257
1258        let p1 = point2(1000.0, 2000.0);
1259        let p2 = m1.transform_point2d(p1);
1260        assert_eq!(p2, Some(point2(1100.0, 2200.0)));
1261
1262        let p3 = m2.transform_point2d(p2.unwrap());
1263        assert_eq!(p3, Some(p1));
1264    }
1265
1266    #[test]
1267    fn test_inverse_none() {
1268        assert!(Mf32::scale(2.0, 0.0, 2.0).inverse().is_none());
1269        assert!(Mf32::scale(2.0, 2.0, 2.0).inverse().is_some());
1270    }
1271
1272    #[test]
1273    pub fn test_pre_post() {
1274        let m1 = default::Transform3D::identity().then_scale(1.0, 2.0, 3.0).then_translate(vec3(1.0, 2.0, 3.0));
1275        let m2 = default::Transform3D::identity().pre_translate(vec3(1.0, 2.0, 3.0)).pre_scale(1.0, 2.0, 3.0);
1276        assert!(m1.approx_eq(&m2));
1277
1278        let r = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1279        let t = Mf32::translation(2.0, 3.0, 0.0);
1280
1281        let a = point3(1.0, 1.0, 1.0);
1282
1283        assert!(r.then(&t).transform_point3d(a).unwrap().approx_eq(&point3(1.0, 4.0, 1.0)));
1284        assert!(t.then(&r).transform_point3d(a).unwrap().approx_eq(&point3(-4.0, 3.0, 1.0)));
1285        assert!(t.then(&r).transform_point3d(a).unwrap().approx_eq(&r.transform_point3d(t.transform_point3d(a).unwrap()).unwrap()));
1286    }
1287
1288    #[test]
1289    fn test_size_of() {
1290        use core::mem::size_of;
1291        assert_eq!(size_of::<default::Transform3D<f32>>(), 16*size_of::<f32>());
1292        assert_eq!(size_of::<default::Transform3D<f64>>(), 16*size_of::<f64>());
1293    }
1294
1295    #[test]
1296    pub fn test_transform_associativity() {
1297        let m1 = Mf32::new(3.0, 2.0, 1.5, 1.0,
1298                                 0.0, 4.5, -1.0, -4.0,
1299                                 0.0, 3.5, 2.5, 40.0,
1300                                 0.0, 3.0, 0.0, 1.0);
1301        let m2 = Mf32::new(1.0, -1.0, 3.0, 0.0,
1302                                 -1.0, 0.5, 0.0, 2.0,
1303                                 1.5, -2.0, 6.0, 0.0,
1304                                 -2.5, 6.0, 1.0, 1.0);
1305
1306        let p = point3(1.0, 3.0, 5.0);
1307        let p1 = m1.then(&m2).transform_point3d(p).unwrap();
1308        let p2 = m2.transform_point3d(m1.transform_point3d(p).unwrap()).unwrap();
1309        assert!(p1.approx_eq(&p2));
1310    }
1311
1312    #[test]
1313    pub fn test_is_identity() {
1314        let m1 = default::Transform3D::identity();
1315        assert!(m1.is_identity());
1316        let m2 = m1.then_translate(vec3(0.1, 0.0, 0.0));
1317        assert!(!m2.is_identity());
1318    }
1319
1320    #[test]
1321    pub fn test_transform_vector() {
1322        // Translation does not apply to vectors.
1323        let m = Mf32::translation(1.0, 2.0, 3.0);
1324        let v1 = vec3(10.0, -10.0, 3.0);
1325        assert_eq!(v1, m.transform_vector3d(v1));
1326        // While it does apply to points.
1327        assert_ne!(Some(v1.to_point()), m.transform_point3d(v1.to_point()));
1328
1329        // same thing with 2d vectors/points
1330        let v2 = vec2(10.0, -5.0);
1331        assert_eq!(v2, m.transform_vector2d(v2));
1332        assert_ne!(Some(v2.to_point()), m.transform_point2d(v2.to_point()));
1333    }
1334
1335    #[test]
1336    pub fn test_is_backface_visible() {
1337        // backface is not visible for rotate-x 0 degree.
1338        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(0.0));
1339        assert!(!r1.is_backface_visible());
1340        // backface is not visible for rotate-x 45 degree.
1341        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI * 0.25));
1342        assert!(!r1.is_backface_visible());
1343        // backface is visible for rotate-x 180 degree.
1344        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI));
1345        assert!(r1.is_backface_visible());
1346        // backface is visible for rotate-x 225 degree.
1347        let r1 = Mf32::rotation(1.0, 0.0, 0.0, rad(PI * 1.25));
1348        assert!(r1.is_backface_visible());
1349        // backface is not visible for non-inverseable matrix
1350        let r1 = Mf32::scale(2.0, 0.0, 2.0);
1351        assert!(!r1.is_backface_visible());
1352    }
1353
1354    #[test]
1355    pub fn test_homogeneous() {
1356        let m = Mf32::new(
1357            1.0, 2.0, 0.5, 5.0,
1358            3.0, 4.0, 0.25, 6.0,
1359            0.5, -1.0, 1.0, -1.0,
1360            -1.0, 1.0, -1.0, 2.0,
1361        );
1362        assert_eq!(
1363            m.transform_point2d_homogeneous(point2(1.0, 2.0)),
1364            HomogeneousVector::new(6.0, 11.0, 0.0, 19.0),
1365        );
1366        assert_eq!(
1367            m.transform_point3d_homogeneous(point3(1.0, 2.0, 4.0)),
1368            HomogeneousVector::new(8.0, 7.0, 4.0, 15.0),
1369        );
1370    }
1371
1372    #[test]
1373    pub fn test_perspective_division() {
1374        let p = point2(1.0, 2.0);
1375        let mut m = Mf32::identity();
1376        assert!(m.transform_point2d(p).is_some());
1377        m.m44 = 0.0;
1378        assert_eq!(None, m.transform_point2d(p));
1379        m.m44 = 1.0;
1380        m.m24 = -1.0;
1381        assert_eq!(None, m.transform_point2d(p));
1382    }
1383
1384    #[cfg(feature = "mint")]
1385    #[test]
1386    pub fn test_mint() {
1387        let m1 = Mf32::rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
1388        let mm: mint::RowMatrix4<_> = m1.into();
1389        let m2 = Mf32::from(mm);
1390
1391        assert_eq!(m1, m2);
1392    }
1393}