-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sphere.hpp
39 lines (34 loc) · 1 KB
/
Sphere.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef SPHERE_HPP
#define SPHERE_HPP
#include"Hittable.hpp"
class sphere :public hittable {
public:
sphere(const point3& center, double radius, shared_ptr<material> mat)
:center(center), radius(std::fmax(0, radius)), mat(mat) {}
bool hit(const ray& r, interval ray_t, hit_record& rec)const override {
vec3 oc = this->center - r.origin();
auto a = dot(r.direction(), r.direction());
auto half_b = dot(r.direction(), oc);
auto c = oc.length_squared() - radius * radius;
auto discriminant = half_b * half_b - a * c;
if (discriminant < 0)return false;
auto root = (half_b - sqrt(discriminant)) / a;
if (!ray_t.contains(root)) {
root = (half_b + sqrt(discriminant)) / a;
if (!ray_t.contains(root)) {
return false;
}
}
rec.p = r.at(root);
rec.t = root;
vec3 outward_normal = (r.at(root) - this->center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat = mat;
return true;
}
private:
point3 center;
double radius;
shared_ptr<material> mat;
};
#endif // !SPHERE_HPP