diff --git a/zigrtiow/src/main.zig b/zigrtiow/src/main.zig index abcae73..82d30fc 100644 --- a/zigrtiow/src/main.zig +++ b/zigrtiow/src/main.zig @@ -12,11 +12,11 @@ const Ray = ray.Ray; fn hit_sphere(center: Point3, radius: f32, r: Ray) f32 { const oc = r.origin().sub(center); - const a = Vec3.dot(r.direction(), r.direction()); - const b = Vec3.dot(oc, r.direction()) * 2; - const c = Vec3.dot(oc, oc) - radius * radius; - const discriminant = b * b - 4 * a * c; - return if (discriminant < 0) -1 else (-b - @sqrt(discriminant)) / (2 * a); + const a = r.direction().length_squared(); + const half_b = Vec3.dot(oc, r.direction()); + const c = oc.length_squared() - radius * radius; + const discriminant = half_b * half_b - a * c; + return if (discriminant < 0) -1 else (-half_b - @sqrt(discriminant)) / a; } fn ray_color(r: Ray) Color { diff --git a/zigrtiow/src/vec.zig b/zigrtiow/src/vec.zig index cb98032..0d785f8 100644 --- a/zigrtiow/src/vec.zig +++ b/zigrtiow/src/vec.zig @@ -17,7 +17,7 @@ pub const Vec3 = struct { pub fn length(vec: Vec3) f32 { 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]; } pub fn add(lhs: Vec3, rhs: Vec3) Vec3 {