cube.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Cube implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <tuple.h>
  10. #include <ray.h>
  11. #include <shape.h>
  12. #include <cube.h>
  13. #include <math_helper.h>
  14. void Cube::checkAxis(double axeOrigin, double axeDirection, double *axeMin, double *axeMax)
  15. {
  16. double tMinNumerator = (-1 - axeOrigin);
  17. double tMaxNumerator = (1 - axeOrigin);
  18. if (fabs(axeDirection) >= getEpsilon())
  19. {
  20. *axeMin = tMinNumerator / axeDirection;
  21. *axeMax = tMaxNumerator / axeDirection;
  22. }
  23. else
  24. {
  25. *axeMin = tMinNumerator * INFINITY;
  26. *axeMax = tMaxNumerator * INFINITY;
  27. }
  28. if (*axeMin > *axeMax)
  29. {
  30. double swap = *axeMax;
  31. *axeMax = *axeMin;
  32. *axeMin = swap;
  33. }
  34. }
  35. Intersect Cube::localIntersect(Ray r)
  36. {
  37. Intersect ret;
  38. double xtMin, xtMax, ytMin, ytMax, ztMin, ztMax;
  39. double tMin, tMax;
  40. this->checkAxis(r.origin.x, r.direction.x, &xtMin, &xtMax);
  41. this->checkAxis(r.origin.y, r.direction.y, &ytMin, &ytMax);
  42. this->checkAxis(r.origin.z, r.direction.z, &ztMin, &ztMax);
  43. tMin = max3(xtMin, ytMin, ztMin);
  44. tMax = min3(xtMax, ytMax, ztMax);
  45. if (tMin <= tMax)
  46. {
  47. ret.add(Intersection(tMin, this));
  48. ret.add(Intersection(tMax, this));
  49. }
  50. return ret;
  51. }
  52. Tuple Cube::localNormalAt(Tuple point)
  53. {
  54. double maxC = max3(fabs(point.x), fabs(point.y), fabs(point.z));
  55. if (maxC == fabs(point.x))
  56. {
  57. return Vector(point.x, 0, 0);
  58. }
  59. else if (maxC == fabs(point.y))
  60. {
  61. return Vector(0, point.y, 0);
  62. }
  63. return Vector(0, 0, point.z);
  64. }