add hittable spheres

This commit is contained in:
Fabien Freling 2021-04-24 19:24:28 +02:00
parent 4c271103b3
commit 79772c0df4
4 changed files with 101 additions and 7 deletions

View file

@ -6,6 +6,8 @@ const Vec3 = vec3.Vec3;
const Color = vec3.Color;
const Point3 = vec3.Point3;
const Ray = @import("ray.zig").Ray;
const Sphere = @import("sphere.zig").Sphere;
const World = @import("world.zig").World;
// From: https://github.com/Nelarius/weekend-raytracer-zig/blob/master/src/main.zig
// See https://github.com/zig-lang/zig/issues/565
@ -29,14 +31,12 @@ fn hitSphere(center: Point3, radius: f32, ray: Ray) f32 {
}
}
fn rayColor(ray: Ray) Color {
var t = hitSphere(Point3{ .x = 0, .y = 0, .z = -1 }, 0.5, ray);
if (t > 0) {
const normal = vec3.unitVector(ray.at(t).sub(Vec3{ .z = -1 }));
return normal.add(Vec3{ .x = 1, .y = 1, .z = 1}).div(2);
fn rayColor(ray: Ray, world: World) Color {
if (world.hit(ray, 0, 99999)) |hit| {
return hit.normal.add(Vec3{ .x = 1, .y = 1, .z = 1}).div(2);
}
const unitDirection = vec3.unitVector(ray.direction);
t = 0.5 * (unitDirection.y + 1.0);
const t = 0.5 * (unitDirection.y + 1.0);
const white = Color{ .x = 1.0, .y = 1.0, .z = 1.0 };
const blue = Color{ .x = 0.5, .y = 0.7, .z = 1.0 };
return white.mul(1.0 - t).add(blue.mul(t));
@ -54,6 +54,13 @@ pub fn main() anyerror!void {
const imageWidth = 600;
const imageHeight = @floatToInt(usize, imageWidth / aspectRatio);
// World
const spheres = [_]Sphere{
Sphere{ .center = Point3{ .x = 0, .y = 0, .z = -1 }, .radius = 0.5 },
Sphere{ .center = Point3{ .x = 0, .y = -100.5, .z = -1 }, .radius = 100 },
};
const world = World{ .spheres = spheres[0..spheres.len] };
// Camera
const viewportHeight = 2.0;
const viewportWidth = viewportHeight * aspectRatio;
@ -95,7 +102,7 @@ pub fn main() anyerror!void {
.origin = origin,
.direction = lowerLeftCorner.add(horizontal.mul(u)).add(vertical.mul(v)).sub(origin),
};
const pixelColor = rayColor(r);
const pixelColor = rayColor(r, world);
sdl.setSurfacePixel(surface, i, j, pixelColor);
i += 1;
}