triangle.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Triangle implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <ray.h>
  10. #include <shape.h>
  11. #include <triangle.h>
  12. #include <math_helper.h>
  13. #include <renderstat.h>
  14. Triangle::Triangle(Point p1, Point p2, Point p3) : Shape(SHAPE_TRIANGLE), p1(p1), p2(p2), p3(p3)
  15. {
  16. stats.addTriangle();
  17. this->e1 = p2 - p1;
  18. this->e2 = p3 - p1;
  19. this->normal = e2.cross(e1).normalise();
  20. }
  21. Intersect Triangle::localIntersect(Ray r)
  22. {
  23. Intersect ret;
  24. Tuple dirCrossE2 = r.direction.cross(this->e2);
  25. double determinant = this->e1.dot(dirCrossE2);
  26. if (fabs(determinant) < getEpsilon())
  27. {
  28. return ret;
  29. }
  30. double f = 1.0 / determinant;
  31. Tuple p1ToOrigin = r.origin - this->p1;
  32. Tuple originCrossE1 = p1ToOrigin.cross(this->e1);
  33. double u = f * p1ToOrigin.dot(dirCrossE2);
  34. double v = f * r.direction.dot(originCrossE1);
  35. if ((u < 0) || (u > 1))
  36. {
  37. return ret;
  38. }
  39. if ((v < 0) || ((u + v) > 1))
  40. {
  41. return ret;
  42. }
  43. double t = f * this->e2.dot(originCrossE1);
  44. ret.add(Intersection(t, this, u, v));
  45. return ret;
  46. }
  47. Tuple Triangle::localNormalAt(Tuple point, Intersection *hit)
  48. {
  49. return this->normal;
  50. }
  51. BoundingBox Triangle::getLocalBounds()
  52. {
  53. BoundingBox ret;
  54. ret | p1;
  55. ret | p2;
  56. ret | p3;
  57. return ret;
  58. }
  59. void Triangle::dumpMe(FILE *fp)
  60. {
  61. fprintf(fp, "\"Type\": \"Triangle\",\n");
  62. Tuple t = this->transformMatrix * this->p1;
  63. fprintf(fp, "\"p1\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  64. t.x, t.y, t.z);
  65. t = this->transformMatrix * this->p2;
  66. fprintf(fp, "\"p2\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  67. t.x, t.y, t.z);
  68. t = this->transformMatrix * this->p3;
  69. fprintf(fp, "\"p3\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  70. t.x, t.y, t.z);
  71. Shape::dumpMe(fp);
  72. }