diff --git a/source/include/tuple.h b/source/include/tuple.h index 67d87ac..88967eb 100644 --- a/source/include/tuple.h +++ b/source/include/tuple.h @@ -41,8 +41,8 @@ public: double magnitude(); Tuple normalise(); double dot(const Tuple &b); - Tuple cross(const Tuple &b) const; + Tuple reflect(const Tuple &normal); }; class Point: public Tuple diff --git a/source/tuple.cpp b/source/tuple.cpp index 19fa169..42a2c27 100644 --- a/source/tuple.cpp +++ b/source/tuple.cpp @@ -33,4 +33,9 @@ Tuple Tuple::cross(const Tuple &b) const this->z * b.x - this->x * b.z, this->x * b.y - this->y * b.x, 0); +} + +Tuple Tuple::reflect(const Tuple &normal) +{ + return *this - normal * 2 * this->dot(normal); } \ No newline at end of file diff --git a/tests/tuple_test.cpp b/tests/tuple_test.cpp index cf698f2..933d7b9 100644 --- a/tests/tuple_test.cpp +++ b/tests/tuple_test.cpp @@ -181,3 +181,23 @@ TEST(TuplesTests, Cross_product_of_two_vector) ASSERT_EQ(a.cross(b), Vector(-1, 2, -1)); ASSERT_EQ(b.cross(a), Vector(1, -2, 1)); } + +TEST(TuplesTests, Reflecting_a_vector_approaching_at_45) +{ + Vector v = Vector(1, -1, 0); /* Vector */ + Vector n = Vector(0, 1, 0); /* Normal */ + + Tuple r = v.reflect(n); + + ASSERT_EQ(r, Vector(1, 1, 0)); +} + +TEST(TuplesTests, Reflecting_a_vector_off_a_slanted_surface) +{ + Vector v = Vector(0, -1, 0); /* Vector */ + Vector n = Vector(sqrt(2)/2, sqrt(2)/2, 0); /* Normal */ + + Tuple r = v.reflect(n); + + ASSERT_EQ(r, Vector(1, 0, 0)); +} \ No newline at end of file