• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Triangle
2class Triangle {
3  // position
4  PVector p1, p2, p3;
5  // color
6  color c1, c2, c3;
7  BoundingBox bbx;
8  Triangle(PVector p1, PVector p2, PVector p3, color c1, color c2, color c3) {
9    this.p1 = p1;
10    this.p2 = p2;
11    this.p3 = p3;
12    this.c1 = c1;
13    this.c2 = c2;
14    this.c3 = c3;
15    bbx = new BoundingBox();
16    bbx.create(this);
17  }
18  // check to see if a ray intersects with the triangle
19  boolean intersect(Ray r, float[] param) {
20    PVector p21 = PVector.sub(p2, p1);
21    PVector p31 = PVector.sub(p3, p1);
22    PVector po1 = PVector.sub(r.ori, p1);
23
24    PVector dxp31 = r.dir.cross(p31);
25    PVector po1xp21 = po1.cross(p21);
26    float denom = p21.dot(dxp31);
27    float t = p31.dot(po1xp21) / denom;
28    float alpha = po1.dot(dxp31) / denom;
29    float beta = r.dir.dot(po1xp21) / denom;
30
31    boolean res = t > 0 && alpha > 0 && alpha < 1 && beta > 0 && beta < 1 &&
32                  alpha + beta < 1;
33    // depth test
34    if (res && t < param[0]) {
35      param[0] = t;
36      param[1] = alpha * p1.x + beta * p2.x + (1 - alpha - beta) * p3.x;
37      param[2] = alpha * p1.y + beta * p2.y + (1 - alpha - beta) * p3.y;
38      param[3] = alpha * p1.z + beta * p2.z + (1 - alpha - beta) * p3.z;
39    }
40    return res;
41  }
42  void render() {
43    beginShape(TRIANGLES);
44    fill(c1);
45    vertex(p1.x, p1.y, p1.z);
46    fill(c2);
47    vertex(p2.x, p2.y, p2.z);
48    fill(c3);
49    vertex(p3.x, p3.y, p3.z);
50    endShape();
51  }
52}
53// Ray
54class Ray {
55  // origin and direction
56  PVector ori, dir;
57  Ray(PVector ori, PVector dir) {
58    this.ori = ori;
59    this.dir = dir;
60  }
61}
62