-
Notifications
You must be signed in to change notification settings - Fork 0
/
triangle.hpp
50 lines (44 loc) · 1.34 KB
/
triangle.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
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "primitive.hpp"
class Triangle : public Primitive {
public:
Point vertices[3];
Triangle() {}
Triangle(Point a, Point b, Point c) : vertices{a, b, c} {}
virtual Vector normal(Point) const {
return vec(vertices[1] - vertices[0], vertices[2] - vertices[0]).normalized();
}
void cache() {
box = BBox(vertices[0], vertices[0]);
box += vertices[1];
box += vertices[2];
}
virtual double intersect(Ray ray) const {
Vector edge1 = vertices[1] - vertices[0];
Vector edge2 = vertices[2] - vertices[0];
//Begin calculating determinant - also used to calculate u parameter
Vector P = vec(ray.direction, edge2);
double det = dot(P, edge1);
if (almost_zero(det)) {
return INFINITY;
}
double inv_det = 1.0 / det;
Vector move = ray.start - vertices[0];
double u = dot(move, P) * inv_det;
if (u < -EPS || u > 1.0 + EPS) {
return INFINITY;
}
Vector Q = vec(move, edge1);
double v = dot(ray.direction, Q) * inv_det;
if(v < -EPS || u + v > 1.0 + EPS) {
return INFINITY;
}
double t = dot(edge2, Q) * inv_det;
return t;
}
virtual const BBox& bbox() const {
return box;
}
};
#endif