optimize hitSphere()

master
Fabien Freling 2021-04-24 17:59:17 +02:00
parent b6c85bcb91
commit 4c271103b3
2 changed files with 9 additions and 5 deletions

View File

@ -18,14 +18,14 @@ const fps = 60;
fn hitSphere(center: Point3, radius: f32, ray: Ray) f32 {
const ssr = ray.origin.sub(center); // Sphere-space ray, (A - C) in book
const a = Vec3.dot(ray.direction, ray.direction);
const b = 2.0 * Vec3.dot(ssr, ray.direction);
const c = Vec3.dot(ssr, ssr) - (radius * radius);
const discriminant = b * b - 4 * a * c;
const a = ray.direction.length_squared();
const half_b = Vec3.dot(ssr, ray.direction);
const c = ssr.length_squared() - (radius * radius);
const discriminant = half_b * half_b - a * c;
if (discriminant < 0) {
return -1;
} else {
return (-b - std.math.sqrt(discriminant)) / (2 * a);
return (-half_b - std.math.sqrt(discriminant)) / a;
}
}

View File

@ -41,6 +41,10 @@ pub const Vec3 = packed struct {
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
}
pub fn length_squared(self: Vec3) f32 {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
pub fn dot(u: Vec3, v: Vec3) f32 {
return u.x * v.x + u.y * v.y + u.z * v.z;
}