toytracer/sphere.h

56 lines
1.5 KiB
C
Raw Normal View History

#ifndef SPHERE_H
#define SPHERE_H
#include <cmath>
#include <memory>
#include "hittable.h"
#include "material.h"
#include "vec3.h"
class Sphere : public Hittable {
public:
Sphere() {}
Sphere(Point3 cen, double r, std::shared_ptr<Material> m) : center(cen), radius(r), mat_ptr(m) {}
virtual bool hit(const Ray& r, double tmin, double tmax, hit_record& rec) const;
private:
Point3 center;
double radius;
std::shared_ptr<Material> mat_ptr;
};
2020-06-03 22:15:32 +00:00
bool Sphere::hit(const Ray& r, double tmin, double tmax, hit_record& rec) const {
Vec3 oc = r.origin() - center;
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;
2020-06-03 22:15:32 +00:00
if (discriminant > 0) {
auto root = std::sqrt(discriminant);
auto temp = (-half_b - root) / a;
2020-06-03 22:15:32 +00:00
if (temp < tmax && temp > tmin) {
rec.t = temp;
rec.p = r.at(rec.t);
2020-06-03 22:15:32 +00:00
Vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
2020-06-03 22:15:32 +00:00
return true;
}
2020-06-03 22:15:32 +00:00
temp = (-half_b + root) / a;
if (temp < tmax && temp > tmin) {
rec.t = temp;
rec.p = r.at(rec.t);
2020-06-03 22:15:32 +00:00
Vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
2020-06-03 22:15:32 +00:00
return true;
}
}
return false;
}
#endif // SPHERE_H