-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sphere.h
59 lines (46 loc) · 1.44 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
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// Sphere.h
// ray-tracing-weekend
//
// Created by Sun, Joy (Agoda) on 2/16/2559 BE.
// Copyright © 2559 Sun, Joy (Agoda). All rights reserved.
//
#ifndef Sphere_h
#define Sphere_h
#include "Hitable.h"
class Sphere:public Hitable{
public:
Sphere(){}
Sphere(Vec3 cent, float r, Material *m):center(cent),radius(r), mat_ptr(m) {};
virtual bool hit(Ray &ray, float t_min, float t_max, hit_record &rec) const;
Vec3 center;
float radius;
Material *mat_ptr;
};
bool Sphere::hit(Ray &ray, float t_min, float t_max, hit_record &rec) const{
Vec3 oc = ray.origin() - center;
float a = ray.direction().dot(ray.direction());
float b = oc.dot(ray.direction());
float c = oc.dot(oc) - radius*radius;
float discriminant = b*b - a*c;
if (discriminant > 0) {
float temp = (-b - sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = ray.point_at_parameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.mat_ptr = mat_ptr;
return true;
}
temp = (-b + sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = ray.point_at_parameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}
#endif /* Sphere_h */