From a7268a2a83d3a3c7bc7c7dee3f220ae3fe5fd707 Mon Sep 17 00:00:00 2001 From: K Tyl Date: Sat, 6 Jun 2020 03:54:05 +0100 Subject: [PATCH] Visualise surface normals --- src/main.cpp | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5c5ff72..660c732 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,12 +8,39 @@ const double ASPECT_RATIO = 16.0 / 9.0; const int WIDTH = 384; const int HEIGHT = static_cast(WIDTH / ASPECT_RATIO); +double hitSphere(const point3& centre, double radius, const ray& r) +{ + vec3 oc = r.origin() - centre; + + auto a = r.direction().lengthSquared(); + auto halfB = dot(oc, r.direction()); + auto c = oc.lengthSquared() - radius*radius; + + auto discriminant = halfB*halfB - a*c; + + if (discriminant < 0) + { + return -1.0; + } + else + { + return (-halfB - sqrt(discriminant)) / a; + } +} + colour rayColour(const ray& r) { - vec3 unitDirection = unitVector(r.direction()); - double t = 0.5 * (unitDirection.y() + 1.0); + auto t = hitSphere(point3(0,0,-1), 0.5, r); + if (t > 0.0) + { + vec3 N = unitVector(r.at(t) - vec3(0,0,-1)); + return 0.5*colour(N.x()+1, N.y()+1, N.z()+1); + } - auto a = colour(1.0, 1.0, 1.0); + vec3 unitDirection = unitVector(r.direction()); + t = 0.5 * (unitDirection.y() + 1.0); + + auto a = colour(1.0, 0.5, 0.6); auto b = colour(0.0, 0.0, 0.0); return lerp(a, b, t);