// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2020 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #pragma once #include #include #include namespace WwiseGTE { template class TIQuery, Sphere3> { public: struct Result { bool intersect; }; Result operator()(Ray3 const& ray, Sphere3 const& sphere) { // The sphere is (X-C)^T*(X-C)-1 = 0 and the line is X = P+t*D. // Substitute the line equation into the sphere equation to // obtain a quadratic equation Q(t) = t^2 + 2*a1*t + a0 = 0, where // a1 = D^T*(P-C) and a0 = (P-C)^T*(P-C)-1. Result result; Vector3 diff = ray.origin - sphere.center; Real a0 = Dot(diff, diff) - sphere.radius * sphere.radius; if (a0 <= (Real)0) { // P is inside the sphere. result.intersect = true; return result; } // else: P is outside the sphere Real a1 = Dot(ray.direction, diff); if (a1 >= (Real)0) { result.intersect = false; return result; } // Intersection occurs when Q(t) has real roots. Real discr = a1 * a1 - a0; result.intersect = (discr >= (Real)0); return result; } }; template class FIQuery, Sphere3> : public FIQuery, Sphere3> { public: struct Result : public FIQuery, Sphere3>::Result { // No additional information to compute. }; Result operator()(Ray3 const& ray, Sphere3 const& sphere) { Result result; DoQuery(ray.origin, ray.direction, sphere, result); for (int i = 0; i < result.numIntersections; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } return result; } protected: void DoQuery(Vector3 const& rayOrigin, Vector3 const& rayDirection, Sphere3 const& sphere, Result& result) { FIQuery, Sphere3>::DoQuery(rayOrigin, rayDirection, sphere, result); if (result.intersect) { // The line containing the ray intersects the sphere; the // t-interval is [t0,t1]. The ray intersects the sphere as // long as [t0,t1] overlaps the ray t-interval [0,+infinity). std::array rayInterval = { (Real)0, std::numeric_limits::max() }; FIQuery, std::array> iiQuery; auto iiResult = iiQuery(result.parameter, rayInterval); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { result.intersect = false; result.numIntersections = 0; } } } }; }