triangle.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. void Triangle::localIntersect(Ray r, Intersect &xs)
  22. {
  23. Tuple dirCrossE2 = r.direction.cross(this->e2);
  24. double determinant = this->e1.dot(dirCrossE2);
  25. if (fabs(determinant) < getEpsilon())
  26. {
  27. return;
  28. }
  29. double f = 1.0 / determinant;
  30. Tuple p1ToOrigin = r.origin - this->p1;
  31. Tuple originCrossE1 = p1ToOrigin.cross(this->e1);
  32. double u = f * p1ToOrigin.dot(dirCrossE2);
  33. double v = f * r.direction.dot(originCrossE1);
  34. if ((u < 0) || (u > 1))
  35. {
  36. return;
  37. }
  38. if ((v < 0) || ((u + v) > 1))
  39. {
  40. return;
  41. }
  42. double t = f * this->e2.dot(originCrossE1);
  43. xs.add(Intersection(t, this, u, v));
  44. }
  45. Tuple Triangle::localNormalAt(Tuple point, Intersection *hit)
  46. {
  47. return this->normal;
  48. }
  49. BoundingBox Triangle::getLocalBounds()
  50. {
  51. BoundingBox ret;
  52. ret | p1;
  53. ret | p2;
  54. ret | p3;
  55. return ret;
  56. }
  57. void Triangle::dumpMe(FILE *fp)
  58. {
  59. fprintf(fp, "\"Type\": \"Triangle\",\n");
  60. /* World points*/
  61. Tuple t = this->transformMatrix * this->p1;
  62. fprintf(fp, "\"p1\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  63. t.x, t.y, t.z);
  64. t = this->transformMatrix * this->p2;
  65. fprintf(fp, "\"p2\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  66. t.x, t.y, t.z);
  67. t = this->transformMatrix * this->p3;
  68. fprintf(fp, "\"p3\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  69. t.x, t.y, t.z);
  70. /* Local points */
  71. t = this->p1;
  72. fprintf(fp, "\"lp1\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  73. t.x, t.y, t.z);
  74. t = this->p2;
  75. fprintf(fp, "\"lp2\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  76. t.x, t.y, t.z);
  77. t = this->p3;
  78. fprintf(fp, "\"lp3\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  79. t.x, t.y, t.z);
  80. Shape::dumpMe(fp);
  81. }