diff options
author | Tom Barrett <tom@tombarrett.xyz> | 2022-12-20 23:10:51 +0100 |
---|---|---|
committer | Tom Barrett <tom@tombarrett.xyz> | 2022-12-20 23:10:51 +0100 |
commit | 545c41f79e37e9b7d4b5bf7ba64aa7efa549aded (patch) | |
tree | f22d738bfcb2f2f276cc84fabbb35133de43d215 /src/main.zig | |
parent | e25ffd24ee2e115d8453644d3670348c3678af67 (diff) |
6.2
Diffstat (limited to 'src/main.zig')
-rw-r--r-- | src/main.zig | 16 |
1 files changed, 10 insertions, 6 deletions
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; } } |