Small optimization on sphere

This commit is contained in:
David 2021-08-20 23:43:44 +02:00
commit 3aea707982
2 changed files with 13 additions and 6 deletions

View file

@ -25,14 +25,15 @@ color ray_color(const ray& r)
double hit_sphere(const point3& center, double radius, const ray& r)
{
vec3 oc = r.origin - center;
double a = dot(r.direction, r.direction);
double b = 2.0 * dot(oc, r.direction);
double c = dot(oc,oc) - radius*radius;
double discriminant = b*b - 4*a*c;
double a = r.direction.length_squared();
double half_b = dot(oc, r.direction);
double c = oc.length_squared() - radius*radius;
double discriminant = half_b*half_b - a*c;
if (discriminant < 0)
return -1;
else
return (-b - sqrt(discriminant)) / (2.0*a);
return (-half_b - sqrt(discriminant)) / a;
}
int main()

View file

@ -59,6 +59,12 @@ struct vec3 {
{
return sqrt(x*x + y*y + z*z);
}
// Length squared, useful for some calculations
double length_squared() const
{
return x*x + y*y + z*z;
}
};
/* Type aliases */