Implement Add, Div, Mul, Neg, Sub traits for tuple.

This commit is contained in:
Bill Thiede 2021-06-24 14:47:53 -07:00
parent b159820bad
commit 758f94acde

View File

@ -1,4 +1,5 @@
#[derive(Debug, PartialEq)]
use std::ops::{Add, Div, Mul, Neg, Sub};
#[derive(Debug, PartialEq, Copy, Clone)]
struct Tuple {
x: f32,
y: f32,
@ -16,6 +17,77 @@ impl Tuple {
}
}
impl Add for Tuple {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
w: self.w + other.w,
}
}
}
impl Div<f32> for Tuple {
type Output = Self;
fn div(self, rhs: f32) -> Self::Output {
Self::Output {
x: self.x / rhs,
y: self.y / rhs,
z: self.z / rhs,
w: self.w / rhs,
}
}
}
impl Mul<f32> for Tuple {
type Output = Self;
fn mul(self, rhs: f32) -> Self::Output {
Self::Output {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
w: self.w * rhs,
}
}
}
impl Mul<Tuple> for f32 {
type Output = Tuple;
fn mul(self, rhs: Tuple) -> Self::Output {
Self::Output {
x: self * rhs.x,
y: self * rhs.y,
z: self * rhs.z,
w: self * rhs.w,
}
}
}
impl Neg for Tuple {
type Output = Self;
fn neg(self) -> Self::Output {
Self {
x: -self.x,
y: -self.y,
z: -self.z,
w: -self.w,
}
}
}
impl Sub for Tuple {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
w: self.w - other.w,
}
}
}
fn point(x: f32, y: f32, z: f32) -> Tuple {
tuple(x, y, z, 1.0)
}
@ -61,4 +133,56 @@ mod tests {
fn vector_tuple() {
assert_eq!(vector(4., -4., 3.), tuple(4., -4., 3., 0.))
}
#[test]
fn add_two_tuples() {
let a1 = tuple(3., -2., 5., 1.);
let a2 = tuple(-2., 3., 1., 0.);
assert_eq!(a1 + a2, tuple(1., 1., 6., 1.));
}
#[test]
fn sub_two_points() {
let p1 = point(3., 2., 1.);
let p2 = point(5., 6., 7.);
assert_eq!(p1 - p2, vector(-2., -4., -6.));
}
#[test]
fn sub_vector_point() {
let p = point(3., 2., 1.);
let v = vector(5., 6., 7.);
assert_eq!(p - v, point(-2., -4., -6.));
}
#[test]
fn sub_two_vectors() {
let v1 = vector(3., 2., 1.);
let v2 = vector(5., 6., 7.);
assert_eq!(v1 - v2, vector(-2., -4., -6.));
}
#[test]
fn sub_zero_vector() {
let zero = vector(0., 0., 0.);
let v = vector(1., -2., 3.);
assert_eq!(zero - v, vector(-1., 2., -3.));
}
#[test]
fn negate_tuple() {
let a = tuple(1., -2., 3., -4.);
assert_eq!(-a, tuple(-1., 2., -3., 4.));
}
#[test]
fn mul_tuple_scalar() {
let a = tuple(1., -2., 3., -4.);
assert_eq!(a * 3.5, tuple(3.5, -7., 10.5, -14.));
assert_eq!(3.5 * a, tuple(3.5, -7., 10.5, -14.));
}
#[test]
fn mul_tuple_fraction() {
let a = tuple(1., -2., 3., -4.);
assert_eq!(a * 0.5, tuple(0.5, -1., 1.5, -2.));
assert_eq!(0.5 * a, tuple(0.5, -1., 1.5, -2.));
}
#[test]
fn div_tuple_scalar() {
let a = tuple(1., -2., 3., -4.);
assert_eq!(a / 2., tuple(0.5, -1., 1.5, -2.));
}
}