Debian Codegraph @

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