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 12 use super::{UnknownUnit, Angle}; 13 #[cfg(feature = "mint")] 14 use 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; 27 use core::fmt; 28 use num_traits::NumCast; 29 #[cfg(feature = "serde")] 30 use serde::{Deserialize, Serialize}; 31 32 /// A 2d transform represented by a column-major 3 by 3 matrix, compressed down to 3 by 2. 33 /// 34 /// Transforms can be parametrized over the source and destination units, to describe a 35 /// transformation from a space to another. 36 /// For example, `Transform2D<f32, WorldSpace, ScreenSpace>::transform_point4d` 37 /// takes a `Point2D<f32, WorldSpace>` and returns a `Point2D<f32, ScreenSpace>`. 38 /// 39 /// Transforms expose a set of convenience methods for pre- and post-transformations. 40 /// Pre-transformations (`pre_*` methods) correspond to adding an operation that is 41 /// applied before the rest of the transformation, while post-transformations (`then_*` 42 /// methods) add an operation that is applied after. 43 /// 44 /// The matrix representation is conceptually equivalent to a 3 by 3 matrix transformation 45 /// compressed to 3 by 2 with the components that aren't needed to describe the set of 2d 46 /// transformations we are interested in implicitly defined: 47 /// 48 /// ```text 49 /// | m11 m12 0 | |x| |x'| 50 /// | m21 m22 0 | x |y| = |y'| 51 /// | m31 m32 1 | |1| |w | 52 /// ``` 53 /// 54 /// When translating Transform2D into general matrix representations, consider that the 55 /// representation follows the column-major notation with column vectors. 56 /// 57 /// The translation terms are m31 and m32. 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 )] 64 pub struct Transform2D<T, Src, Dst> { 65 pub m11: T, pub m12: T, 66 pub m21: T, pub m22: T, 67 pub m31: T, pub m32: T, 68 #[doc(hidden)] 69 pub _unit: PhantomData<(Src, Dst)>, 70 } 71 72 #[cfg(feature = "arbitrary")] 73 impl<'a, T, Src, Dst> arbitrary::Arbitrary<'a> for Transform2D<T, Src, Dst> 74 where 75 T: arbitrary::Arbitrary<'a>, 76 { arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self>77 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> 78 { 79 let (m11, m12, m21, m22, m31, m32) = arbitrary::Arbitrary::arbitrary(u)?; 80 Ok(Transform2D { 81 m11, m12, m21, m22, m31, m32, 82 _unit: PhantomData, 83 }) 84 } 85 } 86 87 impl<T: Copy, Src, Dst> Copy for Transform2D<T, Src, Dst> {} 88 89 impl<T: Clone, Src, Dst> Clone for Transform2D<T, Src, Dst> { clone(&self) -> Self90 fn clone(&self) -> Self { 91 Transform2D { 92 m11: self.m11.clone(), 93 m12: self.m12.clone(), 94 m21: self.m21.clone(), 95 m22: self.m22.clone(), 96 m31: self.m31.clone(), 97 m32: self.m32.clone(), 98 _unit: PhantomData, 99 } 100 } 101 } 102 103 impl<T, Src, Dst> Eq for Transform2D<T, Src, Dst> where T: Eq {} 104 105 impl<T, Src, Dst> PartialEq for Transform2D<T, Src, Dst> 106 where T: PartialEq 107 { eq(&self, other: &Self) -> bool108 fn eq(&self, other: &Self) -> bool { 109 self.m11 == other.m11 && 110 self.m12 == other.m12 && 111 self.m21 == other.m21 && 112 self.m22 == other.m22 && 113 self.m31 == other.m31 && 114 self.m32 == other.m32 115 } 116 } 117 118 impl<T, Src, Dst> Hash for Transform2D<T, Src, Dst> 119 where T: Hash 120 { hash<H: core::hash::Hasher>(&self, h: &mut H)121 fn hash<H: core::hash::Hasher>(&self, h: &mut H) { 122 self.m11.hash(h); 123 self.m12.hash(h); 124 self.m21.hash(h); 125 self.m22.hash(h); 126 self.m31.hash(h); 127 self.m32.hash(h); 128 } 129 } 130 131 132 impl<T, Src, Dst> Transform2D<T, Src, Dst> { 133 /// Create a transform specifying its components in using the column-major-column-vector 134 /// matrix notation. 135 /// 136 /// For example, the translation terms m31 and m32 are the last two parameters parameters. 137 /// 138 /// ``` 139 /// use euclid::default::Transform2D; 140 /// let tx = 1.0; 141 /// let ty = 2.0; 142 /// let translation = Transform2D::new( 143 /// 1.0, 0.0, 144 /// 0.0, 1.0, 145 /// tx, ty, 146 /// ); 147 /// ``` new(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self148 pub const fn new(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self { 149 Transform2D { 150 m11, m12, 151 m21, m22, 152 m31, m32, 153 _unit: PhantomData, 154 } 155 } 156 157 /// Returns true is this transform is approximately equal to the other one, using 158 /// T's default epsilon value. 159 /// 160 /// The same as [`ApproxEq::approx_eq()`] but available without importing trait. 161 /// 162 /// [`ApproxEq::approx_eq()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq 163 #[inline] approx_eq(&self, other: &Self) -> bool where T : ApproxEq<T>164 pub fn approx_eq(&self, other: &Self) -> bool 165 where T : ApproxEq<T> { 166 <Self as ApproxEq<T>>::approx_eq(&self, &other) 167 } 168 169 /// Returns true is this transform is approximately equal to the other one, using 170 /// a provided epsilon value. 171 /// 172 /// The same as [`ApproxEq::approx_eq_eps()`] but available without importing trait. 173 /// 174 /// [`ApproxEq::approx_eq_eps()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq_eps 175 #[inline] approx_eq_eps(&self, other: &Self, eps: &T) -> bool where T : ApproxEq<T>176 pub fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool 177 where T : ApproxEq<T> { 178 <Self as ApproxEq<T>>::approx_eq_eps(&self, &other, &eps) 179 } 180 } 181 182 impl<T: Copy, Src, Dst> Transform2D<T, Src, Dst> { 183 /// Returns an array containing this transform's terms. 184 /// 185 /// The terms are laid out in the same order as they are 186 /// specified in `Transform2D::new`, that is following the 187 /// column-major-column-vector matrix notation. 188 /// 189 /// For example the translation terms are found in the 190 /// last two slots of the array. 191 #[inline] to_array(&self) -> [T; 6]192 pub fn to_array(&self) -> [T; 6] { 193 [ 194 self.m11, self.m12, 195 self.m21, self.m22, 196 self.m31, self.m32 197 ] 198 } 199 200 /// Returns an array containing this transform's terms transposed. 201 /// 202 /// The terms are laid out in transposed order from the same order of 203 /// `Transform3D::new` and `Transform3D::to_array`, that is following 204 /// the row-major-column-vector matrix notation. 205 /// 206 /// For example the translation terms are found at indices 2 and 5 207 /// in the array. 208 #[inline] to_array_transposed(&self) -> [T; 6]209 pub fn to_array_transposed(&self) -> [T; 6] { 210 [ 211 self.m11, self.m21, self.m31, 212 self.m12, self.m22, self.m32 213 ] 214 } 215 216 /// Equivalent to `to_array` with elements packed two at a time 217 /// in an array of arrays. 218 #[inline] to_arrays(&self) -> [[T; 2]; 3]219 pub fn to_arrays(&self) -> [[T; 2]; 3] { 220 [ 221 [self.m11, self.m12], 222 [self.m21, self.m22], 223 [self.m31, self.m32], 224 ] 225 } 226 227 /// Create a transform providing its components via an array 228 /// of 6 elements instead of as individual parameters. 229 /// 230 /// The order of the components corresponds to the 231 /// column-major-column-vector matrix notation (the same order 232 /// as `Transform2D::new`). 233 #[inline] from_array(array: [T; 6]) -> Self234 pub fn from_array(array: [T; 6]) -> Self { 235 Self::new( 236 array[0], array[1], 237 array[2], array[3], 238 array[4], array[5], 239 ) 240 } 241 242 /// Equivalent to `from_array` with elements packed two at a time 243 /// in an array of arrays. 244 /// 245 /// The order of the components corresponds to the 246 /// column-major-column-vector matrix notation (the same order 247 /// as `Transform3D::new`). 248 #[inline] from_arrays(array: [[T; 2]; 3]) -> Self249 pub fn from_arrays(array: [[T; 2]; 3]) -> Self { 250 Self::new( 251 array[0][0], array[0][1], 252 array[1][0], array[1][1], 253 array[2][0], array[2][1], 254 ) 255 } 256 257 /// Drop the units, preserving only the numeric value. 258 #[inline] to_untyped(&self) -> Transform2D<T, UnknownUnit, UnknownUnit>259 pub fn to_untyped(&self) -> Transform2D<T, UnknownUnit, UnknownUnit> { 260 Transform2D::new( 261 self.m11, self.m12, 262 self.m21, self.m22, 263 self.m31, self.m32 264 ) 265 } 266 267 /// Tag a unitless value with units. 268 #[inline] from_untyped(p: &Transform2D<T, UnknownUnit, UnknownUnit>) -> Self269 pub fn from_untyped(p: &Transform2D<T, UnknownUnit, UnknownUnit>) -> Self { 270 Transform2D::new( 271 p.m11, p.m12, 272 p.m21, p.m22, 273 p.m31, p.m32 274 ) 275 } 276 277 /// Returns the same transform with a different source unit. 278 #[inline] with_source<NewSrc>(&self) -> Transform2D<T, NewSrc, Dst>279 pub fn with_source<NewSrc>(&self) -> Transform2D<T, NewSrc, Dst> { 280 Transform2D::new( 281 self.m11, self.m12, 282 self.m21, self.m22, 283 self.m31, self.m32, 284 ) 285 } 286 287 /// Returns the same transform with a different destination unit. 288 #[inline] with_destination<NewDst>(&self) -> Transform2D<T, Src, NewDst>289 pub fn with_destination<NewDst>(&self) -> Transform2D<T, Src, NewDst> { 290 Transform2D::new( 291 self.m11, self.m12, 292 self.m21, self.m22, 293 self.m31, self.m32, 294 ) 295 } 296 297 /// Create a 3D transform from the current transform to_3d(&self) -> Transform3D<T, Src, Dst> where T: Zero + One,298 pub fn to_3d(&self) -> Transform3D<T, Src, Dst> 299 where 300 T: Zero + One, 301 { 302 Transform3D::new_2d(self.m11, self.m12, self.m21, self.m22, self.m31, self.m32) 303 } 304 } 305 306 impl<T: NumCast + Copy, Src, Dst> Transform2D<T, Src, Dst> { 307 /// Cast from one numeric representation to another, preserving the units. 308 #[inline] cast<NewT: NumCast>(&self) -> Transform2D<NewT, Src, Dst>309 pub fn cast<NewT: NumCast>(&self) -> Transform2D<NewT, Src, Dst> { 310 self.try_cast().unwrap() 311 } 312 313 /// Fallible cast from one numeric representation to another, preserving the units. try_cast<NewT: NumCast>(&self) -> Option<Transform2D<NewT, Src, Dst>>314 pub fn try_cast<NewT: NumCast>(&self) -> Option<Transform2D<NewT, Src, Dst>> { 315 match (NumCast::from(self.m11), NumCast::from(self.m12), 316 NumCast::from(self.m21), NumCast::from(self.m22), 317 NumCast::from(self.m31), NumCast::from(self.m32)) { 318 (Some(m11), Some(m12), 319 Some(m21), Some(m22), 320 Some(m31), Some(m32)) => { 321 Some(Transform2D::new( 322 m11, m12, 323 m21, m22, 324 m31, m32 325 )) 326 }, 327 _ => None 328 } 329 } 330 } 331 332 impl<T, Src, Dst> Transform2D<T, Src, Dst> 333 where 334 T: Zero + One, 335 { 336 /// Create an identity matrix: 337 /// 338 /// ```text 339 /// 1 0 340 /// 0 1 341 /// 0 0 342 /// ``` 343 #[inline] identity() -> Self344 pub fn identity() -> Self { 345 Self::translation(T::zero(), T::zero()) 346 } 347 348 /// Intentional not public, because it checks for exact equivalence 349 /// while most consumers will probably want some sort of approximate 350 /// equivalence to deal with floating-point errors. is_identity(&self) -> bool where T: PartialEq,351 fn is_identity(&self) -> bool 352 where 353 T: PartialEq, 354 { 355 *self == Self::identity() 356 } 357 } 358 359 360 /// Methods for combining generic transformations 361 impl<T, Src, Dst> Transform2D<T, Src, Dst> 362 where 363 T: Copy + Add<Output = T> + Mul<Output = T>, 364 { 365 /// Returns the multiplication of the two matrices such that mat's transformation 366 /// applies after self's transformation. 367 #[must_use] then<NewDst>(&self, mat: &Transform2D<T, Dst, NewDst>) -> Transform2D<T, Src, NewDst>368 pub fn then<NewDst>(&self, mat: &Transform2D<T, Dst, NewDst>) -> Transform2D<T, Src, NewDst> { 369 Transform2D::new( 370 self.m11 * mat.m11 + self.m12 * mat.m21, 371 self.m11 * mat.m12 + self.m12 * mat.m22, 372 373 self.m21 * mat.m11 + self.m22 * mat.m21, 374 self.m21 * mat.m12 + self.m22 * mat.m22, 375 376 self.m31 * mat.m11 + self.m32 * mat.m21 + mat.m31, 377 self.m31 * mat.m12 + self.m32 * mat.m22 + mat.m32, 378 ) 379 } 380 } 381 382 /// Methods for creating and combining translation transformations 383 impl<T, Src, Dst> Transform2D<T, Src, Dst> 384 where 385 T: Zero + One, 386 { 387 /// Create a 2d translation transform: 388 /// 389 /// ```text 390 /// 1 0 391 /// 0 1 392 /// x y 393 /// ``` 394 #[inline] translation(x: T, y: T) -> Self395 pub fn translation(x: T, y: T) -> Self { 396 let _0 = || T::zero(); 397 let _1 = || T::one(); 398 399 Self::new( 400 _1(), _0(), 401 _0(), _1(), 402 x, y, 403 ) 404 } 405 406 /// Applies a translation after self's transformation and returns the resulting transform. 407 #[inline] 408 #[must_use] then_translate(&self, v: Vector2D<T, Dst>) -> Self where T: Copy + Add<Output = T> + Mul<Output = T>,409 pub fn then_translate(&self, v: Vector2D<T, Dst>) -> Self 410 where 411 T: Copy + Add<Output = T> + Mul<Output = T>, 412 { 413 self.then(&Transform2D::translation(v.x, v.y)) 414 } 415 416 /// Applies a translation before self's transformation and returns the resulting transform. 417 #[inline] 418 #[must_use] pre_translate(&self, v: Vector2D<T, Src>) -> Self where T: Copy + Add<Output = T> + Mul<Output = T>,419 pub fn pre_translate(&self, v: Vector2D<T, Src>) -> Self 420 where 421 T: Copy + Add<Output = T> + Mul<Output = T>, 422 { 423 Transform2D::translation(v.x, v.y).then(self) 424 } 425 } 426 427 /// Methods for creating and combining rotation transformations 428 impl<T, Src, Dst> Transform2D<T, Src, Dst> 429 where 430 T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Zero + Trig, 431 { 432 /// Returns a rotation transform. 433 #[inline] rotation(theta: Angle<T>) -> Self434 pub fn rotation(theta: Angle<T>) -> Self { 435 let _0 = Zero::zero(); 436 let cos = theta.get().cos(); 437 let sin = theta.get().sin(); 438 Transform2D::new( 439 cos, sin, 440 _0 - sin, cos, 441 _0, _0 442 ) 443 } 444 445 /// Applies a rotation after self's transformation and returns the resulting transform. 446 #[inline] 447 #[must_use] then_rotate(&self, theta: Angle<T>) -> Self448 pub fn then_rotate(&self, theta: Angle<T>) -> Self { 449 self.then(&Transform2D::rotation(theta)) 450 } 451 452 /// Applies a rotation before self's transformation and returns the resulting transform. 453 #[inline] 454 #[must_use] pre_rotate(&self, theta: Angle<T>) -> Self455 pub fn pre_rotate(&self, theta: Angle<T>) -> Self { 456 Transform2D::rotation(theta).then(self) 457 } 458 } 459 460 /// Methods for creating and combining scale transformations 461 impl<T, Src, Dst> Transform2D<T, Src, Dst> { 462 /// Create a 2d scale transform: 463 /// 464 /// ```text 465 /// x 0 466 /// 0 y 467 /// 0 0 468 /// ``` 469 #[inline] scale(x: T, y: T) -> Self where T: Zero,470 pub fn scale(x: T, y: T) -> Self 471 where 472 T: Zero, 473 { 474 let _0 = || Zero::zero(); 475 476 Self::new( 477 x, _0(), 478 _0(), y, 479 _0(), _0(), 480 ) 481 } 482 483 /// Applies a scale after self's transformation and returns the resulting transform. 484 #[inline] 485 #[must_use] then_scale(&self, x: T, y: T) -> Self where T: Copy + Add<Output = T> + Mul<Output = T> + Zero,486 pub fn then_scale(&self, x: T, y: T) -> Self 487 where 488 T: Copy + Add<Output = T> + Mul<Output = T> + Zero, 489 { 490 self.then(&Transform2D::scale(x, y)) 491 } 492 493 /// Applies a scale before self's transformation and returns the resulting transform. 494 #[inline] 495 #[must_use] pre_scale(&self, x: T, y: T) -> Self where T: Copy + Mul<Output = T>,496 pub fn pre_scale(&self, x: T, y: T) -> Self 497 where 498 T: Copy + Mul<Output = T>, 499 { 500 Transform2D::new( 501 self.m11 * x, self.m12 * x, 502 self.m21 * y, self.m22 * y, 503 self.m31, self.m32 504 ) 505 } 506 } 507 508 /// Methods for apply transformations to objects 509 impl<T, Src, Dst> Transform2D<T, Src, Dst> 510 where 511 T: Copy + Add<Output = T> + Mul<Output = T>, 512 { 513 /// Returns the given point transformed by this transform. 514 #[inline] 515 #[must_use] transform_point(&self, point: Point2D<T, Src>) -> Point2D<T, Dst>516 pub fn transform_point(&self, point: Point2D<T, Src>) -> Point2D<T, Dst> { 517 Point2D::new( 518 point.x * self.m11 + point.y * self.m21 + self.m31, 519 point.x * self.m12 + point.y * self.m22 + self.m32 520 ) 521 } 522 523 /// Returns the given vector transformed by this matrix. 524 #[inline] 525 #[must_use] transform_vector(&self, vec: Vector2D<T, Src>) -> Vector2D<T, Dst>526 pub fn transform_vector(&self, vec: Vector2D<T, Src>) -> Vector2D<T, Dst> { 527 vec2(vec.x * self.m11 + vec.y * self.m21, 528 vec.x * self.m12 + vec.y * self.m22) 529 } 530 531 /// Returns a rectangle that encompasses the result of transforming the given rectangle by this 532 /// transform. 533 #[inline] 534 #[must_use] outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Rect<T, Dst> where T: Sub<Output = T> + Zero + PartialOrd,535 pub fn outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Rect<T, Dst> 536 where 537 T: Sub<Output = T> + Zero + PartialOrd, 538 { 539 let min = rect.min(); 540 let max = rect.max(); 541 Rect::from_points(&[ 542 self.transform_point(min), 543 self.transform_point(max), 544 self.transform_point(point2(max.x, min.y)), 545 self.transform_point(point2(min.x, max.y)), 546 ]) 547 } 548 549 550 /// Returns a box that encompasses the result of transforming the given box by this 551 /// transform. 552 #[inline] 553 #[must_use] outer_transformed_box(&self, b: &Box2D<T, Src>) -> Box2D<T, Dst> where T: Sub<Output = T> + Zero + PartialOrd,554 pub fn outer_transformed_box(&self, b: &Box2D<T, Src>) -> Box2D<T, Dst> 555 where 556 T: Sub<Output = T> + Zero + PartialOrd, 557 { 558 Box2D::from_points(&[ 559 self.transform_point(b.min), 560 self.transform_point(b.max), 561 self.transform_point(point2(b.max.x, b.min.y)), 562 self.transform_point(point2(b.min.x, b.max.y)), 563 ]) 564 } 565 } 566 567 568 impl<T, Src, Dst> Transform2D<T, Src, Dst> 569 where 570 T: Copy + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + PartialEq + Zero + One, 571 { 572 /// Computes and returns the determinant of this transform. determinant(&self) -> T573 pub fn determinant(&self) -> T { 574 self.m11 * self.m22 - self.m12 * self.m21 575 } 576 577 /// Returns whether it is possible to compute the inverse transform. 578 #[inline] is_invertible(&self) -> bool579 pub fn is_invertible(&self) -> bool { 580 self.determinant() != Zero::zero() 581 } 582 583 /// Returns the inverse transform if possible. 584 #[must_use] inverse(&self) -> Option<Transform2D<T, Dst, Src>>585 pub fn inverse(&self) -> Option<Transform2D<T, Dst, Src>> { 586 let det = self.determinant(); 587 588 let _0: T = Zero::zero(); 589 let _1: T = One::one(); 590 591 if det == _0 { 592 return None; 593 } 594 595 let inv_det = _1 / det; 596 Some(Transform2D::new( 597 inv_det * self.m22, 598 inv_det * (_0 - self.m12), 599 inv_det * (_0 - self.m21), 600 inv_det * self.m11, 601 inv_det * (self.m21 * self.m32 - self.m22 * self.m31), 602 inv_det * (self.m31 * self.m12 - self.m11 * self.m32), 603 )) 604 } 605 } 606 607 impl <T, Src, Dst> Default for Transform2D<T, Src, Dst> 608 where T: Zero + One 609 { 610 /// Returns the [identity transform](#method.identity). default() -> Self611 fn default() -> Self { 612 Self::identity() 613 } 614 } 615 616 impl<T: ApproxEq<T>, Src, Dst> ApproxEq<T> for Transform2D<T, Src, Dst> { 617 #[inline] approx_epsilon() -> T618 fn approx_epsilon() -> T { T::approx_epsilon() } 619 620 /// Returns true is this transform is approximately equal to the other one, using 621 /// a provided epsilon value. approx_eq_eps(&self, other: &Self, eps: &T) -> bool622 fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool { 623 self.m11.approx_eq_eps(&other.m11, eps) && self.m12.approx_eq_eps(&other.m12, eps) && 624 self.m21.approx_eq_eps(&other.m21, eps) && self.m22.approx_eq_eps(&other.m22, eps) && 625 self.m31.approx_eq_eps(&other.m31, eps) && self.m32.approx_eq_eps(&other.m32, eps) 626 } 627 } 628 629 impl<T, Src, Dst> fmt::Debug for Transform2D<T, Src, Dst> 630 where T: Copy + fmt::Debug + 631 PartialEq + 632 One + Zero { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 634 if self.is_identity() { 635 write!(f, "[I]") 636 } else { 637 self.to_array().fmt(f) 638 } 639 } 640 } 641 642 #[cfg(feature = "mint")] 643 impl<T, Src, Dst> From<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> { from(m: mint::RowMatrix3x2<T>) -> Self644 fn from(m: mint::RowMatrix3x2<T>) -> Self { 645 Transform2D { 646 m11: m.x.x, m12: m.x.y, 647 m21: m.y.x, m22: m.y.y, 648 m31: m.z.x, m32: m.z.y, 649 _unit: PhantomData, 650 } 651 } 652 } 653 #[cfg(feature = "mint")] 654 impl<T, Src, Dst> Into<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> { into(self) -> mint::RowMatrix3x2<T>655 fn into(self) -> mint::RowMatrix3x2<T> { 656 mint::RowMatrix3x2 { 657 x: mint::Vector2 { x: self.m11, y: self.m12 }, 658 y: mint::Vector2 { x: self.m21, y: self.m22 }, 659 z: mint::Vector2 { x: self.m31, y: self.m32 }, 660 } 661 } 662 } 663 664 665 #[cfg(test)] 666 mod test { 667 use super::*; 668 use crate::default; 669 use crate::approxeq::ApproxEq; 670 #[cfg(feature = "mint")] 671 use mint; 672 673 use core::f32::consts::FRAC_PI_2; 674 675 type Mat = default::Transform2D<f32>; 676 rad(v: f32) -> Angle<f32>677 fn rad(v: f32) -> Angle<f32> { Angle::radians(v) } 678 679 #[test] test_translation()680 pub fn test_translation() { 681 let t1 = Mat::translation(1.0, 2.0); 682 let t2 = Mat::identity().pre_translate(vec2(1.0, 2.0)); 683 let t3 = Mat::identity().then_translate(vec2(1.0, 2.0)); 684 assert_eq!(t1, t2); 685 assert_eq!(t1, t3); 686 687 assert_eq!(t1.transform_point(Point2D::new(1.0, 1.0)), Point2D::new(2.0, 3.0)); 688 689 assert_eq!(t1.then(&t1), Mat::translation(2.0, 4.0)); 690 } 691 692 #[test] test_rotation()693 pub fn test_rotation() { 694 let r1 = Mat::rotation(rad(FRAC_PI_2)); 695 let r2 = Mat::identity().pre_rotate(rad(FRAC_PI_2)); 696 let r3 = Mat::identity().then_rotate(rad(FRAC_PI_2)); 697 assert_eq!(r1, r2); 698 assert_eq!(r1, r3); 699 700 assert!(r1.transform_point(Point2D::new(1.0, 2.0)).approx_eq(&Point2D::new(-2.0, 1.0))); 701 702 assert!(r1.then(&r1).approx_eq(&Mat::rotation(rad(FRAC_PI_2*2.0)))); 703 } 704 705 #[test] test_scale()706 pub fn test_scale() { 707 let s1 = Mat::scale(2.0, 3.0); 708 let s2 = Mat::identity().pre_scale(2.0, 3.0); 709 let s3 = Mat::identity().then_scale(2.0, 3.0); 710 assert_eq!(s1, s2); 711 assert_eq!(s1, s3); 712 713 assert!(s1.transform_point(Point2D::new(2.0, 2.0)).approx_eq(&Point2D::new(4.0, 6.0))); 714 } 715 716 717 #[test] test_pre_then_scale()718 pub fn test_pre_then_scale() { 719 let m = Mat::rotation(rad(FRAC_PI_2)).then_translate(vec2(6.0, 7.0)); 720 let s = Mat::scale(2.0, 3.0); 721 assert_eq!(m.then(&s), m.then_scale(2.0, 3.0)); 722 } 723 724 #[test] test_inverse_simple()725 pub fn test_inverse_simple() { 726 let m1 = Mat::identity(); 727 let m2 = m1.inverse().unwrap(); 728 assert!(m1.approx_eq(&m2)); 729 } 730 731 #[test] test_inverse_scale()732 pub fn test_inverse_scale() { 733 let m1 = Mat::scale(1.5, 0.3); 734 let m2 = m1.inverse().unwrap(); 735 assert!(m1.then(&m2).approx_eq(&Mat::identity())); 736 assert!(m2.then(&m1).approx_eq(&Mat::identity())); 737 } 738 739 #[test] test_inverse_translate()740 pub fn test_inverse_translate() { 741 let m1 = Mat::translation(-132.0, 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())); 745 } 746 747 #[test] test_inverse_none()748 fn test_inverse_none() { 749 assert!(Mat::scale(2.0, 0.0).inverse().is_none()); 750 assert!(Mat::scale(2.0, 2.0).inverse().is_some()); 751 } 752 753 #[test] test_pre_post()754 pub fn test_pre_post() { 755 let m1 = default::Transform2D::identity().then_scale(1.0, 2.0).then_translate(vec2(1.0, 2.0)); 756 let m2 = default::Transform2D::identity().pre_translate(vec2(1.0, 2.0)).pre_scale(1.0, 2.0); 757 assert!(m1.approx_eq(&m2)); 758 759 let r = Mat::rotation(rad(FRAC_PI_2)); 760 let t = Mat::translation(2.0, 3.0); 761 762 let a = Point2D::new(1.0, 1.0); 763 764 assert!(r.then(&t).transform_point(a).approx_eq(&Point2D::new(1.0, 4.0))); 765 assert!(t.then(&r).transform_point(a).approx_eq(&Point2D::new(-4.0, 3.0))); 766 assert!(t.then(&r).transform_point(a).approx_eq(&r.transform_point(t.transform_point(a)))); 767 } 768 769 #[test] test_size_of()770 fn test_size_of() { 771 use core::mem::size_of; 772 assert_eq!(size_of::<default::Transform2D<f32>>(), 6*size_of::<f32>()); 773 assert_eq!(size_of::<default::Transform2D<f64>>(), 6*size_of::<f64>()); 774 } 775 776 #[test] test_is_identity()777 pub fn test_is_identity() { 778 let m1 = default::Transform2D::identity(); 779 assert!(m1.is_identity()); 780 let m2 = m1.then_translate(vec2(0.1, 0.0)); 781 assert!(!m2.is_identity()); 782 } 783 784 #[test] test_transform_vector()785 pub fn test_transform_vector() { 786 // Translation does not apply to vectors. 787 let m1 = Mat::translation(1.0, 1.0); 788 let v1 = vec2(10.0, -10.0); 789 assert_eq!(v1, m1.transform_vector(v1)); 790 } 791 792 #[cfg(feature = "mint")] 793 #[test] test_mint()794 pub fn test_mint() { 795 let m1 = Mat::rotation(rad(FRAC_PI_2)); 796 let mm: mint::RowMatrix3x2<_> = m1.into(); 797 let m2 = Mat::from(mm); 798 799 assert_eq!(m1, m2); 800 } 801 } 802