Simplified hit_sphere.

This commit is contained in:
Bill Thiede 2022-07-31 16:57:18 -07:00
parent 622c23d5ed
commit 5043a7e526
2 changed files with 6 additions and 6 deletions

View File

@ -12,11 +12,11 @@ const Ray = ray.Ray;
fn hit_sphere(center: Point3, radius: f32, r: Ray) f32 { fn hit_sphere(center: Point3, radius: f32, r: Ray) f32 {
const oc = r.origin().sub(center); const oc = r.origin().sub(center);
const a = Vec3.dot(r.direction(), r.direction()); const a = r.direction().length_squared();
const b = Vec3.dot(oc, r.direction()) * 2; const half_b = Vec3.dot(oc, r.direction());
const c = Vec3.dot(oc, oc) - radius * radius; const c = oc.length_squared() - radius * radius;
const discriminant = b * b - 4 * a * c; const discriminant = half_b * half_b - a * c;
return if (discriminant < 0) -1 else (-b - @sqrt(discriminant)) / (2 * a); return if (discriminant < 0) -1 else (-half_b - @sqrt(discriminant)) / a;
} }
fn ray_color(r: Ray) Color { fn ray_color(r: Ray) Color {

View File

@ -17,7 +17,7 @@ pub const Vec3 = struct {
pub fn length(vec: Vec3) f32 { pub fn length(vec: Vec3) f32 {
return @sqrt(vec.length_squared()); return @sqrt(vec.length_squared());
} }
fn length_squared(vec: Vec3) f32 { pub fn length_squared(vec: Vec3) f32 {
return vec.v[0] * vec.v[0] + vec.v[1] * vec.v[1] + vec.v[2] * vec.v[2]; return vec.v[0] * vec.v[0] + vec.v[1] * vec.v[1] + vec.v[2] * vec.v[2];
} }
pub fn add(lhs: Vec3, rhs: Vec3) Vec3 { pub fn add(lhs: Vec3, rhs: Vec3) Vec3 {