From ed6a7d7e31e3fa3b23078d55e6a88917ee68c66e Mon Sep 17 00:00:00 2001 From: Keuin Date: Wed, 20 Apr 2022 22:12:17 +0800 Subject: Add vec3::parallel and its test. --- test_vec.cpp | 12 ++++++++++++ vec.h | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/test_vec.cpp b/test_vec.cpp index 1c9390f..a81ee09 100644 --- a/test_vec.cpp +++ b/test_vec.cpp @@ -117,4 +117,16 @@ TEST(Vec, Refract) { TEST(Vec, Refract_TIR) { vec3d n{1, 0, 0}, u{-1, 0, -sqrt(3)}, v{1, 0, -sqrt(3)}; ASSERT_EQ(v.unit_vec(), n.refract(u.unit_vec(), 2)); +} + +TEST(Vec, VecParallel) { + vec3d a{1, 1, 2}, b{1.1, 1.1, 2.2}, c{0,0,0}, d{1, 2, 1}; + ASSERT_TRUE(a.parallel(b)); + ASSERT_TRUE(b.parallel(a)); + ASSERT_TRUE(a.parallel(c)); + ASSERT_TRUE(c.parallel(a)); + ASSERT_FALSE(a.parallel(d)); + ASSERT_FALSE(d.parallel(a)); + ASSERT_FALSE(b.parallel(d)); + ASSERT_FALSE(d.parallel(b)); } \ No newline at end of file diff --git a/vec.h b/vec.h index 84cbaa3..11b9bd3 100644 --- a/vec.h +++ b/vec.h @@ -109,6 +109,15 @@ struct vec3 { return std::isfinite(x) && std::isfinite(y) && std::isfinite(z); } + // Determine if this vector is parallel with another one. + bool parallel(const vec3 &other) const { + const auto dt = dot(other); + const auto dot2 = dt * dt; + const auto sqlp = mod2() * other.mod2(); // squared length product + const auto d = dot2 - sqlp; + return d > -1e-6 && d < 1e-6; + } + // Get the reflected vector. Current vector is the normal vector (length should be 1), v is the incoming vector. vec3 reflect(const vec3 &v) const { assert(fabs(mod2() - 1.0) < 1e-8); -- cgit v1.2.3