-
Notifications
You must be signed in to change notification settings - Fork 0
/
shape.h
112 lines (94 loc) · 2.41 KB
/
shape.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#pragma once
#include <algorithm>
#include "ray.h"
#include "vec.h"
#include "fcolor.h"
struct InterSectionPoint {
public:
Vec position;
Vec normal;
float distance;
bool exist;
InterSectionPoint():
distance(-1), exist(false)
{}
};
struct Material {
FColor ambientFactor;
FColor diffuseFactor;
FColor specularFactor;
float shininess;
};
class Shape {
public:
Material material;
void setMaterial(FColor amb, FColor dif, FColor spe, float s)
{
material.ambientFactor = amb;
material.diffuseFactor = dif;
material.specularFactor = spe;
material.shininess = s;
}
virtual bool testIntersection(const Ray ray, InterSectionPoint& point) = 0;
};
class Sphere : public Shape {
public:
Vec center;
float radius;
Sphere() {}
Sphere(Vec c, float r):
center(c), radius(r)
{}
bool testIntersection(const Ray ray, InterSectionPoint& point) override {
Vec s = ray.start - center;
float t;
float A = fabs(ray.direction.magSg());
float B = 2 * ray.direction.dot(s);
float C = fabs(s.magSg()) - radius*radius;
float D = B*B - 4*A*C;
if (D > 0) {
auto t1 = (- B + sqrtf(D)) / (2 * A);
auto t2 = (- B - sqrtf(D)) / (2 * A);
t = std::min(t1, t2);
} else if (D == 0) {
t = - B / (2 * A);
} else {
t = -1;
}
if (t >= 0) {
point.position = ray.getPoint(t);
point.normal = (point.position - center).normalize();
point.exist = true;
} else {
point.exist = false;
}
return point.exist;
}
};
class Plane : public Shape {
public:
Vec normal;
Vec position;
Plane() {}
Plane(Vec n, Vec p):
normal(n), position(p)
{}
bool testIntersection(const Ray ray, InterSectionPoint& point) override {
auto t = (normal.dot(position - ray.start)) / (normal.dot(ray.direction));
if (t >= 0) {
point.position = ray.getPoint(t);
point.normal = normal.normalize();
point.exist = true;
} else {
point.exist = false;
}
return point.exist;
}
};
class Triangle : public Shape {
public:
Triangle() {}
bool testIntersection(const Ray ray, InterSectionPoint& point) override {
return point.exist;
}
};