Debian Codegraph @

debian/missing-sources/glam-0.16.0/src/affine3.rs

raw symbols SCIP
1 use crate::core::storage::Columns4;
2 use crate::{DMat3, DMat4, DQuat, DVec3, Mat3, Mat3A, Mat4, Quat, Vec3, Vec3A};
3 use core::ops::{Add, Deref, DerefMut, Mul, Sub};
4
5 #[cfg(not(feature = "std"))]
6 use num_traits::Float;
7
8 macro_rules! define_affine3_struct {
9 ($affine3:ident, $matrix:ident, $column:ident) => {
10 /// A 3D affine transform, which can represent translation, rotation, scaling and shear.
11 ///
12 /// The type is composed of a 3x3 matrix containing a linear transformation (e.g. scale,
13 /// rotation, shear, reflection) and a 3D vector translation.
14 #[derive(Copy, Clone)]
15 pub struct $affine3 {
16 pub matrix3: $matrix,
17 pub translation: $column,
18 }
19 };
20 }
21
22 macro_rules! impl_affine3_methods {
23 ($t:ty, $mat3:ident, $mat4:ident, $quat:ident, $vec3:ident, $affine3:ident, $matrix:ident, $column:ident) => {
24 impl $affine3 {
25 /// The degenerate zero transform.
26 ///
27 /// This transforms any finite vector and point to zero.
28 /// The zero transform is non-invertible.
29 pub const ZERO: Self = Self {
30 matrix3: $matrix::ZERO,
31 translation: $column::ZERO,
32 };
33
34 /// The identity transform.
35 ///
36 /// Multiplying a vector with this returns the same vector.
37 pub const IDENTITY: Self = Self {
38 matrix3: $matrix::IDENTITY,
39 translation: $column::ZERO,
40 };
41
42 /// Creates an affine transform from four column vectors.
43 #[inline(always)]
44 pub fn from_cols(
45 x_axis: $column,
46 y_axis: $column,
47 z_axis: $column,
48 w_axis: $column,
49 ) -> Self {
50 Self {
51 matrix3: $matrix::from_cols(x_axis, y_axis, z_axis),
52 translation: w_axis,
53 }
54 }
55
56 /// Creates an affine transform from a `[S; 12]` array stored in column major order.
57 /// If your data is stored in row major you will need to `transpose` the returned
58 /// matrix.
59 #[inline(always)]
60 pub fn from_cols_array(m: &[$t; 12]) -> Self {
61 Self {
62 matrix3: $matrix::from_cols_slice(&m[0..9]),
63 translation: $column::from_slice(&m[9..12]),
64 }
65 }
66
67 /// Creates a `[S; 12]` array storing data in column major order.
68 /// If you require data in row major order `transpose` the matrix first.
69 #[inline(always)]
70 pub fn to_cols_array(&self) -> [$t; 12] {
71 let x = &self.matrix3.x_axis;
72 let y = &self.matrix3.y_axis;
73 let z = &self.matrix3.z_axis;
74 let w = &self.translation;
75 [x.x, x.y, x.z, y.x, y.y, y.z, z.x, z.y, z.z, w.x, w.y, w.z]
76 }
77
78 /// Creates an affine transform from a `[[S; 3]; 4]` 2D array stored in column major order.
79 /// If your data is in row major order you will need to `transpose` the returned
80 /// matrix.
81 #[inline(always)]
82 pub fn from_cols_array_2d(m: &[[$t; 3]; 4]) -> Self {
83 Self {
84 matrix3: $matrix::from_cols(m[0].into(), m[1].into(), m[2].into()),
85 translation: m[3].into(),
86 }
87 }
88
89 /// Creates a `[[S; 3]; 4]` 2D array storing data in column major order.
90 /// If you require data in row major order `transpose` the matrix first.
91 #[inline(always)]
92 pub fn to_cols_array_2d(&self) -> [[$t; 3]; 4] {
93 [
94 self.matrix3.x_axis.into(),
95 self.matrix3.y_axis.into(),
96 self.matrix3.z_axis.into(),
97 self.translation.into(),
98 ]
99 }
100
101 /// Creates an affine transform from the first 12 values in `slice`.
102 ///
103 /// # Panics
104 ///
105 /// Panics if `slice` is less than 12 elements long.
106 #[inline(always)]
107 pub fn from_cols_slice(slice: &[$t]) -> Self {
108 Self {
109 matrix3: $matrix::from_cols_slice(&slice[0..9]),
110 translation: $column::from_slice(&slice[9..12]),
111 }
112 }
113
114 /// Writes the columns of `self` to the first 12 elements in `slice`.
115 ///
116 /// # Panics
117 ///
118 /// Panics if `slice` is less than 12 elements long.
119 #[inline(always)]
120 pub fn write_cols_to_slice(self, slice: &mut [$t]) {
121 self.matrix3.write_cols_to_slice(&mut slice[0..9]);
122 self.translation.write_to_slice(&mut slice[9..12]);
123 }
124
125 /// Creates an affine transform that changes scale.
126 /// Note that if any scale is zero the transform will be non-invertible.
127 #[inline(always)]
128 pub fn from_scale(scale: $vec3) -> Self {
129 Self {
130 matrix3: $matrix::from_diagonal(scale),
131 translation: $column::ZERO,
132 }
133 }
134
135 /// Creates an affine transform from the given `rotation` quaternion.
136 #[inline(always)]
137 pub fn from_quat(rotation: $quat) -> Self {
138 Self {
139 matrix3: $matrix::from_quat(rotation),
140 translation: $column::ZERO,
141 }
142 }
143
144 /// Creates an affine transform containing a 3D rotation around a normalized
145 /// rotation `axis` of `angle` (in radians).
146 #[inline(always)]
147 pub fn from_axis_angle(axis: $vec3, angle: $t) -> Self {
148 Self {
149 matrix3: $matrix::from_axis_angle(axis, angle),
150 translation: $column::ZERO,
151 }
152 }
153
154 /// Creates an affine transform containing a 3D rotation around the x axis of
155 /// `angle` (in radians).
156 #[inline(always)]
157 pub fn from_rotation_x(angle: $t) -> Self {
158 Self {
159 matrix3: $matrix::from_rotation_x(angle),
160 translation: $column::ZERO,
161 }
162 }
163
164 /// Creates an affine transform containing a 3D rotation around the y axis of
165 /// `angle` (in radians).
166 #[inline]
167 pub fn from_rotation_y(angle: $t) -> Self {
168 Self {
169 matrix3: $matrix::from_rotation_y(angle),
170 translation: $column::ZERO,
171 }
172 }
173
174 /// Creates an affine transform containing a 3D rotation around the z axis of
175 /// `angle` (in radians).
176 #[inline]
177 pub fn from_rotation_z(angle: $t) -> Self {
178 Self {
179 matrix3: $matrix::from_rotation_z(angle),
180 translation: $column::ZERO,
181 }
182 }
183
184 /// Creates an affine transformation from the given 3D `translation`.
185 #[inline(always)]
186 pub fn from_translation(translation: $vec3) -> Self {
187 Self {
188 matrix3: $matrix::IDENTITY,
189 translation: translation.into(),
190 }
191 }
192
193 /// Creates an affine transform from a 3x3 matrix (expressing scale, shear and
194 /// rotation)
195 #[inline(always)]
196 pub fn from_mat3(mat3: $mat3) -> Self {
197 Self {
198 matrix3: mat3.into(),
199 translation: $column::ZERO,
200 }
201 }
202
203 /// Creates an affine transform from a 3x3 matrix (expressing scale, shear and rotation)
204 /// and a translation vector.
205 ///
206 /// Equivalent to `Affine3::from_translation(translation) * Affine3::from_mat3(mat3)`
207 #[inline(always)]
208 pub fn from_mat3_translation(mat3: $mat3, translation: $vec3) -> Self {
209 Self {
210 matrix3: mat3.into(),
211 translation: translation.into(),
212 }
213 }
214
215 /// Creates an affine transform from the given 3D `scale`, `rotation` and
216 /// `translation`.
217 ///
218 /// Equivalent to `Affine3::from_translation(translation) *
219 /// Affine3::from_quat(rotation) * Affine3::from_scale(scale)`
220 #[inline(always)]
221 pub fn from_scale_rotation_translation(
222 scale: $vec3,
223 rotation: $quat,
224 translation: $vec3,
225 ) -> Self {
226 let rotation = $matrix::from_quat(rotation);
227 Self {
228 matrix3: $matrix::from_cols(
229 rotation.x_axis * scale.x,
230 rotation.y_axis * scale.y,
231 rotation.z_axis * scale.z,
232 ),
233 translation: translation.into(),
234 }
235 }
236
237 /// Creates an affine transform from the given 3D `rotation` and `translation`.
238 ///
239 /// Equivalent to `Affine3::from_translation(translation) * Affine3::from_quat(rotation)`
240 #[inline(always)]
241 pub fn from_rotation_translation(rotation: $quat, translation: $vec3) -> Self {
242 Self {
243 matrix3: $matrix::from_quat(rotation.into()),
244 translation: translation.into(),
245 }
246 }
247
248 /// The given `Mat4` must be an affine transform,
249 /// i.e. contain no perspective transform.
250 #[inline]
251 pub fn from_mat4(m: $mat4) -> Self {
252 Self {
253 matrix3: $matrix::from_cols(m.x_axis.into(), m.y_axis.into(), m.z_axis.into()),
254 translation: m.w_axis.into(),
255 }
256 }
257
258 /// Extracts `scale`, `rotation` and `translation` from `self`.
259 ///
260 /// The transform is expected to be non-degenerate and without shearing, or the output
261 /// will be invalid.
262 #[inline(always)]
263 pub fn to_scale_rotation_translation(&self) -> ($vec3, $quat, $vec3) {
264 // TODO: migrate to core module
265 let det = self.matrix3.determinant();
266 glam_assert!(det != 0.0);
267
268 let scale = $vec3::new(
269 self.matrix3.x_axis.length() * det.signum(),
270 self.matrix3.y_axis.length(),
271 self.matrix3.z_axis.length(),
272 );
273
274 glam_assert!(scale.cmpne($vec3::ZERO).all());
275
276 let inv_scale = scale.recip();
277
278 let rotation = $quat::from_mat3(&$mat3::from_cols(
279 (self.matrix3.x_axis * inv_scale.x).into(),
280 (self.matrix3.y_axis * inv_scale.y).into(),
281 (self.matrix3.z_axis * inv_scale.z).into(),
282 ));
283
284 (scale, rotation, self.translation.into())
285 }
286
287 #[inline]
288 fn look_to_lh(eye: $vec3, dir: $vec3, up: $vec3) -> Self {
289 let f = dir.normalize();
290 let s = up.cross(f).normalize();
291 let u = f.cross(s);
292 Self {
293 matrix3: $matrix::from_cols(
294 $vec3::new(s.x, u.x, f.x).into(),
295 $vec3::new(s.y, u.y, f.y).into(),
296 $vec3::new(s.z, u.z, f.z).into(),
297 ),
298 translation: $column::new(-s.dot(eye), -u.dot(eye), -f.dot(eye)),
299 }
300 }
301
302 /// Creates a left-handed view transform using a camera position, an up direction, and
303 /// a focal point.
304 ///
305 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
306 #[inline]
307 pub fn look_at_lh(eye: $vec3, center: $vec3, up: $vec3) -> Self {
308 glam_assert!(up.is_normalized());
309 Self::look_to_lh(eye, center - eye, up)
310 }
311
312 /// Creates a right-handed view transform using a camera position, an up direction, and
313 /// a focal point.
314 ///
315 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
316 #[inline]
317 pub fn look_at_rh(eye: $vec3, center: $vec3, up: $vec3) -> Self {
318 glam_assert!(up.is_normalized());
319 Self::look_to_lh(eye, eye - center, up)
320 }
321
322 /// Transforms the given 3D points, applying shear, scale, rotation and translation.
323 #[inline(always)]
324 pub fn transform_point3(&self, other: $vec3) -> $vec3 {
325 ((self.matrix3.x_axis * other.x)
326 + (self.matrix3.y_axis * other.y)
327 + (self.matrix3.z_axis * other.z)
328 + self.translation)
329 .into()
330 }
331
332 /// Transforms the given 3D vector, applying shear, scale and rotation (but NOT
333 /// translation).
334 ///
335 /// To also apply translation, use [`Self::transform_point3`] instead.
336 #[inline(always)]
337 pub fn transform_vector3(&self, other: $vec3) -> $vec3 {
338 ((self.matrix3.x_axis * other.x)
339 + (self.matrix3.y_axis * other.y)
340 + (self.matrix3.z_axis * other.z))
341 .into()
342 }
343
344 /// Returns `true` if, and only if, all elements are finite.
345 ///
346 /// If any element is either `NaN`, positive or negative infinity, this will return
347 /// `false`.
348 #[inline]
349 pub fn is_finite(&self) -> bool {
350 self.matrix3.is_finite() && self.translation.is_finite()
351 }
352
353 /// Returns `true` if any elements are `NaN`.
354 #[inline]
355 pub fn is_nan(&self) -> bool {
356 self.matrix3.is_nan() || self.translation.is_nan()
357 }
358
359 /// Returns true if the absolute difference of all elements between `self` and `other`
360 /// is less than or equal to `max_abs_diff`.
361 ///
362 /// This can be used to compare if two 3x4 matrices contain similar elements. It works
363 /// best when comparing with a known value. The `max_abs_diff` that should be used used
364 /// depends on the values being compared against.
365 ///
366 /// For more see
367 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
368 #[inline]
369 pub fn abs_diff_eq(&self, other: Self, max_abs_diff: $t) -> bool {
370 self.matrix3.abs_diff_eq(other.matrix3, max_abs_diff)
371 && self
372 .translation
373 .abs_diff_eq(other.translation, max_abs_diff)
374 }
375
376 /// Return the inverse of this transform.
377 ///
378 /// Note that if the transform is not invertible the result will be invalid.
379 #[must_use]
380 #[inline]
381 pub fn inverse(&self) -> Self {
382 let matrix3 = self.matrix3.inverse();
383 // transform negative translation by the 3x3 inverse:
384 let translation = -(matrix3 * self.translation);
385
386 Self {
387 matrix3,
388 translation,
389 }
390 }
391 }
392 };
393 }
394
395 macro_rules! impl_affine3_traits {
396 ($t:ty, $mat3:ident, $mat4:ident, $vec3:ident, $vec4:ident, $affine3:ident, $matrix:ident, $column:ident, $deref:ident) => {
397 impl Default for $affine3 {
398 #[inline(always)]
399 fn default() -> Self {
400 Self::IDENTITY
401 }
402 }
403
404 impl Deref for $affine3 {
405 type Target = $deref;
406 #[inline(always)]
407 fn deref(&self) -> &Self::Target {
408 unsafe { &*(self as *const Self as *const Self::Target) }
409 }
410 }
411
412 impl DerefMut for $affine3 {
413 #[inline(always)]
414 fn deref_mut(&mut self) -> &mut Self::Target {
415 unsafe { &mut *(self as *mut Self as *mut Self::Target) }
416 }
417 }
418
419 impl PartialEq for $affine3 {
420 #[inline]
421 fn eq(&self, other: &Self) -> bool {
422 self.matrix3.eq(&other.matrix3) && self.translation.eq(&other.translation)
423 }
424 }
425
426 #[cfg(not(target_arch = "spirv"))]
427 impl core::fmt::Debug for $affine3 {
428 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
429 fmt.debug_struct(stringify!($affine3))
430 .field("matrix3", &self.matrix3)
431 .field("translation", &self.translation)
432 .finish()
433 }
434 }
435
436 #[cfg(not(target_arch = "spirv"))]
437 impl core::fmt::Display for $affine3 {
438 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
439 write!(
440 f,
441 "[{}, {}, {}, {}]",
442 self.x_axis, self.y_axis, self.z_axis, self.w_axis
443 )
444 }
445 }
446
447 impl From<$affine3> for $mat4 {
448 #[inline]
449 fn from(m: $affine3) -> $mat4 {
450 $mat4::from_cols(
451 m.matrix3.x_axis.extend(0.0),
452 m.matrix3.y_axis.extend(0.0),
453 m.matrix3.z_axis.extend(0.0),
454 m.translation.extend(1.0),
455 )
456 }
457 }
458
459 impl Mul for $affine3 {
460 type Output = $affine3;
461
462 #[inline(always)]
463 fn mul(self, other: $affine3) -> Self::Output {
464 Self {
465 matrix3: self.matrix3 * other.matrix3,
466 translation: self.matrix3 * other.translation + self.translation,
467 }
468 }
469 }
470
471 impl Mul<$affine3> for $t {
472 type Output = $affine3;
473 #[inline(always)]
474 fn mul(self, other: $affine3) -> Self::Output {
475 $affine3 {
476 matrix3: self * other.matrix3,
477 translation: self * other.translation,
478 }
479 }
480 }
481
482 impl Mul<$t> for $affine3 {
483 type Output = Self;
484 #[inline(always)]
485 fn mul(self, other: $t) -> Self::Output {
486 Self {
487 matrix3: self.matrix3 * other,
488 translation: self.translation * other,
489 }
490 }
491 }
492
493 impl Add<$affine3> for $affine3 {
494 type Output = Self;
495 #[inline(always)]
496 fn add(self, other: Self) -> Self::Output {
497 Self {
498 matrix3: self.matrix3 + other.matrix3,
499 translation: self.translation + other.translation,
500 }
501 }
502 }
503
504 impl Sub<$affine3> for $affine3 {
505 type Output = Self;
506 #[inline(always)]
507 fn sub(self, other: Self) -> Self::Output {
508 Self {
509 matrix3: self.matrix3 - other.matrix3,
510 translation: self.translation - other.translation,
511 }
512 }
513 }
514
515 impl Mul<$mat4> for $affine3 {
516 type Output = $mat4;
517
518 #[inline(always)]
519 fn mul(self, rhs: $mat4) -> Self::Output {
520 $mat4::from(self) * rhs
521 }
522 }
523
524 impl Mul<$affine3> for $mat4 {
525 type Output = $mat4;
526
527 #[inline(always)]
528 fn mul(self, rhs: $affine3) -> Self::Output {
529 self * $mat4::from(rhs)
530 }
531 }
532
533 impl<'a> core::iter::Product<&'a Self> for $affine3 {
534 fn product<I>(iter: I) -> Self
535 where
536 I: Iterator<Item = &'a Self>,
537 {
538 iter.fold(Self::IDENTITY, |a, &b| a * b)
539 }
540 }
541 };
542 }
543
544 type TransformF32 = Mat3A;
545 type TranslateF32 = Vec3A;
546 type DerefTargetF32 = Columns4<crate::Vec3A>;
547
548 define_affine3_struct!(Affine3A, TransformF32, TranslateF32);
549 impl_affine3_methods!(
550 f32,
551 Mat3,
552 Mat4,
553 Quat,
554 Vec3,
555 Affine3A,
556 TransformF32,
557 TranslateF32
558 );
559 impl_affine3_traits!(
560 f32,
561 Mat3,
562 Mat4,
563 Vec3,
564 Vec4,
565 Affine3A,
566 TransformF32,
567 TranslateF32,
568 DerefTargetF32
569 );
570
571 impl Affine3A {
572 /// Transforms the given `Vec3A`, applying shear, scale, rotation and translation.
573 #[inline(always)]
574 pub fn transform_point3a(&self, other: Vec3A) -> Vec3A {
575 self.matrix3 * other + self.translation
576 }
577
578 /// Transforms the given `Vec3A`, applying shear, scale and rotation (but NOT
579 /// translation).
580 ///
581 /// To also apply translation, use [`Self::transform_point3`] instead.
582 #[inline(always)]
583 pub fn transform_vector3a(&self, other: Vec3A) -> Vec3A {
584 self.matrix3 * other
585 }
586 }
587
588 type TransformF64 = DMat3;
589 type TranslateF64 = DVec3;
590 type DerefTargetF64 = Columns4<DVec3>;
591
592 define_affine3_struct!(DAffine3, TransformF64, TranslateF64);
593 impl_affine3_methods!(
594 f64,
595 DMat3,
596 DMat4,
597 DQuat,
598 DVec3,
599 DAffine3,
600 TransformF64,
601 TranslateF64
602 );
603 impl_affine3_traits!(
604 f64,
605 DMat3,
606 DMat4,
607 DVec3,
608 DVec4,
609 DAffine3,
610 TransformF64,
611 TranslateF64,
612 DerefTargetF64
613 );
614
615 mod const_test_affine3a {
616 const_assert_eq!(16, core::mem::align_of::<super::Affine3A>());
617 const_assert_eq!(64, core::mem::size_of::<super::Affine3A>());
618 }
619
620 mod const_test_daffine3 {
621 const_assert_eq!(8, core::mem::align_of::<super::DAffine3>());
622 const_assert_eq!(96, core::mem::size_of::<super::DAffine3>());
623 }