summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig16
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;
}
}