summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/main.zig16
1 files changed, 16 insertions, 0 deletions
diff --git a/src/main.zig b/src/main.zig
index 7ae5c9e..7012bfb 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -6,6 +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 };
+ }
const direction = unit_vector(r.direction);
const t = 0.5 * (direction[1] + 1.0);
return scalar(1.0 - t) * vec{ 1.0, 1.0, 1.0 } + scalar(t) * vec{ 0.5, 0.7, 1.0 };
@@ -18,11 +21,24 @@ 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 {
+ 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;
+}
+
const vec = @Vector(3, f32);
pub fn scalar(x: f32) vec {
return @splat(3, x);
}
+pub fn dot(x: vec, y: vec) f32 {
+ return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
+}
+
const ray = struct { origin: vec, direction: vec };
pub fn main() !void {