toytracer/wtracer.cpp
2020-06-07 00:03:25 +02:00

79 lines
2.6 KiB
C++

#include <iostream>
#include <memory>
#include "color.h"
#include "vec3.h"
#include "ray.h"
#include "util.h"
#include "hittable_list.h"
#include "sphere.h"
#include "camera.h"
Color ray_color(const Ray& r, const Hittable& world, int depth) {
hit_record rec;
if (depth <= 0)
return Color(0, 0, 0);
if (world.hit(r, 0.001, infinity, rec)) {
Ray scattered;
Color attenuation;
if (rec.mat_ptr->scatter(r, rec, attenuation, scattered))
return attenuation * ray_color(scattered, world, depth - 1);
return Color(0, 0, 0);
}
Vec3 unit_direction = unit_vector(r.direction());
auto t = 0.5 * (unit_direction.y() + 1.0);
return (1.0 - t) * Color(1.0, 1.0, 1.0) + t * Color(0.5, 0.7, 1.0);
}
int main() {
const auto aspect_ratio = 16.0 / 9.0;
//const int image_width = 1280;
const int image_width = 768;
//const int image_width = 384;
const int image_height = static_cast<int>(image_width / aspect_ratio);
//const int samples_per_pixel = 1000;
const int samples_per_pixel = 400;
const int max_depth = 50;
std::cout << "P3\n" << image_width << " " << image_height << "\n255\n";
Hittable_list world;
world.add(std::make_shared<Sphere>(Point3(0, 0, -1), 0.5, std::make_shared<Lambertian>(Color(0.1, 0.2, 0.5))));
world.add(std::make_shared<Sphere>(Point3(0, -100.5, -1), 100, std::make_shared<Lambertian>(Color(0.8, 0.8, 0.0))));
world.add(std::make_shared<Sphere>(Point3(1, 0, -1), 0.5, std::make_shared<Metal>(Color(0.8, 0.6, 0.2), 0.0)));
world.add(std::make_shared<Sphere>(Point3(-1, 0, -1), 0.5, std::make_shared<Dielectric>(1.45)));
Camera cam;
auto image = std::make_unique<Color[]>(image_height*image_width);
for (int j = image_height - 1; j >= 0; --j) {
std::cerr << "\rScanlines remaining: " << j << " " << std::flush;
#pragma omp parallel for
for (int i = 0; i < image_width; ++i) {
Color pixel_color(0, 0, 0);
for (int s = 0; s<samples_per_pixel; ++s) {
auto u = double(i + random_double(-0.5, 0.5)) / (image_width - 1);
auto v = double(j + random_double(-0.5, 0.5)) / (image_height - 1);
Ray r = cam.get_ray(u, v);
pixel_color += ray_color(r, world, max_depth);
}
image[i*image_height+j] = pixel_color;
}
}
std::cerr << "\nWriting file.\n";
for (int j = image_height - 1; j >= 0; --j) {
for (int i = 0; i < image_width; ++i) {
write_color(std::cout, image[i*image_height+j], samples_per_pixel);
}
}
std::cerr << "Done.\n";
}