From be2d23914d0b41ba6b2f264897ac543b0c5c691b Mon Sep 17 00:00:00 2001 From: Jon Janzen Date: Fri, 3 Sep 2021 19:13:26 -0600 Subject: [PATCH] transformation function --- features/src/matrix.rs | 2 +- features/src/transformations.rs | 46 +++++++++++++++++++++++++++++++-- features/src/tuples.rs | 4 ++- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/features/src/matrix.rs b/features/src/matrix.rs index 2c488e9..58626a9 100644 --- a/features/src/matrix.rs +++ b/features/src/matrix.rs @@ -534,7 +534,7 @@ mod tests { } - fn assert_matrix_eq(_lhs: &Matrix, _rhs: &Matrix, max_relative: f32) -> bool { + pub fn assert_matrix_eq(_lhs: &Matrix, _rhs: &Matrix, max_relative: f32) -> bool { if _lhs.matrix.len() != _rhs.matrix.len() { return false; } diff --git a/features/src/transformations.rs b/features/src/transformations.rs index d3126d3..316c0d3 100644 --- a/features/src/transformations.rs +++ b/features/src/transformations.rs @@ -1,8 +1,50 @@ +use crate::matrix::Matrix; +use crate::structs::Tuple; + + +impl Matrix { + pub fn translation(x: f32, y: f32, z: f32) -> Self { + Matrix::from_array([ + [1.0, 0.0, 0.0, x], + [0.0, 1.0, 0.0, y], + [0.0, 0.0, 1.0, z], + [0.0, 0.0, 0.0, 1.0], + ]) + } +} #[cfg(test)] mod tests { + use super::*; + #[test] - fn it_works() { - assert_eq!(2 + 2, 4); + fn multiply_by_a_translations_matrix() { + let transform = Matrix::translation(5.0, -3.0, 2.0); + let p = Tuple::point(-3.0, 4.0, 5.0); + + + let expected_point = Tuple::point(2.0, 1.0, 7.0); + + let translated_point = &transform * &p; + + assert_eq!(expected_point, translated_point); + } + + #[test] + fn multiply_by_the_inverse_of_a_translation_matrix() { + let transform = Matrix::translation(5.0, -3.0, 2.0); + let inv = transform.inverse(); + let p = Tuple::point(-3.0, 4.0, 5.0); + + let expected_point = Tuple::point(-8.0, 7.0, 3.0); + assert_eq!(&inv * &p, expected_point); + } + + #[test] + fn translation_does_not_affect_vectors() { + let transform = Matrix::translation(5.0, -3.0, 2.0); + let v = Tuple::vector(-3.0, 4.0, 5.0); + + assert_eq!(&transform * &v, v); } } diff --git a/features/src/tuples.rs b/features/src/tuples.rs index 1dea01a..b1dd0bb 100644 --- a/features/src/tuples.rs +++ b/features/src/tuples.rs @@ -104,7 +104,7 @@ fn cross(lhs: PointVector, rhs: PointVector) -> PointVector { } #[cfg(test)] -mod tests { +pub mod tests { use super::*; #[test] @@ -318,4 +318,6 @@ mod tests { assert_eq!(b_cross_a, cross(b, a)); } + + pub fn }