From 7dfbf9f0a42e3784427ea87cb33b4e01f437fda8 Mon Sep 17 00:00:00 2001 From: Jonas Volman Date: Sun, 26 Jul 2026 01:44:57 -0700 Subject: [PATCH] Match fast sphere intersection distance --- source/math/real_math.c | 40 ++++++++++++++++++++++++++++++++++++++++ source/math/real_math.h | 5 +++++ 2 files changed, 45 insertions(+) diff --git a/source/math/real_math.c b/source/math/real_math.c index a5f5399b..9d85df48 100644 --- a/source/math/real_math.c +++ b/source/math/real_math.c @@ -444,6 +444,46 @@ boolean fast_vector_intersects_sphere( } } +real fast_vector_intersection_with_sphere( + real_point3d const *point, + real_vector3d const *vector, + real_point3d const *center, + real radius) +{ + real_point3d p = + { + point->x - center->x, + point->y - center->y, + point->z - center->z + }; + real c = p.x * p.x + p.y * p.y + p.z * p.z - radius * radius; + real_vector3d direction; + real b; + real a; + real discriminant; + + if (c < 0.0f) + return 0.0f; + + direction = *vector; + b = + direction.i * p.x + + direction.j * p.y + + direction.k * p.z; + if (b >= 0.0f) + return REAL_MAX; + + a = + direction.i * direction.i + + direction.j * direction.j + + direction.k * direction.k; + discriminant = b * b - a * c; + if (discriminant <= 0.0f) + return REAL_MAX; + + return (-b - square_root(discriminant)) / a; +} + boolean point_in_rectangle2d( real_point2d const *point, real_rectangle2d const *bounds) diff --git a/source/math/real_math.h b/source/math/real_math.h index 9b2fe450..144161e7 100644 --- a/source/math/real_math.h +++ b/source/math/real_math.h @@ -409,6 +409,11 @@ void quaternion_transform_point(real_quaternion const *q, real_point3d const *p, void vectors3d_from_euler_angles3d(real_vector3d *forward, real_vector3d *up, real_euler_angles3d const *angles); boolean fast_vector_intersects_sphere(real_point3d const *point, real_vector3d const *vector, real_point3d const *center, real radius); +real fast_vector_intersection_with_sphere( + real_point3d const *point, + real_vector3d const *vector, + real_point3d const *center, + real radius); boolean point_in_rectangle2d(real_point2d const *point, real_rectangle2d const *bounds); boolean point_in_rectangle3d(real_point3d const *point, real_rectangle3d const *bounds);