Debian Codegraph @

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