commit 1f5e37de40bc25385517b822bd3e8e72added319 Author: MrBounty Date: Wed Aug 21 13:40:52 2024 +0200 End of tuto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aaf4f8b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.zig-cache +zig-out +*.png +*.ppm diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..d3bcd37 --- /dev/null +++ b/build.zig @@ -0,0 +1,66 @@ +const std = @import("std"); + +// Although this function looks imperative, note that its job is to +// declaratively construct a build graph that will be executed by an external +// runner. +pub fn build(b: *std.Build) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard optimization options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not + // set a preferred release mode, allowing the user to decide how to optimize. + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "thermal", + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + // This declares intent for the executable to be installed into the + // standard location when the user invokes the "install" step (the default + // step when running `zig build`). + b.installArtifact(exe); + + // This *creates* a Run step in the build graph, to be executed when another + // step is evaluated that depends on it. The next line below will establish + // such a dependency. + const run_cmd = b.addRunArtifact(exe); + + // By making the run step depend on the install step, it will be run from the + // installation directory rather than directly from within the cache directory. + // This is not necessary, however, if the application depends on other installed + // files, this ensures they will be present and in the expected location. + run_cmd.step.dependOn(b.getInstallStep()); + + // This allows the user to pass arguments to the application in the build + // command itself, like this: `zig build run -- arg1 arg2 etc` + if (b.args) |args| { + run_cmd.addArgs(args); + } + + // This creates a build step. It will be visible in the `zig build --help` menu, + // and can be selected like this: `zig build run` + // This will evaluate the `run` step rather than the default, which is "install". + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); + + const exe_unit_tests = b.addTest(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); + + // Similar to creating the run step earlier, this exposes a `test` step to + // the `zig build --help` menu, providing a way for the user to request + // running the unit tests. + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&run_exe_unit_tests.step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..6cdeecb --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,72 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = "thermal", + + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // This field is optional. + // This is currently advisory only; Zig does not yet do anything + // with this value. + //.minimum_zig_version = "0.11.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + // See `zig fetch --save ` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from a `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiformats.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. Only files listed here will remain on disk + // when using the zig package manager. As a rule of thumb, one should list + // files required for compilation plus any license(s). + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/src/camera.zig b/src/camera.zig new file mode 100644 index 0000000..a49c9ab --- /dev/null +++ b/src/camera.zig @@ -0,0 +1,223 @@ +const std = @import("std"); +const print = std.debug.print; +const math = std.math; +const vec3 = @Vector(3, f64); +const Ray = @import("hittable.zig").Ray; + +const utils = @import("utils.zig"); +const toVec3 = utils.toVec3; +const Interval = utils.Interval; + +const hit = @import("hittable.zig"); +const HittableList = hit.HittableList; +const HitRecord = hit.HitRecord; + +const mat_math = @import("mat_math.zig"); +const unit_vector = mat_math.unit_vector; +const length = mat_math.length; +const cross = mat_math.cross; + +pub const Camera = struct { + aspect_ratio: f64, + image_width: i64, + samples_per_pixel: i64, + max_depth: i64, + vfov: f64, + defocus_angle: f64, + focus_dist: f64, + + image_height: i64, + center: vec3, + pixel_samples_scale: f64, + pixel00_loc: vec3, + pixel_delta_u: vec3, + pixel_delta_v: vec3, + defocus_disk_u: vec3, + defocus_disk_v: vec3, + + u: vec3, + v: vec3, + w: vec3, + + pub fn new() Camera { + const aspect_ratio: f64 = 16.0 / 9.0; + const image_width: i64 = 512; // Possible 128, 256, 512, 1024, 1280, 1920, 2560, 3840, 7680 + const samples_per_pixel = 50; + const max_depth = 10; + const vfov = 20; + const lookfrom = vec3{ 13, 2, 3 }; + const lookat = vec3{ 0, 0, 0 }; + const vup = vec3{ 0, 1, 0 }; + + const defocus_angle = 0.6; + const focus_dist = 10; + + const camera_center = lookfrom; + const image_height: i64 = image_width / aspect_ratio; + const pixel_samples_scale = 1.0 / @as(f64, @floatFromInt(samples_per_pixel)); + + // Camera + const theta = utils.degrees_to_radians(vfov); + const h = @tan(theta / 2); + + const viewport_height: f64 = 2.0 * h * focus_dist; + const viewport_width: f64 = viewport_height * aspect_ratio; + + const w = unit_vector(lookfrom - lookat); + const u = unit_vector(cross(vup, w)); + const v = cross(w, u); + + const viewport_u = toVec3(viewport_width) * u; + const viewport_v = toVec3(viewport_height) * -v; + + const pixel_delta_u = viewport_u / toVec3(image_width); + const pixel_delta_v = viewport_v / toVec3(image_height); + + const viewport_upper_left = camera_center - toVec3(focus_dist) * w - viewport_u / toVec3(2) - viewport_v / toVec3(2); + const pixel00_loc = viewport_upper_left + toVec3(0.5) * (pixel_delta_u + pixel_delta_v); + + const defocus_radius = focus_dist * @tan(utils.degrees_to_radians(defocus_angle / 2)); + const defocus_disk_u = u * toVec3(defocus_radius); + const defocus_disk_v = v * toVec3(defocus_radius); + + return Camera{ + .aspect_ratio = aspect_ratio, + .image_width = image_width, + .samples_per_pixel = samples_per_pixel, + .max_depth = max_depth, + .vfov = vfov, + .focus_dist = focus_dist, + .defocus_angle = defocus_angle, + + .u = u, + .v = v, + .w = w, + + .defocus_disk_v = defocus_disk_v, + .defocus_disk_u = defocus_disk_u, + .image_height = image_height, + .center = camera_center, + .pixel_samples_scale = pixel_samples_scale, + .pixel00_loc = pixel00_loc, + .pixel_delta_u = pixel_delta_u, + .pixel_delta_v = pixel_delta_v, + }; + } + + pub fn render(self: Camera, world: HittableList, writer: anytype) !void { + // Write the PPM header + try writer.print("P3\n{} {}\n255\n", .{ self.image_width, self.image_height }); + + // Write the pixel data + for (0..@as(usize, @intCast(self.image_height))) |i| { + const h = @as(i64, @intCast(i)); + pbar(h, self.image_height); + for (0..@as(usize, @intCast(self.image_width))) |j| { + const w = @as(i64, @intCast(j)); + + var pixel_color = vec3{ 0, 0, 0 }; + for (0..@as(usize, @intCast(self.samples_per_pixel))) |_| { + const r = self.get_ray(h, w); + pixel_color += ray_color(r, self.max_depth, world); + } + + try writeColor(pixel_color * toVec3(self.pixel_samples_scale), writer); + } + } + } + + fn get_ray(self: Camera, h: i64, w: i64) Ray { + // Construct a camera ray originating from the origin and directed at randomly sampled + // point around the pixel location i, j. + + const offset = sample_square(); + const pixel_sample = self.pixel00_loc + + (toVec3((@as(f64, @floatFromInt(h))) + offset[0]) * self.pixel_delta_v) + + (toVec3((@as(f64, @floatFromInt(w))) + offset[1]) * self.pixel_delta_u); + + const ray_origin = if (self.defocus_angle <= 0) self.center else self.defocus_disk_sample(); + const ray_direction = pixel_sample - ray_origin; + + return Ray{ .orig = ray_origin, .dir = ray_direction }; + } + + fn defocus_disk_sample(self: Camera) vec3 { + const p = random_in_unit_disk(); + return self.center + (toVec3(p[0]) * self.defocus_disk_u) + (toVec3(p[1]) * self.defocus_disk_v); + } +}; + +fn random_in_unit_disk() vec3 { + while (true) { + const p = vec3{ utils.rand_mm(-1, 1), utils.rand_mm(-1, 1), 0 }; + if (mat_math.length_squared(p) < 1) + return p; + } +} + +fn ray_color(ray: Ray, depth: i64, world: HittableList) vec3 { + if (depth <= 0) { + return vec3{ 0, 0, 0 }; + } + + var rec = HitRecord.new(); + if (world.hit(ray, Interval{ .min = 0.001, .max = math.inf(f64) }, &rec)) { + var ray_scattered = Ray{ .orig = vec3{ 0, 0, 0 }, .dir = vec3{ 0, 0, 0 } }; + var attenuation = vec3{ 0, 0, 0 }; + + if (rec.material.scatter(ray, &rec, &attenuation, &ray_scattered)) { + return attenuation * ray_color(ray_scattered, depth - 1, world); + } + + return vec3{ 0, 0, 0 }; + } + + const unit_direction = unit_vector(ray.dir); + const a = 0.5 * (unit_direction[1] + 1.0); + return toVec3(1.0 - a) * toVec3(1.0) + toVec3(a) * vec3{ 0.5, 0.7, 1.0 }; +} + +fn sample_square() vec3 { + return vec3{ utils.rand_01() - 0.5, utils.rand_01() - 0.5, 0 }; +} + +fn writeColor(color: vec3, writer: anytype) !void { + var r_float = color[0]; + var g_float = color[1]; + var b_float = color[2]; + + r_float = utils.linear_to_gamma(r_float); + g_float = utils.linear_to_gamma(g_float); + b_float = utils.linear_to_gamma(b_float); + + const intensity = Interval{ .min = 0, .max = 0.99 }; + + const r: u8 = @intFromFloat(256 * intensity.clamp(r_float)); + const g: u8 = @intFromFloat(256 * intensity.clamp(g_float)); + const b: u8 = @intFromFloat(256 * intensity.clamp(b_float)); + try writer.print("{} {} {}\n", .{ r, g, b }); +} + +fn pbar(value: i64, max: i64) void { + const used_char = "-"; + const number_of_char = 60; + const percent_done: i64 = if (value == max - 1) 100 else @divFloor(value * 100, max); + const full_char: i64 = @divFloor(number_of_char * percent_done, 100); + + print("\r|", .{}); + + var i: usize = 0; + while (i < number_of_char) : (i += 1) { + if (i < full_char) { + print("{s}", .{used_char}); + } else { + print(" ", .{}); + } + } + + print("| {}%", .{percent_done}); + + if (percent_done == 100) { + print("\n", .{}); + } +} diff --git a/src/hittable.zig b/src/hittable.zig new file mode 100644 index 0000000..4dbe761 --- /dev/null +++ b/src/hittable.zig @@ -0,0 +1,107 @@ +const std = @import("std"); +const vec3 = @Vector(3, f64); + +const utils = @import("utils.zig"); +const Interval = utils.Interval; +const toVec3 = utils.toVec3; + +const mat_math = @import("mat_math.zig"); +const dot = mat_math.dot; +const set_face_normal = mat_math.set_face_normal; + +const material_import = @import("material.zig"); +const Material = material_import.Material; +const Metal = material_import.Metal; + +pub const Ray = struct { + orig: vec3, + dir: vec3, +}; + +pub const Hittable = union(enum) { + sphere: Sphere, + //cube: Cube, + + pub fn hit(self: *const Hittable, ray: Ray, interval: Interval, rec: *HitRecord) bool { + return switch (self.*) { + .sphere => |*s| s.hit(ray, interval, rec), + //.cube => |*c| c.hit(), + }; + } +}; + +pub const HittableList = struct { + list: []const Hittable, + + pub fn hit(self: *const HittableList, ray: Ray, ray_t: Interval, rec: *HitRecord) bool { + var temp_rec: HitRecord = HitRecord.new(); + var hit_anything = false; + var closest_so_far = ray_t.max; + + for (self.list) |obj| { + if (obj.hit(ray, Interval{ .min = ray_t.min, .max = closest_so_far }, &temp_rec)) { + hit_anything = true; + closest_so_far = temp_rec.t; + rec.* = temp_rec; + } + } + + return hit_anything; + } +}; + +pub const HitRecord = struct { + p: vec3, + normal: vec3, + material: Material, + t: f64, + front_face: bool, + + pub fn new() HitRecord { + return HitRecord{ + .p = vec3{ 0, 0, 0 }, + .normal = vec3{ 0, 0, 0 }, + .material = Material{ .metal = Metal{ .albedo = vec3{ 0, 0, 0 }, .fuzz = 1.0 } }, + .t = 0, + .front_face = false, + }; + } +}; + +pub const Sphere = struct { + center: vec3, + radius: f64, + material: Material, + + pub fn hit(self: Sphere, ray: Ray, ray_t: Interval, rec: *HitRecord) bool { + const oc = self.center - ray.orig; + const a = dot(ray.dir, ray.dir); + const h = dot(ray.dir, oc); + const c = dot(oc, oc) - self.radius * self.radius; + const discriminant = h * h - a * c; + if (discriminant < 0) { + return false; + } + + const sqrtd = @sqrt(discriminant); + + // Find the nearest root that lies in the acceptable range. + const root = (h - sqrtd) / a; + if (!ray_t.surrounds(root)) { + return false; + } + + rec.t = root; + rec.p = at(ray, rec.t); + rec.normal = (rec.p - self.center) / toVec3(self.radius); + const outward_normal = (rec.p - self.center) / toVec3(self.radius); + set_face_normal(rec, ray, outward_normal); + rec.material = self.material; + + return true; + } +}; + +fn at(ray: Ray, t: f64) vec3 { + return ray.orig + toVec3(t) * ray.dir; +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..d47db3b --- /dev/null +++ b/src/main.zig @@ -0,0 +1,176 @@ +const std = @import("std"); +const print = std.debug.print; +const math = std.math; +const vec3 = @Vector(3, f64); + +const utils = @import("utils.zig"); +const Interval = utils.Interval; +const toVec3 = utils.toVec3; + +const hit = @import("hittable.zig"); +const Sphere = hit.Sphere; +const Hittable = hit.Hittable; +const HittableList = hit.HittableList; +const HitRecord = hit.HitRecord; +const Ray = hit.Ray; + +const mat_math = @import("mat_math.zig"); +const unit_vector = mat_math.unit_vector; +const length = mat_math.length; + +const cam = @import("camera.zig"); +const Camera = cam.Camera; + +const mat_import = @import("material.zig"); +const Material = mat_import.Material; +const Lambertian = mat_import.Lambertian; +const Metal = mat_import.Metal; +const Dielectric = mat_import.Dielectric; + +pub fn main() !void { + const file = try std.fs.cwd().createFile("image.ppm", .{}); + defer file.close(); + var buffered_writer = std.io.bufferedWriter(file.writer()); + const writer = buffered_writer.writer(); + const camera = Camera.new(); + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const alloc = arena.allocator(); + + const world = try generateRandomScene(alloc); + + const start_time: i64 = std.time.milliTimestamp(); + try camera.render(world, &writer); + const end_time: i64 = std.time.milliTimestamp(); + const total_time: f64 = @as(f64, @floatFromInt(end_time - start_time)) / 1000; + + print("Rendering took {} s\n", .{total_time}); + print("Potential FPS: {}\n", .{1 / total_time}); + + // Flush the buffered writer to ensure all data is written to the file + try buffered_writer.flush(); + + try run_convert_image(); + try run_open_image(); +} + +pub fn run_convert_image() !void { + const exec_result = try std.process.Child.run(.{ + .allocator = std.heap.page_allocator, + .argv = &[_][]const u8{ + "convert", + "image.ppm", + "image.png", + }, + }); + + switch (exec_result.term) { + .Exited => |code| { + if (code != 0) { + std.debug.print("Convert image: Command exited with non-zero status code: {}\n", .{code}); + } + }, + else => { + std.debug.print("Convert image: Command did not exit normally\n", .{}); + }, + } +} + +pub fn run_open_image() !void { + const exec_result = try std.process.Child.run(.{ + .allocator = std.heap.page_allocator, + .argv = &[_][]const u8{ + "explorer.exe", + "image.png", + }, + }); + + switch (exec_result.term) { + .Exited => |code| { + if (code != 0) { + std.debug.print("Open image: Command exited with non-zero status code: {}\n", .{code}); + } + }, + else => { + std.debug.print("Open image: Command did not exit normally\n", .{}); + }, + } +} + +pub fn generateRandomScene(alloc: std.mem.Allocator) !HittableList { + var spheres = std.ArrayList(Hittable).init(alloc); + + // Ground sphere + try spheres.append(.{ + .sphere = Sphere{ + .center = vec3{ 0, -1000, 0 }, + .radius = 1000, + .material = Material{ .lambertian = Lambertian{ .albedo = vec3{ 0.5, 0.5, 0.5 } } }, + }, + }); + + // Smaller spheres + var a: i32 = -11; + while (a < 11) : (a += 1) { + var b: i32 = -11; + while (b < 11) : (b += 1) { + const choose_mat = utils.rand_01(); + const center = vec3{ + @as(f64, @floatFromInt(a)) + 0.9 * utils.rand_01(), + 0.2, + @as(f64, @floatFromInt(b)) + 0.9 * utils.rand_01(), + }; + + var sphere_material: Material = undefined; + + if (choose_mat < 0.5) { + // diffuse + const albedo = utils.rand_vec3_01(); + sphere_material = Material{ .lambertian = Lambertian{ .albedo = albedo } }; + } else if (choose_mat < 0.8) { + // metal + const albedo = utils.rand_vec3_01(); + const fuzz = utils.rand_01() * 0.5; + sphere_material = Material{ .metal = Metal{ .albedo = albedo, .fuzz = fuzz } }; + } else { + // glass + sphere_material = Material{ .dielectric = Dielectric{ .refraction_index = 1.5 } }; + } + + try spheres.append(.{ + .sphere = Sphere{ + .center = center, + .radius = 0.2, + .material = sphere_material, + }, + }); + } + } + + // Three large spheres + try spheres.append(.{ + .sphere = Sphere{ + .center = vec3{ 0, 1, 0 }, + .radius = 1.0, + .material = Material{ .dielectric = Dielectric{ .refraction_index = 1.5 } }, + }, + }); + try spheres.append(.{ + .sphere = Sphere{ + .center = vec3{ -4, 1, 0 }, + .radius = 1.0, + .material = Material{ .lambertian = Lambertian{ .albedo = vec3{ 0.4, 0.2, 0.1 } } }, + }, + }); + try spheres.append(.{ + .sphere = Sphere{ + .center = vec3{ 4, 1, 0 }, + .radius = 1.0, + .material = Material{ .metal = Metal{ .albedo = vec3{ 0.7, 0.6, 0.5 }, .fuzz = 0.0 } }, + }, + }); + + // Convert ArrayList to a slice and create HittableList + return HittableList{ .list = spheres.items }; +} diff --git a/src/mat_math.zig b/src/mat_math.zig new file mode 100644 index 0000000..ba47f2b --- /dev/null +++ b/src/mat_math.zig @@ -0,0 +1,66 @@ +const vec3 = @Vector(3, f64); +const std = @import("std"); +const math = std.math; + +const utils = @import("utils.zig"); +const toVec3 = utils.toVec3; + +const hit = @import("hittable.zig"); +const HitRecord = hit.HitRecord; +const Ray = hit.Ray; + +pub fn dot(u: vec3, v: vec3) f64 { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; +} + +pub fn length(v: vec3) f64 { + return math.sqrt(math.pow(f64, v[0], 2) + math.pow(f64, v[1], 2) + math.pow(f64, v[2], 2)); +} + +pub fn length_squared(v: vec3) f64 { + return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; +} + +pub fn unit_vector(v: vec3) vec3 { + return v / toVec3(length(v)); +} + +pub fn random_in_unit_sphere() vec3 { + while (true) { + const p = utils.rand_vec3_mm(-1, 1); + if (length_squared(p) < 1.0) { + return p; + } + } +} + +pub fn random_on_hemisphere(normal: vec3) vec3 { + const on_unit_sphere = random_unit_vector(); + if (dot(on_unit_sphere, normal) > 0.0) { + return on_unit_sphere; + } else { + return -on_unit_sphere; + } +} + +pub fn random_unit_vector() vec3 { + return unit_vector(random_in_unit_sphere()); +} + +pub fn set_face_normal(rec: *HitRecord, ray: Ray, outward_normal: vec3) void { + rec.front_face = dot(ray.dir, outward_normal) < 0; + rec.normal = if (rec.front_face) outward_normal else -outward_normal; +} + +pub fn near_zero(v: vec3) bool { + const s = 1e-8; + return ((@abs(v[0]) < s) and (@abs(v[1]) < s) and (@abs(v[2]) < s)); +} + +pub fn cross(u: vec3, v: vec3) vec3 { + return vec3{ + u[1] * v[2] - u[2] * v[1], + u[2] * v[0] - u[0] * v[2], + u[0] * v[1] - u[1] * v[0], + }; +} diff --git a/src/material.zig b/src/material.zig new file mode 100644 index 0000000..5b679f4 --- /dev/null +++ b/src/material.zig @@ -0,0 +1,111 @@ +const vec3 = @Vector(3, f64); + +const utils = @import("utils.zig"); +const Interval = utils.Interval; +const toVec3 = utils.toVec3; + +const hit = @import("hittable.zig"); +const Sphere = hit.Sphere; +const Hittable = hit.Hittable; +const HittableList = hit.HittableList; +const HitRecord = hit.HitRecord; +const Ray = hit.Ray; + +const mat_math = @import("mat_math.zig"); +const near_zero = mat_math.near_zero; +const unit_vector = mat_math.unit_vector; +const random_unit_vector = mat_math.random_unit_vector; +const dot = mat_math.dot; +const length_squared = mat_math.length_squared; +const math = @import("std").math; + +// Mother struct + +pub const Material = union(enum) { + lambertian: Lambertian, + metal: Metal, + dielectric: Dielectric, + + pub fn scatter(self: *const Material, ray_in: Ray, rec: *HitRecord, attenuation: *vec3, ray_scattered: *Ray) bool { + return switch (self.*) { + .lambertian => |s| s.scatter(rec, attenuation, ray_scattered), + .metal => |s| s.scatter(ray_in, rec, attenuation, ray_scattered), + .dielectric => |s| s.scatter(ray_in, rec, attenuation, ray_scattered), + }; + } +}; + +// Materiaux + +pub const Lambertian = struct { + albedo: vec3, + + pub fn scatter(self: *const Lambertian, rec: *HitRecord, attenuation: *vec3, ray_scattered: *Ray) bool { + var scatter_direction = rec.*.normal + random_unit_vector(); + + if (near_zero(scatter_direction)) { + scatter_direction = rec.*.normal; + } + + ray_scattered.* = Ray{ .orig = rec.*.p, .dir = scatter_direction }; + attenuation.* = self.albedo; + + return true; + } +}; + +pub const Metal = struct { + albedo: vec3, + fuzz: f64, + + pub fn scatter(self: *const Metal, r_in: Ray, rec: *HitRecord, attenuation: *vec3, ray_scattered: *Ray) bool { + var reflected = reflect(r_in.dir, rec.*.normal); + reflected = unit_vector(reflected) + (toVec3(self.fuzz) * random_unit_vector()); + ray_scattered.* = Ray{ .orig = rec.p, .dir = reflected }; + attenuation.* = self.albedo; + return (dot(ray_scattered.dir, rec.normal) > 0); + } +}; + +pub const Dielectric = struct { + refraction_index: f64, + + pub fn scatter(self: *const Dielectric, r_in: Ray, rec: *HitRecord, attenuation: *vec3, ray_scattered: *Ray) bool { + attenuation.* = vec3{ 1, 1, 1 }; + const ri = if (rec.front_face) (1.0 / self.refraction_index) else self.refraction_index; + + const unit_direction = unit_vector(r_in.dir); + const cos_theta = @min(dot(-unit_direction, rec.normal), 1.0); + const sin_theta = @sqrt(1.0 - cos_theta * cos_theta); + + const cannot_refract = ri * sin_theta > 1.0; + var direction = vec3{ 0, 0, 0 }; + if ((cannot_refract) and (reflectance(cos_theta, ri) > utils.rand_01())) { + direction = reflect(unit_direction, rec.normal); + } else { + direction = refract(unit_direction, rec.normal, ri); + } + + ray_scattered.* = Ray{ .orig = rec.p, .dir = direction }; + return true; + } +}; + +// Physics + +fn reflect(v: vec3, n: vec3) vec3 { + return v - toVec3(2 * dot(v, n)) * n; +} + +fn refract(uv: vec3, n: vec3, etai_over_etat: f64) vec3 { + const cos_theta = @min(dot(-uv, n), 1.0); + const r_out_perp = toVec3(etai_over_etat) * (uv + toVec3(cos_theta) * n); + const r_out_parallel = toVec3(-@sqrt(@abs(1.0 - length_squared(r_out_perp)))) * n; + return r_out_perp + r_out_parallel; +} + +fn reflectance(cosine: f64, refraction_index: f64) f64 { + var r0 = (1 - refraction_index) / (1 + refraction_index); + r0 = r0 * r0; + return r0 + (1 - r0) * math.pow(f64, (1 - cosine), 5); +} diff --git a/src/utils.zig b/src/utils.zig new file mode 100644 index 0000000..6ba54bf --- /dev/null +++ b/src/utils.zig @@ -0,0 +1,103 @@ +const std = @import("std"); +const math = std.math; +const vec3 = @Vector(3, f64); + +pub const Interval = struct { + min: f64, + max: f64, + + pub fn inf() Interval { + return Interval{ + .min = -math.inf(f64), + .max = math.inf(f64), + }; + } + + pub fn new(min: f64, max: f64) Interval { + return Interval{ + .min = min, + .max = max, + }; + } + + pub fn size(self: Interval) f64 { + return self.max - self.min; + } + + pub fn contains(self: Interval, x: f64) bool { + return ((self.min <= x) and (x <= self.max)); + } + + pub fn surrounds(self: Interval, x: f64) bool { + return ((self.min < x) and (x < self.max)); + } + + pub fn clamp(self: Interval, x: f64) f64 { + if (x < self.min) { + return self.min; + } + if (x > self.max) { + return self.max; + } + return x; + } +}; + +pub fn toVec3(x: anytype) vec3 { + switch (@TypeOf(x)) { + comptime_float => { + const x_float = @as(f64, x); + return vec3{ x_float, x_float, x_float }; + }, + i64 => { + const x_float = @as(f64, @floatFromInt(x)); + return vec3{ x_float, x_float, x_float }; + }, + comptime_int => { + const x_float = @as(f64, @floatFromInt(x)); + return vec3{ x_float, x_float, x_float }; + }, + f64 => { + return vec3{ x, x, x }; + }, + @Vector(3, f64) => { + return x; + }, + usize => { + const x_float = @as(f64, @floatFromInt(@as(i64, @intCast(x)))); + return vec3{ x_float, x_float, x_float }; + }, + else => { + @panic("Unknow type passed through toVec3\n\n"); + }, + } +} + +var rnd = std.rand.DefaultPrng.init(0); + +pub fn rand_01() f64 { + return rnd.random().float(f64); +} + +pub fn rand_mm(min: f64, max: f64) f64 { + return rnd.random().float(f64) * (max - min) + min; +} + +pub fn rand_vec3_01() vec3 { + return vec3{ rand_01(), rand_01(), rand_01() }; +} + +pub fn rand_vec3_mm(min: f64, max: f64) vec3 { + return vec3{ rand_mm(min, max), rand_mm(min, max), rand_mm(min, max) }; +} + +pub fn linear_to_gamma(linear_component: f64) f64 { + if (linear_component > 0) { + return @sqrt(linear_component); + } + return 0; +} + +pub fn degrees_to_radians(degrees: f64) f64 { + return degrees * math.pi / 180; +}