Implement dot and cross product for tuples.

This commit is contained in:
Bill Thiede 2021-06-24 15:15:31 -07:00
parent 1ea90770bc
commit 21afbf8e7c

View File

@ -113,11 +113,22 @@ fn tuple(x: f32, y: f32, z: f32, w: f32) -> Tuple {
Tuple { x, y, z, w }
}
fn dot(a: Tuple, b: Tuple) -> f32 {
a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
}
fn cross(a: Tuple, b: Tuple) -> Tuple {
vector(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
)
}
#[cfg(test)]
mod tests {
use float_cmp::approx_eq;
use super::{point, tuple, vector};
use super::{cross, dot, point, tuple, vector};
#[test]
fn is_point() {
// A tuple with w = 1 is a point
@ -225,4 +236,17 @@ mod tests {
ulps = 1
));
}
#[test]
fn dot_two_tuples() {
let a = vector(1., 2., 3.);
let b = vector(2., 3., 4.);
assert_eq!(20., dot(a, b));
}
#[test]
fn cross_two_tuples() {
let a = vector(1., 2., 3.);
let b = vector(2., 3., 4.);
assert_eq!(vector(-1., 2., -1.), cross(a, b));
assert_eq!(vector(1., -2., 1.), cross(b, a));
}
}