#include #include #include "rtweekend.hpp" #include "color.hpp" #include "hittable_list.hpp" #include "sphere.hpp" color ray_color(const ray& r, const hittable& world); double hit_sphere(const point3& center, double radius, const ray& r); color ray_color(const ray& r, const hittable& world) { hit_record rec; if (world.hit(r, 0, INFINITY, rec)) { return 0.5 * (rec.normal + color(1,1,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); // 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 double viewport_height = 2.0; double viewport_width = aspect_ratio * viewport_height; double focal_length = 1.0; point3 origin = point3(0,0,0); vec3 horizontal = vec3(viewport_width, 0, 0); vec3 vertical = vec3(0, viewport_height, 0); vec3 lower_left_corner = origin - horizontal/2 - vertical/2 - vec3(0, 0, focal_length); // 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) { double u = (double)i / (image_width-1); double v = (double)j / (image_height-1); ray r = ray(origin, lower_left_corner + u*horizontal + v*vertical - origin); color pixel_color = ray_color(r, world); write_color(stdout, pixel_color); } } fprintf(stderr, "\nDone\n"); }