Debian Codegraph @

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