From b2265d26a323c2457c065848ff846e3a9b512c7b Mon Sep 17 00:00:00 2001 From: Faerbit Date: Wed, 3 Jun 2020 22:39:40 +0200 Subject: [PATCH] Adding rays, origin and horizon. --- Makefile | 2 +- ray.h | 24 ++++++++++++++++++++++++ wtracer.cpp | 28 +++++++++++++++++++++++----- 3 files changed, 48 insertions(+), 6 deletions(-) create mode 100644 ray.h diff --git a/Makefile b/Makefile index 6068de4..e289431 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ CXX = g++ CXXFLAGS = -Wall -Wextra -O2 -std=c++14 -DEPS = vec3.h color.h +DEPS = vec3.h color.h ray.h OBJ = wtracer.o TARGET = wtracer diff --git a/ray.h b/ray.h new file mode 100644 index 0000000..99c5d61 --- /dev/null +++ b/ray.h @@ -0,0 +1,24 @@ +#ifndef RAY_H +#define RAY_H + +#include "vec3.h" + +class Ray { + public: + Ray() {} + Ray(const Point3& origin, const Vec3& direction) + : orig(origin), dir(direction) {} + + Point3 origin() const { return orig; } + Vec3 direction() const { return dir; } + + Point3 at(double t) const { + return orig + t * dir; + } + + private: + Point3 orig; + Vec3 dir; +}; + +#endif //RAY_H diff --git a/wtracer.cpp b/wtracer.cpp index c0de864..6aa422f 100644 --- a/wtracer.cpp +++ b/wtracer.cpp @@ -2,19 +2,37 @@ #include "color.h" #include "vec3.h" +#include "ray.h" + +Color ray_color(const Ray& r) { + 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 int image_width = 256; - const int image_height = 256; + const auto aspect_ratio = 16.0 / 9.0; + const int image_width = 1280; + const int image_height = static_cast(image_width / aspect_ratio); std::cout << "P3\n" << image_width << " " << image_height << "\n255\n"; + auto viewport_height = 2.0; + auto viewport_width = aspect_ratio * viewport_height; + auto focal_length = 1.0; + + auto origin = Point3(0, 0, 0); + auto horizontal = Vec3(viewport_width, 0, 0); + auto vertical = Vec3(0, viewport_height, 0); + auto lower_left_corner = origin - horizontal/2 - vertical/2 - Vec3(0, 0, focal_length); + for (int j = image_height - 1; j >= 0; --j) { std::cerr << "\rScanlines remaining: " << j << " " << std::flush; for (int i = 0; i < image_width; ++i) { - Color pixel_color(double(i) / (image_width - 1), - double(j) / (image_height - 1), - 0.25); + auto u = double(i) / (image_width - 1); + auto v = double(j) / (image_height - 1); + Ray r(origin, lower_left_corner + u*horizontal + v*vertical - origin); + Color pixel_color = ray_color(r); write_color(std::cout, pixel_color); } }