#include #include #include "rtweekend.hpp" #include "color.hpp" #include "hittable_list.hpp" #include "sphere.hpp" #include "camera.hpp" color ray_color(const ray& r, const hittable& world, int32_t depth); double hit_sphere(const point3& center, double radius, const ray& r); color ray_color(const ray& r, const hittable& world, int32_t depth) { if (depth <= 0) { return color(0,0,0); } hit_record rec; if (world.hit(r, 0.001, INFINITY, rec)) { point3 target = rec.p + rec.normal + random_in_unit_sphere(); return 0.5 * ray_color(ray(rec.p, target - rec.p), world, depth-1); } vec3 unit_direction = normalize(r.direction); double t = 0.5 * (unit_direction.y + 1.0); return (1-t) * color(1,1,1) + t*color(0.5,0.7,1.0); } double hit_sphere(const point3& center, double radius, const ray& r) { vec3 oc = r.origin - center; double a = r.direction.length_squared(); double half_b = dot(oc, r.direction); double c = oc.length_squared() - radius*radius; double discriminant = half_b*half_b - a*c; if (discriminant < 0) return -1; else return (-half_b - sqrt(discriminant)) / a; } int main() { // Image double aspect_ratio = 16.0 / 9; const int32_t image_width = 400; const int32_t image_height = (int32_t) (image_width / aspect_ratio); int32_t samples_per_pixel = 100; int32_t max_depth = 50; if (getenv("SPP")) { samples_per_pixel = strtol(getenv("SPP"), NULL, 10); } // World hittable_list world; world.add(std::make_shared(point3(0,0,-1), 0.5)); world.add(std::make_shared(point3(0,-100.5,-1), 100)); // Camera camera cam; // Render printf("P3\n%d %d\n255\n", image_width, image_height); for (int32_t j = image_height - 1; j >= 0; --j) { fprintf(stderr, "\rScanlines remaining: %d ", j); fflush(stderr); for (int32_t i = 0; i < image_width; ++i) { color pixel_color = color(0,0,0); for (int32_t s = 0; s < samples_per_pixel; ++s) { double u = ((i + random_double()) / (image_width-1)); double v = ((j + random_double()) / (image_height-1)); ray r = cam.get_ray(u,v); pixel_color += ray_color(r, world, max_depth); } write_color(stdout, pixel_color, samples_per_pixel); } } fprintf(stderr, "\nDone\n"); }