summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig13
1 files changed, 9 insertions, 4 deletions
diff --git a/src/main.zig b/src/main.zig
index 7012bfb..c55bc06 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -6,8 +6,9 @@ pub fn unit_vector(v: vec) vec {
}
pub fn ray_color(r: ray) vec {
- if (hit_sphere(vec{ 0, 0, -1 }, 0.5, r)) {
- return vec{ 1.0, 0, 0 };
+ if (hit_sphere(vec{ 0, 0, -1 }, 0.5, r)) |t| {
+ const n = unit_vector(r.origin + scalar(t) * r.direction - vec{ 0, 0, -1 });
+ return scalar(0.5) * vec{ n[0] + 1, n[1] + 1, n[2] + 1 };
}
const direction = unit_vector(r.direction);
const t = 0.5 * (direction[1] + 1.0);
@@ -21,13 +22,17 @@ pub fn write_color(stdout: anytype, v: vec) !void {
try stdout.print("{} {} {}\n", .{ r, g, b });
}
-pub fn hit_sphere(center: vec, radius: f32, r: ray) bool {
+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;
- return discriminant > 0;
+ if (discriminant < 0) {
+ return null;
+ } else {
+ return (-b - @sqrt(discriminant)) / (2 * a);
+ }
}
const vec = @Vector(3, f32);