matrix3.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /*************************************************************************/
  2. /* matrix3.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "matrix3.h"
  31. #include "math_funcs.h"
  32. #include "os/copymem.h"
  33. #include "print_string.h"
  34. #define cofac(row1, col1, row2, col2) \
  35. (elements[row1][col1] * elements[row2][col2] - elements[row1][col2] * elements[row2][col1])
  36. void Basis::from_z(const Vector3 &p_z) {
  37. if (Math::abs(p_z.z) > Math_SQRT12) {
  38. // choose p in y-z plane
  39. real_t a = p_z[1] * p_z[1] + p_z[2] * p_z[2];
  40. real_t k = 1.0 / Math::sqrt(a);
  41. elements[0] = Vector3(0, -p_z[2] * k, p_z[1] * k);
  42. elements[1] = Vector3(a * k, -p_z[0] * elements[0][2], p_z[0] * elements[0][1]);
  43. } else {
  44. // choose p in x-y plane
  45. real_t a = p_z.x * p_z.x + p_z.y * p_z.y;
  46. real_t k = 1.0 / Math::sqrt(a);
  47. elements[0] = Vector3(-p_z.y * k, p_z.x * k, 0);
  48. elements[1] = Vector3(-p_z.z * elements[0].y, p_z.z * elements[0].x, a * k);
  49. }
  50. elements[2] = p_z;
  51. }
  52. void Basis::invert() {
  53. real_t co[3] = {
  54. cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)
  55. };
  56. real_t det = elements[0][0] * co[0] +
  57. elements[0][1] * co[1] +
  58. elements[0][2] * co[2];
  59. #ifdef MATH_CHECKS
  60. ERR_FAIL_COND(det == 0);
  61. #endif
  62. real_t s = 1.0 / det;
  63. set(co[0] * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
  64. co[1] * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
  65. co[2] * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
  66. }
  67. void Basis::orthonormalize() {
  68. #ifdef MATH_CHECKS
  69. ERR_FAIL_COND(determinant() == 0);
  70. #endif
  71. // Gram-Schmidt Process
  72. Vector3 x = get_axis(0);
  73. Vector3 y = get_axis(1);
  74. Vector3 z = get_axis(2);
  75. x.normalize();
  76. y = (y - x * (x.dot(y)));
  77. y.normalize();
  78. z = (z - x * (x.dot(z)) - y * (y.dot(z)));
  79. z.normalize();
  80. set_axis(0, x);
  81. set_axis(1, y);
  82. set_axis(2, z);
  83. }
  84. Basis Basis::orthonormalized() const {
  85. Basis c = *this;
  86. c.orthonormalize();
  87. return c;
  88. }
  89. bool Basis::is_orthogonal() const {
  90. Basis id;
  91. Basis m = (*this) * transposed();
  92. return is_equal_approx(id, m);
  93. }
  94. bool Basis::is_diagonal() const {
  95. return (
  96. Math::is_equal_approx(elements[0][1], 0) && Math::is_equal_approx(elements[0][2], 0) &&
  97. Math::is_equal_approx(elements[1][0], 0) && Math::is_equal_approx(elements[1][2], 0) &&
  98. Math::is_equal_approx(elements[2][0], 0) && Math::is_equal_approx(elements[2][1], 0));
  99. }
  100. bool Basis::is_rotation() const {
  101. return Math::is_equal_approx(determinant(), 1) && is_orthogonal();
  102. }
  103. bool Basis::is_symmetric() const {
  104. if (!Math::is_equal_approx(elements[0][1], elements[1][0]))
  105. return false;
  106. if (!Math::is_equal_approx(elements[0][2], elements[2][0]))
  107. return false;
  108. if (!Math::is_equal_approx(elements[1][2], elements[2][1]))
  109. return false;
  110. return true;
  111. }
  112. Basis Basis::diagonalize() {
  113. //NOTE: only implemented for symmetric matrices
  114. //with the Jacobi iterative method method
  115. #ifdef MATH_CHECKS
  116. ERR_FAIL_COND_V(!is_symmetric(), Basis());
  117. #endif
  118. const int ite_max = 1024;
  119. real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2];
  120. int ite = 0;
  121. Basis acc_rot;
  122. while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max) {
  123. real_t el01_2 = elements[0][1] * elements[0][1];
  124. real_t el02_2 = elements[0][2] * elements[0][2];
  125. real_t el12_2 = elements[1][2] * elements[1][2];
  126. // Find the pivot element
  127. int i, j;
  128. if (el01_2 > el02_2) {
  129. if (el12_2 > el01_2) {
  130. i = 1;
  131. j = 2;
  132. } else {
  133. i = 0;
  134. j = 1;
  135. }
  136. } else {
  137. if (el12_2 > el02_2) {
  138. i = 1;
  139. j = 2;
  140. } else {
  141. i = 0;
  142. j = 2;
  143. }
  144. }
  145. // Compute the rotation angle
  146. real_t angle;
  147. if (Math::is_equal_approx(elements[j][j], elements[i][i])) {
  148. angle = Math_PI / 4;
  149. } else {
  150. angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i]));
  151. }
  152. // Compute the rotation matrix
  153. Basis rot;
  154. rot.elements[i][i] = rot.elements[j][j] = Math::cos(angle);
  155. rot.elements[i][j] = -(rot.elements[j][i] = Math::sin(angle));
  156. // Update the off matrix norm
  157. off_matrix_norm_2 -= elements[i][j] * elements[i][j];
  158. // Apply the rotation
  159. *this = rot * *this * rot.transposed();
  160. acc_rot = rot * acc_rot;
  161. }
  162. return acc_rot;
  163. }
  164. Basis Basis::inverse() const {
  165. Basis inv = *this;
  166. inv.invert();
  167. return inv;
  168. }
  169. void Basis::transpose() {
  170. SWAP(elements[0][1], elements[1][0]);
  171. SWAP(elements[0][2], elements[2][0]);
  172. SWAP(elements[1][2], elements[2][1]);
  173. }
  174. Basis Basis::transposed() const {
  175. Basis tr = *this;
  176. tr.transpose();
  177. return tr;
  178. }
  179. // Multiplies the matrix from left by the scaling matrix: M -> S.M
  180. // See the comment for Basis::rotated for further explanation.
  181. void Basis::scale(const Vector3 &p_scale) {
  182. elements[0][0] *= p_scale.x;
  183. elements[0][1] *= p_scale.x;
  184. elements[0][2] *= p_scale.x;
  185. elements[1][0] *= p_scale.y;
  186. elements[1][1] *= p_scale.y;
  187. elements[1][2] *= p_scale.y;
  188. elements[2][0] *= p_scale.z;
  189. elements[2][1] *= p_scale.z;
  190. elements[2][2] *= p_scale.z;
  191. }
  192. Basis Basis::scaled(const Vector3 &p_scale) const {
  193. Basis m = *this;
  194. m.scale(p_scale);
  195. return m;
  196. }
  197. void Basis::set_scale(const Vector3 &p_scale) {
  198. set_axis(0, get_axis(0).normalized() * p_scale.x);
  199. set_axis(1, get_axis(1).normalized() * p_scale.y);
  200. set_axis(2, get_axis(2).normalized() * p_scale.z);
  201. }
  202. Vector3 Basis::get_scale() const {
  203. return Vector3(
  204. Vector3(elements[0][0], elements[1][0], elements[2][0]).length(),
  205. Vector3(elements[0][1], elements[1][1], elements[2][1]).length(),
  206. Vector3(elements[0][2], elements[1][2], elements[2][2]).length());
  207. }
  208. Vector3 Basis::get_signed_scale() const {
  209. // FIXME: We are assuming M = R.S (R is rotation and S is scaling), and use polar decomposition to extract R and S.
  210. // A polar decomposition is M = O.P, where O is an orthogonal matrix (meaning rotation and reflection) and
  211. // P is a positive semi-definite matrix (meaning it contains absolute values of scaling along its diagonal).
  212. //
  213. // Despite being different from what we want to achieve, we can nevertheless make use of polar decomposition
  214. // here as follows. We can split O into a rotation and a reflection as O = R.Q, and obtain M = R.S where
  215. // we defined S = Q.P. Now, R is a proper rotation matrix and S is a (signed) scaling matrix,
  216. // which can involve negative scalings. However, there is a catch: unlike the polar decomposition of M = O.P,
  217. // the decomposition of O into a rotation and reflection matrix as O = R.Q is not unique.
  218. // Therefore, we are going to do this decomposition by sticking to a particular convention.
  219. // This may lead to confusion for some users though.
  220. //
  221. // The convention we use here is to absorb the sign flip into the scaling matrix.
  222. // The same convention is also used in other similar functions such as get_rotation_axis_angle, get_rotation, ...
  223. //
  224. // A proper way to get rid of this issue would be to store the scaling values (or at least their signs)
  225. // as a part of Basis. However, if we go that path, we need to disable direct (write) access to the
  226. // matrix elements.
  227. //
  228. // The rotation part of this decomposition is returned by get_rotation* functions.
  229. real_t det_sign = determinant() > 0 ? 1 : -1;
  230. return det_sign * Vector3(
  231. Vector3(elements[0][0], elements[1][0], elements[2][0]).length(),
  232. Vector3(elements[0][1], elements[1][1], elements[2][1]).length(),
  233. Vector3(elements[0][2], elements[1][2], elements[2][2]).length());
  234. }
  235. // Decomposes a Basis into a rotation-reflection matrix (an element of the group O(3)) and a positive scaling matrix as B = O.S.
  236. // Returns the rotation-reflection matrix via reference argument, and scaling information is returned as a Vector3.
  237. // This (internal) function is too specific and named too ugly to expose to users, and probably there's no need to do so.
  238. Vector3 Basis::rotref_posscale_decomposition(Basis &rotref) const {
  239. #ifdef MATH_CHECKS
  240. ERR_FAIL_COND_V(determinant() == 0, Vector3());
  241. Basis m = transposed() * (*this);
  242. ERR_FAIL_COND_V(m.is_diagonal() == false, Vector3());
  243. #endif
  244. Vector3 scale = get_scale();
  245. Basis inv_scale = Basis().scaled(scale.inverse()); // this will also absorb the sign of scale
  246. rotref = (*this) * inv_scale;
  247. #ifdef MATH_CHECKS
  248. ERR_FAIL_COND_V(rotref.is_orthogonal() == false, Vector3());
  249. #endif
  250. return scale.abs();
  251. }
  252. // Multiplies the matrix from left by the rotation matrix: M -> R.M
  253. // Note that this does *not* rotate the matrix itself.
  254. //
  255. // The main use of Basis is as Transform.basis, which is used a the transformation matrix
  256. // of 3D object. Rotate here refers to rotation of the object (which is R * (*this)),
  257. // not the matrix itself (which is R * (*this) * R.transposed()).
  258. Basis Basis::rotated(const Vector3 &p_axis, real_t p_phi) const {
  259. return Basis(p_axis, p_phi) * (*this);
  260. }
  261. void Basis::rotate(const Vector3 &p_axis, real_t p_phi) {
  262. *this = rotated(p_axis, p_phi);
  263. }
  264. Basis Basis::rotated(const Vector3 &p_euler) const {
  265. return Basis(p_euler) * (*this);
  266. }
  267. void Basis::rotate(const Vector3 &p_euler) {
  268. *this = rotated(p_euler);
  269. }
  270. // TODO: rename this to get_rotation_euler
  271. Vector3 Basis::get_rotation() const {
  272. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  273. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  274. // See the comment in get_scale() for further information.
  275. Basis m = orthonormalized();
  276. real_t det = m.determinant();
  277. if (det < 0) {
  278. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  279. m.scale(Vector3(-1, -1, -1));
  280. }
  281. return m.get_euler();
  282. }
  283. void Basis::get_rotation_axis_angle(Vector3 &p_axis, real_t &p_angle) const {
  284. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  285. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  286. // See the comment in get_scale() for further information.
  287. Basis m = orthonormalized();
  288. real_t det = m.determinant();
  289. if (det < 0) {
  290. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  291. m.scale(Vector3(-1, -1, -1));
  292. }
  293. m.get_axis_angle(p_axis, p_angle);
  294. }
  295. // get_euler_xyz returns a vector containing the Euler angles in the format
  296. // (a1,a2,a3), where a3 is the angle of the first rotation, and a1 is the last
  297. // (following the convention they are commonly defined in the literature).
  298. //
  299. // The current implementation uses XYZ convention (Z is the first rotation),
  300. // so euler.z is the angle of the (first) rotation around Z axis and so on,
  301. //
  302. // And thus, assuming the matrix is a rotation matrix, this function returns
  303. // the angles in the decomposition R = X(a1).Y(a2).Z(a3) where Z(a) rotates
  304. // around the z-axis by a and so on.
  305. Vector3 Basis::get_euler_xyz() const {
  306. // Euler angles in XYZ convention.
  307. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  308. //
  309. // rot = cy*cz -cy*sz sy
  310. // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
  311. // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
  312. Vector3 euler;
  313. #ifdef MATH_CHECKS
  314. ERR_FAIL_COND_V(is_rotation() == false, euler);
  315. #endif
  316. real_t sy = elements[0][2];
  317. if (sy < 1.0) {
  318. if (sy > -1.0) {
  319. // is this a pure Y rotation?
  320. if (elements[1][0] == 0.0 && elements[0][1] == 0.0 && elements[1][2] == 0 && elements[2][1] == 0 && elements[1][1] == 1) {
  321. // return the simplest form (human friendlier in editor and scripts)
  322. euler.x = 0;
  323. euler.y = atan2(elements[0][2], elements[0][0]);
  324. euler.z = 0;
  325. } else {
  326. euler.x = Math::atan2(-elements[1][2], elements[2][2]);
  327. euler.y = Math::asin(sy);
  328. euler.z = Math::atan2(-elements[0][1], elements[0][0]);
  329. }
  330. } else {
  331. euler.x = -Math::atan2(elements[0][1], elements[1][1]);
  332. euler.y = -Math_PI / 2.0;
  333. euler.z = 0.0;
  334. }
  335. } else {
  336. euler.x = Math::atan2(elements[0][1], elements[1][1]);
  337. euler.y = Math_PI / 2.0;
  338. euler.z = 0.0;
  339. }
  340. return euler;
  341. }
  342. // set_euler_xyz expects a vector containing the Euler angles in the format
  343. // (ax,ay,az), where ax is the angle of rotation around x axis,
  344. // and similar for other axes.
  345. // The current implementation uses XYZ convention (Z is the first rotation).
  346. void Basis::set_euler_xyz(const Vector3 &p_euler) {
  347. real_t c, s;
  348. c = Math::cos(p_euler.x);
  349. s = Math::sin(p_euler.x);
  350. Basis xmat(1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c);
  351. c = Math::cos(p_euler.y);
  352. s = Math::sin(p_euler.y);
  353. Basis ymat(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c);
  354. c = Math::cos(p_euler.z);
  355. s = Math::sin(p_euler.z);
  356. Basis zmat(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0);
  357. //optimizer will optimize away all this anyway
  358. *this = xmat * (ymat * zmat);
  359. }
  360. // get_euler_yxz returns a vector containing the Euler angles in the YXZ convention,
  361. // as in first-Z, then-X, last-Y. The angles for X, Y, and Z rotations are returned
  362. // as the x, y, and z components of a Vector3 respectively.
  363. Vector3 Basis::get_euler_yxz() const {
  364. // Euler angles in YXZ convention.
  365. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  366. //
  367. // rot = cy*cz+sy*sx*sz cz*sy*sx-cy*sz cx*sy
  368. // cx*sz cx*cz -sx
  369. // cy*sx*sz-cz*sy cy*cz*sx+sy*sz cy*cx
  370. Vector3 euler;
  371. #ifdef MATH_CHECKS
  372. ERR_FAIL_COND_V(is_rotation() == false, euler);
  373. #endif
  374. real_t m12 = elements[1][2];
  375. if (m12 < 1) {
  376. if (m12 > -1) {
  377. // is this a pure X rotation?
  378. if (elements[1][0] == 0 && elements[0][1] == 0 && elements[0][2] == 0 && elements[2][0] == 0 && elements[0][0] == 1) {
  379. // return the simplest form (human friendlier in editor and scripts)
  380. euler.x = atan2(-m12, elements[1][1]);
  381. euler.y = 0;
  382. euler.z = 0;
  383. } else {
  384. euler.x = asin(-m12);
  385. euler.y = atan2(elements[0][2], elements[2][2]);
  386. euler.z = atan2(elements[1][0], elements[1][1]);
  387. }
  388. } else { // m12 == -1
  389. euler.x = Math_PI * 0.5;
  390. euler.y = -atan2(-elements[0][1], elements[0][0]);
  391. euler.z = 0;
  392. }
  393. } else { // m12 == 1
  394. euler.x = -Math_PI * 0.5;
  395. euler.y = -atan2(-elements[0][1], elements[0][0]);
  396. euler.z = 0;
  397. }
  398. return euler;
  399. }
  400. // set_euler_yxz expects a vector containing the Euler angles in the format
  401. // (ax,ay,az), where ax is the angle of rotation around x axis,
  402. // and similar for other axes.
  403. // The current implementation uses YXZ convention (Z is the first rotation).
  404. void Basis::set_euler_yxz(const Vector3 &p_euler) {
  405. real_t c, s;
  406. c = Math::cos(p_euler.x);
  407. s = Math::sin(p_euler.x);
  408. Basis xmat(1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c);
  409. c = Math::cos(p_euler.y);
  410. s = Math::sin(p_euler.y);
  411. Basis ymat(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c);
  412. c = Math::cos(p_euler.z);
  413. s = Math::sin(p_euler.z);
  414. Basis zmat(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0);
  415. //optimizer will optimize away all this anyway
  416. *this = ymat * xmat * zmat;
  417. }
  418. bool Basis::is_equal_approx(const Basis &a, const Basis &b) const {
  419. for (int i = 0; i < 3; i++) {
  420. for (int j = 0; j < 3; j++) {
  421. if (Math::is_equal_approx(a.elements[i][j], b.elements[i][j]) == false)
  422. return false;
  423. }
  424. }
  425. return true;
  426. }
  427. bool Basis::operator==(const Basis &p_matrix) const {
  428. for (int i = 0; i < 3; i++) {
  429. for (int j = 0; j < 3; j++) {
  430. if (elements[i][j] != p_matrix.elements[i][j])
  431. return false;
  432. }
  433. }
  434. return true;
  435. }
  436. bool Basis::operator!=(const Basis &p_matrix) const {
  437. return (!(*this == p_matrix));
  438. }
  439. Basis::operator String() const {
  440. String mtx;
  441. for (int i = 0; i < 3; i++) {
  442. for (int j = 0; j < 3; j++) {
  443. if (i != 0 || j != 0)
  444. mtx += ", ";
  445. mtx += rtos(elements[i][j]);
  446. }
  447. }
  448. return mtx;
  449. }
  450. Quat Basis::get_quat() const {
  451. //commenting this check because precision issues cause it to fail when it shouldn't
  452. //#ifdef MATH_CHECKS
  453. //ERR_FAIL_COND_V(is_rotation() == false, Quat());
  454. //#endif
  455. real_t trace = elements[0][0] + elements[1][1] + elements[2][2];
  456. real_t temp[4];
  457. if (trace > 0.0) {
  458. real_t s = Math::sqrt(trace + 1.0);
  459. temp[3] = (s * 0.5);
  460. s = 0.5 / s;
  461. temp[0] = ((elements[2][1] - elements[1][2]) * s);
  462. temp[1] = ((elements[0][2] - elements[2][0]) * s);
  463. temp[2] = ((elements[1][0] - elements[0][1]) * s);
  464. } else {
  465. int i = elements[0][0] < elements[1][1] ?
  466. (elements[1][1] < elements[2][2] ? 2 : 1) :
  467. (elements[0][0] < elements[2][2] ? 2 : 0);
  468. int j = (i + 1) % 3;
  469. int k = (i + 2) % 3;
  470. real_t s = Math::sqrt(elements[i][i] - elements[j][j] - elements[k][k] + 1.0);
  471. temp[i] = s * 0.5;
  472. s = 0.5 / s;
  473. temp[3] = (elements[k][j] - elements[j][k]) * s;
  474. temp[j] = (elements[j][i] + elements[i][j]) * s;
  475. temp[k] = (elements[k][i] + elements[i][k]) * s;
  476. }
  477. return Quat(temp[0], temp[1], temp[2], temp[3]);
  478. }
  479. static const Basis _ortho_bases[24] = {
  480. Basis(1, 0, 0, 0, 1, 0, 0, 0, 1),
  481. Basis(0, -1, 0, 1, 0, 0, 0, 0, 1),
  482. Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1),
  483. Basis(0, 1, 0, -1, 0, 0, 0, 0, 1),
  484. Basis(1, 0, 0, 0, 0, -1, 0, 1, 0),
  485. Basis(0, 0, 1, 1, 0, 0, 0, 1, 0),
  486. Basis(-1, 0, 0, 0, 0, 1, 0, 1, 0),
  487. Basis(0, 0, -1, -1, 0, 0, 0, 1, 0),
  488. Basis(1, 0, 0, 0, -1, 0, 0, 0, -1),
  489. Basis(0, 1, 0, 1, 0, 0, 0, 0, -1),
  490. Basis(-1, 0, 0, 0, 1, 0, 0, 0, -1),
  491. Basis(0, -1, 0, -1, 0, 0, 0, 0, -1),
  492. Basis(1, 0, 0, 0, 0, 1, 0, -1, 0),
  493. Basis(0, 0, -1, 1, 0, 0, 0, -1, 0),
  494. Basis(-1, 0, 0, 0, 0, -1, 0, -1, 0),
  495. Basis(0, 0, 1, -1, 0, 0, 0, -1, 0),
  496. Basis(0, 0, 1, 0, 1, 0, -1, 0, 0),
  497. Basis(0, -1, 0, 0, 0, 1, -1, 0, 0),
  498. Basis(0, 0, -1, 0, -1, 0, -1, 0, 0),
  499. Basis(0, 1, 0, 0, 0, -1, -1, 0, 0),
  500. Basis(0, 0, 1, 0, -1, 0, 1, 0, 0),
  501. Basis(0, 1, 0, 0, 0, 1, 1, 0, 0),
  502. Basis(0, 0, -1, 0, 1, 0, 1, 0, 0),
  503. Basis(0, -1, 0, 0, 0, -1, 1, 0, 0)
  504. };
  505. int Basis::get_orthogonal_index() const {
  506. //could be sped up if i come up with a way
  507. Basis orth = *this;
  508. for (int i = 0; i < 3; i++) {
  509. for (int j = 0; j < 3; j++) {
  510. real_t v = orth[i][j];
  511. if (v > 0.5)
  512. v = 1.0;
  513. else if (v < -0.5)
  514. v = -1.0;
  515. else
  516. v = 0;
  517. orth[i][j] = v;
  518. }
  519. }
  520. for (int i = 0; i < 24; i++) {
  521. if (_ortho_bases[i] == orth)
  522. return i;
  523. }
  524. return 0;
  525. }
  526. void Basis::set_orthogonal_index(int p_index) {
  527. //there only exist 24 orthogonal bases in r3
  528. ERR_FAIL_INDEX(p_index, 24);
  529. *this = _ortho_bases[p_index];
  530. }
  531. void Basis::get_axis_angle(Vector3 &r_axis, real_t &r_angle) const {
  532. #ifdef MATH_CHECKS
  533. ERR_FAIL_COND(is_rotation() == false);
  534. #endif
  535. real_t angle, x, y, z; // variables for result
  536. real_t epsilon = 0.01; // margin to allow for rounding errors
  537. real_t epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees
  538. if ((Math::abs(elements[1][0] - elements[0][1]) < epsilon) && (Math::abs(elements[2][0] - elements[0][2]) < epsilon) && (Math::abs(elements[2][1] - elements[1][2]) < epsilon)) {
  539. // singularity found
  540. // first check for identity matrix which must have +1 for all terms
  541. // in leading diagonaland zero in other terms
  542. if ((Math::abs(elements[1][0] + elements[0][1]) < epsilon2) && (Math::abs(elements[2][0] + elements[0][2]) < epsilon2) && (Math::abs(elements[2][1] + elements[1][2]) < epsilon2) && (Math::abs(elements[0][0] + elements[1][1] + elements[2][2] - 3) < epsilon2)) {
  543. // this singularity is identity matrix so angle = 0
  544. r_axis = Vector3(0, 1, 0);
  545. r_angle = 0;
  546. return;
  547. }
  548. // otherwise this singularity is angle = 180
  549. angle = Math_PI;
  550. real_t xx = (elements[0][0] + 1) / 2;
  551. real_t yy = (elements[1][1] + 1) / 2;
  552. real_t zz = (elements[2][2] + 1) / 2;
  553. real_t xy = (elements[1][0] + elements[0][1]) / 4;
  554. real_t xz = (elements[2][0] + elements[0][2]) / 4;
  555. real_t yz = (elements[2][1] + elements[1][2]) / 4;
  556. if ((xx > yy) && (xx > zz)) { // elements[0][0] is the largest diagonal term
  557. if (xx < epsilon) {
  558. x = 0;
  559. y = 0.7071;
  560. z = 0.7071;
  561. } else {
  562. x = Math::sqrt(xx);
  563. y = xy / x;
  564. z = xz / x;
  565. }
  566. } else if (yy > zz) { // elements[1][1] is the largest diagonal term
  567. if (yy < epsilon) {
  568. x = 0.7071;
  569. y = 0;
  570. z = 0.7071;
  571. } else {
  572. y = Math::sqrt(yy);
  573. x = xy / y;
  574. z = yz / y;
  575. }
  576. } else { // elements[2][2] is the largest diagonal term so base result on this
  577. if (zz < epsilon) {
  578. x = 0.7071;
  579. y = 0.7071;
  580. z = 0;
  581. } else {
  582. z = Math::sqrt(zz);
  583. x = xz / z;
  584. y = yz / z;
  585. }
  586. }
  587. r_axis = Vector3(x, y, z);
  588. r_angle = angle;
  589. return;
  590. }
  591. // as we have reached here there are no singularities so we can handle normally
  592. real_t s = Math::sqrt((elements[1][2] - elements[2][1]) * (elements[1][2] - elements[2][1]) + (elements[2][0] - elements[0][2]) * (elements[2][0] - elements[0][2]) + (elements[0][1] - elements[1][0]) * (elements[0][1] - elements[1][0])); // s=|axis||sin(angle)|, used to normalise
  593. angle = Math::acos((elements[0][0] + elements[1][1] + elements[2][2] - 1) / 2);
  594. if (angle < 0) s = -s;
  595. x = (elements[2][1] - elements[1][2]) / s;
  596. y = (elements[0][2] - elements[2][0]) / s;
  597. z = (elements[1][0] - elements[0][1]) / s;
  598. r_axis = Vector3(x, y, z);
  599. r_angle = angle;
  600. }
  601. void Basis::set_quat(const Quat &p_quat) {
  602. real_t d = p_quat.length_squared();
  603. real_t s = 2.0 / d;
  604. real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s;
  605. real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs;
  606. real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs;
  607. real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs;
  608. set(1.0 - (yy + zz), xy - wz, xz + wy,
  609. xy + wz, 1.0 - (xx + zz), yz - wx,
  610. xz - wy, yz + wx, 1.0 - (xx + yy));
  611. }
  612. void Basis::set_axis_angle(const Vector3 &p_axis, real_t p_phi) {
  613. // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_angle
  614. #ifdef MATH_CHECKS
  615. ERR_FAIL_COND(p_axis.is_normalized() == false);
  616. #endif
  617. Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z);
  618. real_t cosine = Math::cos(p_phi);
  619. real_t sine = Math::sin(p_phi);
  620. elements[0][0] = axis_sq.x + cosine * (1.0 - axis_sq.x);
  621. elements[0][1] = p_axis.x * p_axis.y * (1.0 - cosine) - p_axis.z * sine;
  622. elements[0][2] = p_axis.z * p_axis.x * (1.0 - cosine) + p_axis.y * sine;
  623. elements[1][0] = p_axis.x * p_axis.y * (1.0 - cosine) + p_axis.z * sine;
  624. elements[1][1] = axis_sq.y + cosine * (1.0 - axis_sq.y);
  625. elements[1][2] = p_axis.y * p_axis.z * (1.0 - cosine) - p_axis.x * sine;
  626. elements[2][0] = p_axis.z * p_axis.x * (1.0 - cosine) - p_axis.y * sine;
  627. elements[2][1] = p_axis.y * p_axis.z * (1.0 - cosine) + p_axis.x * sine;
  628. elements[2][2] = axis_sq.z + cosine * (1.0 - axis_sq.z);
  629. }