-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.h
43 lines (39 loc) · 1.25 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
#ifndef SPHEREH
#define SPHEREH
#include "hittable.h"
class sphere: public hittable {
public:
sphere() {}
sphere (vec3 cen, float r, material *m) : center(cen), radius(r), mat_ptr(m) {};
virtual bool hit(const ray &r, float tmin, float tmax, hit_records &rec) const;
vec3 center;
float radius;
material *mat_ptr;
};
bool sphere::hit(const ray &r, float t_min, float t_max, hit_records &rec) const {
vec3 oc = r.origin() - center;
float a = dot(r.direction(), r.direction());
float b = dot(oc, r.direction());
float c = dot(oc, oc) - radius*radius;
float discrimant = b*b - a*c;
if (discrimant > 0) {
float temp = (-b - sqrt(b*b-a*c))/a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = r.point_at_parameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.mat_ptr = mat_ptr;
return true;
}
temp = (-b + sqrt(b*b-a*c))/a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = r.point_at_parameter(rec.t);
rec.normal = (rec.p - center)/radius;
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}
#endif