Debian Codegraph @

debian/missing-sources/glam-0.19.0/src/mat3.rs

raw symbols SCIP
1 use crate::core::{
2 storage::{Columns3, XYZ},
3 traits::matrix::{FloatMatrix3x3, Matrix3x3, MatrixConst},
4 };
5 use crate::{DMat2, DMat4, DQuat, DVec2, DVec3, EulerRot, Mat2, Mat4, Quat, Vec2, Vec3, Vec3A};
6 #[cfg(not(target_arch = "spirv"))]
7 use core::fmt;
8 use core::iter::{Product, Sum};
9 use core::ops::{Add, AddAssign, Deref, DerefMut, Mul, MulAssign, Sub, SubAssign};
10
11 #[cfg(all(
12 target_arch = "x86",
13 target_feature = "sse2",
14 not(feature = "scalar-math")
15 ))]
16 use core::arch::x86::*;
17 #[cfg(all(
18 target_arch = "x86_64",
19 target_feature = "sse2",
20 not(feature = "scalar-math")
21 ))]
22 use core::arch::x86_64::*;
23
24 #[cfg(target_feature = "simd128")]
25 use core::arch::wasm32::v128;
26
27 macro_rules! define_mat3_struct {
28 ($mat3:ident, $inner:ident) => {
29 /// A 3x3 column major matrix.
30 ///
31 /// This 3x3 matrix type features convenience methods for creating and using linear and
32 /// affine transformations. If you are primarily dealing with 2D affine transformations the
33 /// [`Affine2`][crate::Affine2] type is much faster and more space efficient than using a
34 /// 3x3 matrix.
35 ///
36 /// Linear transformations including 3D rotation and scale can be created using methods
37 /// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
38 /// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
39 /// [`Self::from_rotation_z()`].
40 ///
41 /// The resulting matrices can be use to transform 3D vectors using regular vector
42 /// multiplication.
43 ///
44 /// Affine transformations including 2D translation, rotation and scale can be created
45 /// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
46 /// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
47 ///
48 /// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
49 /// are provided for performing affine transforms on 2D vectors and points. These multiply
50 /// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
51 /// vectors respectively. These methods assume that `Self` contains a valid affine
52 /// transform.
53 #[derive(Clone, Copy)]
54 #[cfg_attr(not(target_arch = "spirv"), repr(C))]
55 pub struct $mat3(pub(crate) $inner);
56 };
57 }
58
59 macro_rules! impl_mat3_methods {
60 ($t:ty, $vec3:ident, $vec3a:ident, $vec2:ident, $quat:ident, $mat2:ident, $mat4:ident, $inner:ident) => {
61 /// A 3x3 matrix with all elements set to `0.0`.
62 pub const ZERO: Self = Self($inner::ZERO);
63
64 /// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal
65 /// elements are `0`.
66 pub const IDENTITY: Self = Self($inner::IDENTITY);
67
68 /// All NAN:s.
69 pub const NAN: Self = Self(<$inner as crate::core::traits::scalar::NanConstEx>::NAN);
70
71 /// Creates a 3x3 matrix from three column vectors.
72 #[inline(always)]
73 pub fn from_cols(x_axis: $vec3a, y_axis: $vec3a, z_axis: $vec3a) -> Self {
74 Self(Matrix3x3::from_cols(x_axis.0, y_axis.0, z_axis.0))
75 }
76
77 /// Creates a 3x3 matrix from a `[S; 9]` array stored in column major order.
78 /// If your data is stored in row major you will need to `transpose` the returned
79 /// matrix.
80 #[inline(always)]
81 pub fn from_cols_array(m: &[$t; 9]) -> Self {
82 Self(Matrix3x3::from_cols_array(m))
83 }
84
85 /// Creates a `[S; 9]` array storing data in column major order.
86 /// If you require data in row major order `transpose` the matrix first.
87 #[inline(always)]
88 pub fn to_cols_array(&self) -> [$t; 9] {
89 self.0.to_cols_array()
90 }
91
92 /// Creates a 3x3 matrix from a `[[S; 3]; 3]` 2D array stored in column major order.
93 /// If your data is in row major order you will need to `transpose` the returned
94 /// matrix.
95 #[inline(always)]
96 pub fn from_cols_array_2d(m: &[[$t; 3]; 3]) -> Self {
97 Self(Matrix3x3::from_cols_array_2d(m))
98 }
99
100 /// Creates a `[[S; 3]; 3]` 2D array storing data in column major order.
101 /// If you require data in row major order `transpose` the matrix first.
102 #[inline(always)]
103 pub fn to_cols_array_2d(&self) -> [[$t; 3]; 3] {
104 self.0.to_cols_array_2d()
105 }
106
107 /// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
108 /// The resulting matrix is a 3D scale transfom.
109 #[doc(alias = "scale")]
110 #[inline(always)]
111 pub fn from_diagonal(diagonal: $vec3) -> Self {
112 Self($inner::from_diagonal(diagonal.0))
113 }
114
115 /// Creates a 3x3 matrix from a 4x4 matrix, discarding the 3rd row and column.
116 pub fn from_mat4(m: $mat4) -> Self {
117 Self::from_cols(
118 $vec3a(m.x_axis.0.into()),
119 $vec3a(m.y_axis.0.into()),
120 $vec3a(m.z_axis.0.into()),
121 )
122 }
123
124 /// Creates a 3D rotation matrix from the given quaternion.
125 ///
126 /// # Panics
127 ///
128 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
129 #[inline(always)]
130 pub fn from_quat(rotation: $quat) -> Self {
131 // TODO: SIMD?
132 Self($inner::from_quaternion(rotation.0.into()))
133 }
134
135 /// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
136 /// radians).
137 ///
138 /// # Panics
139 ///
140 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
141 #[inline(always)]
142 pub fn from_axis_angle(axis: $vec3, angle: $t) -> Self {
143 Self(FloatMatrix3x3::from_axis_angle(axis.0, angle))
144 }
145
146 #[inline(always)]
147 /// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
148 /// radians).
149 pub fn from_euler(order: EulerRot, a: $t, b: $t, c: $t) -> Self {
150 let quat = $quat::from_euler(order, a, b, c);
151 Self::from_quat(quat)
152 }
153
154 /// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
155 #[inline(always)]
156 pub fn from_rotation_x(angle: $t) -> Self {
157 Self($inner::from_rotation_x(angle))
158 }
159
160 /// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
161 #[inline(always)]
162 pub fn from_rotation_y(angle: $t) -> Self {
163 Self($inner::from_rotation_y(angle))
164 }
165
166 /// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
167 #[inline(always)]
168 pub fn from_rotation_z(angle: $t) -> Self {
169 Self($inner::from_rotation_z(angle))
170 }
171
172 /// Creates an affine transformation matrix from the given 2D `translation`.
173 ///
174 /// The resulting matrix can be used to transform 2D points and vectors. See
175 /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
176 #[inline(always)]
177 pub fn from_translation(translation: $vec2) -> Self {
178 Self(Matrix3x3::from_translation(translation.0))
179 }
180
181 /// Creates an affine transformation matrix from the given 2D rotation `angle` (in
182 /// radians).
183 ///
184 /// The resulting matrix can be used to transform 2D points and vectors. See
185 /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
186 #[inline(always)]
187 pub fn from_angle(angle: $t) -> Self {
188 Self(FloatMatrix3x3::from_angle(angle))
189 }
190
191 /// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
192 /// radians) and `translation`.
193 ///
194 /// The resulting matrix can be used to transform 2D points and vectors. See
195 /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
196 #[inline(always)]
197 pub fn from_scale_angle_translation(scale: $vec2, angle: $t, translation: $vec2) -> Self {
198 Self(FloatMatrix3x3::from_scale_angle_translation(
199 scale.0,
200 angle,
201 translation.0,
202 ))
203 }
204
205 /// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
206 ///
207 /// The resulting matrix can be used to transform 2D points and vectors. See
208 /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
209 ///
210 /// # Panics
211 ///
212 /// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
213 #[inline(always)]
214 pub fn from_scale(scale: $vec2) -> Self {
215 Self(Matrix3x3::from_scale(scale.0))
216 }
217
218 /// Creates an affine transformation matrix from the given 2x2 matrix.
219 ///
220 /// The resulting matrix can be used to transform 2D points and vectors. See
221 /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
222 #[inline(always)]
223 pub fn from_mat2(m: $mat2) -> Self {
224 Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), $vec3a::Z)
225 }
226
227 /// Creates a 3x3 matrix from the first 9 values in `slice`.
228 ///
229 /// # Panics
230 ///
231 /// Panics if `slice` is less than 9 elements long.
232 #[inline(always)]
233 pub fn from_cols_slice(slice: &[$t]) -> Self {
234 Self(Matrix3x3::from_cols_slice(slice))
235 }
236
237 /// Writes the columns of `self` to the first 9 elements in `slice`.
238 ///
239 /// # Panics
240 ///
241 /// Panics if `slice` is less than 9 elements long.
242 #[inline(always)]
243 pub fn write_cols_to_slice(self, slice: &mut [$t]) {
244 Matrix3x3::write_cols_to_slice(&self.0, slice)
245 }
246
247 /// Returns the matrix column for the given `index`.
248 ///
249 /// # Panics
250 ///
251 /// Panics if `index` is greater than 2.
252 #[inline]
253 pub fn col(&self, index: usize) -> $vec3a {
254 match index {
255 0 => self.x_axis,
256 1 => self.y_axis,
257 2 => self.z_axis,
258 _ => panic!("index out of bounds"),
259 }
260 }
261
262 /// Returns a mutable reference to the matrix column for the given `index`.
263 ///
264 /// # Panics
265 ///
266 /// Panics if `index` is greater than 2.
267 #[inline]
268 pub fn col_mut(&mut self, index: usize) -> &mut $vec3a {
269 match index {
270 0 => &mut self.x_axis,
271 1 => &mut self.y_axis,
272 2 => &mut self.z_axis,
273 _ => panic!("index out of bounds"),
274 }
275 }
276
277 /// Returns the matrix row for the given `index`.
278 ///
279 /// # Panics
280 ///
281 /// Panics if `index` is greater than 2.
282 #[inline]
283 pub fn row(&self, index: usize) -> $vec3a {
284 match index {
285 0 => $vec3a::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
286 1 => $vec3a::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
287 2 => $vec3a::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
288 _ => panic!("index out of bounds"),
289 }
290 }
291
292 /// Returns `true` if, and only if, all elements are finite.
293 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
294 #[inline]
295 pub fn is_finite(&self) -> bool {
296 self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
297 }
298
299 /// Returns `true` if any elements are `NaN`.
300 #[inline]
301 pub fn is_nan(&self) -> bool {
302 self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
303 }
304
305 /// Returns the transpose of `self`.
306 #[must_use]
307 #[inline(always)]
308 pub fn transpose(&self) -> Self {
309 Self(self.0.transpose())
310 }
311
312 /// Returns the determinant of `self`.
313 #[inline(always)]
314 pub fn determinant(&self) -> $t {
315 self.0.determinant()
316 }
317
318 /// Returns the inverse of `self`.
319 ///
320 /// If the matrix is not invertible the returned matrix will be invalid.
321 ///
322 /// # Panics
323 ///
324 /// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
325 #[must_use]
326 #[inline(always)]
327 pub fn inverse(&self) -> Self {
328 Self(self.0.inverse())
329 }
330
331 /// Transforms a 3D vector.
332 #[inline(always)]
333 pub fn mul_vec3(&self, other: $vec3) -> $vec3 {
334 $vec3(self.0.mul_vector(other.0.into()).into())
335 }
336
337 /// Multiplies two 3x3 matrices.
338 #[inline]
339 pub fn mul_mat3(&self, other: &Self) -> Self {
340 Self(self.0.mul_matrix(&other.0))
341 }
342
343 /// Adds two 3x3 matrices.
344 #[inline(always)]
345 pub fn add_mat3(&self, other: &Self) -> Self {
346 Self(self.0.add_matrix(&other.0))
347 }
348
349 /// Subtracts two 3x3 matrices.
350 #[inline(always)]
351 pub fn sub_mat3(&self, other: &Self) -> Self {
352 Self(self.0.sub_matrix(&other.0))
353 }
354
355 /// Multiplies a 3x3 matrix by a scalar.
356 #[inline(always)]
357 pub fn mul_scalar(&self, other: $t) -> Self {
358 Self(self.0.mul_scalar(other))
359 }
360
361 /// Transforms the given 2D vector as a point.
362 ///
363 /// This is the equivalent of multiplying `other` as a 3D vector where `z` is `1`.
364 ///
365 /// This method assumes that `self` contains a valid affine transform.
366 #[inline(always)]
367 pub fn transform_point2(&self, other: $vec2) -> $vec2 {
368 $mat2::from_cols($vec2(self.x_axis.0.into()), $vec2(self.y_axis.0.into())) * other
369 + $vec2(self.z_axis.0.into())
370 }
371
372 /// Rotates the given 2D vector.
373 ///
374 /// This is the equivalent of multiplying `other` as a 3D vector where `z` is `0`.
375 ///
376 /// This method assumes that `self` contains a valid affine transform.
377 #[inline(always)]
378 pub fn transform_vector2(&self, other: $vec2) -> $vec2 {
379 $mat2::from_cols($vec2(self.x_axis.0.into()), $vec2(self.y_axis.0.into())) * other
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 matrices contain similar elements. It works best
386 /// 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(always)]
392 pub fn abs_diff_eq(&self, other: Self, max_abs_diff: $t) -> bool {
393 self.0.abs_diff_eq(&other.0, max_abs_diff)
394 }
395 };
396 }
397
398 macro_rules! impl_mat3_traits {
399 ($t:ty, $new:ident, $mat3:ident, $vec3:ident, $vec3a:ident) => {
400 /// Creates a 3x3 matrix from three column vectors.
401 #[inline(always)]
402 pub fn $new(x_axis: $vec3a, y_axis: $vec3a, z_axis: $vec3a) -> $mat3 {
403 $mat3::from_cols(x_axis, y_axis, z_axis)
404 }
405
406 impl_matn_common_traits!($t, $mat3, $vec3a);
407
408 impl PartialEq for $mat3 {
409 #[inline]
410 fn eq(&self, other: &Self) -> bool {
411 self.x_axis.eq(&other.x_axis)
412 && self.y_axis.eq(&other.y_axis)
413 && self.z_axis.eq(&other.z_axis)
414 }
415 }
416
417 impl Deref for $mat3 {
418 type Target = Columns3<$vec3a>;
419 #[inline(always)]
420 fn deref(&self) -> &Self::Target {
421 unsafe { &*(self as *const Self as *const Self::Target) }
422 }
423 }
424
425 impl DerefMut for $mat3 {
426 #[inline(always)]
427 fn deref_mut(&mut self) -> &mut Self::Target {
428 unsafe { &mut *(self as *mut Self as *mut Self::Target) }
429 }
430 }
431
432 #[cfg(not(target_arch = "spirv"))]
433 impl fmt::Display for $mat3 {
434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435 write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
436 }
437 }
438
439 #[cfg(not(target_arch = "spirv"))]
440 impl fmt::Debug for $mat3 {
441 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
442 fmt.debug_struct("$mat3")
443 .field("x_axis", &self.x_axis)
444 .field("y_axis", &self.y_axis)
445 .field("z_axis", &self.z_axis)
446 .finish()
447 }
448 }
449 };
450 }
451
452 macro_rules! impl_mat3_traits_unsafe {
453 ($t:ty, $mat3:ident) => {
454 #[cfg(not(target_arch = "spriv"))]
455 impl AsRef<[$t; 9]> for $mat3 {
456 #[inline(always)]
457 fn as_ref(&self) -> &[$t; 9] {
458 unsafe { &*(self as *const Self as *const [$t; 9]) }
459 }
460 }
461
462 #[cfg(not(target_arch = "spriv"))]
463 impl AsMut<[$t; 9]> for $mat3 {
464 #[inline(always)]
465 fn as_mut(&mut self) -> &mut [$t; 9] {
466 unsafe { &mut *(self as *mut Self as *mut [$t; 9]) }
467 }
468 }
469 };
470 }
471
472 type InnerF32 = Columns3<XYZ<f32>>;
473 define_mat3_struct!(Mat3, InnerF32);
474
475 impl Mat3 {
476 impl_mat3_methods!(f32, Vec3, Vec3, Vec2, Quat, Mat2, Mat4, InnerF32);
477
478 /// Transforms a `Vec3A`.
479 #[inline]
480 pub fn mul_vec3a(&self, other: Vec3A) -> Vec3A {
481 self.mul_vec3(other.into()).into()
482 }
483
484 #[deprecated(since = "0.18.0", note = "please use `as_dmat3()` instead")]
485 #[inline(always)]
486 pub fn as_f64(&self) -> DMat3 {
487 self.as_dmat3()
488 }
489
490 #[inline(always)]
491 pub fn as_dmat3(&self) -> DMat3 {
492 DMat3::from_cols(
493 self.x_axis.as_dvec3(),
494 self.y_axis.as_dvec3(),
495 self.z_axis.as_dvec3(),
496 )
497 }
498 }
499 impl_mat3_traits!(f32, mat3, Mat3, Vec3, Vec3);
500 impl_mat3_traits_unsafe!(f32, Mat3);
501
502 impl Mul<Vec3A> for Mat3 {
503 type Output = Vec3A;
504 #[inline(always)]
505 fn mul(self, other: Vec3A) -> Vec3A {
506 self.mul_vec3a(other)
507 }
508 }
509
510 #[cfg(all(target_feature = "sse2", not(feature = "scalar-math")))]
511 type InnerF32A = Columns3<__m128>;
512
513 #[cfg(all(target_feature = "simd128", not(feature = "scalar-math")))]
514 type InnerF32A = Columns3<v128>;
515
516 #[cfg(any(
517 not(any(target_feature = "sse2", target_feature = "simd128")),
518 feature = "scalar-math"
519 ))]
520 type InnerF32A = Columns3<crate::core::storage::XYZF32A16>;
521 define_mat3_struct!(Mat3A, InnerF32A);
522
523 impl Mat3A {
524 impl_mat3_methods!(f32, Vec3, Vec3A, Vec2, Quat, Mat2, Mat4, InnerF32A);
525
526 /// Transforms a `Vec3A`.
527 #[inline]
528 pub fn mul_vec3a(&self, other: Vec3A) -> Vec3A {
529 Vec3A(self.0.mul_vector(other.0))
530 }
531
532 #[deprecated(since = "0.18.0", note = "please use `as_dmat3()` instead")]
533 #[inline(always)]
534 pub fn as_f64(&self) -> DMat3 {
535 self.as_dmat3()
536 }
537
538 #[inline(always)]
539 pub fn as_dmat3(&self) -> DMat3 {
540 DMat3::from_cols(
541 self.x_axis.as_dvec3(),
542 self.y_axis.as_dvec3(),
543 self.z_axis.as_dvec3(),
544 )
545 }
546 }
547 impl_mat3_traits!(f32, mat3a, Mat3A, Vec3, Vec3A);
548
549 impl Mul<Vec3> for Mat3A {
550 type Output = Vec3;
551 #[inline(always)]
552 fn mul(self, other: Vec3) -> Vec3 {
553 self.mul_vec3(other)
554 }
555 }
556
557 impl From<Mat3> for Mat3A {
558 #[inline(always)]
559 fn from(m: Mat3) -> Self {
560 Self(m.0.into())
561 }
562 }
563
564 impl From<Mat3A> for Mat3 {
565 #[inline(always)]
566 fn from(m: Mat3A) -> Self {
567 Self(m.0.into())
568 }
569 }
570
571 type InnerF64 = Columns3<XYZ<f64>>;
572 define_mat3_struct!(DMat3, InnerF64);
573
574 impl DMat3 {
575 impl_mat3_methods!(f64, DVec3, DVec3, DVec2, DQuat, DMat2, DMat4, InnerF64);
576
577 #[deprecated(since = "0.18.0", note = "please use `as_mat3()` instead")]
578 #[inline(always)]
579 pub fn as_f32(&self) -> Mat3 {
580 self.as_mat3()
581 }
582
583 #[inline(always)]
584 pub fn as_mat3(&self) -> Mat3 {
585 Mat3::from_cols(
586 self.x_axis.as_vec3(),
587 self.y_axis.as_vec3(),
588 self.z_axis.as_vec3(),
589 )
590 }
591 }
592 impl_mat3_traits!(f64, dmat3, DMat3, DVec3, DVec3);
593 impl_mat3_traits_unsafe!(f64, DMat3);
594
595 mod const_test_mat3 {
596 const_assert_eq!(
597 core::mem::align_of::<f32>(),
598 core::mem::align_of::<super::Mat3>()
599 );
600 const_assert_eq!(36, core::mem::size_of::<super::Mat3>());
601 }
602
603 mod const_test_mat3a {
604 const_assert_eq!(16, core::mem::align_of::<super::Mat3A>());
605 const_assert_eq!(48, core::mem::size_of::<super::Mat3A>());
606 }
607
608 mod const_test_dmat3 {
609 const_assert_eq!(
610 core::mem::align_of::<f64>(),
611 core::mem::align_of::<super::DMat3>()
612 );
613 const_assert_eq!(72, core::mem::size_of::<super::DMat3>());
614 }