1 // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
10 #![cfg_attr(feature = "cargo-clippy", allow(just_underscores_and_digits))]
12 use super::{UnknownUnit, Angle};
13 #[cfg(feature = "mint")]
15 use crate::num::{One, Zero};
16 use crate::point::{Point2D, point2};
17 use crate::vector::{Vector2D, vec2};
18 use crate::rect::Rect;
19 use crate::box2d::Box2D;
20 use crate::transform3d::Transform3D;
21 use core::ops::{Add, Mul, Div, Sub};
22 use core::marker::PhantomData;
23 use core::cmp::{Eq, PartialEq};
24 use core::hash::{Hash};
25 use crate::approxeq::ApproxEq;
26 use crate::trig::Trig;
28 use num_traits::NumCast;
29 #[cfg(feature = "serde")]
30 use serde::{Deserialize, Serialize};
31 #[cfg(feature = "bytemuck")]
32 use bytemuck::{Zeroable, Pod};
34 /// A 2d transform represented by a column-major 3 by 3 matrix, compressed down to 3 by 2.
36 /// Transforms can be parametrized over the source and destination units, to describe a
37 /// transformation from a space to another.
38 /// For example, `Transform2D<f32, WorldSpace, ScreenSpace>::transform_point4d`
39 /// takes a `Point2D<f32, WorldSpace>` and returns a `Point2D<f32, ScreenSpace>`.
41 /// Transforms expose a set of convenience methods for pre- and post-transformations.
42 /// Pre-transformations (`pre_*` methods) correspond to adding an operation that is
43 /// applied before the rest of the transformation, while post-transformations (`then_*`
44 /// methods) add an operation that is applied after.
46 /// The matrix representation is conceptually equivalent to a 3 by 3 matrix transformation
47 /// compressed to 3 by 2 with the components that aren't needed to describe the set of 2d
48 /// transformations we are interested in implicitly defined:
51 /// | m11 m12 0 | |x| |x'|
52 /// | m21 m22 0 | x |y| = |y'|
53 /// | m31 m32 1 | |1| |w |
56 /// When translating Transform2D into general matrix representations, consider that the
57 /// representation follows the column-major notation with column vectors.
59 /// The translation terms are m31 and m32.
61 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
64 serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))
66 pub struct Transform2D<T, Src, Dst> {
67 pub m11: T, pub m12: T,
68 pub m21: T, pub m22: T,
69 pub m31: T, pub m32: T,
71 pub _unit: PhantomData<(Src, Dst)>,
74 #[cfg(feature = "arbitrary")]
75 impl<'a, T, Src, Dst> arbitrary::Arbitrary<'a> for Transform2D<T, Src, Dst>
77 T: arbitrary::Arbitrary<'a>,
79 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self>
81 let (m11, m12, m21, m22, m31, m32) = arbitrary::Arbitrary::arbitrary(u)?;
83 m11, m12, m21, m22, m31, m32,
89 #[cfg(feature = "bytemuck")]
90 unsafe impl<T: Zeroable, Src, Dst> Zeroable for Transform2D<T, Src, Dst> {}
92 #[cfg(feature = "bytemuck")]
93 unsafe impl<T: Pod, Src: 'static, Dst: 'static> Pod for Transform2D<T, Src, Dst> {}
95 impl<T: Copy, Src, Dst> Copy for Transform2D<T, Src, Dst> {}
97 impl<T: Clone, Src, Dst> Clone for Transform2D<T, Src, Dst> {
98 fn clone(&self) -> Self {
100 m11: self.m11.clone(),
101 m12: self.m12.clone(),
102 m21: self.m21.clone(),
103 m22: self.m22.clone(),
104 m31: self.m31.clone(),
105 m32: self.m32.clone(),
111 impl<T, Src, Dst> Eq for Transform2D<T, Src, Dst> where T: Eq {}
113 impl<T, Src, Dst> PartialEq for Transform2D<T, Src, Dst>
116 fn eq(&self, other: &Self) -> bool {
117 self.m11 == other.m11 &&
118 self.m12 == other.m12 &&
119 self.m21 == other.m21 &&
120 self.m22 == other.m22 &&
121 self.m31 == other.m31 &&
122 self.m32 == other.m32
126 impl<T, Src, Dst> Hash for Transform2D<T, Src, Dst>
129 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
140 impl<T, Src, Dst> Transform2D<T, Src, Dst> {
141 /// Create a transform specifying its components in using the column-major-column-vector
144 /// For example, the translation terms m31 and m32 are the last two parameters parameters.
147 /// use euclid::default::Transform2D;
150 /// let translation = Transform2D::new(
156 pub const fn new(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self {
165 /// Returns true is this transform is approximately equal to the other one, using
166 /// T's default epsilon value.
168 /// The same as [`ApproxEq::approx_eq()`] but available without importing trait.
170 /// [`ApproxEq::approx_eq()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq
172 pub fn approx_eq(&self, other: &Self) -> bool
173 where T : ApproxEq<T> {
174 <Self as ApproxEq<T>>::approx_eq(&self, &other)
177 /// Returns true is this transform is approximately equal to the other one, using
178 /// a provided epsilon value.
180 /// The same as [`ApproxEq::approx_eq_eps()`] but available without importing trait.
182 /// [`ApproxEq::approx_eq_eps()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq_eps
184 pub fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool
185 where T : ApproxEq<T> {
186 <Self as ApproxEq<T>>::approx_eq_eps(&self, &other, &eps)
190 impl<T: Copy, Src, Dst> Transform2D<T, Src, Dst> {
191 /// Returns an array containing this transform's terms.
193 /// The terms are laid out in the same order as they are
194 /// specified in `Transform2D::new`, that is following the
195 /// column-major-column-vector matrix notation.
197 /// For example the translation terms are found in the
198 /// last two slots of the array.
200 pub fn to_array(&self) -> [T; 6] {
208 /// Returns an array containing this transform's terms transposed.
210 /// The terms are laid out in transposed order from the same order of
211 /// `Transform3D::new` and `Transform3D::to_array`, that is following
212 /// the row-major-column-vector matrix notation.
214 /// For example the translation terms are found at indices 2 and 5
217 pub fn to_array_transposed(&self) -> [T; 6] {
219 self.m11, self.m21, self.m31,
220 self.m12, self.m22, self.m32
224 /// Equivalent to `to_array` with elements packed two at a time
225 /// in an array of arrays.
227 pub fn to_arrays(&self) -> [[T; 2]; 3] {
229 [self.m11, self.m12],
230 [self.m21, self.m22],
231 [self.m31, self.m32],
235 /// Create a transform providing its components via an array
236 /// of 6 elements instead of as individual parameters.
238 /// The order of the components corresponds to the
239 /// column-major-column-vector matrix notation (the same order
240 /// as `Transform2D::new`).
242 pub fn from_array(array: [T; 6]) -> Self {
250 /// Equivalent to `from_array` with elements packed two at a time
251 /// in an array of arrays.
253 /// The order of the components corresponds to the
254 /// column-major-column-vector matrix notation (the same order
255 /// as `Transform3D::new`).
257 pub fn from_arrays(array: [[T; 2]; 3]) -> Self {
259 array[0][0], array[0][1],
260 array[1][0], array[1][1],
261 array[2][0], array[2][1],
265 /// Drop the units, preserving only the numeric value.
267 pub fn to_untyped(&self) -> Transform2D<T, UnknownUnit, UnknownUnit> {
275 /// Tag a unitless value with units.
277 pub fn from_untyped(p: &Transform2D<T, UnknownUnit, UnknownUnit>) -> Self {
285 /// Returns the same transform with a different source unit.
287 pub fn with_source<NewSrc>(&self) -> Transform2D<T, NewSrc, Dst> {
295 /// Returns the same transform with a different destination unit.
297 pub fn with_destination<NewDst>(&self) -> Transform2D<T, Src, NewDst> {
305 /// Create a 3D transform from the current transform
306 pub fn to_3d(&self) -> Transform3D<T, Src, Dst>
310 Transform3D::new_2d(self.m11, self.m12, self.m21, self.m22, self.m31, self.m32)
314 impl<T: NumCast + Copy, Src, Dst> Transform2D<T, Src, Dst> {
315 /// Cast from one numeric representation to another, preserving the units.
317 pub fn cast<NewT: NumCast>(&self) -> Transform2D<NewT, Src, Dst> {
318 self.try_cast().unwrap()
321 /// Fallible cast from one numeric representation to another, preserving the units.
322 pub fn try_cast<NewT: NumCast>(&self) -> Option<Transform2D<NewT, Src, Dst>> {
323 match (NumCast::from(self.m11), NumCast::from(self.m12),
324 NumCast::from(self.m21), NumCast::from(self.m22),
325 NumCast::from(self.m31), NumCast::from(self.m32)) {
326 (Some(m11), Some(m12),
327 Some(m21), Some(m22),
328 Some(m31), Some(m32)) => {
329 Some(Transform2D::new(
340 impl<T, Src, Dst> Transform2D<T, Src, Dst>
344 /// Create an identity matrix:
352 pub fn identity() -> Self {
353 Self::translation(T::zero(), T::zero())
356 /// Intentional not public, because it checks for exact equivalence
357 /// while most consumers will probably want some sort of approximate
358 /// equivalence to deal with floating-point errors.
359 fn is_identity(&self) -> bool
363 *self == Self::identity()
368 /// Methods for combining generic transformations
369 impl<T, Src, Dst> Transform2D<T, Src, Dst>
371 T: Copy + Add<Output = T> + Mul<Output = T>,
373 /// Returns the multiplication of the two matrices such that mat's transformation
374 /// applies after self's transformation.
376 pub fn then<NewDst>(&self, mat: &Transform2D<T, Dst, NewDst>) -> Transform2D<T, Src, NewDst> {
378 self.m11 * mat.m11 + self.m12 * mat.m21,
379 self.m11 * mat.m12 + self.m12 * mat.m22,
381 self.m21 * mat.m11 + self.m22 * mat.m21,
382 self.m21 * mat.m12 + self.m22 * mat.m22,
384 self.m31 * mat.m11 + self.m32 * mat.m21 + mat.m31,
385 self.m31 * mat.m12 + self.m32 * mat.m22 + mat.m32,
390 /// Methods for creating and combining translation transformations
391 impl<T, Src, Dst> Transform2D<T, Src, Dst>
395 /// Create a 2d translation transform:
403 pub fn translation(x: T, y: T) -> Self {
404 let _0 = || T::zero();
405 let _1 = || T::one();
414 /// Applies a translation after self's transformation and returns the resulting transform.
417 pub fn then_translate(&self, v: Vector2D<T, Dst>) -> Self
419 T: Copy + Add<Output = T> + Mul<Output = T>,
421 self.then(&Transform2D::translation(v.x, v.y))
424 /// Applies a translation before self's transformation and returns the resulting transform.
427 pub fn pre_translate(&self, v: Vector2D<T, Src>) -> Self
429 T: Copy + Add<Output = T> + Mul<Output = T>,
431 Transform2D::translation(v.x, v.y).then(self)
435 /// Methods for creating and combining rotation transformations
436 impl<T, Src, Dst> Transform2D<T, Src, Dst>
438 T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Zero + Trig,
440 /// Returns a rotation transform.
442 pub fn rotation(theta: Angle<T>) -> Self {
443 let _0 = Zero::zero();
444 let cos = theta.get().cos();
445 let sin = theta.get().sin();
453 /// Applies a rotation after self's transformation and returns the resulting transform.
456 pub fn then_rotate(&self, theta: Angle<T>) -> Self {
457 self.then(&Transform2D::rotation(theta))
460 /// Applies a rotation before self's transformation and returns the resulting transform.
463 pub fn pre_rotate(&self, theta: Angle<T>) -> Self {
464 Transform2D::rotation(theta).then(self)
468 /// Methods for creating and combining scale transformations
469 impl<T, Src, Dst> Transform2D<T, Src, Dst> {
470 /// Create a 2d scale transform:
478 pub fn scale(x: T, y: T) -> Self
482 let _0 = || Zero::zero();
491 /// Applies a scale after self's transformation and returns the resulting transform.
494 pub fn then_scale(&self, x: T, y: T) -> Self
496 T: Copy + Add<Output = T> + Mul<Output = T> + Zero,
498 self.then(&Transform2D::scale(x, y))
501 /// Applies a scale before self's transformation and returns the resulting transform.
504 pub fn pre_scale(&self, x: T, y: T) -> Self
506 T: Copy + Mul<Output = T>,
509 self.m11 * x, self.m12 * x,
510 self.m21 * y, self.m22 * y,
516 /// Methods for apply transformations to objects
517 impl<T, Src, Dst> Transform2D<T, Src, Dst>
519 T: Copy + Add<Output = T> + Mul<Output = T>,
521 /// Returns the given point transformed by this transform.
524 pub fn transform_point(&self, point: Point2D<T, Src>) -> Point2D<T, Dst> {
526 point.x * self.m11 + point.y * self.m21 + self.m31,
527 point.x * self.m12 + point.y * self.m22 + self.m32
531 /// Returns the given vector transformed by this matrix.
534 pub fn transform_vector(&self, vec: Vector2D<T, Src>) -> Vector2D<T, Dst> {
535 vec2(vec.x * self.m11 + vec.y * self.m21,
536 vec.x * self.m12 + vec.y * self.m22)
539 /// Returns a rectangle that encompasses the result of transforming the given rectangle by this
543 pub fn outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Rect<T, Dst>
545 T: Sub<Output = T> + Zero + PartialOrd,
547 let min = rect.min();
548 let max = rect.max();
550 self.transform_point(min),
551 self.transform_point(max),
552 self.transform_point(point2(max.x, min.y)),
553 self.transform_point(point2(min.x, max.y)),
558 /// Returns a box that encompasses the result of transforming the given box by this
562 pub fn outer_transformed_box(&self, b: &Box2D<T, Src>) -> Box2D<T, Dst>
564 T: Sub<Output = T> + Zero + PartialOrd,
566 Box2D::from_points(&[
567 self.transform_point(b.min),
568 self.transform_point(b.max),
569 self.transform_point(point2(b.max.x, b.min.y)),
570 self.transform_point(point2(b.min.x, b.max.y)),
576 impl<T, Src, Dst> Transform2D<T, Src, Dst>
578 T: Copy + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + PartialEq + Zero + One,
580 /// Computes and returns the determinant of this transform.
581 pub fn determinant(&self) -> T {
582 self.m11 * self.m22 - self.m12 * self.m21
585 /// Returns whether it is possible to compute the inverse transform.
587 pub fn is_invertible(&self) -> bool {
588 self.determinant() != Zero::zero()
591 /// Returns the inverse transform if possible.
593 pub fn inverse(&self) -> Option<Transform2D<T, Dst, Src>> {
594 let det = self.determinant();
596 let _0: T = Zero::zero();
597 let _1: T = One::one();
603 let inv_det = _1 / det;
604 Some(Transform2D::new(
606 inv_det * (_0 - self.m12),
607 inv_det * (_0 - self.m21),
609 inv_det * (self.m21 * self.m32 - self.m22 * self.m31),
610 inv_det * (self.m31 * self.m12 - self.m11 * self.m32),
615 impl <T, Src, Dst> Default for Transform2D<T, Src, Dst>
618 /// Returns the [identity transform](#method.identity).
619 fn default() -> Self {
624 impl<T: ApproxEq<T>, Src, Dst> ApproxEq<T> for Transform2D<T, Src, Dst> {
626 fn approx_epsilon() -> T { T::approx_epsilon() }
628 /// Returns true is this transform is approximately equal to the other one, using
629 /// a provided epsilon value.
630 fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
631 self.m11.approx_eq_eps(&other.m11, eps) && self.m12.approx_eq_eps(&other.m12, eps) &&
632 self.m21.approx_eq_eps(&other.m21, eps) && self.m22.approx_eq_eps(&other.m22, eps) &&
633 self.m31.approx_eq_eps(&other.m31, eps) && self.m32.approx_eq_eps(&other.m32, eps)
637 impl<T, Src, Dst> fmt::Debug for Transform2D<T, Src, Dst>
638 where T: Copy + fmt::Debug +
641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 if self.is_identity() {
645 self.to_array().fmt(f)
650 #[cfg(feature = "mint")]
651 impl<T, Src, Dst> From<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> {
652 fn from(m: mint::RowMatrix3x2<T>) -> Self {
654 m11: m.x.x, m12: m.x.y,
655 m21: m.y.x, m22: m.y.y,
656 m31: m.z.x, m32: m.z.y,
661 #[cfg(feature = "mint")]
662 impl<T, Src, Dst> Into<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> {
663 fn into(self) -> mint::RowMatrix3x2<T> {
665 x: mint::Vector2 { x: self.m11, y: self.m12 },
666 y: mint::Vector2 { x: self.m21, y: self.m22 },
667 z: mint::Vector2 { x: self.m31, y: self.m32 },
677 use crate::approxeq::ApproxEq;
678 #[cfg(feature = "mint")]
681 use core::f32::consts::FRAC_PI_2;
683 type Mat = default::Transform2D<f32>;
685 fn rad(v: f32) -> Angle<f32> { Angle::radians(v) }
688 pub fn test_translation() {
689 let t1 = Mat::translation(1.0, 2.0);
690 let t2 = Mat::identity().pre_translate(vec2(1.0, 2.0));
691 let t3 = Mat::identity().then_translate(vec2(1.0, 2.0));
695 assert_eq!(t1.transform_point(Point2D::new(1.0, 1.0)), Point2D::new(2.0, 3.0));
697 assert_eq!(t1.then(&t1), Mat::translation(2.0, 4.0));
701 pub fn test_rotation() {
702 let r1 = Mat::rotation(rad(FRAC_PI_2));
703 let r2 = Mat::identity().pre_rotate(rad(FRAC_PI_2));
704 let r3 = Mat::identity().then_rotate(rad(FRAC_PI_2));
708 assert!(r1.transform_point(Point2D::new(1.0, 2.0)).approx_eq(&Point2D::new(-2.0, 1.0)));
710 assert!(r1.then(&r1).approx_eq(&Mat::rotation(rad(FRAC_PI_2*2.0))));
714 pub fn test_scale() {
715 let s1 = Mat::scale(2.0, 3.0);
716 let s2 = Mat::identity().pre_scale(2.0, 3.0);
717 let s3 = Mat::identity().then_scale(2.0, 3.0);
721 assert!(s1.transform_point(Point2D::new(2.0, 2.0)).approx_eq(&Point2D::new(4.0, 6.0)));
726 pub fn test_pre_then_scale() {
727 let m = Mat::rotation(rad(FRAC_PI_2)).then_translate(vec2(6.0, 7.0));
728 let s = Mat::scale(2.0, 3.0);
729 assert_eq!(m.then(&s), m.then_scale(2.0, 3.0));
733 pub fn test_inverse_simple() {
734 let m1 = Mat::identity();
735 let m2 = m1.inverse().unwrap();
736 assert!(m1.approx_eq(&m2));
740 pub fn test_inverse_scale() {
741 let m1 = Mat::scale(1.5, 0.3);
742 let m2 = m1.inverse().unwrap();
743 assert!(m1.then(&m2).approx_eq(&Mat::identity()));
744 assert!(m2.then(&m1).approx_eq(&Mat::identity()));
748 pub fn test_inverse_translate() {
749 let m1 = Mat::translation(-132.0, 0.3);
750 let m2 = m1.inverse().unwrap();
751 assert!(m1.then(&m2).approx_eq(&Mat::identity()));
752 assert!(m2.then(&m1).approx_eq(&Mat::identity()));
756 fn test_inverse_none() {
757 assert!(Mat::scale(2.0, 0.0).inverse().is_none());
758 assert!(Mat::scale(2.0, 2.0).inverse().is_some());
762 pub fn test_pre_post() {
763 let m1 = default::Transform2D::identity().then_scale(1.0, 2.0).then_translate(vec2(1.0, 2.0));
764 let m2 = default::Transform2D::identity().pre_translate(vec2(1.0, 2.0)).pre_scale(1.0, 2.0);
765 assert!(m1.approx_eq(&m2));
767 let r = Mat::rotation(rad(FRAC_PI_2));
768 let t = Mat::translation(2.0, 3.0);
770 let a = Point2D::new(1.0, 1.0);
772 assert!(r.then(&t).transform_point(a).approx_eq(&Point2D::new(1.0, 4.0)));
773 assert!(t.then(&r).transform_point(a).approx_eq(&Point2D::new(-4.0, 3.0)));
774 assert!(t.then(&r).transform_point(a).approx_eq(&r.transform_point(t.transform_point(a))));
779 use core::mem::size_of;
780 assert_eq!(size_of::<default::Transform2D<f32>>(), 6*size_of::<f32>());
781 assert_eq!(size_of::<default::Transform2D<f64>>(), 6*size_of::<f64>());
785 pub fn test_is_identity() {
786 let m1 = default::Transform2D::identity();
787 assert!(m1.is_identity());
788 let m2 = m1.then_translate(vec2(0.1, 0.0));
789 assert!(!m2.is_identity());
793 pub fn test_transform_vector() {
794 // Translation does not apply to vectors.
795 let m1 = Mat::translation(1.0, 1.0);
796 let v1 = vec2(10.0, -10.0);
797 assert_eq!(v1, m1.transform_vector(v1));
800 #[cfg(feature = "mint")]
803 let m1 = Mat::rotation(rad(FRAC_PI_2));
804 let mm: mint::RowMatrix3x2<_> = m1.into();
805 let m2 = Mat::from(mm);