-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.h
46 lines (37 loc) · 1.16 KB
/
sphere.h
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
40
41
42
43
44
45
46
#pragma once
#include "hittable.h"
#include "vec3.h"
class sphere : public hittable {
public:
sphere() : center(0, 0, 0), radius(1) {};
sphere(point3 cen, real r, shared_ptr<material> m)
: center(cen), radius(r), mat_ptr(m) {};
virtual bool hit(const ray& r, real t_min, real t_max, hit_record& rec) const override;
private:
point3 center;
real radius;
shared_ptr<material> mat_ptr;
};
bool sphere::hit(const ray& r, real t_min, real t_max, hit_record& rec) const {
vec3 oc = r.origin() - center;
real a = r.direction().length_squared();
real half_b = dot(oc, r.direction());
real c = oc.length_squared() - radius * radius;
real discriminant = half_b * half_b - a * c;
if (discriminant < 0)
return false;
real sqrtd = sqrt(discriminant);
// Find the nearest root that lies in the acceptable range.
real root = (-half_b - sqrtd) / a;
if (root < t_min || t_max < root) {
root = (-half_b + sqrtd) / a;
if (root < t_min || t_max < root)
return false;
}
rec.t = root;
rec.p = r.at(rec.t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}