summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
authorTom Barrett <tom@tombarrett.xyz>2022-12-19 17:34:33 +0100
committerTom Barrett <tom@tombarrett.xyz>2022-12-19 17:34:33 +0100
commit60592281229a8c6ff4f440e2b16ed4ff7bb1af20 (patch)
treea16260702928925d0a08a8a2f4fe9aa90acf5abe /src/main.zig
parent1dd46df3cec9814534f13d3808014b5ae698df4f (diff)
6.1
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);