1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
const std = @import("std");
const warn = @import("std").debug.print;
const vec = @import("vec.zig");
pub fn writeColor(stdout: anytype, v: vec.Vec) !void {
const r = @floatToInt(usize, v[0] * 255.999);
const g = @floatToInt(usize, v[1] * 255.999);
const b = @floatToInt(usize, v[2] * 255.999);
try stdout.print("{} {} {}\n", .{ r, g, b });
}
pub fn hitSphere(center: vec.Vec, radius: f32, r: Ray) ?f32 {
const oc = r.origin - center;
const a = vec.lengthSquared(r.direction);
const half_b = vec.dot(oc, r.direction);
const c = vec.lengthSquared(oc) - radius * radius;
const discriminant = half_b * half_b - a * c;
if (discriminant < 0) {
return null;
} else {
return (-half_b - @sqrt(discriminant)) / a;
}
}
const Ray = struct {
origin: vec.Vec,
direction: vec.Vec,
pub fn color(self: Ray) vec.Vec {
if (hitSphere(vec.init(0, 0, -1), 0.5, self)) |t| {
const n = vec.unitVec(self.origin + vec.scalar(t) * self.direction - vec.init(0, 0, -1));
return vec.scalar(0.5) * vec.init(n[0] + 1, n[1] + 1, n[2] + 1);
}
const direction = vec.unitVec(self.direction);
const t = 0.5 * (direction[1] + 1.0);
return vec.scalar(1.0 - t) * vec.init(1.0, 1.0, 1.0) + vec.scalar(t) * vec.init(0.5, 0.7, 1.0);
}
};
pub fn main() !void {
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.init(0, 0, 0);
const horizontal = vec.init(viewport_width, 0, 0);
const vertical = vec.init(0, viewport_height, 0);
const lower_left_corner = origin - (horizontal / vec.scalar(2.0)) - (vertical / vec.scalar(2.0)) - vec.init(0, 0, focal_length);
try stdout.print("P3\n{} {}\n255\n", .{ width, height });
var j: usize = height;
while (j > 0) : (j -= 1) {
warn("remaining: {}\n", .{j});
var i: usize = 0;
while (i < width) : (i += 1) {
var u = vec.scalar(@intToFloat(f32, i) / @intToFloat(f32, width - 1));
var v = vec.scalar(@intToFloat(f32, j) / @intToFloat(f32, height - 1));
var r = Ray{ .origin = origin, .direction = lower_left_corner + u * horizontal + v * vertical - origin };
try writeColor(stdout, r.color());
}
}
try bw.flush();
}
|