Added multiplying a tuple by a matrix

This commit is contained in:
Jon Janzen
2021-09-03 19:21:09 -06:00
parent be2d23914d
commit 48b5d0a400
2 changed files with 30 additions and 1 deletions

View File

@@ -203,6 +203,19 @@ impl std::ops::Mul<&Tuple> for &Matrix {
} }
impl std::ops::Mul<&Matrix> for &Tuple {
type Output = Tuple;
fn mul(self, rhs: &Matrix) -> Tuple {
Tuple::new(
rhs.calc_val_for_mul_tuple(0, &self),
rhs.calc_val_for_mul_tuple(1, &self),
rhs.calc_val_for_mul_tuple(2, &self),
rhs.calc_val_for_mul_tuple(3, &self),
)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -356,6 +369,22 @@ mod tests {
assert_eq!(&matrix * &tuple, expected); assert_eq!(&matrix * &tuple, expected);
} }
#[test]
fn multiply_by_tuple_reverse() {
let matrix = Matrix::from_array([
[1.0, 2.0, 3.0, 4.0],
[2.0, 4.0, 4.0, 2.0],
[8.0, 6.0, 4.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
]);
let tuple = Tuple::new(1.0, 2.0, 3.0, 1.0);
let expected = Tuple::new(18.0, 24.0, 33.0, 1.0);
assert_eq!(&tuple * &matrix, expected);
}
#[test] #[test]
fn matrix_by_identity() { fn matrix_by_identity() {
let matrix = Matrix::from_array([ let matrix = Matrix::from_array([

View File

@@ -25,7 +25,7 @@ mod tests {
let expected_point = Tuple::point(2.0, 1.0, 7.0); let expected_point = Tuple::point(2.0, 1.0, 7.0);
let translated_point = &transform * &p; let translated_point = &p * &transform;
assert_eq!(expected_point, translated_point); assert_eq!(expected_point, translated_point);
} }