Implement 4x4 * 4x1

This commit is contained in:
Bill Thiede 2021-06-30 21:02:42 -07:00
parent 3d2d763a3b
commit 4d649c735b

View File

@ -1,6 +1,8 @@
use std::fmt;
use std::ops::{Add, Div, Index, Mul, Neg, Sub};
use crate::tuples::Tuple;
#[derive(Default, Clone, Copy)]
/// Matrix4x4 represents a 4x4 matrix in row-major form. So, element `m[i][j]` corresponds to m<sub>i,j</sub>
/// where `i` is the row number and `j` is the column number.
@ -246,6 +248,37 @@ impl Mul<Matrix4x4> for Matrix4x4 {
}
}
impl Mul<Tuple> for Matrix4x4 {
type Output = Tuple;
/// Implement matrix multiplication for `Matrix4x4` * `Tuple`.
///
/// # Examples
/// ```
/// use rtchallenge::matrices::Matrix4x4;
/// use rtchallenge::tuples::Tuple;
///
/// let a = Matrix4x4::new(
/// [1., 2., 3., 4.],
/// [2., 4., 4., 2.],
/// [8., 6., 4., 1.],
/// [0., 0., 0., 1.],
/// );
/// let b = Tuple::new(1.,2.,3.,1.);
///
/// assert_eq!(a * b, Tuple::new(18., 24., 33., 1.));
/// ```
fn mul(self, t: Tuple) -> Tuple {
let m = self;
Tuple {
x: m.m[0][0] * t.x + m.m[0][1] * t.y + m.m[0][2] * t.z + m.m[0][3] * t.w,
y: m.m[1][0] * t.x + m.m[1][1] * t.y + m.m[1][2] * t.z + m.m[1][3] * t.w,
z: m.m[2][0] * t.x + m.m[2][1] * t.y + m.m[2][2] * t.z + m.m[2][3] * t.w,
w: m.m[3][0] * t.x + m.m[3][1] * t.y + m.m[3][2] * t.z + m.m[3][3] * t.w,
}
}
}
impl PartialEq for Matrix4x4 {
fn eq(&self, rhs: &Matrix4x4) -> bool {
let l = self.m;