]> Dogcows Code - chaz/rasterize/blob - triangle.hh
basic ray tracing with hard shadows
[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 "color.hh"
12 #include "element.hh"
13
14
15 namespace rt {
16
17
18 /*
19 * A class for a triangle object.
20 */
21 class triangle : public element
22 {
23 public:
24
25 color_t material;
26 vec_t a;
27 vec_t b;
28 vec_t c;
29
30 triangle(vec_t a, vec_t b, vec_t c, color_t color = COLOR_WHITE) :
31 a(a), b(b), c(c), material(color)
32 {}
33
34 virtual ~triangle()
35 {}
36
37 virtual bool intersect(ray_t ray, contact_t& hit) const
38 {
39 plane p = plane(a, b, c);
40 if (!p.intersect(ray, hit)) {
41 return false;
42 }
43
44 scal_t bc[3];
45 if (barycentric(bc, hit.p)) {
46 return true;
47 }
48
49 return false;
50 }
51
52 virtual color_t color(vec_t point) const
53 {
54 return material;
55 }
56
57 /*
58 * Calculate barycentric coordinates for the triangle.
59 */
60 bool barycentric(scal_t* bc, vec_t v) const
61 {
62 scal_t denom = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);
63 bc[0] = ((b.y - c.y) * (v.x - c.x) + (c.x - b.x) * (v.y - c.y)) / denom;
64 bc[1] = ((c.y - a.y) * (v.x - c.x) + (a.x - c.x) * (v.y - c.y)) / denom;
65 bc[2] = S(1.0) - bc[0] - bc[1];
66 if (S(0.0) <= bc[0] && bc[0] <= S(1.0) &&
67 S(0.0) <= bc[1] && bc[1] <= S(1.0) &&
68 S(0.0) <= bc[2] && bc[2] <= S(1.0)) {
69 return true;
70 }
71 return false;
72 }
73 };
74
75
76 /*
77 * Destroy a new'd triangle, releasing its memory.
78 */
79 INLINE_MAYBE
80 void triangle_destroy(plane* t)
81 {
82 delete t;
83 }
84
85
86 } // namespace rt
87
88 #endif // _PLANE_HH_
89
90
This page took 0.036698 seconds and 4 git commands to generate.