Debian Codegraph @

debian/missing-sources/glam-0.29.3/src/f32/wasm32/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 swizzles::*,
7 wasm32::*,
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::wasm32::*;
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 // Based on https://github.com/microsoft/DirectXMath `XMMatrixTranspose`
596 let tmp0 = i32x4_shuffle::<0, 1, 4, 5>(self.x_axis.0, self.y_axis.0);
597 let tmp1 = i32x4_shuffle::<2, 3, 6, 7>(self.x_axis.0, self.y_axis.0);
598 let tmp2 = i32x4_shuffle::<0, 1, 4, 5>(self.z_axis.0, self.w_axis.0);
599 let tmp3 = i32x4_shuffle::<2, 3, 6, 7>(self.z_axis.0, self.w_axis.0);
600
601 Self {
602 x_axis: Vec4(i32x4_shuffle::<0, 2, 4, 6>(tmp0, tmp2)),
603 y_axis: Vec4(i32x4_shuffle::<1, 3, 5, 7>(tmp0, tmp2)),
604 z_axis: Vec4(i32x4_shuffle::<0, 2, 4, 6>(tmp1, tmp3)),
605 w_axis: Vec4(i32x4_shuffle::<1, 3, 5, 7>(tmp1, tmp3)),
606 }
607 }
608
609 /// Returns the determinant of `self`.
610 #[must_use]
611 pub fn determinant(&self) -> f32 {
612 // Based on https://github.com/g-truc/glm `glm_mat4_determinant`
613 let swp2a = i32x4_shuffle::<2, 1, 1, 0>(self.z_axis.0, self.z_axis.0);
614 let swp3a = i32x4_shuffle::<3, 3, 2, 3>(self.w_axis.0, self.w_axis.0);
615 let swp2b = i32x4_shuffle::<3, 3, 2, 3>(self.z_axis.0, self.z_axis.0);
616 let swp3b = i32x4_shuffle::<2, 1, 1, 0>(self.w_axis.0, self.w_axis.0);
617 let swp2c = i32x4_shuffle::<2, 1, 0, 0>(self.z_axis.0, self.z_axis.0);
618 let swp3c = i32x4_shuffle::<0, 0, 2, 1>(self.w_axis.0, self.w_axis.0);
619
620 let mula = f32x4_mul(swp2a, swp3a);
621 let mulb = f32x4_mul(swp2b, swp3b);
622 let mulc = f32x4_mul(swp2c, swp3c);
623 let sube = f32x4_sub(mula, mulb);
624 let subf = f32x4_sub(i32x4_shuffle::<6, 7, 2, 3>(mulc, mulc), mulc);
625
626 let subfaca = i32x4_shuffle::<0, 0, 1, 2>(sube, sube);
627 let swpfaca = i32x4_shuffle::<1, 0, 0, 0>(self.y_axis.0, self.y_axis.0);
628 let mulfaca = f32x4_mul(swpfaca, subfaca);
629
630 let subtmpb = i32x4_shuffle::<1, 3, 4, 4>(sube, subf);
631 let subfacb = i32x4_shuffle::<0, 1, 1, 3>(subtmpb, subtmpb);
632 let swpfacb = i32x4_shuffle::<2, 2, 1, 1>(self.y_axis.0, self.y_axis.0);
633 let mulfacb = f32x4_mul(swpfacb, subfacb);
634
635 let subres = f32x4_sub(mulfaca, mulfacb);
636 let subtmpc = i32x4_shuffle::<2, 2, 4, 5>(sube, subf);
637 let subfacc = i32x4_shuffle::<0, 2, 3, 3>(subtmpc, subtmpc);
638 let swpfacc = i32x4_shuffle::<3, 3, 3, 2>(self.y_axis.0, self.y_axis.0);
639 let mulfacc = f32x4_mul(swpfacc, subfacc);
640
641 let addres = f32x4_add(subres, mulfacc);
642 let detcof = f32x4_mul(addres, f32x4(1.0, -1.0, 1.0, -1.0));
643
644 dot4(self.x_axis.0, detcof)
645 }
646
647 /// Returns the inverse of `self`.
648 ///
649 /// If the matrix is not invertible the returned matrix will be invalid.
650 ///
651 /// # Panics
652 ///
653 /// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
654 #[must_use]
655 pub fn inverse(&self) -> Self {
656 // Based on https://github.com/g-truc/glm `glm_mat4_inverse`
657 let fac0 = {
658 let swp0a = i32x4_shuffle::<3, 3, 7, 7>(self.w_axis.0, self.z_axis.0);
659 let swp0b = i32x4_shuffle::<2, 2, 6, 6>(self.w_axis.0, self.z_axis.0);
660
661 let swp00 = i32x4_shuffle::<2, 2, 6, 6>(self.z_axis.0, self.y_axis.0);
662 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
663 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
664 let swp03 = i32x4_shuffle::<3, 3, 7, 7>(self.z_axis.0, self.y_axis.0);
665
666 let mul00 = f32x4_mul(swp00, swp01);
667 let mul01 = f32x4_mul(swp02, swp03);
668 f32x4_sub(mul00, mul01)
669 };
670 let fac1 = {
671 let swp0a = i32x4_shuffle::<3, 3, 7, 7>(self.w_axis.0, self.z_axis.0);
672 let swp0b = i32x4_shuffle::<1, 1, 5, 5>(self.w_axis.0, self.z_axis.0);
673
674 let swp00 = i32x4_shuffle::<1, 1, 5, 5>(self.z_axis.0, self.y_axis.0);
675 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
676 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
677 let swp03 = i32x4_shuffle::<3, 3, 7, 7>(self.z_axis.0, self.y_axis.0);
678
679 let mul00 = f32x4_mul(swp00, swp01);
680 let mul01 = f32x4_mul(swp02, swp03);
681 f32x4_sub(mul00, mul01)
682 };
683 let fac2 = {
684 let swp0a = i32x4_shuffle::<2, 2, 6, 6>(self.w_axis.0, self.z_axis.0);
685 let swp0b = i32x4_shuffle::<1, 1, 5, 5>(self.w_axis.0, self.z_axis.0);
686
687 let swp00 = i32x4_shuffle::<1, 1, 5, 5>(self.z_axis.0, self.y_axis.0);
688 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
689 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
690 let swp03 = i32x4_shuffle::<2, 2, 6, 6>(self.z_axis.0, self.y_axis.0);
691
692 let mul00 = f32x4_mul(swp00, swp01);
693 let mul01 = f32x4_mul(swp02, swp03);
694 f32x4_sub(mul00, mul01)
695 };
696 let fac3 = {
697 let swp0a = i32x4_shuffle::<3, 3, 7, 7>(self.w_axis.0, self.z_axis.0);
698 let swp0b = i32x4_shuffle::<0, 0, 4, 4>(self.w_axis.0, self.z_axis.0);
699
700 let swp00 = i32x4_shuffle::<0, 0, 4, 4>(self.z_axis.0, self.y_axis.0);
701 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
702 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
703 let swp03 = i32x4_shuffle::<3, 3, 7, 7>(self.z_axis.0, self.y_axis.0);
704
705 let mul00 = f32x4_mul(swp00, swp01);
706 let mul01 = f32x4_mul(swp02, swp03);
707 f32x4_sub(mul00, mul01)
708 };
709 let fac4 = {
710 let swp0a = i32x4_shuffle::<2, 2, 6, 6>(self.w_axis.0, self.z_axis.0);
711 let swp0b = i32x4_shuffle::<0, 0, 4, 4>(self.w_axis.0, self.z_axis.0);
712
713 let swp00 = i32x4_shuffle::<0, 0, 4, 4>(self.z_axis.0, self.y_axis.0);
714 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
715 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
716 let swp03 = i32x4_shuffle::<2, 2, 6, 6>(self.z_axis.0, self.y_axis.0);
717
718 let mul00 = f32x4_mul(swp00, swp01);
719 let mul01 = f32x4_mul(swp02, swp03);
720 f32x4_sub(mul00, mul01)
721 };
722 let fac5 = {
723 let swp0a = i32x4_shuffle::<1, 1, 5, 5>(self.w_axis.0, self.z_axis.0);
724 let swp0b = i32x4_shuffle::<0, 0, 4, 4>(self.w_axis.0, self.z_axis.0);
725
726 let swp00 = i32x4_shuffle::<0, 0, 4, 4>(self.z_axis.0, self.y_axis.0);
727 let swp01 = i32x4_shuffle::<0, 0, 4, 6>(swp0a, swp0a);
728 let swp02 = i32x4_shuffle::<0, 0, 4, 6>(swp0b, swp0b);
729 let swp03 = i32x4_shuffle::<1, 1, 5, 5>(self.z_axis.0, self.y_axis.0);
730
731 let mul00 = f32x4_mul(swp00, swp01);
732 let mul01 = f32x4_mul(swp02, swp03);
733 f32x4_sub(mul00, mul01)
734 };
735 let sign_a = f32x4(-1.0, 1.0, -1.0, 1.0);
736 let sign_b = f32x4(1.0, -1.0, 1.0, -1.0);
737
738 let temp0 = i32x4_shuffle::<0, 0, 4, 4>(self.y_axis.0, self.x_axis.0);
739 let vec0 = i32x4_shuffle::<0, 2, 6, 6>(temp0, temp0);
740
741 let temp1 = i32x4_shuffle::<1, 1, 5, 5>(self.y_axis.0, self.x_axis.0);
742 let vec1 = i32x4_shuffle::<0, 2, 6, 6>(temp1, temp1);
743
744 let temp2 = i32x4_shuffle::<2, 2, 6, 6>(self.y_axis.0, self.x_axis.0);
745 let vec2 = i32x4_shuffle::<0, 2, 6, 6>(temp2, temp2);
746
747 let temp3 = i32x4_shuffle::<3, 3, 7, 7>(self.y_axis.0, self.x_axis.0);
748 let vec3 = i32x4_shuffle::<0, 2, 6, 6>(temp3, temp3);
749
750 let mul00 = f32x4_mul(vec1, fac0);
751 let mul01 = f32x4_mul(vec2, fac1);
752 let mul02 = f32x4_mul(vec3, fac2);
753 let sub00 = f32x4_sub(mul00, mul01);
754 let add00 = f32x4_add(sub00, mul02);
755 let inv0 = f32x4_mul(sign_b, add00);
756
757 let mul03 = f32x4_mul(vec0, fac0);
758 let mul04 = f32x4_mul(vec2, fac3);
759 let mul05 = f32x4_mul(vec3, fac4);
760 let sub01 = f32x4_sub(mul03, mul04);
761 let add01 = f32x4_add(sub01, mul05);
762 let inv1 = f32x4_mul(sign_a, add01);
763
764 let mul06 = f32x4_mul(vec0, fac1);
765 let mul07 = f32x4_mul(vec1, fac3);
766 let mul08 = f32x4_mul(vec3, fac5);
767 let sub02 = f32x4_sub(mul06, mul07);
768 let add02 = f32x4_add(sub02, mul08);
769 let inv2 = f32x4_mul(sign_b, add02);
770
771 let mul09 = f32x4_mul(vec0, fac2);
772 let mul10 = f32x4_mul(vec1, fac4);
773 let mul11 = f32x4_mul(vec2, fac5);
774 let sub03 = f32x4_sub(mul09, mul10);
775 let add03 = f32x4_add(sub03, mul11);
776 let inv3 = f32x4_mul(sign_a, add03);
777
778 let row0 = i32x4_shuffle::<0, 0, 4, 4>(inv0, inv1);
779 let row1 = i32x4_shuffle::<0, 0, 4, 4>(inv2, inv3);
780 let row2 = i32x4_shuffle::<0, 2, 4, 6>(row0, row1);
781
782 let dot0 = dot4(self.x_axis.0, row2);
783 glam_assert!(dot0 != 0.0);
784
785 let rcp0 = f32x4_splat(dot0.recip());
786
787 Self {
788 x_axis: Vec4(f32x4_mul(inv0, rcp0)),
789 y_axis: Vec4(f32x4_mul(inv1, rcp0)),
790 z_axis: Vec4(f32x4_mul(inv2, rcp0)),
791 w_axis: Vec4(f32x4_mul(inv3, rcp0)),
792 }
793 }
794
795 /// Creates a left-handed view matrix using a camera position, an up direction, and a facing
796 /// direction.
797 ///
798 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
799 #[inline]
800 #[must_use]
801 pub fn look_to_lh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
802 Self::look_to_rh(eye, -dir, up)
803 }
804
805 /// Creates a right-handed view matrix using a camera position, an up direction, and a facing
806 /// direction.
807 ///
808 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
809 #[inline]
810 #[must_use]
811 pub fn look_to_rh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
812 let f = dir.normalize();
813 let s = f.cross(up).normalize();
814 let u = s.cross(f);
815
816 Self::from_cols(
817 Vec4::new(s.x, u.x, -f.x, 0.0),
818 Vec4::new(s.y, u.y, -f.y, 0.0),
819 Vec4::new(s.z, u.z, -f.z, 0.0),
820 Vec4::new(-eye.dot(s), -eye.dot(u), eye.dot(f), 1.0),
821 )
822 }
823
824 /// Creates a left-handed view matrix using a camera position, an up direction, and a focal
825 /// point.
826 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
827 ///
828 /// # Panics
829 ///
830 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
831 #[inline]
832 #[must_use]
833 pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
834 glam_assert!(up.is_normalized());
835 Self::look_to_lh(eye, center.sub(eye), up)
836 }
837
838 /// Creates a right-handed view matrix using a camera position, an up direction, and a focal
839 /// point.
840 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
841 ///
842 /// # Panics
843 ///
844 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
845 #[inline]
846 pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
847 glam_assert!(up.is_normalized());
848 Self::look_to_rh(eye, center.sub(eye), up)
849 }
850
851 /// Creates a right-handed perspective projection matrix with `[-1,1]` depth range.
852 ///
853 /// Useful to map the standard right-handed coordinate system into what OpenGL expects.
854 ///
855 /// This is the same as the OpenGL `gluPerspective` function.
856 /// See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml>
857 #[inline]
858 #[must_use]
859 pub fn perspective_rh_gl(
860 fov_y_radians: f32,
861 aspect_ratio: f32,
862 z_near: f32,
863 z_far: f32,
864 ) -> Self {
865 let inv_length = 1.0 / (z_near - z_far);
866 let f = 1.0 / math::tan(0.5 * fov_y_radians);
867 let a = f / aspect_ratio;
868 let b = (z_near + z_far) * inv_length;
869 let c = (2.0 * z_near * z_far) * inv_length;
870 Self::from_cols(
871 Vec4::new(a, 0.0, 0.0, 0.0),
872 Vec4::new(0.0, f, 0.0, 0.0),
873 Vec4::new(0.0, 0.0, b, -1.0),
874 Vec4::new(0.0, 0.0, c, 0.0),
875 )
876 }
877
878 /// Creates a left-handed perspective projection matrix with `[0,1]` depth range.
879 ///
880 /// Useful to map the standard left-handed coordinate system into what WebGPU/Metal/Direct3D expect.
881 ///
882 /// # Panics
883 ///
884 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
885 /// enabled.
886 #[inline]
887 #[must_use]
888 pub fn perspective_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
889 glam_assert!(z_near > 0.0 && z_far > 0.0);
890 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
891 let h = cos_fov / sin_fov;
892 let w = h / aspect_ratio;
893 let r = z_far / (z_far - z_near);
894 Self::from_cols(
895 Vec4::new(w, 0.0, 0.0, 0.0),
896 Vec4::new(0.0, h, 0.0, 0.0),
897 Vec4::new(0.0, 0.0, r, 1.0),
898 Vec4::new(0.0, 0.0, -r * z_near, 0.0),
899 )
900 }
901
902 /// Creates a right-handed perspective projection matrix with `[0,1]` depth range.
903 ///
904 /// Useful to map the standard right-handed coordinate system into what WebGPU/Metal/Direct3D expect.
905 ///
906 /// # Panics
907 ///
908 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
909 /// enabled.
910 #[inline]
911 #[must_use]
912 pub fn perspective_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
913 glam_assert!(z_near > 0.0 && z_far > 0.0);
914 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
915 let h = cos_fov / sin_fov;
916 let w = h / aspect_ratio;
917 let r = z_far / (z_near - z_far);
918 Self::from_cols(
919 Vec4::new(w, 0.0, 0.0, 0.0),
920 Vec4::new(0.0, h, 0.0, 0.0),
921 Vec4::new(0.0, 0.0, r, -1.0),
922 Vec4::new(0.0, 0.0, r * z_near, 0.0),
923 )
924 }
925
926 /// Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range.
927 ///
928 /// Like `perspective_lh`, but with an infinite value for `z_far`.
929 /// The result is that points near `z_near` are mapped to depth `0`, and as they move towards infinity the depth approaches `1`.
930 ///
931 /// # Panics
932 ///
933 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
934 /// enabled.
935 #[inline]
936 #[must_use]
937 pub fn perspective_infinite_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
938 glam_assert!(z_near > 0.0);
939 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
940 let h = cos_fov / sin_fov;
941 let w = h / aspect_ratio;
942 Self::from_cols(
943 Vec4::new(w, 0.0, 0.0, 0.0),
944 Vec4::new(0.0, h, 0.0, 0.0),
945 Vec4::new(0.0, 0.0, 1.0, 1.0),
946 Vec4::new(0.0, 0.0, -z_near, 0.0),
947 )
948 }
949
950 /// Creates an infinite reverse left-handed perspective projection matrix with `[0,1]` depth range.
951 ///
952 /// Similar to `perspective_infinite_lh`, but maps `Z = z_near` to a depth of `1` and `Z = infinity` to a depth of `0`.
953 ///
954 /// # Panics
955 ///
956 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
957 #[inline]
958 #[must_use]
959 pub fn perspective_infinite_reverse_lh(
960 fov_y_radians: f32,
961 aspect_ratio: f32,
962 z_near: f32,
963 ) -> Self {
964 glam_assert!(z_near > 0.0);
965 let (sin_fov, cos_fov) = math::sin_cos(0.5 * fov_y_radians);
966 let h = cos_fov / sin_fov;
967 let w = h / aspect_ratio;
968 Self::from_cols(
969 Vec4::new(w, 0.0, 0.0, 0.0),
970 Vec4::new(0.0, h, 0.0, 0.0),
971 Vec4::new(0.0, 0.0, 0.0, 1.0),
972 Vec4::new(0.0, 0.0, z_near, 0.0),
973 )
974 }
975
976 /// Creates an infinite right-handed perspective projection matrix with `[0,1]` depth range.
977 ///
978 /// Like `perspective_rh`, but with an infinite value for `z_far`.
979 /// The result is that points near `z_near` are mapped to depth `0`, and as they move towards infinity the depth approaches `1`.
980 ///
981 /// # Panics
982 ///
983 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
984 /// enabled.
985 #[inline]
986 #[must_use]
987 pub fn perspective_infinite_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
988 glam_assert!(z_near > 0.0);
989 let f = 1.0 / math::tan(0.5 * fov_y_radians);
990 Self::from_cols(
991 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
992 Vec4::new(0.0, f, 0.0, 0.0),
993 Vec4::new(0.0, 0.0, -1.0, -1.0),
994 Vec4::new(0.0, 0.0, -z_near, 0.0),
995 )
996 }
997
998 /// Creates an infinite reverse right-handed perspective projection matrix with `[0,1]` depth range.
999 ///
1000 /// Similar to `perspective_infinite_rh`, but maps `Z = z_near` to a depth of `1` and `Z = infinity` to a depth of `0`.
1001 ///
1002 /// # Panics
1003 ///
1004 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
1005 #[inline]
1006 #[must_use]
1007 pub fn perspective_infinite_reverse_rh(
1008 fov_y_radians: f32,
1009 aspect_ratio: f32,
1010 z_near: f32,
1011 ) -> Self {
1012 glam_assert!(z_near > 0.0);
1013 let f = 1.0 / math::tan(0.5 * fov_y_radians);
1014 Self::from_cols(
1015 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
1016 Vec4::new(0.0, f, 0.0, 0.0),
1017 Vec4::new(0.0, 0.0, 0.0, -1.0),
1018 Vec4::new(0.0, 0.0, z_near, 0.0),
1019 )
1020 }
1021
1022 /// Creates a right-handed orthographic projection matrix with `[-1,1]` depth
1023 /// range. This is the same as the OpenGL `glOrtho` function in OpenGL.
1024 /// See
1025 /// <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml>
1026 ///
1027 /// Useful to map a right-handed coordinate system to the normalized device coordinates that OpenGL expects.
1028 #[inline]
1029 #[must_use]
1030 pub fn orthographic_rh_gl(
1031 left: f32,
1032 right: f32,
1033 bottom: f32,
1034 top: f32,
1035 near: f32,
1036 far: f32,
1037 ) -> Self {
1038 let a = 2.0 / (right - left);
1039 let b = 2.0 / (top - bottom);
1040 let c = -2.0 / (far - near);
1041 let tx = -(right + left) / (right - left);
1042 let ty = -(top + bottom) / (top - bottom);
1043 let tz = -(far + near) / (far - near);
1044
1045 Self::from_cols(
1046 Vec4::new(a, 0.0, 0.0, 0.0),
1047 Vec4::new(0.0, b, 0.0, 0.0),
1048 Vec4::new(0.0, 0.0, c, 0.0),
1049 Vec4::new(tx, ty, tz, 1.0),
1050 )
1051 }
1052
1053 /// Creates a left-handed orthographic projection matrix with `[0,1]` depth range.
1054 ///
1055 /// Useful to map a left-handed coordinate system to the normalized device coordinates that WebGPU/Direct3D/Metal expect.
1056 #[inline]
1057 #[must_use]
1058 pub fn orthographic_lh(
1059 left: f32,
1060 right: f32,
1061 bottom: f32,
1062 top: f32,
1063 near: f32,
1064 far: f32,
1065 ) -> Self {
1066 let rcp_width = 1.0 / (right - left);
1067 let rcp_height = 1.0 / (top - bottom);
1068 let r = 1.0 / (far - near);
1069 Self::from_cols(
1070 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
1071 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
1072 Vec4::new(0.0, 0.0, r, 0.0),
1073 Vec4::new(
1074 -(left + right) * rcp_width,
1075 -(top + bottom) * rcp_height,
1076 -r * near,
1077 1.0,
1078 ),
1079 )
1080 }
1081
1082 /// Creates a right-handed orthographic projection matrix with `[0,1]` depth range.
1083 ///
1084 /// Useful to map a right-handed coordinate system to the normalized device coordinates that WebGPU/Direct3D/Metal expect.
1085 #[inline]
1086 #[must_use]
1087 pub fn orthographic_rh(
1088 left: f32,
1089 right: f32,
1090 bottom: f32,
1091 top: f32,
1092 near: f32,
1093 far: f32,
1094 ) -> Self {
1095 let rcp_width = 1.0 / (right - left);
1096 let rcp_height = 1.0 / (top - bottom);
1097 let r = 1.0 / (near - far);
1098 Self::from_cols(
1099 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
1100 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
1101 Vec4::new(0.0, 0.0, r, 0.0),
1102 Vec4::new(
1103 -(left + right) * rcp_width,
1104 -(top + bottom) * rcp_height,
1105 r * near,
1106 1.0,
1107 ),
1108 )
1109 }
1110
1111 /// Transforms the given 3D vector as a point, applying perspective correction.
1112 ///
1113 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is `1.0`.
1114 /// The perspective divide is performed meaning the resulting 3D vector is divided by `w`.
1115 ///
1116 /// This method assumes that `self` contains a projective transform.
1117 #[inline]
1118 #[must_use]
1119 pub fn project_point3(&self, rhs: Vec3) -> Vec3 {
1120 let mut res = self.x_axis.mul(rhs.x);
1121 res = self.y_axis.mul(rhs.y).add(res);
1122 res = self.z_axis.mul(rhs.z).add(res);
1123 res = self.w_axis.add(res);
1124 res = res.div(res.w);
1125 res.xyz()
1126 }
1127
1128 /// Transforms the given 3D vector as a point.
1129 ///
1130 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1131 /// `1.0`.
1132 ///
1133 /// This method assumes that `self` contains a valid affine transform. It does not perform
1134 /// a perspective divide, if `self` contains a perspective transform, or if you are unsure,
1135 /// the [`Self::project_point3()`] method should be used instead.
1136 ///
1137 /// # Panics
1138 ///
1139 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1140 #[inline]
1141 #[must_use]
1142 pub fn transform_point3(&self, rhs: Vec3) -> Vec3 {
1143 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1144 let mut res = self.x_axis.mul(rhs.x);
1145 res = self.y_axis.mul(rhs.y).add(res);
1146 res = self.z_axis.mul(rhs.z).add(res);
1147 res = self.w_axis.add(res);
1148 res.xyz()
1149 }
1150
1151 /// Transforms the give 3D vector as a direction.
1152 ///
1153 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1154 /// `0.0`.
1155 ///
1156 /// This method assumes that `self` contains a valid affine transform.
1157 ///
1158 /// # Panics
1159 ///
1160 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1161 #[inline]
1162 #[must_use]
1163 pub fn transform_vector3(&self, rhs: Vec3) -> Vec3 {
1164 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1165 let mut res = self.x_axis.mul(rhs.x);
1166 res = self.y_axis.mul(rhs.y).add(res);
1167 res = self.z_axis.mul(rhs.z).add(res);
1168 res.xyz()
1169 }
1170
1171 /// Transforms the given [`Vec3A`] as a 3D point, applying perspective correction.
1172 ///
1173 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `1.0`.
1174 /// The perspective divide is performed meaning the resulting 3D vector is divided by `w`.
1175 ///
1176 /// This method assumes that `self` contains a projective transform.
1177 #[inline]
1178 #[must_use]
1179 pub fn project_point3a(&self, rhs: Vec3A) -> Vec3A {
1180 let mut res = self.x_axis.mul(rhs.xxxx());
1181 res = self.y_axis.mul(rhs.yyyy()).add(res);
1182 res = self.z_axis.mul(rhs.zzzz()).add(res);
1183 res = self.w_axis.add(res);
1184 res = res.div(res.wwww());
1185 Vec3A::from_vec4(res)
1186 }
1187
1188 /// Transforms the given [`Vec3A`] as 3D point.
1189 ///
1190 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `1.0`.
1191 #[inline]
1192 #[must_use]
1193 pub fn transform_point3a(&self, rhs: Vec3A) -> Vec3A {
1194 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1195 let mut res = self.x_axis.mul(rhs.xxxx());
1196 res = self.y_axis.mul(rhs.yyyy()).add(res);
1197 res = self.z_axis.mul(rhs.zzzz()).add(res);
1198 res = self.w_axis.add(res);
1199 Vec3A::from_vec4(res)
1200 }
1201
1202 /// Transforms the give [`Vec3A`] as 3D vector.
1203 ///
1204 /// This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `0.0`.
1205 #[inline]
1206 #[must_use]
1207 pub fn transform_vector3a(&self, rhs: Vec3A) -> Vec3A {
1208 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1209 let mut res = self.x_axis.mul(rhs.xxxx());
1210 res = self.y_axis.mul(rhs.yyyy()).add(res);
1211 res = self.z_axis.mul(rhs.zzzz()).add(res);
1212 Vec3A::from_vec4(res)
1213 }
1214
1215 /// Transforms a 4D vector.
1216 #[inline]
1217 #[must_use]
1218 pub fn mul_vec4(&self, rhs: Vec4) -> Vec4 {
1219 let mut res = self.x_axis.mul(rhs.xxxx());
1220 res = res.add(self.y_axis.mul(rhs.yyyy()));
1221 res = res.add(self.z_axis.mul(rhs.zzzz()));
1222 res = res.add(self.w_axis.mul(rhs.wwww()));
1223 res
1224 }
1225
1226 /// Multiplies two 4x4 matrices.
1227 #[inline]
1228 #[must_use]
1229 pub fn mul_mat4(&self, rhs: &Self) -> Self {
1230 Self::from_cols(
1231 self.mul(rhs.x_axis),
1232 self.mul(rhs.y_axis),
1233 self.mul(rhs.z_axis),
1234 self.mul(rhs.w_axis),
1235 )
1236 }
1237
1238 /// Adds two 4x4 matrices.
1239 #[inline]
1240 #[must_use]
1241 pub fn add_mat4(&self, rhs: &Self) -> Self {
1242 Self::from_cols(
1243 self.x_axis.add(rhs.x_axis),
1244 self.y_axis.add(rhs.y_axis),
1245 self.z_axis.add(rhs.z_axis),
1246 self.w_axis.add(rhs.w_axis),
1247 )
1248 }
1249
1250 /// Subtracts two 4x4 matrices.
1251 #[inline]
1252 #[must_use]
1253 pub fn sub_mat4(&self, rhs: &Self) -> Self {
1254 Self::from_cols(
1255 self.x_axis.sub(rhs.x_axis),
1256 self.y_axis.sub(rhs.y_axis),
1257 self.z_axis.sub(rhs.z_axis),
1258 self.w_axis.sub(rhs.w_axis),
1259 )
1260 }
1261
1262 /// Multiplies a 4x4 matrix by a scalar.
1263 #[inline]
1264 #[must_use]
1265 pub fn mul_scalar(&self, rhs: f32) -> Self {
1266 Self::from_cols(
1267 self.x_axis.mul(rhs),
1268 self.y_axis.mul(rhs),
1269 self.z_axis.mul(rhs),
1270 self.w_axis.mul(rhs),
1271 )
1272 }
1273
1274 /// Divides a 4x4 matrix by a scalar.
1275 #[inline]
1276 #[must_use]
1277 pub fn div_scalar(&self, rhs: f32) -> Self {
1278 let rhs = Vec4::splat(rhs);
1279 Self::from_cols(
1280 self.x_axis.div(rhs),
1281 self.y_axis.div(rhs),
1282 self.z_axis.div(rhs),
1283 self.w_axis.div(rhs),
1284 )
1285 }
1286
1287 /// Returns true if the absolute difference of all elements between `self` and `rhs`
1288 /// is less than or equal to `max_abs_diff`.
1289 ///
1290 /// This can be used to compare if two matrices contain similar elements. It works best
1291 /// when comparing with a known value. The `max_abs_diff` that should be used used
1292 /// depends on the values being compared against.
1293 ///
1294 /// For more see
1295 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
1296 #[inline]
1297 #[must_use]
1298 pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
1299 self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
1300 && self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
1301 && self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
1302 && self.w_axis.abs_diff_eq(rhs.w_axis, max_abs_diff)
1303 }
1304
1305 /// Takes the absolute value of each element in `self`
1306 #[inline]
1307 #[must_use]
1308 pub fn abs(&self) -> Self {
1309 Self::from_cols(
1310 self.x_axis.abs(),
1311 self.y_axis.abs(),
1312 self.z_axis.abs(),
1313 self.w_axis.abs(),
1314 )
1315 }
1316
1317 #[inline]
1318 pub fn as_dmat4(&self) -> DMat4 {
1319 DMat4::from_cols(
1320 self.x_axis.as_dvec4(),
1321 self.y_axis.as_dvec4(),
1322 self.z_axis.as_dvec4(),
1323 self.w_axis.as_dvec4(),
1324 )
1325 }
1326 }
1327
1328 impl Default for Mat4 {
1329 #[inline]
1330 fn default() -> Self {
1331 Self::IDENTITY
1332 }
1333 }
1334
1335 impl Add<Mat4> for Mat4 {
1336 type Output = Self;
1337 #[inline]
1338 fn add(self, rhs: Self) -> Self::Output {
1339 self.add_mat4(&rhs)
1340 }
1341 }
1342
1343 impl AddAssign<Mat4> for Mat4 {
1344 #[inline]
1345 fn add_assign(&mut self, rhs: Self) {
1346 *self = self.add_mat4(&rhs);
1347 }
1348 }
1349
1350 impl Sub<Mat4> for Mat4 {
1351 type Output = Self;
1352 #[inline]
1353 fn sub(self, rhs: Self) -> Self::Output {
1354 self.sub_mat4(&rhs)
1355 }
1356 }
1357
1358 impl SubAssign<Mat4> for Mat4 {
1359 #[inline]
1360 fn sub_assign(&mut self, rhs: Self) {
1361 *self = self.sub_mat4(&rhs);
1362 }
1363 }
1364
1365 impl Neg for Mat4 {
1366 type Output = Self;
1367 #[inline]
1368 fn neg(self) -> Self::Output {
1369 Self::from_cols(
1370 self.x_axis.neg(),
1371 self.y_axis.neg(),
1372 self.z_axis.neg(),
1373 self.w_axis.neg(),
1374 )
1375 }
1376 }
1377
1378 impl Mul<Mat4> for Mat4 {
1379 type Output = Self;
1380 #[inline]
1381 fn mul(self, rhs: Self) -> Self::Output {
1382 self.mul_mat4(&rhs)
1383 }
1384 }
1385
1386 impl MulAssign<Mat4> for Mat4 {
1387 #[inline]
1388 fn mul_assign(&mut self, rhs: Self) {
1389 *self = self.mul_mat4(&rhs);
1390 }
1391 }
1392
1393 impl Mul<Vec4> for Mat4 {
1394 type Output = Vec4;
1395 #[inline]
1396 fn mul(self, rhs: Vec4) -> Self::Output {
1397 self.mul_vec4(rhs)
1398 }
1399 }
1400
1401 impl Mul<Mat4> for f32 {
1402 type Output = Mat4;
1403 #[inline]
1404 fn mul(self, rhs: Mat4) -> Self::Output {
1405 rhs.mul_scalar(self)
1406 }
1407 }
1408
1409 impl Mul<f32> for Mat4 {
1410 type Output = Self;
1411 #[inline]
1412 fn mul(self, rhs: f32) -> Self::Output {
1413 self.mul_scalar(rhs)
1414 }
1415 }
1416
1417 impl MulAssign<f32> for Mat4 {
1418 #[inline]
1419 fn mul_assign(&mut self, rhs: f32) {
1420 *self = self.mul_scalar(rhs);
1421 }
1422 }
1423
1424 impl Div<Mat4> for f32 {
1425 type Output = Mat4;
1426 #[inline]
1427 fn div(self, rhs: Mat4) -> Self::Output {
1428 rhs.div_scalar(self)
1429 }
1430 }
1431
1432 impl Div<f32> for Mat4 {
1433 type Output = Self;
1434 #[inline]
1435 fn div(self, rhs: f32) -> Self::Output {
1436 self.div_scalar(rhs)
1437 }
1438 }
1439
1440 impl DivAssign<f32> for Mat4 {
1441 #[inline]
1442 fn div_assign(&mut self, rhs: f32) {
1443 *self = self.div_scalar(rhs);
1444 }
1445 }
1446
1447 impl Sum<Self> for Mat4 {
1448 fn sum<I>(iter: I) -> Self
1449 where
1450 I: Iterator<Item = Self>,
1451 {
1452 iter.fold(Self::ZERO, Self::add)
1453 }
1454 }
1455
1456 impl<'a> Sum<&'a Self> for Mat4 {
1457 fn sum<I>(iter: I) -> Self
1458 where
1459 I: Iterator<Item = &'a Self>,
1460 {
1461 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1462 }
1463 }
1464
1465 impl Product for Mat4 {
1466 fn product<I>(iter: I) -> Self
1467 where
1468 I: Iterator<Item = Self>,
1469 {
1470 iter.fold(Self::IDENTITY, Self::mul)
1471 }
1472 }
1473
1474 impl<'a> Product<&'a Self> for Mat4 {
1475 fn product<I>(iter: I) -> Self
1476 where
1477 I: Iterator<Item = &'a Self>,
1478 {
1479 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1480 }
1481 }
1482
1483 impl PartialEq for Mat4 {
1484 #[inline]
1485 fn eq(&self, rhs: &Self) -> bool {
1486 self.x_axis.eq(&rhs.x_axis)
1487 && self.y_axis.eq(&rhs.y_axis)
1488 && self.z_axis.eq(&rhs.z_axis)
1489 && self.w_axis.eq(&rhs.w_axis)
1490 }
1491 }
1492
1493 #[cfg(not(target_arch = "spirv"))]
1494 impl AsRef<[f32; 16]> for Mat4 {
1495 #[inline]
1496 fn as_ref(&self) -> &[f32; 16] {
1497 unsafe { &*(self as *const Self as *const [f32; 16]) }
1498 }
1499 }
1500
1501 #[cfg(not(target_arch = "spirv"))]
1502 impl AsMut<[f32; 16]> for Mat4 {
1503 #[inline]
1504 fn as_mut(&mut self) -> &mut [f32; 16] {
1505 unsafe { &mut *(self as *mut Self as *mut [f32; 16]) }
1506 }
1507 }
1508
1509 impl fmt::Debug for Mat4 {
1510 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1511 fmt.debug_struct(stringify!(Mat4))
1512 .field("x_axis", &self.x_axis)
1513 .field("y_axis", &self.y_axis)
1514 .field("z_axis", &self.z_axis)
1515 .field("w_axis", &self.w_axis)
1516 .finish()
1517 }
1518 }
1519
1520 impl fmt::Display for Mat4 {
1521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1522 if let Some(p) = f.precision() {
1523 write!(
1524 f,
1525 "[{:.*}, {:.*}, {:.*}, {:.*}]",
1526 p, self.x_axis, p, self.y_axis, p, self.z_axis, p, self.w_axis
1527 )
1528 } else {
1529 write!(
1530 f,
1531 "[{}, {}, {}, {}]",
1532 self.x_axis, self.y_axis, self.z_axis, self.w_axis
1533 )
1534 }
1535 }
1536 }