transformation.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Transformation implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <math.h>
  10. #include <transformation.h>
  11. Matrix translation(double x, double y, double z)
  12. {
  13. Matrix ret = Matrix4().identity();
  14. ret.set(0, 3, x);
  15. ret.set(1, 3, y);
  16. ret.set(2, 3, z);
  17. return ret;
  18. }
  19. Matrix scaling(double x, double y, double z)
  20. {
  21. Matrix ret = Matrix4();
  22. ret.set(0, 0, x);
  23. ret.set(1, 1, y);
  24. ret.set(2, 2, z);
  25. ret.set(3, 3, 1);
  26. return ret;
  27. }
  28. Matrix rotationX(double angle)
  29. {
  30. Matrix ret = Matrix4().identity();
  31. ret.set(1, 1, cos(angle));
  32. ret.set(1, 2, -sin(angle));
  33. ret.set(2, 1, sin(angle));
  34. ret.set(2, 2, cos(angle));
  35. return ret;
  36. }
  37. Matrix rotationY(double angle)
  38. {
  39. Matrix ret = Matrix4().identity();
  40. ret.set(0, 0, cos(angle));
  41. ret.set(0, 2, sin(angle));
  42. ret.set(2, 0, -sin(angle));
  43. ret.set(2, 2, cos(angle));
  44. return ret;
  45. }
  46. Matrix rotationZ(double angle)
  47. {
  48. Matrix ret = Matrix4().identity();
  49. ret.set(0, 0, cos(angle));
  50. ret.set(0, 1, -sin(angle));
  51. ret.set(1, 0, sin(angle));
  52. ret.set(1, 1, cos(angle));
  53. return ret;
  54. }
  55. Matrix shearing(double Xy, double Xz, double Yx, double Yz, double Zx, double Zy)
  56. {
  57. Matrix ret = Matrix4().identity();
  58. ret.set(0, 1, Xy);
  59. ret.set(0, 2, Xz);
  60. ret.set(1, 0, Yx);
  61. ret.set(1, 2, Yz);
  62. ret.set(2, 0, Zx);
  63. ret.set(2, 1, Zy);
  64. return ret;
  65. }
  66. Matrix viewTransform(Tuple from, Tuple to, Tuple up)
  67. {
  68. Tuple forward = (to - from).normalise();
  69. Tuple left = forward.cross(up.normalise());
  70. Tuple true_up = left.cross(forward);
  71. double orientationValues[] = { left.x, left.y, left.z, 0,
  72. true_up.x, true_up.y, true_up.z, 0,
  73. -forward.x, -forward.y, -forward.z, 0,
  74. 0, 0, 0, 1 };
  75. Matrix orientation = Matrix4(orientationValues);
  76. return orientation * translation(-from.x, -from.y, -from.z);
  77. }