From cb4149ae6049f080e562f43dfd039b0bf6f6f2ab Mon Sep 17 00:00:00 2001 From: NADAL Jean-Baptiste Date: Fri, 16 Feb 2024 17:09:56 +0100 Subject: [PATCH] [FEAT] add tuple reflect --- raytracing/src/tuple.cpp | 7 ++++++ raytracing/src/tuple.h | 2 ++ tests/06_light_shading.cpp | 44 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/raytracing/src/tuple.cpp b/raytracing/src/tuple.cpp index d0ec55c..6a8b1c6 100644 --- a/raytracing/src/tuple.cpp +++ b/raytracing/src/tuple.cpp @@ -331,6 +331,13 @@ Tuple Tuple::cross(const Tuple &a_tuple) /* ------------------------------------------------------------------------- */ +Tuple Tuple::reflect(const Tuple &a_normal) +{ + return *this - a_normal * 2 * dot(a_normal); +} + +/* ------------------------------------------------------------------------- */ + void Tuple::set_at_index(uint8_t an_index, double a_value) { if (an_index == 0) diff --git a/raytracing/src/tuple.h b/raytracing/src/tuple.h index d4e5b69..1146329 100644 --- a/raytracing/src/tuple.h +++ b/raytracing/src/tuple.h @@ -87,6 +87,8 @@ namespace Raytracer double dot(const Tuple &a_tuple); Tuple cross(const Tuple &a_tuple); + Tuple reflect(const Tuple &a_normal); + private: void set_at_index(uint8_t an_index, double a_value); diff --git a/tests/06_light_shading.cpp b/tests/06_light_shading.cpp index 99b5493..78b40c8 100644 --- a/tests/06_light_shading.cpp +++ b/tests/06_light_shading.cpp @@ -168,3 +168,47 @@ SCENARIO("Computing the normal on a transformed sphere", "[features/spheres.feat } } } + +/* ------------------------------------------------------------------------- */ + +SCENARIO("Reflecting a vector approaching at 45°", "[features/tuples.feature]") +{ + GIVEN("v <-vector(1, -1, 0)") + { + Tuple v = Tuple::Vector(1, -1, 0); + AND_GIVEN("n <-vector(0, 1, 0)") + { + Tuple n = Tuple::Vector(0, 1, 0); + WHEN("r <- reflect(v,n)") + { + Tuple r = v.reflect(n); + THEN("r = vector(1,1,0)") + { + REQUIRE(r == Tuple::Vector(1, 1, 0)); + } + } + } + } +} + +/* ------------------------------------------------------------------------- */ + +SCENARIO("Reflecting a vector off a slanted surface", "[features/tuples.feature]") +{ + GIVEN("v <-vector(0, -1, 0)") + { + Tuple v = Tuple::Vector(0, -1, 0); + AND_GIVEN("n <-vector(sqrt(2)/2, sqrt(2)/2, 0)") + { + Tuple n = Tuple::Vector(sqrt(2) / 2, sqrt(2) / 2, 0); + WHEN("r <- reflect(v,n)") + { + Tuple r = v.reflect(n); + THEN("r = vector(1,0,0)") + { + REQUIRE(r == Tuple::Vector(1, 0, 0)); + } + } + } + } +}