toytracer/moving_sphere.cpp

36 lines
1.2 KiB
C++
Raw Normal View History

2020-06-07 20:25:43 +00:00
#include "moving_sphere.h"
Point3 Moving_sphere::center(double time) const {
return center0 + ((time - time0) / (time1 - time0)) * (center1 - center0);
}
bool Moving_sphere::hit(const Ray& r, double tmin, double tmax, hit_record& rec) const {
Vec3 oc = r.origin() - center(r.time());
auto a = r.direction().length_squared();
auto half_b = dot(oc, r.direction());
auto c = oc.length_squared() - radius * radius;
auto discriminant = half_b*half_b - a*c;
if (discriminant > 0) {
auto root = std::sqrt(discriminant);
auto temp = (-half_b - root) / a;
if (temp < tmax && temp > tmin) {
rec.t = temp;
rec.p = r.at(rec.t);
Vec3 outward_normal = (rec.p - center(r.time())) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
temp = (-half_b + root) / a;
if (temp < tmax && temp > tmin) {
rec.t = temp;
rec.p = r.at(rec.t);
Vec3 outward_normal = (rec.p - center(r.time())) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}