Debian Codegraph @

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