55 lines
1.4 KiB
Zig
55 lines
1.4 KiB
Zig
const std = @import("std");
|
|
const Random = std.rand.Random;
|
|
|
|
const vec3 = @import("vec3.zig");
|
|
const Color = @import("color.zig").Color;
|
|
const Ray = @import("ray.zig").Ray;
|
|
const HitRecord = @import("hittable.zig").HitRecord;
|
|
|
|
pub const MaterialType = enum {
|
|
Lambertian,
|
|
Metal,
|
|
};
|
|
|
|
pub const Material = struct {
|
|
materialType: MaterialType,
|
|
color: Color,
|
|
};
|
|
|
|
pub const ScatteredRay = struct {
|
|
ray: Ray,
|
|
color: Color,
|
|
};
|
|
|
|
pub fn scatter(ray: Ray, hit: HitRecord, rng: *Random) ?ScatteredRay {
|
|
const scatteredDirection = switch (hit.material.materialType) {
|
|
|
|
.Lambertian => blk: {
|
|
var scatterDirection = hit.normal.add(vec3.random_unit_vector(rng));
|
|
// Catch degenerate scatter direction
|
|
if (scatterDirection.nearZero()) {
|
|
scatterDirection = hit.normal;
|
|
}
|
|
break :blk scatterDirection;
|
|
},
|
|
|
|
.Metal => blk: {
|
|
const reflected = ray.direction.unit().reflect(hit.normal);
|
|
const scattered = Ray{ .origin = hit.p, .direction = reflected };
|
|
if (scattered.direction.dot(hit.normal) <= 0) {
|
|
break :blk null;
|
|
}
|
|
break :blk scattered.direction;
|
|
},
|
|
|
|
};
|
|
|
|
if (scatteredDirection) |dir| {
|
|
return ScatteredRay{
|
|
.ray = Ray{ .origin = hit.p, .direction = dir},
|
|
.color = hit.material.color,
|
|
};
|
|
}
|
|
|
|
return null;
|
|
} |