-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsphere.hpp
51 lines (45 loc) · 1.24 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
40
41
42
43
44
45
46
47
48
49
50
51
#ifndef SPHERE_H
#define SPHERE_H
#include "ray.hpp"
#include "hitable.h"
class sphere: public hitable
{
public:
sphere() {}
sphere(glm::vec3 cen, float r): center(cen), radius(r) {};
virtual bool hit(const ray& r, float t_min, float t_max, hit_record& rec) const;
//Data
glm::vec3 center;
float radius;
};
bool sphere::hit(const ray& r, float t_min, float t_max, hit_record& rec) const
{
glm::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 discriminant = b*b - a*c;
if(discriminant > 0)
{
//First root
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;
return true;
}
//Other root
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;
return true;
}
}
return false;
}
#endif