From 545c41f79e37e9b7d4b5bf7ba64aa7efa549aded Mon Sep 17 00:00:00 2001 From: Tom Barrett Date: Tue, 20 Dec 2022 23:10:51 +0100 Subject: 6.2 --- src/main.zig | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/main.zig b/src/main.zig index 40ac9c7..1a8e14c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5,8 +5,12 @@ pub fn unit_vector(v: vec) vec { return v / scalar(length(v)); } +pub fn length_squared(v: vec) f32 { + return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; +} + pub fn length(v: vec) f32 { - return @sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + return @sqrt(length_squared(v)); } pub fn ray_color(r: ray) vec { @@ -28,14 +32,14 @@ pub fn write_color(stdout: anytype, v: vec) !void { pub fn hit_sphere(center: vec, radius: f32, r: ray) ?f32 { const oc = r.origin - center; - const a = dot(r.direction, r.direction); - const b = 2 * dot(oc, r.direction); - const c = dot(oc, oc) - radius * radius; - const discriminant = b * b - 4 * a * c; + const a = length_squared(r.direction); + const half_b = dot(oc, r.direction); + const c = length_squared(oc) - radius * radius; + const discriminant = half_b * half_b - a * c; if (discriminant < 0) { return null; } else { - return (-b - @sqrt(discriminant)) / (2 * a); + return (-half_b - @sqrt(discriminant)) / a; } } -- cgit v1.2.3