Debian Codegraph @

debian/missing-sources/glam-0.29.3/src/f32/neon/mat4.rs

raw
1 // Generated from mat.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{
4 euler::{FromEuler, ToEuler},
5 f32::math,
6 neon::*,
7 swizzles::*,
8 DMat4, EulerRot, Mat3, Mat3A, Quat, Vec3, Vec3A, Vec4,
9 };
10 use core::fmt;
11 use core::iter::{Product, Sum};
12 use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
13
14 use core::arch::aarch64::*;
15
16 /// Creates a 4x4 matrix from four column vectors.
17 #[inline(always)]
18 #[must_use]
19 pub const fn mat4(x_axis: Vec4, y_axis: Vec4, z_axis: Vec4, w_axis: Vec4) -> Mat4 {
20 Mat4::from_cols(x_axis, y_axis, z_axis, w_axis)
21 }
22
23 /// A 4x4 column major matrix.
24 ///
25 /// This 4x4 matrix type features convenience methods for creating and using affine transforms and
26 /// perspective projections. If you are primarily dealing with 3D affine transformations
27 /// considering using [`Affine3A`](crate::Affine3A) which is faster than a 4x4 matrix
28 /// for some affine operations.
29 ///
30 /// Affine transformations including 3D translation, rotation and scale can be created
31 /// using methods such as [`Self::from_translation()`], [`Self::from_quat()`],
32 /// [`Self::from_scale()`] and [`Self::from_scale_rotation_translation()`].
33 ///
34 /// Orthographic projections can be created using the methods [`Self::orthographic_lh()`] for
35 /// left-handed coordinate systems and [`Self::orthographic_rh()`] for right-handed
36 /// systems. The resulting matrix is also an affine transformation.
37 ///
38 /// The [`Self::transform_point3()`] and [`Self::transform_vector3()`] convenience methods
39 /// are provided for performing affine transformations on 3D vectors and points. These
40 /// multiply 3D inputs as 4D vectors with an implicit `w` value of `1` for points and `0`
41 /// for vectors respectively. These methods assume that `Self` contains a valid affine
42 /// transform.
43 ///
44 /// Perspective projections can be created using methods such as
45 /// [`Self::perspective_lh()`], [`Self::perspective_infinite_lh()`] and
46 /// [`Self::perspective_infinite_reverse_lh()`] for left-handed co-ordinate systems and
47 /// [`Self::perspective_rh()`], [`Self::perspective_infinite_rh()`] and
48 /// [`Self::perspective_infinite_reverse_rh()`] for right-handed co-ordinate systems.
49 ///
50 /// The resulting perspective project can be use to transform 3D vectors as points with
51 /// perspective correction using the [`Self::project_point3()`] convenience method.
52 #[derive(Clone, Copy)]
53 #[repr(C)]
54 pub struct Mat4 {
55 pub x_axis: Vec4,
56 pub y_axis: Vec4,
57 pub z_axis: Vec4,
58 pub w_axis: Vec4,
59 }
60
61 impl Mat4 {
62 /// A 4x4 matrix with all elements set to `0.0`.
63 pub const ZERO: Self = Self::from_cols(Vec4::ZERO, Vec4::ZERO, Vec4::ZERO, Vec4::ZERO);
64
65 /// A 4x4 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
66 pub const IDENTITY: Self = Self::from_cols(Vec4::X, Vec4::Y, Vec4::Z, Vec4::W);
67
68 /// All NAN:s.
69 pub const NAN: Self = Self::from_cols(Vec4::NAN, Vec4::NAN, Vec4::NAN, Vec4::NAN);
70
71 #[allow(clippy::too_many_arguments)]
72 #[inline(always)]
73 #[must_use]
74 const fn new(
75 m00: f32,
76 m01: f32,
77 m02: f32,
78 m03: f32,
79 m10: f32,
80 m11: f32,
81 m12: f32,
82 m13: f32,
83 m20: f32,
84 m21: f32,
85 m22: f32,
86 m23: f32,
87 m30: f32,
88 m31: f32,
89 m32: f32,
90 m33: f32,
91 ) -> Self {
92 Self {
93 x_axis: Vec4::new(m00, m01, m02, m03),
94 y_axis: Vec4::new(m10, m11, m12, m13),
95 z_axis: Vec4::new(m20, m21, m22, m23),
96 w_axis: Vec4::new(m30, m31, m32, m33),
97 }
98 }
99
100 /// Creates a 4x4 matrix from four column vectors.
101 #[inline(always)]
102 #[must_use]
103 pub const fn from_cols(x_axis: Vec4, y_axis: Vec4, z_axis: Vec4, w_axis: Vec4) -> Self {
104 Self {
105 x_axis,
106 y_axis,
107 z_axis,
108 w_axis,
109 }
110 }
111
112 /// Creates a 4x4 matrix from a `[f32; 16]` array stored in column major order.
113 /// If your data is stored in row major you will need to `transpose` the returned
114 /// matrix.
115 #[inline]
116 #[must_use]
117 pub const fn from_cols_array(m: &[f32; 16]) -> Self {
118 Self::new(
119 m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13],
120 m[14], m[15],
121 )
122 }
123
124 /// Creates a `[f32; 16]` array storing data in column major order.
125 /// If you require data in row major order `transpose` the matrix first.
126 #[inline]
127 #[must_use]
128 pub const fn to_cols_array(&self) -> [f32; 16] {
129 let [x_axis_x, x_axis_y, x_axis_z, x_axis_w] = self.x_axis.to_array();
130 let [y_axis_x, y_axis_y, y_axis_z, y_axis_w] = self.y_axis.to_array();
131 let [z_axis_x, z_axis_y, z_axis_z, z_axis_w] = self.z_axis.to_array();
132 let [w_axis_x, w_axis_y, w_axis_z, w_axis_w] = self.w_axis.to_array();
133
134 [
135 x_axis_x, x_axis_y, x_axis_z, x_axis_w, y_axis_x, y_axis_y, y_axis_z, y_axis_w,
136 z_axis_x, z_axis_y, z_axis_z, z_axis_w, w_axis_x, w_axis_y, w_axis_z, w_axis_w,
137 ]
138 }
139
140 /// Creates a 4x4 matrix from a `[[f32; 4]; 4]` 4D array stored in column major order.
141 /// If your data is in row major order you will need to `transpose` the returned
142 /// matrix.
143 #[inline]
144 #[must_use]
145 pub const fn from_cols_array_2d(m: &[[f32; 4]; 4]) -> Self {
146 Self::from_cols(
147 Vec4::from_array(m[0]),
148 Vec4::from_array(m[1]),
149 Vec4::from_array(m[2]),
150 Vec4::from_array(m[3]),
151 )
152 }
153
154 /// Creates a `[[f32; 4]; 4]` 4D array storing data in column major order.
155 /// If you require data in row major order `transpose` the matrix first.
156 #[inline]
157 #[must_use]
158 pub const fn to_cols_array_2d(&self) -> [[f32; 4]; 4] {
159 [
160 self.x_axis.to_array(),
161 self.y_axis.to_array(),
162 self.z_axis.to_array(),
163 self.w_axis.to_array(),
164 ]
165 }
166
167 /// Creates a 4x4 matrix with its diagonal set to `diagonal` and all other entries set to 0.
168 #[doc(alias = "scale")]
169 #[inline]
170 #[must_use]
171 pub const fn from_diagonal(diagonal: Vec4) -> Self {
172 // diagonal.x, diagonal.y etc can't be done in a const-context
173 let [x, y, z, w] = diagonal.to_array();
174 Self::new(
175 x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, w,
176 )
177 }
178
179 #[inline]
180 #[must_use]
181 fn quat_to_axes(rotation: Quat) -> (Vec4, Vec4, Vec4) {
182 glam_assert!(rotation.is_normalized());
183
184 let (x, y, z, w) = rotation.into();
185 let x2 = x + x;
186 let y2 = y + y;
187 let z2 = z + z;
188 let xx = x * x2;
189 let xy = x * y2;
190 let xz = x * z2;
191 let yy = y * y2;
192 let yz = y * z2;
193 let zz = z * z2;
194 let wx = w * x2;
195 let wy = w * y2;
196 let wz = w * z2;
197
198 let x_axis = Vec4::new(1.0 - (yy + zz), xy + wz, xz - wy, 0.0);
199 let y_axis = Vec4::new(xy - wz, 1.0 - (xx + zz), yz + wx, 0.0);
200 let z_axis = Vec4::new(xz + wy, yz - wx, 1.0 - (xx + yy), 0.0);
201 (x_axis, y_axis, z_axis)
202 }
203
204 /// Creates an affine transformation matrix from the given 3D `scale`, `rotation` and
205 /// `translation`.
206 ///
207 /// The resulting matrix can be used to transform 3D points and vectors. See
208 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
209 ///
210 /// # Panics
211 ///
212 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
213 #[inline]
214 #[must_use]
215 pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
216 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
217 Self::from_cols(
218 x_axis.mul(scale.x),
219 y_axis.mul(scale.y),
220 z_axis.mul(scale.z),
221 Vec4::from((translation, 1.0)),
222 )
223 }
224
225 /// Creates an affine transformation matrix from the given 3D `translation`.
226 ///
227 /// The resulting matrix can be used to transform 3D points and vectors. See
228 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
229 ///
230 /// # Panics
231 ///
232 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
233 #[inline]
234 #[must_use]
235 pub fn from_rotation_translation(rotation: Quat, translation: Vec3) -> Self {
236 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
237 Self::from_cols(x_axis, y_axis, z_axis, Vec4::from((translation, 1.0)))
238 }
239
240 /// Extracts `scale`, `rotation` and `translation` from `self`. The input matrix is
241 /// expected to be a 3D affine transformation matrix otherwise the output will be invalid.
242 ///
243 /// # Panics
244 ///
245 /// Will panic if the determinant of `self` is zero or if the resulting scale vector
246 /// contains any zero elements when `glam_assert` is enabled.
247 #[inline]
248 #[must_use]
249 pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
250 let det = self.determinant();
251 glam_assert!(det != 0.0);
252
253 let scale = Vec3::new(
254 self.x_axis.length() * math::signum(det),
255 self.y_axis.length(),
256 self.z_axis.length(),
257 );
258
259 glam_assert!(scale.cmpne(Vec3::ZERO).all());
260
261 let inv_scale = scale.recip();
262
263 let rotation = Quat::from_rotation_axes(
264 self.x_axis.mul(inv_scale.x).xyz(),
265 self.y_axis.mul(inv_scale.y).xyz(),
266 self.z_axis.mul(inv_scale.z).xyz(),
267 );
268
269 let translation = self.w_axis.xyz();
270
271 (scale, rotation, translation)
272 }
273
274 /// Creates an affine transformation matrix from the given `rotation` quaternion.
275 ///
276 /// The resulting matrix can be used to transform 3D points and vectors. See
277 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
278 ///
279 /// # Panics
280 ///
281 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
282 #[inline]
283 #[must_use]
284 pub fn from_quat(rotation: Quat) -> Self {
285 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
286 Self::from_cols(x_axis, y_axis, z_axis, Vec4::W)
287 }
288
289 /// Creates an affine transformation matrix from the given 3x3 linear transformation
290 /// matrix.
291 ///
292 /// The resulting matrix can be used to transform 3D points and vectors. See
293 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
294 #[inline]
295 #[must_use]
296 pub fn from_mat3(m: Mat3) -> Self {
297 Self::from_cols(
298 Vec4::from((m.x_axis, 0.0)),
299 Vec4::from((m.y_axis, 0.0)),
300 Vec4::from((m.z_axis, 0.0)),
301 Vec4::W,
302 )
303 }
304
305 /// Creates an affine transformation matrix from the given 3x3 linear transformation
306 /// matrix.
307 ///
308 /// The resulting matrix can be used to transform 3D points and vectors. See
309 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
310 #[inline]
311 #[must_use]
312 pub fn from_mat3a(m: Mat3A) -> Self {
313 Self::from_cols(
314 Vec4::from((m.x_axis, 0.0)),
315 Vec4::from((m.y_axis, 0.0)),
316 Vec4::from((m.z_axis, 0.0)),
317 Vec4::W,
318 )
319 }
320
321 /// Creates an affine transformation matrix from the given 3D `translation`.
322 ///
323 /// The resulting matrix can be used to transform 3D points and vectors. See
324 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
325 #[inline]
326 #[must_use]
327 pub fn from_translation(translation: Vec3) -> Self {
328 Self::from_cols(
329 Vec4::X,
330 Vec4::Y,
331 Vec4::Z,
332 Vec4::new(translation.x, translation.y, translation.z, 1.0),
333 )
334 }
335
336 /// Creates an affine transformation matrix containing a 3D rotation around a normalized
337 /// rotation `axis` of `angle` (in radians).
338 ///
339 /// The resulting matrix can be used to transform 3D points and vectors. See
340 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
341 ///
342 /// # Panics
343 ///
344 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
345 #[inline]
346 #[must_use]
347 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
348 glam_assert!(axis.is_normalized());
349
350 let (sin, cos) = math::sin_cos(angle);
351 let axis_sin = axis.mul(sin);
352 let axis_sq = axis.mul(axis);
353 let omc = 1.0 - cos;
354 let xyomc = axis.x * axis.y * omc;
355 let xzomc = axis.x * axis.z * omc;
356 let yzomc = axis.y * axis.z * omc;
357 Self::from_cols(
358 Vec4::new(
359 axis_sq.x * omc + cos,
360 xyomc + axis_sin.z,
361 xzomc - axis_sin.y,
362 0.0,
363 ),
364 Vec4::new(
365 xyomc - axis_sin.z,
366 axis_sq.y * omc + cos,
367 yzomc + axis_sin.x,
368 0.0,
369 ),
370 Vec4::new(
371 xzomc + axis_sin.y,
372 yzomc - axis_sin.x,
373 axis_sq.z * omc + cos,
374 0.0,
375 ),
376 Vec4::W,
377 )
378 }
379
380 /// Creates a affine transformation matrix containing a rotation from the given euler
381 /// rotation sequence and angles (in radians).
382 ///
383 /// The resulting matrix can be used to transform 3D points and vectors. See
384 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
385 #[inline]
386 #[must_use]
387 pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
388 Self::from_euler_angles(order, a, b, c)
389 }
390
391 /// Extract Euler angles with the given Euler rotation order.
392 ///
393 /// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
394 /// then the resulting Euler angles will be ill-defined.
395 ///
396 /// # Panics
397 ///
398 /// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
399 /// `glam_assert` is enabled.
400 #[inline]
401 #[must_use]
402 pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
403 glam_assert!(
404 self.x_axis.xyz().is_normalized()
405 && self.y_axis.xyz().is_normalized()
406 && self.z_axis.xyz().is_normalized()
407 );
408 self.to_euler_angles(order)
409 }
410
411 /// Creates an affine transformation matrix containing a 3D rotation around the x axis of
412 /// `angle` (in radians).
413 ///
414 /// The resulting matrix can be used to transform 3D points and vectors. See
415 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
416 #[inline]
417 #[must_use]
418 pub fn from_rotation_x(angle: f32) -> Self {
419 let (sina, cosa) = math::sin_cos(angle);
420 Self::from_cols(
421 Vec4::X,
422 Vec4::new(0.0, cosa, sina, 0.0),
423 Vec4::new(0.0, -sina, cosa, 0.0),
424 Vec4::W,
425 )
426 }
427
428 /// Creates an affine transformation matrix containing a 3D rotation around the y axis of
429 /// `angle` (in radians).
430 ///
431 /// The resulting matrix can be used to transform 3D points and vectors. See
432 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
433 #[inline]
434 #[must_use]
435 pub fn from_rotation_y(angle: f32) -> Self {
436 let (sina, cosa) = math::sin_cos(angle);
437 Self::from_cols(
438 Vec4::new(cosa, 0.0, -sina, 0.0),
439 Vec4::Y,
440 Vec4::new(sina, 0.0, cosa, 0.0),
441 Vec4::W,
442 )
443 }
444
445 /// Creates an affine transformation matrix containing a 3D rotation around the z axis of
446 /// `angle` (in radians).
447 ///
448 /// The resulting matrix can be used to transform 3D points and vectors. See
449 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
450 #[inline]
451 #[must_use]
452 pub fn from_rotation_z(angle: f32) -> Self {
453 let (sina, cosa) = math::sin_cos(angle);
454 Self::from_cols(
455 Vec4::new(cosa, sina, 0.0, 0.0),
456 Vec4::new(-sina, cosa, 0.0, 0.0),
457 Vec4::Z,
458 Vec4::W,
459 )
460 }
461
462 /// Creates an affine transformation matrix containing the given 3D non-uniform `scale`.
463 ///
464 /// The resulting matrix can be used to transform 3D points and vectors. See
465 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
466 ///
467 /// # Panics
468 ///
469 /// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
470 #[inline]
471 #[must_use]
472 pub fn from_scale(scale: Vec3) -> Self {
473 // Do not panic as long as any component is non-zero
474 glam_assert!(scale.cmpne(Vec3::ZERO).any());
475
476 Self::from_cols(
477 Vec4::new(scale.x, 0.0, 0.0, 0.0),
478 Vec4::new(0.0, scale.y, 0.0, 0.0),
479 Vec4::new(0.0, 0.0, scale.z, 0.0),
480 Vec4::W,
481 )
482 }
483
484 /// Creates a 4x4 matrix from the first 16 values in `slice`.
485 ///
486 /// # Panics
487 ///
488 /// Panics if `slice` is less than 16 elements long.
489 #[inline]
490 #[must_use]
491 pub const fn from_cols_slice(slice: &[f32]) -> Self {
492 Self::new(
493 slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
494 slice[8], slice[9], slice[10], slice[11], slice[12], slice[13], slice[14], slice[15],
495 )
496 }
497
498 /// Writes the columns of `self` to the first 16 elements in `slice`.
499 ///
500 /// # Panics
501 ///
502 /// Panics if `slice` is less than 16 elements long.
503 #[inline]
504 pub fn write_cols_to_slice(self, slice: &mut [f32]) {
505 slice[0] = self.x_axis.x;
506 slice[1] = self.x_axis.y;
507 slice[2] = self.x_axis.z;
508 slice[3] = self.x_axis.w;
509 slice[4] = self.y_axis.x;
510 slice[5] = self.y_axis.y;
511 slice[6] = self.y_axis.z;
512 slice[7] = self.y_axis.w;
513 slice[8] = self.z_axis.x;
514 slice[9] = self.z_axis.y;
515 slice[10] = self.z_axis.z;
516 slice[11] = self.z_axis.w;
517 slice[12] = self.w_axis.x;
518 slice[13] = self.w_axis.y;
519 slice[14] = self.w_axis.z;
520 slice[15] = self.w_axis.w;
521 }
522
523 /// Returns the matrix column for the given `index`.
524 ///
525 /// # Panics
526 ///
527 /// Panics if `index` is greater than 3.
528 #[inline]
529 #[must_use]
530 pub fn col(&self, index: usize) -> Vec4 {
531 match index {
532 0 => self.x_axis,
533 1 => self.y_axis,
534 2 => self.z_axis,
535 3 => self.w_axis,
536 _ => panic!("index out of bounds"),
537 }
538 }
539
540 /// Returns a mutable reference to the matrix column for the given `index`.
541 ///
542 /// # Panics
543 ///
544 /// Panics if `index` is greater than 3.
545 #[inline]
546 pub fn col_mut(&mut self, index: usize) -> &mut Vec4 {
547 match index {
548 0 => &mut self.x_axis,
549 1 => &mut self.y_axis,
550 2 => &mut self.z_axis,
551 3 => &mut self.w_axis,
552 _ => panic!("index out of bounds"),
553 }
554 }
555
556 /// Returns the matrix row for the given `index`.
557 ///
558 /// # Panics
559 ///
560 /// Panics if `index` is greater than 3.
561 #[inline]
562 #[must_use]
563 pub fn row(&self, index: usize) -> Vec4 {
564 match index {
565 0 => Vec4::new(self.x_axis.x, self.y_axis.x, self.z_axis.x, self.w_axis.x),
566 1 => Vec4::new(self.x_axis.y, self.y_axis.y, self.z_axis.y, self.w_axis.y),
567 2 => Vec4::new(self.x_axis.z, self.y_axis.z, self.z_axis.z, self.w_axis.z),
568 3 => Vec4::new(self.x_axis.w, self.y_axis.w, self.z_axis.w, self.w_axis.w),
569 _ => panic!("index out of bounds"),
570 }
571 }
572
573 /// Returns `true` if, and only if, all elements are finite.
574 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
575 #[inline]
576 #[must_use]
577 pub fn is_finite(&self) -> bool {
578 self.x_axis.is_finite()
579 && self.y_axis.is_finite()
580 && self.z_axis.is_finite()
581 && self.w_axis.is_finite()
582 }
583
584 /// Returns `true` if any elements are `NaN`.
585 #[inline]
586 #[must_use]
587 pub fn is_nan(&self) -> bool {
588 self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan() || self.w_axis.is_nan()
589 }
590
591 /// Returns the transpose of `self`.
592 #[inline]
593 #[must_use]
594 pub fn transpose(&self) -> Self {
595 Self {
596 x_axis: Vec4::new(self.x_axis.x, self.y_axis.x, self.z_axis.x, self.w_axis.x),
597 y_axis: Vec4::new(self.x_axis.y, self.y_axis.y, self.z_axis.y, self.w_axis.y),
598 z_axis: Vec4::new(self.x_axis.z, self.y_axis.z, self.z_axis.z, self.w_axis.z),
599 w_axis: Vec4::new(self.x_axis.w, self.y_axis.w, self.z_axis.w, self.w_axis.w),
600 }
601 }
602
603 /// Returns the determinant of `self`.
604 #[must_use]
605 pub fn determinant(&self) -> f32 {
606 let (m00, m01, m02, m03) = self.x_axis.into();
607 let (m10, m11, m12, m13) = self.y_axis.into();
608 let (m20, m21, m22, m23) = self.z_axis.into();
609 let (m30, m31, m32, m33) = self.w_axis.into();
610
611 let a2323 = m22 * m33 - m23 * m32;
612 let a1323 = m21 * m33 - m23 * m31;
613 let a1223 = m21 * m32 - m22 * m31;
614 let a0323 = m20 * m33 - m23 * m30;
615 let a0223 = m20 * m32 - m22 * m30;
616 let a0123 = m20 * m31 - m21 * m30;
617
618 m00 * (m11 * a2323 - m12 * a1323 + m13 * a1223)
619 - m01 * (m10 * a2323 - m12 * a0323 + m13 * a0223)
620 + m02 * (m10 * a1323 - m11 * a0323 + m13 * a0123)
621 - m03 * (m10 * a1223 - m11 * a0223 + m12 * a0123)
622 }
623
624 /// Returns the inverse of `self`.
625 ///
626 /// If the matrix is not invertible the returned matrix will be invalid.
627 ///
628 /// # Panics
629 ///
630 /// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
631 #[must_use]
632 pub fn inverse(&self) -> Self {
633 unsafe {
634 // Based on https://github.com/g-truc/glm `glm_mat4_inverse`
635 let swizzle3377 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
636 let r = vuzp2q_f32(a, b);
637 vtrn2q_f32(r, r)
638 };
639 let swizzle2266 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
640 let r = vuzp1q_f32(a, b);
641 vtrn2q_f32(r, r)
642 };
643 let swizzle0046 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
644 let r = vuzp1q_f32(a, a);
645 vuzp1q_f32(r, b)
646 };
647 let swizzle1155 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
648 let r = vzip1q_f32(a, b);
649 vzip2q_f32(r, r)
650 };
651 let swizzle0044 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
652 let r = vuzp1q_f32(a, b);
653 vtrn1q_f32(r, r)
654 };
655 let swizzle0266 = |a: float32x4_t, b: float32x4_t| -> float32x4_t {
656 let r = vuzp1q_f32(a, b);
657 vsetq_lane_f32(vgetq_lane_f32(b, 2), r, 2)
658 };
659 let swizzle0246 = |a: float32x4_t, b: float32x4_t| -> float32x4_t { vuzp1q_f32(a, b) };
660 let fac0 = {
661 let swp0a = swizzle3377(self.w_axis.0, self.z_axis.0);
662 let swp0b = swizzle2266(self.w_axis.0, self.z_axis.0);
663
664 let swp00 = swizzle2266(self.z_axis.0, self.y_axis.0);
665 let swp01 = swizzle0046(swp0a, swp0a);
666 let swp02 = swizzle0046(swp0b, swp0b);
667 let swp03 = swizzle3377(self.z_axis.0, self.y_axis.0);
668
669 let mul00 = vmulq_f32(swp00, swp01);
670 let mul01 = vmulq_f32(swp02, swp03);
671 vsubq_f32(mul00, mul01)
672 };
673 let fac1 = {
674 let swp0a = swizzle3377(self.w_axis.0, self.z_axis.0);
675 let swp0b = swizzle1155(self.w_axis.0, self.z_axis.0);
676
677 let swp00 = swizzle1155(self.z_axis.0, self.y_axis.0);
678 let swp01 = swizzle0046(swp0a, swp0a);
679 let swp02 = swizzle0046(swp0b, swp0b);
680 let swp03 = swizzle3377(self.z_axis.0, self.y_axis.0);
681
682 let mul00 = vmulq_f32(swp00, swp01);
683 let mul01 = vmulq_f32(swp02, swp03);
684 vsubq_f32(mul00, mul01)
685 };
686 let fac2 = {
687 let swp0a = swizzle2266(self.w_axis.0, self.z_axis.0);
688 let swp0b = swizzle1155(self.w_axis.0, self.z_axis.0);
689
690 let swp00 = swizzle1155(self.z_axis.0, self.y_axis.0);
691 let swp01 = swizzle0046(swp0a, swp0a);
692 let swp02 = swizzle0046(swp0b, swp0b);
693 let swp03 = swizzle2266(self.z_axis.0, self.y_axis.0);
694
695 let mul00 = vmulq_f32(swp00, swp01);
696 let mul01 = vmulq_f32(swp02, swp03);
697 vsubq_f32(mul00, mul01)
698 };
699 let fac3 = {
700 let swp0a = swizzle3377(self.w_axis.0, self.z_axis.0);
701 let swp0b = swizzle0044(self.w_axis.0, self.z_axis.0);
702
703 let swp00 = swizzle0044(self.z_axis.0, self.y_axis.0);
704 let swp01 = swizzle0046(swp0a, swp0a);
705 let swp02 = swizzle0046(swp0b, swp0b);
706 let swp03 = swizzle3377(self.z_axis.0, self.y_axis.0);
707
708 let mul00 = vmulq_f32(swp00, swp01);
709 let mul01 = vmulq_f32(swp02, swp03);
710 vsubq_f32(mul00, mul01)
711 };
712 let fac4 = {
713 let swp0a = swizzle2266(self.w_axis.0, self.z_axis.0);
714 let swp0b = swizzle0044(self.w_axis.0, self.z_axis.0);
715
716 let swp00 = swizzle0044(self.z_axis.0, self.y_axis.0);
717 let swp01 = swizzle0046(swp0a, swp0a);
718 let swp02 = swizzle0046(swp0b, swp0b);
719 let swp03 = swizzle2266(self.z_axis.0, self.y_axis.0);
720
721 let mul00 = vmulq_f32(swp00, swp01);
722 let mul01 = vmulq_f32(swp02, swp03);
723 vsubq_f32(mul00, mul01)
724 };
725 let fac5 = {
726 let swp0a = swizzle1155(self.w_axis.0, self.z_axis.0);
727 let swp0b = swizzle0044(self.w_axis.0, self.z_axis.0);
728
729 let swp00 = swizzle0044(self.z_axis.0, self.y_axis.0);
730 let swp01 = swizzle0046(swp0a, swp0a);
731 let swp02 = swizzle0046(swp0b, swp0b);
732 let swp03 = swizzle1155(self.z_axis.0, self.y_axis.0);
733
734 let mul00 = vmulq_f32(swp00, swp01);
735 let mul01 = vmulq_f32(swp02, swp03);
736 vsubq_f32(mul00, mul01)
737 };
738
739 const SIGN_A: float32x4_t = Vec4::new(-1.0, 1.0, -1.0, 1.0).0;
740 const SIGN_B: float32x4_t = Vec4::new(1.0, -1.0, 1.0, -1.0).0;
741
742 let temp0 = swizzle0044(self.y_axis.0, self.x_axis.0);
743 let vec0 = swizzle0266(temp0, temp0);
744
745 let temp1 = swizzle1155(self.y_axis.0, self.x_axis.0);
746 let vec1 = swizzle0266(temp1, temp1);
747
748 let temp2 = swizzle2266(self.y_axis.0, self.x_axis.0);
749 let vec2 = swizzle0266(temp2, temp2);
750
751 let temp3 = swizzle3377(self.y_axis.0, self.x_axis.0);
752 let vec3 = swizzle0266(temp3, temp3);
753
754 let mul00 = vmulq_f32(vec1, fac0);
755 let mul01 = vmulq_f32(vec2, fac1);
756 let mul02 = vmulq_f32(vec3, fac2);
757 let sub00 = vsubq_f32(mul00, mul01);
758 let add00 = vaddq_f32(sub00, mul02);
759 let inv0 = vmulq_f32(SIGN_B, add00);
760
761 let mul03 = vmulq_f32(vec0, fac0);
762 let mul04 = vmulq_f32(vec2, fac3);
763 let mul05 = vmulq_f32(vec3, fac4);
764 let sub01 = vsubq_f32(mul03, mul04);
765 let add01 = vaddq_f32(sub01, mul05);
766 let inv1 = vmulq_f32(SIGN_A, add01);
767
768 let mul06 = vmulq_f32(vec0, fac1);
769 let mul07 = vmulq_f32(vec1, fac3);
770 let mul08 = vmulq_f32(vec3, fac5);
771 let sub02 = vsubq_f32(mul06, mul07);
772 let add02 = vaddq_f32(sub02, mul08);
773 let inv2 = vmulq_f32(SIGN_B, add02);
774
775 let mul09 = vmulq_f32(vec0, fac2);
776 let mul10 = vmulq_f32(vec1, fac4);
777 let mul11 = vmulq_f32(vec2, fac5);
778 let sub03 = vsubq_f32(mul09, mul10);
779 let add03 = vaddq_f32(sub03, mul11);
780 let inv3 = vmulq_f32(SIGN_A, add03);
781
782 let row0 = swizzle0044(inv0, inv1);
783 let row1 = swizzle0044(inv2, inv3);
784 let row2 = swizzle0246(row0, row1);
785
786 let dot0 = dot4(self.x_axis.0, row2);
787 glam_assert!(dot0 != 0.0);
788
789 let rcp0 = dot0.recip();
790
791 Self {
792 x_axis: Vec4(vmulq_n_f32(inv0, rcp0)),
793 y_axis: Vec4(vmulq_n_f32(inv1, rcp0)),
794 z_axis: Vec4(vmulq_n_f32(inv2, rcp0)),
795 w_axis: Vec4(vmulq_n_f32(inv3, rcp0)),
796 }
797 }
798 }
799
800 /// Creates a left-handed view matrix using a camera position, an up direction, and a facing
801 /// direction.
802 ///
803 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
804 #[inline]
805 #[must_use]
806 pub fn look_to_lh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
807 Self::look_to_rh(eye, -dir, up)
808 }
809
810 /// Creates a right-handed view matrix using a camera position, an up direction, and a facing
811 /// direction.
812 ///
813 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
814 #[inline]
815 #[must_use]
816 pub fn look_to_rh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
817 let f = dir.normalize();
818 let s = f.cross(up).normalize();
819 let u = s.cross(f);
820
821 Self::from_cols(
822 Vec4::new(s.x, u.x, -f.x, 0.0),
823 Vec4::new(s.y, u.y, -f.y, 0.0),
824 Vec4::new(s.z, u.z, -f.z, 0.0),
825 Vec4::new(-eye.dot(s), -eye.dot(u), eye.dot(f), 1.0),
826 )
827 }
828
829 /// Creates a left-handed view matrix using a camera position, an up direction, and a focal
830 /// point.
831 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
832 ///
833 /// # Panics
834 ///
835 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
836 #[inline]
837 #[must_use]
838 pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
839 glam_assert!(up.is_normalized());
840 Self::look_to_lh(eye, center.sub(eye), up)
841 }
842
843 /// Creates a right-handed view matrix using a camera position, an up direction, and a focal
844 /// point.
845 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
846 ///
847 /// # Panics
848 ///
849 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
850 #[inline]
851 pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
852 glam_assert!(up.is_normalized());
853 Self::look_to_rh(eye, center.sub(eye), up)
854 }
855
856 /// Creates a right-handed perspective projection matrix with `[-1,1]` depth range.
857 ///
858 /// Useful to map the standard right-handed coordinate system into what OpenGL expects.
859 ///
860 /// This is the same as the OpenGL `gluPerspective` function.
861 /// See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml>
862 #[inline]
863 #[must_use]
864 pub fn perspective_rh_gl(
865 fov_y_radians: f32,
866 aspect_ratio: f32,
867 z_near: f32,
868 z_far: f32,
869 ) -> Self {
870 let inv_length = 1.0 / (z_near - z_far);
871 let f = 1.0 / math::tan(0.5 * fov_y_radians);
872 let a = f / aspect_ratio;
873 let b = (z_near + z_far) * inv_length;
874 let c = (2.0 * z_near * z_far) * inv_length;
875 Self::from_cols(
876 Vec4::new(a, 0.0, 0.0, 0.0),
877 Vec4::new(0.0, f, 0.0, 0.0),
878 Vec4::new(0.0, 0.0, b, -1.0),
879 Vec4::new(0.0, 0.0, c, 0.0),
880 )
881 }
882
883 /// Creates a left-handed perspective projection matrix with `[0,1]` depth range.
884 ///
885 /// Useful to map the standard left-handed coordinate system into what WebGPU/Metal/Direct3D expect.
886 ///
887 /// # Panics
888 ///
889 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
890 /// enabled.
891 #[inline]
892 #[must_use]
893 pub fn perspective_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
894 glam_assert!(z_near > 0.0 && z_far > 0.0);
895 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
896 let h = cos_fov / sin_fov;
897 let w = h / aspect_ratio;
898 let r = z_far / (z_far - z_near);
899 Self::from_cols(
900 Vec4::new(w, 0.0, 0.0, 0.0),
901 Vec4::new(0.0, h, 0.0, 0.0),
902 Vec4::new(0.0, 0.0, r, 1.0),
903 Vec4::new(0.0, 0.0, -r * z_near, 0.0),
904 )
905 }
906
907 /// Creates a right-handed perspective projection matrix with `[0,1]` depth range.
908 ///
909 /// Useful to map the standard right-handed coordinate system into what WebGPU/Metal/Direct3D expect.
910 ///
911 /// # Panics
912 ///
913 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
914 /// enabled.
915 #[inline]
916 #[must_use]
917 pub fn perspective_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
918 glam_assert!(z_near > 0.0 && z_far > 0.0);
919 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
920 let h = cos_fov / sin_fov;
921 let w = h / aspect_ratio;
922 let r = z_far / (z_near - z_far);
923 Self::from_cols(
924 Vec4::new(w, 0.0, 0.0, 0.0),
925 Vec4::new(0.0, h, 0.0, 0.0),
926 Vec4::new(0.0, 0.0, r, -1.0),
927 Vec4::new(0.0, 0.0, r * z_near, 0.0),
928 )
929 }
930
931 /// Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range.
932 ///
933 /// Like `perspective_lh`, but with an infinite value for `z_far`.
934 /// The result is that points near `z_near` are mapped to depth `0`, and as they move towards infinity the depth approaches `1`.
935 ///
936 /// # Panics
937 ///
938 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
939 /// enabled.
940 #[inline]
941 #[must_use]
942 pub fn perspective_infinite_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
943 glam_assert!(z_near > 0.0);
944 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
945 let h = cos_fov / sin_fov;
946 let w = h / aspect_ratio;
947 Self::from_cols(
948 Vec4::new(w, 0.0, 0.0, 0.0),
949 Vec4::new(0.0, h, 0.0, 0.0),
950 Vec4::new(0.0, 0.0, 1.0, 1.0),
951 Vec4::new(0.0, 0.0, -z_near, 0.0),
952 )
953 }
954
955 /// Creates an infinite reverse left-handed perspective projection matrix with `[0,1]` depth range.
956 ///
957 /// Similar to `perspective_infinite_lh`, but maps `Z = z_near` to a depth of `1` and `Z = infinity` to a depth of `0`.
958 ///
959 /// # Panics
960 ///
961 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
962 #[inline]
963 #[must_use]
964 pub fn perspective_infinite_reverse_lh(
965 fov_y_radians: f32,
966 aspect_ratio: f32,
967 z_near: f32,
968 ) -> Self {
969 glam_assert!(z_near > 0.0);
970 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
971 let h = cos_fov / sin_fov;
972 let w = h / aspect_ratio;
973 Self::from_cols(
974 Vec4::new(w, 0.0, 0.0, 0.0),
975 Vec4::new(0.0, h, 0.0, 0.0),
976 Vec4::new(0.0, 0.0, 0.0, 1.0),
977 Vec4::new(0.0, 0.0, z_near, 0.0),
978 )
979 }
980
981 /// Creates an infinite right-handed perspective projection matrix with `[0,1]` depth range.
982 ///
983 /// Like `perspective_rh`, but with an infinite value for `z_far`.
984 /// The result is that points near `z_near` are mapped to depth `0`, and as they move towards infinity the depth approaches `1`.
985 ///
986 /// # Panics
987 ///
988 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
989 /// enabled.
990 #[inline]
991 #[must_use]
992 pub fn perspective_infinite_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
993 glam_assert!(z_near > 0.0);
994 let f = 1.0 / math::tan(0.5 * fov_y_radians);
995 Self::from_cols(
996 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
997 Vec4::new(0.0, f, 0.0, 0.0),
998 Vec4::new(0.0, 0.0, -1.0, -1.0),
999 Vec4::new(0.0, 0.0, -z_near, 0.0),
1000 )
1001 }
1002
1003 /// Creates an infinite reverse right-handed perspective projection matrix with `[0,1]` depth range.
1004 ///
1005 /// Similar to `perspective_infinite_rh`, but maps `Z = z_near` to a depth of `1` and `Z = infinity` to a depth of `0`.
1006 ///
1007 /// # Panics
1008 ///
1009 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
1010 #[inline]
1011 #[must_use]
1012 pub fn perspective_infinite_reverse_rh(
1013 fov_y_radians: f32,
1014 aspect_ratio: f32,
1015 z_near: f32,
1016 ) -> Self {
1017 glam_assert!(z_near > 0.0);
1018 let f = 1.0 / math::tan(0.5 * fov_y_radians);
1019 Self::from_cols(
1020 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
1021 Vec4::new(0.0, f, 0.0, 0.0),
1022 Vec4::new(0.0, 0.0, 0.0, -1.0),
1023 Vec4::new(0.0, 0.0, z_near, 0.0),
1024 )
1025 }
1026
1027 /// Creates a right-handed orthographic projection matrix with `[-1,1]` depth
1028 /// range. This is the same as the OpenGL `glOrtho` function in OpenGL.
1029 /// See
1030 /// <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml>
1031 ///
1032 /// Useful to map a right-handed coordinate system to the normalized device coordinates that OpenGL expects.
1033 #[inline]
1034 #[must_use]
1035 pub fn orthographic_rh_gl(
1036 left: f32,
1037 right: f32,
1038 bottom: f32,
1039 top: f32,
1040 near: f32,
1041 far: f32,
1042 ) -> Self {
1043 let a = 2.0 / (right - left);
1044 let b = 2.0 / (top - bottom);
1045 let c = -2.0 / (far - near);
1046 let tx = -(right + left) / (right - left);
1047 let ty = -(top + bottom) / (top - bottom);
1048 let tz = -(far + near) / (far - near);
1049
1050 Self::from_cols(
1051 Vec4::new(a, 0.0, 0.0, 0.0),
1052 Vec4::new(0.0, b, 0.0, 0.0),
1053 Vec4::new(0.0, 0.0, c, 0.0),
1054 Vec4::new(tx, ty, tz, 1.0),
1055 )
1056 }
1057
1058 /// Creates a left-handed orthographic projection matrix with `[0,1]` depth range.
1059 ///
1060 /// Useful to map a left-handed coordinate system to the normalized device coordinates that WebGPU/Direct3D/Metal expect.
1061 #[inline]
1062 #[must_use]
1063 pub fn orthographic_lh(
1064 left: f32,
1065 right: f32,
1066 bottom: f32,
1067 top: f32,
1068 near: f32,
1069 far: f32,
1070 ) -> Self {
1071 let rcp_width = 1.0 / (right - left);
1072 let rcp_height = 1.0 / (top - bottom);
1073 let r = 1.0 / (far - near);
1074 Self::from_cols(
1075 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
1076 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
1077 Vec4::new(0.0, 0.0, r, 0.0),
1078 Vec4::new(
1079 -(left + right) * rcp_width,
1080 -(top + bottom) * rcp_height,
1081 -r * near,
1082 1.0,
1083 ),
1084 )
1085 }
1086
1087 /// Creates a right-handed orthographic projection matrix with `[0,1]` depth range.
1088 ///
1089 /// Useful to map a right-handed coordinate system to the normalized device coordinates that WebGPU/Direct3D/Metal expect.
1090 #[inline]
1091 #[must_use]
1092 pub fn orthographic_rh(
1093 left: f32,
1094 right: f32,
1095 bottom: f32,
1096 top: f32,
1097 near: f32,
1098 far: f32,
1099 ) -> Self {
1100 let rcp_width = 1.0 / (right - left);
1101 let rcp_height = 1.0 / (top - bottom);
1102 let r = 1.0 / (near - far);
1103 Self::from_cols(
1104 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
1105 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
1106 Vec4::new(0.0, 0.0, r, 0.0),
1107 Vec4::new(
1108 -(left + right) * rcp_width,
1109 -(top + bottom) * rcp_height,
1110 r * near,
1111 1.0,
1112 ),
1113 )
1114 }
1115
1116 /// Transforms the given 3D vector as a point, applying perspective correction.
1117 ///
1118 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is `1.0`.
1119 /// The perspective divide is performed meaning the resulting 3D vector is divided by `w`.
1120 ///
1121 /// This method assumes that `self` contains a projective transform.
1122 #[inline]
1123 #[must_use]
1124 pub fn project_point3(&self, rhs: Vec3) -> Vec3 {
1125 let mut res = self.x_axis.mul(rhs.x);
1126 res = self.y_axis.mul(rhs.y).add(res);
1127 res = self.z_axis.mul(rhs.z).add(res);
1128 res = self.w_axis.add(res);
1129 res = res.div(res.w);
1130 res.xyz()
1131 }
1132
1133 /// Transforms the given 3D vector as a point.
1134 ///
1135 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1136 /// `1.0`.
1137 ///
1138 /// This method assumes that `self` contains a valid affine transform. It does not perform
1139 /// a perspective divide, if `self` contains a perspective transform, or if you are unsure,
1140 /// the [`Self::project_point3()`] method should be used instead.
1141 ///
1142 /// # Panics
1143 ///
1144 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1145 #[inline]
1146 #[must_use]
1147 pub fn transform_point3(&self, rhs: Vec3) -> Vec3 {
1148 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1149 let mut res = self.x_axis.mul(rhs.x);
1150 res = self.y_axis.mul(rhs.y).add(res);
1151 res = self.z_axis.mul(rhs.z).add(res);
1152 res = self.w_axis.add(res);
1153 res.xyz()
1154 }
1155
1156 /// Transforms the give 3D vector as a direction.
1157 ///
1158 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1159 /// `0.0`.
1160 ///
1161 /// This method assumes that `self` contains a valid affine transform.
1162 ///
1163 /// # Panics
1164 ///
1165 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1166 #[inline]
1167 #[must_use]
1168 pub fn transform_vector3(&self, rhs: Vec3) -> Vec3 {
1169 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1170 let mut res = self.x_axis.mul(rhs.x);
1171 res = self.y_axis.mul(rhs.y).add(res);
1172 res = self.z_axis.mul(rhs.z).add(res);
1173 res.xyz()
1174 }
1175
1176 /// Transforms the given [`Vec3A`] as a 3D point, applying perspective correction.
1177 ///
1178 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `1.0`.
1179 /// The perspective divide is performed meaning the resulting 3D vector is divided by `w`.
1180 ///
1181 /// This method assumes that `self` contains a projective transform.
1182 #[inline]
1183 #[must_use]
1184 pub fn project_point3a(&self, rhs: Vec3A) -> Vec3A {
1185 let mut res = self.x_axis.mul(rhs.xxxx());
1186 res = self.y_axis.mul(rhs.yyyy()).add(res);
1187 res = self.z_axis.mul(rhs.zzzz()).add(res);
1188 res = self.w_axis.add(res);
1189 res = res.div(res.wwww());
1190 Vec3A::from_vec4(res)
1191 }
1192
1193 /// Transforms the given [`Vec3A`] as 3D point.
1194 ///
1195 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `1.0`.
1196 #[inline]
1197 #[must_use]
1198 pub fn transform_point3a(&self, rhs: Vec3A) -> Vec3A {
1199 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1200 let mut res = self.x_axis.mul(rhs.xxxx());
1201 res = self.y_axis.mul(rhs.yyyy()).add(res);
1202 res = self.z_axis.mul(rhs.zzzz()).add(res);
1203 res = self.w_axis.add(res);
1204 Vec3A::from_vec4(res)
1205 }
1206
1207 /// Transforms the give [`Vec3A`] as 3D vector.
1208 ///
1209 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `0.0`.
1210 #[inline]
1211 #[must_use]
1212 pub fn transform_vector3a(&self, rhs: Vec3A) -> Vec3A {
1213 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1214 let mut res = self.x_axis.mul(rhs.xxxx());
1215 res = self.y_axis.mul(rhs.yyyy()).add(res);
1216 res = self.z_axis.mul(rhs.zzzz()).add(res);
1217 Vec3A::from_vec4(res)
1218 }
1219
1220 /// Transforms a 4D vector.
1221 #[inline]
1222 #[must_use]
1223 pub fn mul_vec4(&self, rhs: Vec4) -> Vec4 {
1224 let mut res = self.x_axis.mul(rhs.xxxx());
1225 res = res.add(self.y_axis.mul(rhs.yyyy()));
1226 res = res.add(self.z_axis.mul(rhs.zzzz()));
1227 res = res.add(self.w_axis.mul(rhs.wwww()));
1228 res
1229 }
1230
1231 /// Multiplies two 4x4 matrices.
1232 #[inline]
1233 #[must_use]
1234 pub fn mul_mat4(&self, rhs: &Self) -> Self {
1235 Self::from_cols(
1236 self.mul(rhs.x_axis),
1237 self.mul(rhs.y_axis),
1238 self.mul(rhs.z_axis),
1239 self.mul(rhs.w_axis),
1240 )
1241 }
1242
1243 /// Adds two 4x4 matrices.
1244 #[inline]
1245 #[must_use]
1246 pub fn add_mat4(&self, rhs: &Self) -> Self {
1247 Self::from_cols(
1248 self.x_axis.add(rhs.x_axis),
1249 self.y_axis.add(rhs.y_axis),
1250 self.z_axis.add(rhs.z_axis),
1251 self.w_axis.add(rhs.w_axis),
1252 )
1253 }
1254
1255 /// Subtracts two 4x4 matrices.
1256 #[inline]
1257 #[must_use]
1258 pub fn sub_mat4(&self, rhs: &Self) -> Self {
1259 Self::from_cols(
1260 self.x_axis.sub(rhs.x_axis),
1261 self.y_axis.sub(rhs.y_axis),
1262 self.z_axis.sub(rhs.z_axis),
1263 self.w_axis.sub(rhs.w_axis),
1264 )
1265 }
1266
1267 /// Multiplies a 4x4 matrix by a scalar.
1268 #[inline]
1269 #[must_use]
1270 pub fn mul_scalar(&self, rhs: f32) -> Self {
1271 Self::from_cols(
1272 self.x_axis.mul(rhs),
1273 self.y_axis.mul(rhs),
1274 self.z_axis.mul(rhs),
1275 self.w_axis.mul(rhs),
1276 )
1277 }
1278
1279 /// Divides a 4x4 matrix by a scalar.
1280 #[inline]
1281 #[must_use]
1282 pub fn div_scalar(&self, rhs: f32) -> Self {
1283 let rhs = Vec4::splat(rhs);
1284 Self::from_cols(
1285 self.x_axis.div(rhs),
1286 self.y_axis.div(rhs),
1287 self.z_axis.div(rhs),
1288 self.w_axis.div(rhs),
1289 )
1290 }
1291
1292 /// Returns true if the absolute difference of all elements between `self` and `rhs`
1293 /// is less than or equal to `max_abs_diff`.
1294 ///
1295 /// This can be used to compare if two matrices contain similar elements. It works best
1296 /// when comparing with a known value. The `max_abs_diff` that should be used used
1297 /// depends on the values being compared against.
1298 ///
1299 /// For more see
1300 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
1301 #[inline]
1302 #[must_use]
1303 pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
1304 self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
1305 && self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
1306 && self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
1307 && self.w_axis.abs_diff_eq(rhs.w_axis, max_abs_diff)
1308 }
1309
1310 /// Takes the absolute value of each element in `self`
1311 #[inline]
1312 #[must_use]
1313 pub fn abs(&self) -> Self {
1314 Self::from_cols(
1315 self.x_axis.abs(),
1316 self.y_axis.abs(),
1317 self.z_axis.abs(),
1318 self.w_axis.abs(),
1319 )
1320 }
1321
1322 #[inline]
1323 pub fn as_dmat4(&self) -> DMat4 {
1324 DMat4::from_cols(
1325 self.x_axis.as_dvec4(),
1326 self.y_axis.as_dvec4(),
1327 self.z_axis.as_dvec4(),
1328 self.w_axis.as_dvec4(),
1329 )
1330 }
1331 }
1332
1333 impl Default for Mat4 {
1334 #[inline]
1335 fn default() -> Self {
1336 Self::IDENTITY
1337 }
1338 }
1339
1340 impl Add<Mat4> for Mat4 {
1341 type Output = Self;
1342 #[inline]
1343 fn add(self, rhs: Self) -> Self::Output {
1344 self.add_mat4(&rhs)
1345 }
1346 }
1347
1348 impl AddAssign<Mat4> for Mat4 {
1349 #[inline]
1350 fn add_assign(&mut self, rhs: Self) {
1351 *self = self.add_mat4(&rhs);
1352 }
1353 }
1354
1355 impl Sub<Mat4> for Mat4 {
1356 type Output = Self;
1357 #[inline]
1358 fn sub(self, rhs: Self) -> Self::Output {
1359 self.sub_mat4(&rhs)
1360 }
1361 }
1362
1363 impl SubAssign<Mat4> for Mat4 {
1364 #[inline]
1365 fn sub_assign(&mut self, rhs: Self) {
1366 *self = self.sub_mat4(&rhs);
1367 }
1368 }
1369
1370 impl Neg for Mat4 {
1371 type Output = Self;
1372 #[inline]
1373 fn neg(self) -> Self::Output {
1374 Self::from_cols(
1375 self.x_axis.neg(),
1376 self.y_axis.neg(),
1377 self.z_axis.neg(),
1378 self.w_axis.neg(),
1379 )
1380 }
1381 }
1382
1383 impl Mul<Mat4> for Mat4 {
1384 type Output = Self;
1385 #[inline]
1386 fn mul(self, rhs: Self) -> Self::Output {
1387 self.mul_mat4(&rhs)
1388 }
1389 }
1390
1391 impl MulAssign<Mat4> for Mat4 {
1392 #[inline]
1393 fn mul_assign(&mut self, rhs: Self) {
1394 *self = self.mul_mat4(&rhs);
1395 }
1396 }
1397
1398 impl Mul<Vec4> for Mat4 {
1399 type Output = Vec4;
1400 #[inline]
1401 fn mul(self, rhs: Vec4) -> Self::Output {
1402 self.mul_vec4(rhs)
1403 }
1404 }
1405
1406 impl Mul<Mat4> for f32 {
1407 type Output = Mat4;
1408 #[inline]
1409 fn mul(self, rhs: Mat4) -> Self::Output {
1410 rhs.mul_scalar(self)
1411 }
1412 }
1413
1414 impl Mul<f32> for Mat4 {
1415 type Output = Self;
1416 #[inline]
1417 fn mul(self, rhs: f32) -> Self::Output {
1418 self.mul_scalar(rhs)
1419 }
1420 }
1421
1422 impl MulAssign<f32> for Mat4 {
1423 #[inline]
1424 fn mul_assign(&mut self, rhs: f32) {
1425 *self = self.mul_scalar(rhs);
1426 }
1427 }
1428
1429 impl Div<Mat4> for f32 {
1430 type Output = Mat4;
1431 #[inline]
1432 fn div(self, rhs: Mat4) -> Self::Output {
1433 rhs.div_scalar(self)
1434 }
1435 }
1436
1437 impl Div<f32> for Mat4 {
1438 type Output = Self;
1439 #[inline]
1440 fn div(self, rhs: f32) -> Self::Output {
1441 self.div_scalar(rhs)
1442 }
1443 }
1444
1445 impl DivAssign<f32> for Mat4 {
1446 #[inline]
1447 fn div_assign(&mut self, rhs: f32) {
1448 *self = self.div_scalar(rhs);
1449 }
1450 }
1451
1452 impl Sum<Self> for Mat4 {
1453 fn sum<I>(iter: I) -> Self
1454 where
1455 I: Iterator<Item = Self>,
1456 {
1457 iter.fold(Self::ZERO, Self::add)
1458 }
1459 }
1460
1461 impl<'a> Sum<&'a Self> for Mat4 {
1462 fn sum<I>(iter: I) -> Self
1463 where
1464 I: Iterator<Item = &'a Self>,
1465 {
1466 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1467 }
1468 }
1469
1470 impl Product for Mat4 {
1471 fn product<I>(iter: I) -> Self
1472 where
1473 I: Iterator<Item = Self>,
1474 {
1475 iter.fold(Self::IDENTITY, Self::mul)
1476 }
1477 }
1478
1479 impl<'a> Product<&'a Self> for Mat4 {
1480 fn product<I>(iter: I) -> Self
1481 where
1482 I: Iterator<Item = &'a Self>,
1483 {
1484 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1485 }
1486 }
1487
1488 impl PartialEq for Mat4 {
1489 #[inline]
1490 fn eq(&self, rhs: &Self) -> bool {
1491 self.x_axis.eq(&rhs.x_axis)
1492 && self.y_axis.eq(&rhs.y_axis)
1493 && self.z_axis.eq(&rhs.z_axis)
1494 && self.w_axis.eq(&rhs.w_axis)
1495 }
1496 }
1497
1498 #[cfg(not(target_arch = "spirv"))]
1499 impl AsRef<[f32; 16]> for Mat4 {
1500 #[inline]
1501 fn as_ref(&self) -> &[f32; 16] {
1502 unsafe { &*(self as *const Self as *const [f32; 16]) }
1503 }
1504 }
1505
1506 #[cfg(not(target_arch = "spirv"))]
1507 impl AsMut<[f32; 16]> for Mat4 {
1508 #[inline]
1509 fn as_mut(&mut self) -> &mut [f32; 16] {
1510 unsafe { &mut *(self as *mut Self as *mut [f32; 16]) }
1511 }
1512 }
1513
1514 impl fmt::Debug for Mat4 {
1515 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1516 fmt.debug_struct(stringify!(Mat4))
1517 .field("x_axis", &self.x_axis)
1518 .field("y_axis", &self.y_axis)
1519 .field("z_axis", &self.z_axis)
1520 .field("w_axis", &self.w_axis)
1521 .finish()
1522 }
1523 }
1524
1525 impl fmt::Display for Mat4 {
1526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527 if let Some(p) = f.precision() {
1528 write!(
1529 f,
1530 "[{:.*}, {:.*}, {:.*}, {:.*}]",
1531 p, self.x_axis, p, self.y_axis, p, self.z_axis, p, self.w_axis
1532 )
1533 } else {
1534 write!(
1535 f,
1536 "[{}, {}, {}, {}]",
1537 self.x_axis, self.y_axis, self.z_axis, self.w_axis
1538 )
1539 }
1540 }
1541 }