transformation function

This commit is contained in:
Jon Janzen
2021-09-03 19:13:26 -06:00
parent 909aa52dd6
commit be2d23914d
3 changed files with 48 additions and 4 deletions

View File

@@ -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() { if _lhs.matrix.len() != _rhs.matrix.len() {
return false; return false;
} }

View File

@@ -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)] #[cfg(test)]
mod tests { mod tests {
use super::*;
#[test] #[test]
fn it_works() { fn multiply_by_a_translations_matrix() {
assert_eq!(2 + 2, 4); 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);
} }
} }

View File

@@ -104,7 +104,7 @@ fn cross(lhs: PointVector, rhs: PointVector) -> PointVector {
} }
#[cfg(test)] #[cfg(test)]
mod tests { pub mod tests {
use super::*; use super::*;
#[test] #[test]
@@ -318,4 +318,6 @@ mod tests {
assert_eq!(b_cross_a, cross(b, a)); assert_eq!(b_cross_a, cross(b, a));
} }
pub fn
} }