matrix.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Matrix header
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #ifndef DORAYME_MATRIX_H
  10. #define DORAYME_MATRIX_H
  11. #include <tuple.h>
  12. /* Some **** linux distro seems to define "minor" as a macro
  13. * and wreak havoc.
  14. * Let's make sure we are clean here
  15. */
  16. #ifdef minor
  17. #undef minor
  18. #endif
  19. #define FastGet4(_x, _y) (this->data[4 * (_x) + (_y)])
  20. class Matrix
  21. {
  22. protected:
  23. /* 4x4 is the default */
  24. double data[4*4];
  25. int size;
  26. public:
  27. Matrix(int size = 4);
  28. Matrix(double values[], int size);
  29. double get(int x, int y) const { return this->data[this->size * x + y]; };
  30. void set(int x, int y, double v) { this->data[this->size * x + y] = v; };
  31. Matrix identity();
  32. Matrix transpose();
  33. double determinant();
  34. Matrix submatrix(int row, int column);
  35. Matrix inverse();
  36. double minor(int row, int column) { return this->submatrix(row, column).determinant(); }
  37. double cofactor(int row, int column) { return (((column+row)&1)?-1:1) * this->minor(row, column); }
  38. bool operator==(const Matrix &b) const;
  39. bool operator!=(const Matrix &b) const;
  40. bool isInvertible() { return this->determinant() != 0; }
  41. Matrix operator*(const Matrix &b) const;
  42. Tuple operator*(const Tuple &b) const {
  43. return Tuple(b.x * FastGet4(0, 0) + b.y * FastGet4(0, 1) + b.z * FastGet4(0, 2) + b.w * FastGet4(0, 3),
  44. b.x * FastGet4(1, 0) + b.y * FastGet4(1, 1) + b.z * FastGet4(1, 2) + b.w * FastGet4(1, 3),
  45. b.x * FastGet4(2, 0) + b.y * FastGet4(2, 1) + b.z * FastGet4(2, 2) + b.w * FastGet4(2, 3),
  46. b.x * FastGet4(3, 0) + b.y * FastGet4(3, 1) + b.z * FastGet4(3, 2) + b.w * FastGet4(3, 3));
  47. }
  48. };
  49. class Matrix4: public Matrix
  50. {
  51. public:
  52. Matrix4() : Matrix(4) { };
  53. Matrix4(double values[]) : Matrix(values, 4) { };
  54. };
  55. class Matrix3 : public Matrix
  56. {
  57. public:
  58. Matrix3() : Matrix(3) { };
  59. Matrix3(double values[]) : Matrix(values, 3) { };
  60. };
  61. class Matrix2 : public Matrix
  62. {
  63. private:
  64. using Matrix::data;
  65. public:
  66. Matrix2() : Matrix(2) { };
  67. Matrix2(double values[]) : Matrix(values, 2) { };
  68. };
  69. #endif /* DORAYME_MATRIX_H */