diff options
author | Tom Barrett <tom@tombarrett.xyz> | 2022-12-19 15:44:49 +0100 |
---|---|---|
committer | Tom Barrett <tom@tombarrett.xyz> | 2022-12-19 15:44:49 +0100 |
commit | 875a863a41f7ad46d4cfb63f421907e16e90c228 (patch) | |
tree | ec0fa9d18c900f080236e4051eec6131459e9faa /src/main.zig | |
parent | 91f12439280eee0fb6e3c8f922882a598f6844ab (diff) |
4.2
Diffstat (limited to 'src/main.zig')
-rw-r--r-- | src/main.zig | 36 |
1 files changed, 29 insertions, 7 deletions
diff --git a/src/main.zig b/src/main.zig index 2d42772..7ae5c9e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,6 +1,16 @@ const std = @import("std"); const warn = @import("std").debug.print; +pub fn unit_vector(v: vec) vec { + return v / scalar(3); +} + +pub fn ray_color(r: ray) vec { + 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 }; +} + pub fn write_color(stdout: anytype, v: vec) !void { const r = @floatToInt(usize, v[0] * 255.999); const g = @floatToInt(usize, v[1] * 255.999); @@ -9,14 +19,28 @@ pub fn write_color(stdout: anytype, v: vec) !void { } const vec = @Vector(3, f32); +pub fn scalar(x: f32) vec { + return @splat(3, x); +} + +const ray = struct { origin: vec, direction: vec }; pub fn main() !void { - const width = 512; - const height = 512; + const aspect_ratio: f32 = 16.0 / 9.0; + const width: usize = 1000; + const height: usize = @floatToInt(usize, @intToFloat(f32, width) / aspect_ratio); const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); + const viewport_height = 2.0; + const viewport_width = aspect_ratio * viewport_height; + const focal_length = 1.0; + const origin = vec{ 0, 0, 0 }; + const horizontal = vec{ viewport_width, 0, 0 }; + const vertical = vec{ 0, viewport_height, 0 }; + const lower_left_corner = origin - (horizontal / scalar(2.0)) - (vertical / scalar(2.0)) - vec{ 0, 0, focal_length }; + try stdout.print("P3\n{} {}\n255\n", .{ width, height }); var j: usize = height; @@ -24,11 +48,9 @@ pub fn main() !void { warn("remaining: {}\n", .{j}); var i: usize = 0; while (i < width) : (i += 1) { - var color = vec{ - @intToFloat(f32, i) / (width - 1), - @intToFloat(f32, j) / (height - 1), - 0.25, - }; + var u = scalar(@intToFloat(f32, i) / @intToFloat(f32, width - 1)); + var v = scalar(@intToFloat(f32, j) / @intToFloat(f32, height - 1)); + var color = ray_color(ray{ .origin = origin, .direction = lower_left_corner + u * horizontal + v * vertical - origin }); try write_color(stdout, color); } |