diff --git a/rtchallenge/src/matrices.rs b/rtchallenge/src/matrices.rs index dd66764..6b32bbd 100644 --- a/rtchallenge/src/matrices.rs +++ b/rtchallenge/src/matrices.rs @@ -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 mi,j /// where `i` is the row number and `j` is the column number. @@ -246,6 +248,37 @@ impl Mul for Matrix4x4 { } } +impl Mul 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;