Use normals to color sphere.

This commit is contained in:
Bill Thiede 2022-07-31 16:52:48 -07:00
parent f2c68e0b6f
commit 622c23d5ed

View File

@ -10,21 +10,27 @@ const info = std.log.info;
const write_color = color.write_color; const write_color = color.write_color;
const Ray = ray.Ray; const Ray = ray.Ray;
fn hit_sphere(center: Point3, radius: f32, r: Ray) bool { fn hit_sphere(center: Point3, radius: f32, r: Ray) f32 {
const oc = r.origin().sub(center); const oc = r.origin().sub(center);
const a = Vec3.dot(r.direction(), r.direction()); const a = Vec3.dot(r.direction(), r.direction());
const b = Vec3.dot(oc, r.direction()) * 2; const b = Vec3.dot(oc, r.direction()) * 2;
const c = Vec3.dot(oc, oc) - radius * radius; const c = Vec3.dot(oc, oc) - radius * radius;
const discriminant = b * b - 4 * a * c; const discriminant = b * b - 4 * a * c;
return discriminant > 0; return if (discriminant < 0) -1 else (-b - @sqrt(discriminant)) / (2 * a);
} }
fn ray_color(r: Ray) Color { fn ray_color(r: Ray) Color {
if (hit_sphere(Point3.init(0, 0, -1), 0.5, r)) { var t = hit_sphere(Point3.init(0, 0, -1), 0.5, r);
return Color.init(1, 0, 0); if (t > 0) {
const n = r.at(t).sub(Vec3.init(0, 0, -1)).unit();
return Color.init(
n.x() + 1,
n.y() + 1,
n.z() + 1,
).scale(0.5);
} }
var unit_direction = r.direction().unit(); var unit_direction = r.direction().unit();
var t = 0.5 * (unit_direction.y() + 1); t = 0.5 * (unit_direction.y() + 1);
return Color.init(1, 1, 1).scale(1 - t).add(Color.init(0.5, 0.7, 1.0).scale(t)); return Color.init(1, 1, 1).scale(1 - t).add(Color.init(0.5, 0.7, 1.0).scale(t));
} }