]> Dogcows Code - chaz/rasterize/blob - triangle.hh
finishing fifth project
[chaz/rasterize] / triangle.hh
1
2 /*
3 * CS5600 University of Utah
4 * Charles McGarvey
5 * mcgarvey@eng.utah.edu
6 */
7
8 #ifndef _TRIANGLE_HH_
9 #define _TRIANGLE_HH_
10
11 #include "element.hh"
12
13
14 namespace rt {
15
16
17 /*
18 * A class for a triangle object.
19 */
20 class triangle : public element
21 {
22 vec_t a;
23 vec_t b;
24 vec_t c;
25
26 public:
27
28 triangle(vec_t a, vec_t b, vec_t c) :
29 a(a), b(b), c(c)
30 {}
31
32 virtual ~triangle()
33 {}
34
35 virtual bool intersect(ray_t ray, contact_t& hit) const
36 {
37 plane p = plane(a, b, c);
38 if (!p.intersect(ray, hit)) {
39 return false;
40 }
41
42 scal_t bc[3];
43 if (!barycentric(bc, hit.p)) {
44 return false;
45 }
46
47 #if QUIRKS
48 if (vec_dot(p.normal(), hit.n) < S(0.0)) {
49 hit.n = vec_neg(hit.n);
50 }
51 #endif
52
53 return true;
54 }
55
56 /*
57 * Calculate barycentric coordinates for the triangle.
58 */
59 bool barycentric(scal_t* bc, vec_t v) const
60 {
61 scal_t denom = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);
62 bc[0] = ((b.y - c.y) * (v.x - c.x) + (c.x - b.x) * (v.y - c.y)) / denom;
63 bc[1] = ((c.y - a.y) * (v.x - c.x) + (a.x - c.x) * (v.y - c.y)) / denom;
64 bc[2] = S(1.0) - bc[0] - bc[1];
65 if (S(0.0) <= bc[0] && bc[0] <= S(1.0) &&
66 S(0.0) <= bc[1] && bc[1] <= S(1.0) &&
67 S(0.0) <= bc[2] && bc[2] <= S(1.0)) {
68 return true;
69 }
70 return false;
71 }
72
73 virtual vec_t txcoord(vec_t point) const
74 {
75 vec_t t1 = vec_new(S(0.0), S(0.0), S(0.0));
76 vec_t t2 = vec_new(S(1.0), S(0.0), S(0.0));
77 vec_t t3 = vec_new(S(1.0), S(1.0), S(0.0));
78 scal_t bc[3];
79 barycentric(bc, point);
80 return vec_interp(t1, t2, t3, bc);
81 }
82 };
83
84
85 /*
86 * Destroy a new'd triangle, releasing its memory.
87 */
88 INLINE_MAYBE
89 void triangle_destroy(plane* t)
90 {
91 delete t;
92 }
93
94
95 } // namespace rt
96
97 #endif // _PLANE_HH_
98
99
This page took 0.043239 seconds and 4 git commands to generate.