basis.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. /**************************************************************************/
  2. /* basis.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "basis.h"
  31. #include "core/math/math_funcs.h"
  32. #include "core/string/ustring.h"
  33. #define cofac(row1, col1, row2, col2) \
  34. (rows[row1][col1] * rows[row2][col2] - rows[row1][col2] * rows[row2][col1])
  35. void Basis::invert() {
  36. real_t co[3] = {
  37. cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)
  38. };
  39. real_t det = rows[0][0] * co[0] +
  40. rows[0][1] * co[1] +
  41. rows[0][2] * co[2];
  42. #ifdef MATH_CHECKS
  43. ERR_FAIL_COND(det == 0);
  44. #endif
  45. real_t s = 1.0f / det;
  46. set(co[0] * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
  47. co[1] * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
  48. co[2] * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
  49. }
  50. void Basis::orthonormalize() {
  51. // Gram-Schmidt Process
  52. Vector3 x = get_column(0);
  53. Vector3 y = get_column(1);
  54. Vector3 z = get_column(2);
  55. x.normalize();
  56. y = (y - x * (x.dot(y)));
  57. y.normalize();
  58. z = (z - x * (x.dot(z)) - y * (y.dot(z)));
  59. z.normalize();
  60. set_column(0, x);
  61. set_column(1, y);
  62. set_column(2, z);
  63. }
  64. Basis Basis::orthonormalized() const {
  65. Basis c = *this;
  66. c.orthonormalize();
  67. return c;
  68. }
  69. void Basis::orthogonalize() {
  70. Vector3 scl = get_scale();
  71. orthonormalize();
  72. scale_local(scl);
  73. }
  74. Basis Basis::orthogonalized() const {
  75. Basis c = *this;
  76. c.orthogonalize();
  77. return c;
  78. }
  79. bool Basis::is_orthogonal() const {
  80. Basis identity;
  81. Basis m = (*this) * transposed();
  82. return m.is_equal_approx(identity);
  83. }
  84. bool Basis::is_conformal() const {
  85. const Vector3 x = get_column(0);
  86. const Vector3 y = get_column(1);
  87. const Vector3 z = get_column(2);
  88. const real_t x_len_sq = x.length_squared();
  89. return Math::is_equal_approx(x_len_sq, y.length_squared()) && Math::is_equal_approx(x_len_sq, z.length_squared()) && Math::is_zero_approx(x.dot(y)) && Math::is_zero_approx(x.dot(z)) && Math::is_zero_approx(y.dot(z));
  90. }
  91. bool Basis::is_diagonal() const {
  92. return (
  93. Math::is_zero_approx(rows[0][1]) && Math::is_zero_approx(rows[0][2]) &&
  94. Math::is_zero_approx(rows[1][0]) && Math::is_zero_approx(rows[1][2]) &&
  95. Math::is_zero_approx(rows[2][0]) && Math::is_zero_approx(rows[2][1]));
  96. }
  97. bool Basis::is_rotation() const {
  98. return Math::is_equal_approx(determinant(), 1, (real_t)UNIT_EPSILON) && is_orthogonal();
  99. }
  100. #ifdef MATH_CHECKS
  101. // This method is only used once, in diagonalize. If it's desired elsewhere, feel free to remove the #ifdef.
  102. bool Basis::is_symmetric() const {
  103. if (!Math::is_equal_approx(rows[0][1], rows[1][0])) {
  104. return false;
  105. }
  106. if (!Math::is_equal_approx(rows[0][2], rows[2][0])) {
  107. return false;
  108. }
  109. if (!Math::is_equal_approx(rows[1][2], rows[2][1])) {
  110. return false;
  111. }
  112. return true;
  113. }
  114. #endif
  115. Basis Basis::diagonalize() {
  116. // NOTE: only implemented for symmetric matrices
  117. // with the Jacobi iterative method
  118. #ifdef MATH_CHECKS
  119. ERR_FAIL_COND_V(!is_symmetric(), Basis());
  120. #endif
  121. const int ite_max = 1024;
  122. real_t off_matrix_norm_2 = rows[0][1] * rows[0][1] + rows[0][2] * rows[0][2] + rows[1][2] * rows[1][2];
  123. int ite = 0;
  124. Basis acc_rot;
  125. while (off_matrix_norm_2 > (real_t)CMP_EPSILON2 && ite++ < ite_max) {
  126. real_t el01_2 = rows[0][1] * rows[0][1];
  127. real_t el02_2 = rows[0][2] * rows[0][2];
  128. real_t el12_2 = rows[1][2] * rows[1][2];
  129. // Find the pivot element
  130. int i, j;
  131. if (el01_2 > el02_2) {
  132. if (el12_2 > el01_2) {
  133. i = 1;
  134. j = 2;
  135. } else {
  136. i = 0;
  137. j = 1;
  138. }
  139. } else {
  140. if (el12_2 > el02_2) {
  141. i = 1;
  142. j = 2;
  143. } else {
  144. i = 0;
  145. j = 2;
  146. }
  147. }
  148. // Compute the rotation angle
  149. real_t angle;
  150. if (Math::is_equal_approx(rows[j][j], rows[i][i])) {
  151. angle = Math_PI / 4;
  152. } else {
  153. angle = 0.5f * Math::atan(2 * rows[i][j] / (rows[j][j] - rows[i][i]));
  154. }
  155. // Compute the rotation matrix
  156. Basis rot;
  157. rot.rows[i][i] = rot.rows[j][j] = Math::cos(angle);
  158. rot.rows[i][j] = -(rot.rows[j][i] = Math::sin(angle));
  159. // Update the off matrix norm
  160. off_matrix_norm_2 -= rows[i][j] * rows[i][j];
  161. // Apply the rotation
  162. *this = rot * *this * rot.transposed();
  163. acc_rot = rot * acc_rot;
  164. }
  165. return acc_rot;
  166. }
  167. Basis Basis::inverse() const {
  168. Basis inv = *this;
  169. inv.invert();
  170. return inv;
  171. }
  172. void Basis::transpose() {
  173. SWAP(rows[0][1], rows[1][0]);
  174. SWAP(rows[0][2], rows[2][0]);
  175. SWAP(rows[1][2], rows[2][1]);
  176. }
  177. Basis Basis::transposed() const {
  178. Basis tr = *this;
  179. tr.transpose();
  180. return tr;
  181. }
  182. Basis Basis::from_scale(const Vector3 &p_scale) {
  183. return Basis(p_scale.x, 0, 0, 0, p_scale.y, 0, 0, 0, p_scale.z);
  184. }
  185. // Multiplies the matrix from left by the scaling matrix: M -> S.M
  186. // See the comment for Basis::rotated for further explanation.
  187. void Basis::scale(const Vector3 &p_scale) {
  188. rows[0][0] *= p_scale.x;
  189. rows[0][1] *= p_scale.x;
  190. rows[0][2] *= p_scale.x;
  191. rows[1][0] *= p_scale.y;
  192. rows[1][1] *= p_scale.y;
  193. rows[1][2] *= p_scale.y;
  194. rows[2][0] *= p_scale.z;
  195. rows[2][1] *= p_scale.z;
  196. rows[2][2] *= p_scale.z;
  197. }
  198. Basis Basis::scaled(const Vector3 &p_scale) const {
  199. Basis m = *this;
  200. m.scale(p_scale);
  201. return m;
  202. }
  203. void Basis::scale_local(const Vector3 &p_scale) {
  204. // performs a scaling in object-local coordinate system:
  205. // M -> (M.S.Minv).M = M.S.
  206. *this = scaled_local(p_scale);
  207. }
  208. void Basis::scale_orthogonal(const Vector3 &p_scale) {
  209. *this = scaled_orthogonal(p_scale);
  210. }
  211. Basis Basis::scaled_orthogonal(const Vector3 &p_scale) const {
  212. Basis m = *this;
  213. Vector3 s = Vector3(-1, -1, -1) + p_scale;
  214. bool sign = signbit(s.x + s.y + s.z);
  215. Basis b = m.orthonormalized();
  216. s = b.xform_inv(s);
  217. Vector3 dots;
  218. for (int i = 0; i < 3; i++) {
  219. for (int j = 0; j < 3; j++) {
  220. dots[j] += s[i] * abs(m.get_column(i).normalized().dot(b.get_column(j)));
  221. }
  222. }
  223. if (sign != signbit(dots.x + dots.y + dots.z)) {
  224. dots = -dots;
  225. }
  226. m.scale_local(Vector3(1, 1, 1) + dots);
  227. return m;
  228. }
  229. float Basis::get_uniform_scale() const {
  230. return (rows[0].length() + rows[1].length() + rows[2].length()) / 3.0f;
  231. }
  232. Basis Basis::scaled_local(const Vector3 &p_scale) const {
  233. return (*this) * Basis::from_scale(p_scale);
  234. }
  235. Vector3 Basis::get_scale_abs() const {
  236. return Vector3(
  237. Vector3(rows[0][0], rows[1][0], rows[2][0]).length(),
  238. Vector3(rows[0][1], rows[1][1], rows[2][1]).length(),
  239. Vector3(rows[0][2], rows[1][2], rows[2][2]).length());
  240. }
  241. Vector3 Basis::get_scale_local() const {
  242. real_t det_sign = SIGN(determinant());
  243. return det_sign * Vector3(rows[0].length(), rows[1].length(), rows[2].length());
  244. }
  245. // get_scale works with get_rotation, use get_scale_abs if you need to enforce positive signature.
  246. Vector3 Basis::get_scale() const {
  247. // FIXME: We are assuming M = R.S (R is rotation and S is scaling), and use polar decomposition to extract R and S.
  248. // A polar decomposition is M = O.P, where O is an orthogonal matrix (meaning rotation and reflection) and
  249. // P is a positive semi-definite matrix (meaning it contains absolute values of scaling along its diagonal).
  250. //
  251. // Despite being different from what we want to achieve, we can nevertheless make use of polar decomposition
  252. // here as follows. We can split O into a rotation and a reflection as O = R.Q, and obtain M = R.S where
  253. // we defined S = Q.P. Now, R is a proper rotation matrix and S is a (signed) scaling matrix,
  254. // which can involve negative scalings. However, there is a catch: unlike the polar decomposition of M = O.P,
  255. // the decomposition of O into a rotation and reflection matrix as O = R.Q is not unique.
  256. // Therefore, we are going to do this decomposition by sticking to a particular convention.
  257. // This may lead to confusion for some users though.
  258. //
  259. // The convention we use here is to absorb the sign flip into the scaling matrix.
  260. // The same convention is also used in other similar functions such as get_rotation_axis_angle, get_rotation, ...
  261. //
  262. // A proper way to get rid of this issue would be to store the scaling values (or at least their signs)
  263. // as a part of Basis. However, if we go that path, we need to disable direct (write) access to the
  264. // matrix elements.
  265. //
  266. // The rotation part of this decomposition is returned by get_rotation* functions.
  267. real_t det_sign = SIGN(determinant());
  268. return det_sign * get_scale_abs();
  269. }
  270. // Decomposes a Basis into a rotation-reflection matrix (an element of the group O(3)) and a positive scaling matrix as B = O.S.
  271. // Returns the rotation-reflection matrix via reference argument, and scaling information is returned as a Vector3.
  272. // This (internal) function is too specific and named too ugly to expose to users, and probably there's no need to do so.
  273. Vector3 Basis::rotref_posscale_decomposition(Basis &rotref) const {
  274. #ifdef MATH_CHECKS
  275. ERR_FAIL_COND_V(determinant() == 0, Vector3());
  276. Basis m = transposed() * (*this);
  277. ERR_FAIL_COND_V(!m.is_diagonal(), Vector3());
  278. #endif
  279. Vector3 scale = get_scale();
  280. Basis inv_scale = Basis().scaled(scale.inverse()); // this will also absorb the sign of scale
  281. rotref = (*this) * inv_scale;
  282. #ifdef MATH_CHECKS
  283. ERR_FAIL_COND_V(!rotref.is_orthogonal(), Vector3());
  284. #endif
  285. return scale.abs();
  286. }
  287. // Multiplies the matrix from left by the rotation matrix: M -> R.M
  288. // Note that this does *not* rotate the matrix itself.
  289. //
  290. // The main use of Basis is as Transform.basis, which is used by the transformation matrix
  291. // of 3D object. Rotate here refers to rotation of the object (which is R * (*this)),
  292. // not the matrix itself (which is R * (*this) * R.transposed()).
  293. Basis Basis::rotated(const Vector3 &p_axis, real_t p_angle) const {
  294. return Basis(p_axis, p_angle) * (*this);
  295. }
  296. void Basis::rotate(const Vector3 &p_axis, real_t p_angle) {
  297. *this = rotated(p_axis, p_angle);
  298. }
  299. void Basis::rotate_local(const Vector3 &p_axis, real_t p_angle) {
  300. // performs a rotation in object-local coordinate system:
  301. // M -> (M.R.Minv).M = M.R.
  302. *this = rotated_local(p_axis, p_angle);
  303. }
  304. Basis Basis::rotated_local(const Vector3 &p_axis, real_t p_angle) const {
  305. return (*this) * Basis(p_axis, p_angle);
  306. }
  307. Basis Basis::rotated(const Vector3 &p_euler, EulerOrder p_order) const {
  308. return Basis::from_euler(p_euler, p_order) * (*this);
  309. }
  310. void Basis::rotate(const Vector3 &p_euler, EulerOrder p_order) {
  311. *this = rotated(p_euler, p_order);
  312. }
  313. Basis Basis::rotated(const Quaternion &p_quaternion) const {
  314. return Basis(p_quaternion) * (*this);
  315. }
  316. void Basis::rotate(const Quaternion &p_quaternion) {
  317. *this = rotated(p_quaternion);
  318. }
  319. Vector3 Basis::get_euler_normalized(EulerOrder p_order) const {
  320. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  321. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  322. // See the comment in get_scale() for further information.
  323. Basis m = orthonormalized();
  324. real_t det = m.determinant();
  325. if (det < 0) {
  326. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  327. m.scale(Vector3(-1, -1, -1));
  328. }
  329. return m.get_euler(p_order);
  330. }
  331. Quaternion Basis::get_rotation_quaternion() const {
  332. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  333. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  334. // See the comment in get_scale() for further information.
  335. Basis m = orthonormalized();
  336. real_t det = m.determinant();
  337. if (det < 0) {
  338. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  339. m.scale(Vector3(-1, -1, -1));
  340. }
  341. return m.get_quaternion();
  342. }
  343. void Basis::rotate_to_align(Vector3 p_start_direction, Vector3 p_end_direction) {
  344. // Takes two vectors and rotates the basis from the first vector to the second vector.
  345. // Adopted from: https://gist.github.com/kevinmoran/b45980723e53edeb8a5a43c49f134724
  346. const Vector3 axis = p_start_direction.cross(p_end_direction).normalized();
  347. if (axis.length_squared() != 0) {
  348. real_t dot = p_start_direction.dot(p_end_direction);
  349. dot = CLAMP(dot, -1.0f, 1.0f);
  350. const real_t angle_rads = Math::acos(dot);
  351. *this = Basis(axis, angle_rads) * (*this);
  352. }
  353. }
  354. void Basis::get_rotation_axis_angle(Vector3 &p_axis, real_t &p_angle) const {
  355. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  356. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  357. // See the comment in get_scale() for further information.
  358. Basis m = orthonormalized();
  359. real_t det = m.determinant();
  360. if (det < 0) {
  361. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  362. m.scale(Vector3(-1, -1, -1));
  363. }
  364. m.get_axis_angle(p_axis, p_angle);
  365. }
  366. void Basis::get_rotation_axis_angle_local(Vector3 &p_axis, real_t &p_angle) const {
  367. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  368. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  369. // See the comment in get_scale() for further information.
  370. Basis m = transposed();
  371. m.orthonormalize();
  372. real_t det = m.determinant();
  373. if (det < 0) {
  374. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  375. m.scale(Vector3(-1, -1, -1));
  376. }
  377. m.get_axis_angle(p_axis, p_angle);
  378. p_angle = -p_angle;
  379. }
  380. Vector3 Basis::get_euler(EulerOrder p_order) const {
  381. switch (p_order) {
  382. case EulerOrder::XYZ: {
  383. // Euler angles in XYZ convention.
  384. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  385. //
  386. // rot = cy*cz -cy*sz sy
  387. // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
  388. // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
  389. Vector3 euler;
  390. real_t sy = rows[0][2];
  391. if (sy < (1.0f - (real_t)CMP_EPSILON)) {
  392. if (sy > -(1.0f - (real_t)CMP_EPSILON)) {
  393. // is this a pure Y rotation?
  394. if (rows[1][0] == 0 && rows[0][1] == 0 && rows[1][2] == 0 && rows[2][1] == 0 && rows[1][1] == 1) {
  395. // return the simplest form (human friendlier in editor and scripts)
  396. euler.x = 0;
  397. euler.y = atan2(rows[0][2], rows[0][0]);
  398. euler.z = 0;
  399. } else {
  400. euler.x = Math::atan2(-rows[1][2], rows[2][2]);
  401. euler.y = Math::asin(sy);
  402. euler.z = Math::atan2(-rows[0][1], rows[0][0]);
  403. }
  404. } else {
  405. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  406. euler.y = -Math_PI / 2.0f;
  407. euler.z = 0.0f;
  408. }
  409. } else {
  410. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  411. euler.y = Math_PI / 2.0f;
  412. euler.z = 0.0f;
  413. }
  414. return euler;
  415. }
  416. case EulerOrder::XZY: {
  417. // Euler angles in XZY convention.
  418. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  419. //
  420. // rot = cz*cy -sz cz*sy
  421. // sx*sy+cx*cy*sz cx*cz cx*sz*sy-cy*sx
  422. // cy*sx*sz cz*sx cx*cy+sx*sz*sy
  423. Vector3 euler;
  424. real_t sz = rows[0][1];
  425. if (sz < (1.0f - (real_t)CMP_EPSILON)) {
  426. if (sz > -(1.0f - (real_t)CMP_EPSILON)) {
  427. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  428. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  429. euler.z = Math::asin(-sz);
  430. } else {
  431. // It's -1
  432. euler.x = -Math::atan2(rows[1][2], rows[2][2]);
  433. euler.y = 0.0f;
  434. euler.z = Math_PI / 2.0f;
  435. }
  436. } else {
  437. // It's 1
  438. euler.x = -Math::atan2(rows[1][2], rows[2][2]);
  439. euler.y = 0.0f;
  440. euler.z = -Math_PI / 2.0f;
  441. }
  442. return euler;
  443. }
  444. case EulerOrder::YXZ: {
  445. // Euler angles in YXZ convention.
  446. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  447. //
  448. // rot = cy*cz+sy*sx*sz cz*sy*sx-cy*sz cx*sy
  449. // cx*sz cx*cz -sx
  450. // cy*sx*sz-cz*sy cy*cz*sx+sy*sz cy*cx
  451. Vector3 euler;
  452. real_t m12 = rows[1][2];
  453. if (m12 < (1 - (real_t)CMP_EPSILON)) {
  454. if (m12 > -(1 - (real_t)CMP_EPSILON)) {
  455. // is this a pure X rotation?
  456. if (rows[1][0] == 0 && rows[0][1] == 0 && rows[0][2] == 0 && rows[2][0] == 0 && rows[0][0] == 1) {
  457. // return the simplest form (human friendlier in editor and scripts)
  458. euler.x = atan2(-m12, rows[1][1]);
  459. euler.y = 0;
  460. euler.z = 0;
  461. } else {
  462. euler.x = asin(-m12);
  463. euler.y = atan2(rows[0][2], rows[2][2]);
  464. euler.z = atan2(rows[1][0], rows[1][1]);
  465. }
  466. } else { // m12 == -1
  467. euler.x = Math_PI * 0.5f;
  468. euler.y = atan2(rows[0][1], rows[0][0]);
  469. euler.z = 0;
  470. }
  471. } else { // m12 == 1
  472. euler.x = -Math_PI * 0.5f;
  473. euler.y = -atan2(rows[0][1], rows[0][0]);
  474. euler.z = 0;
  475. }
  476. return euler;
  477. }
  478. case EulerOrder::YZX: {
  479. // Euler angles in YZX convention.
  480. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  481. //
  482. // rot = cy*cz sy*sx-cy*cx*sz cx*sy+cy*sz*sx
  483. // sz cz*cx -cz*sx
  484. // -cz*sy cy*sx+cx*sy*sz cy*cx-sy*sz*sx
  485. Vector3 euler;
  486. real_t sz = rows[1][0];
  487. if (sz < (1.0f - (real_t)CMP_EPSILON)) {
  488. if (sz > -(1.0f - (real_t)CMP_EPSILON)) {
  489. euler.x = Math::atan2(-rows[1][2], rows[1][1]);
  490. euler.y = Math::atan2(-rows[2][0], rows[0][0]);
  491. euler.z = Math::asin(sz);
  492. } else {
  493. // It's -1
  494. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  495. euler.y = 0.0f;
  496. euler.z = -Math_PI / 2.0f;
  497. }
  498. } else {
  499. // It's 1
  500. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  501. euler.y = 0.0f;
  502. euler.z = Math_PI / 2.0f;
  503. }
  504. return euler;
  505. } break;
  506. case EulerOrder::ZXY: {
  507. // Euler angles in ZXY convention.
  508. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  509. //
  510. // rot = cz*cy-sz*sx*sy -cx*sz cz*sy+cy*sz*sx
  511. // cy*sz+cz*sx*sy cz*cx sz*sy-cz*cy*sx
  512. // -cx*sy sx cx*cy
  513. Vector3 euler;
  514. real_t sx = rows[2][1];
  515. if (sx < (1.0f - (real_t)CMP_EPSILON)) {
  516. if (sx > -(1.0f - (real_t)CMP_EPSILON)) {
  517. euler.x = Math::asin(sx);
  518. euler.y = Math::atan2(-rows[2][0], rows[2][2]);
  519. euler.z = Math::atan2(-rows[0][1], rows[1][1]);
  520. } else {
  521. // It's -1
  522. euler.x = -Math_PI / 2.0f;
  523. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  524. euler.z = 0;
  525. }
  526. } else {
  527. // It's 1
  528. euler.x = Math_PI / 2.0f;
  529. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  530. euler.z = 0;
  531. }
  532. return euler;
  533. } break;
  534. case EulerOrder::ZYX: {
  535. // Euler angles in ZYX convention.
  536. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  537. //
  538. // rot = cz*cy cz*sy*sx-cx*sz sz*sx+cz*cx*cy
  539. // cy*sz cz*cx+sz*sy*sx cx*sz*sy-cz*sx
  540. // -sy cy*sx cy*cx
  541. Vector3 euler;
  542. real_t sy = rows[2][0];
  543. if (sy < (1.0f - (real_t)CMP_EPSILON)) {
  544. if (sy > -(1.0f - (real_t)CMP_EPSILON)) {
  545. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  546. euler.y = Math::asin(-sy);
  547. euler.z = Math::atan2(rows[1][0], rows[0][0]);
  548. } else {
  549. // It's -1
  550. euler.x = 0;
  551. euler.y = Math_PI / 2.0f;
  552. euler.z = -Math::atan2(rows[0][1], rows[1][1]);
  553. }
  554. } else {
  555. // It's 1
  556. euler.x = 0;
  557. euler.y = -Math_PI / 2.0f;
  558. euler.z = -Math::atan2(rows[0][1], rows[1][1]);
  559. }
  560. return euler;
  561. }
  562. default: {
  563. ERR_FAIL_V_MSG(Vector3(), "Invalid parameter for get_euler(order)");
  564. }
  565. }
  566. return Vector3();
  567. }
  568. void Basis::set_euler(const Vector3 &p_euler, EulerOrder p_order) {
  569. real_t c, s;
  570. c = Math::cos(p_euler.x);
  571. s = Math::sin(p_euler.x);
  572. Basis xmat(1, 0, 0, 0, c, -s, 0, s, c);
  573. c = Math::cos(p_euler.y);
  574. s = Math::sin(p_euler.y);
  575. Basis ymat(c, 0, s, 0, 1, 0, -s, 0, c);
  576. c = Math::cos(p_euler.z);
  577. s = Math::sin(p_euler.z);
  578. Basis zmat(c, -s, 0, s, c, 0, 0, 0, 1);
  579. switch (p_order) {
  580. case EulerOrder::XYZ: {
  581. *this = xmat * (ymat * zmat);
  582. } break;
  583. case EulerOrder::XZY: {
  584. *this = xmat * zmat * ymat;
  585. } break;
  586. case EulerOrder::YXZ: {
  587. *this = ymat * xmat * zmat;
  588. } break;
  589. case EulerOrder::YZX: {
  590. *this = ymat * zmat * xmat;
  591. } break;
  592. case EulerOrder::ZXY: {
  593. *this = zmat * xmat * ymat;
  594. } break;
  595. case EulerOrder::ZYX: {
  596. *this = zmat * ymat * xmat;
  597. } break;
  598. default: {
  599. ERR_FAIL_MSG("Invalid order parameter for set_euler(vec3,order)");
  600. }
  601. }
  602. }
  603. bool Basis::is_equal_approx(const Basis &p_basis) const {
  604. return rows[0].is_equal_approx(p_basis.rows[0]) && rows[1].is_equal_approx(p_basis.rows[1]) && rows[2].is_equal_approx(p_basis.rows[2]);
  605. }
  606. bool Basis::is_finite() const {
  607. return rows[0].is_finite() && rows[1].is_finite() && rows[2].is_finite();
  608. }
  609. bool Basis::operator==(const Basis &p_matrix) const {
  610. for (int i = 0; i < 3; i++) {
  611. for (int j = 0; j < 3; j++) {
  612. if (rows[i][j] != p_matrix.rows[i][j]) {
  613. return false;
  614. }
  615. }
  616. }
  617. return true;
  618. }
  619. bool Basis::operator!=(const Basis &p_matrix) const {
  620. return (!(*this == p_matrix));
  621. }
  622. Basis::operator String() const {
  623. return "[X: " + get_column(0).operator String() +
  624. ", Y: " + get_column(1).operator String() +
  625. ", Z: " + get_column(2).operator String() + "]";
  626. }
  627. Quaternion Basis::get_quaternion() const {
  628. #ifdef MATH_CHECKS
  629. ERR_FAIL_COND_V_MSG(!is_rotation(), Quaternion(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quaternion() or call orthonormalized() if the Basis contains linearly independent vectors.");
  630. #endif
  631. /* Allow getting a quaternion from an unnormalized transform */
  632. Basis m = *this;
  633. real_t trace = m.rows[0][0] + m.rows[1][1] + m.rows[2][2];
  634. real_t temp[4];
  635. if (trace > 0.0f) {
  636. real_t s = Math::sqrt(trace + 1.0f);
  637. temp[3] = (s * 0.5f);
  638. s = 0.5f / s;
  639. temp[0] = ((m.rows[2][1] - m.rows[1][2]) * s);
  640. temp[1] = ((m.rows[0][2] - m.rows[2][0]) * s);
  641. temp[2] = ((m.rows[1][0] - m.rows[0][1]) * s);
  642. } else {
  643. int i = m.rows[0][0] < m.rows[1][1]
  644. ? (m.rows[1][1] < m.rows[2][2] ? 2 : 1)
  645. : (m.rows[0][0] < m.rows[2][2] ? 2 : 0);
  646. int j = (i + 1) % 3;
  647. int k = (i + 2) % 3;
  648. real_t s = Math::sqrt(m.rows[i][i] - m.rows[j][j] - m.rows[k][k] + 1.0f);
  649. temp[i] = s * 0.5f;
  650. s = 0.5f / s;
  651. temp[3] = (m.rows[k][j] - m.rows[j][k]) * s;
  652. temp[j] = (m.rows[j][i] + m.rows[i][j]) * s;
  653. temp[k] = (m.rows[k][i] + m.rows[i][k]) * s;
  654. }
  655. return Quaternion(temp[0], temp[1], temp[2], temp[3]);
  656. }
  657. void Basis::get_axis_angle(Vector3 &r_axis, real_t &r_angle) const {
  658. /* checking this is a bad idea, because obtaining from scaled transform is a valid use case
  659. #ifdef MATH_CHECKS
  660. ERR_FAIL_COND(!is_rotation());
  661. #endif
  662. */
  663. // https://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  664. real_t x, y, z; // Variables for result.
  665. if (Math::is_zero_approx(rows[0][1] - rows[1][0]) && Math::is_zero_approx(rows[0][2] - rows[2][0]) && Math::is_zero_approx(rows[1][2] - rows[2][1])) {
  666. // Singularity found.
  667. // First check for identity matrix which must have +1 for all terms in leading diagonal and zero in other terms.
  668. if (is_diagonal() && (Math::abs(rows[0][0] + rows[1][1] + rows[2][2] - 3) < 3 * CMP_EPSILON)) {
  669. // This singularity is identity matrix so angle = 0.
  670. r_axis = Vector3(0, 1, 0);
  671. r_angle = 0;
  672. return;
  673. }
  674. // Otherwise this singularity is angle = 180.
  675. real_t xx = (rows[0][0] + 1) / 2;
  676. real_t yy = (rows[1][1] + 1) / 2;
  677. real_t zz = (rows[2][2] + 1) / 2;
  678. real_t xy = (rows[0][1] + rows[1][0]) / 4;
  679. real_t xz = (rows[0][2] + rows[2][0]) / 4;
  680. real_t yz = (rows[1][2] + rows[2][1]) / 4;
  681. if ((xx > yy) && (xx > zz)) { // rows[0][0] is the largest diagonal term.
  682. if (xx < CMP_EPSILON) {
  683. x = 0;
  684. y = Math_SQRT12;
  685. z = Math_SQRT12;
  686. } else {
  687. x = Math::sqrt(xx);
  688. y = xy / x;
  689. z = xz / x;
  690. }
  691. } else if (yy > zz) { // rows[1][1] is the largest diagonal term.
  692. if (yy < CMP_EPSILON) {
  693. x = Math_SQRT12;
  694. y = 0;
  695. z = Math_SQRT12;
  696. } else {
  697. y = Math::sqrt(yy);
  698. x = xy / y;
  699. z = yz / y;
  700. }
  701. } else { // rows[2][2] is the largest diagonal term so base result on this.
  702. if (zz < CMP_EPSILON) {
  703. x = Math_SQRT12;
  704. y = Math_SQRT12;
  705. z = 0;
  706. } else {
  707. z = Math::sqrt(zz);
  708. x = xz / z;
  709. y = yz / z;
  710. }
  711. }
  712. r_axis = Vector3(x, y, z);
  713. r_angle = Math_PI;
  714. return;
  715. }
  716. // As we have reached here there are no singularities so we can handle normally.
  717. double s = Math::sqrt((rows[2][1] - rows[1][2]) * (rows[2][1] - rows[1][2]) + (rows[0][2] - rows[2][0]) * (rows[0][2] - rows[2][0]) + (rows[1][0] - rows[0][1]) * (rows[1][0] - rows[0][1])); // Used to normalize.
  718. if (Math::abs(s) < CMP_EPSILON) {
  719. // Prevent divide by zero, should not happen if matrix is orthogonal and should be caught by singularity test above.
  720. s = 1;
  721. }
  722. x = (rows[2][1] - rows[1][2]) / s;
  723. y = (rows[0][2] - rows[2][0]) / s;
  724. z = (rows[1][0] - rows[0][1]) / s;
  725. r_axis = Vector3(x, y, z);
  726. // acos does clamping.
  727. r_angle = Math::acos((rows[0][0] + rows[1][1] + rows[2][2] - 1) / 2);
  728. }
  729. void Basis::set_quaternion(const Quaternion &p_quaternion) {
  730. real_t d = p_quaternion.length_squared();
  731. real_t s = 2.0f / d;
  732. real_t xs = p_quaternion.x * s, ys = p_quaternion.y * s, zs = p_quaternion.z * s;
  733. real_t wx = p_quaternion.w * xs, wy = p_quaternion.w * ys, wz = p_quaternion.w * zs;
  734. real_t xx = p_quaternion.x * xs, xy = p_quaternion.x * ys, xz = p_quaternion.x * zs;
  735. real_t yy = p_quaternion.y * ys, yz = p_quaternion.y * zs, zz = p_quaternion.z * zs;
  736. set(1.0f - (yy + zz), xy - wz, xz + wy,
  737. xy + wz, 1.0f - (xx + zz), yz - wx,
  738. xz - wy, yz + wx, 1.0f - (xx + yy));
  739. }
  740. void Basis::set_axis_angle(const Vector3 &p_axis, real_t p_angle) {
  741. // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_angle
  742. #ifdef MATH_CHECKS
  743. ERR_FAIL_COND_MSG(!p_axis.is_normalized(), "The axis Vector3 must be normalized.");
  744. #endif
  745. Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z);
  746. real_t cosine = Math::cos(p_angle);
  747. rows[0][0] = axis_sq.x + cosine * (1.0f - axis_sq.x);
  748. rows[1][1] = axis_sq.y + cosine * (1.0f - axis_sq.y);
  749. rows[2][2] = axis_sq.z + cosine * (1.0f - axis_sq.z);
  750. real_t sine = Math::sin(p_angle);
  751. real_t t = 1 - cosine;
  752. real_t xyzt = p_axis.x * p_axis.y * t;
  753. real_t zyxs = p_axis.z * sine;
  754. rows[0][1] = xyzt - zyxs;
  755. rows[1][0] = xyzt + zyxs;
  756. xyzt = p_axis.x * p_axis.z * t;
  757. zyxs = p_axis.y * sine;
  758. rows[0][2] = xyzt + zyxs;
  759. rows[2][0] = xyzt - zyxs;
  760. xyzt = p_axis.y * p_axis.z * t;
  761. zyxs = p_axis.x * sine;
  762. rows[1][2] = xyzt - zyxs;
  763. rows[2][1] = xyzt + zyxs;
  764. }
  765. void Basis::set_axis_angle_scale(const Vector3 &p_axis, real_t p_angle, const Vector3 &p_scale) {
  766. _set_diagonal(p_scale);
  767. rotate(p_axis, p_angle);
  768. }
  769. void Basis::set_euler_scale(const Vector3 &p_euler, const Vector3 &p_scale, EulerOrder p_order) {
  770. _set_diagonal(p_scale);
  771. rotate(p_euler, p_order);
  772. }
  773. void Basis::set_quaternion_scale(const Quaternion &p_quaternion, const Vector3 &p_scale) {
  774. _set_diagonal(p_scale);
  775. rotate(p_quaternion);
  776. }
  777. // This also sets the non-diagonal elements to 0, which is misleading from the
  778. // name, so we want this method to be private. Use `from_scale` externally.
  779. void Basis::_set_diagonal(const Vector3 &p_diag) {
  780. rows[0][0] = p_diag.x;
  781. rows[0][1] = 0;
  782. rows[0][2] = 0;
  783. rows[1][0] = 0;
  784. rows[1][1] = p_diag.y;
  785. rows[1][2] = 0;
  786. rows[2][0] = 0;
  787. rows[2][1] = 0;
  788. rows[2][2] = p_diag.z;
  789. }
  790. Basis Basis::lerp(const Basis &p_to, const real_t &p_weight) const {
  791. Basis b;
  792. b.rows[0] = rows[0].lerp(p_to.rows[0], p_weight);
  793. b.rows[1] = rows[1].lerp(p_to.rows[1], p_weight);
  794. b.rows[2] = rows[2].lerp(p_to.rows[2], p_weight);
  795. return b;
  796. }
  797. Basis Basis::slerp(const Basis &p_to, const real_t &p_weight) const {
  798. //consider scale
  799. Quaternion from(*this);
  800. Quaternion to(p_to);
  801. Basis b(from.slerp(to, p_weight));
  802. b.rows[0] *= Math::lerp(rows[0].length(), p_to.rows[0].length(), p_weight);
  803. b.rows[1] *= Math::lerp(rows[1].length(), p_to.rows[1].length(), p_weight);
  804. b.rows[2] *= Math::lerp(rows[2].length(), p_to.rows[2].length(), p_weight);
  805. return b;
  806. }
  807. void Basis::rotate_sh(real_t *p_values) {
  808. // code by John Hable
  809. // http://filmicworlds.com/blog/simple-and-fast-spherical-harmonic-rotation/
  810. // this code is Public Domain
  811. const static real_t s_c3 = 0.94617469575; // (3*sqrt(5))/(4*sqrt(pi))
  812. const static real_t s_c4 = -0.31539156525; // (-sqrt(5))/(4*sqrt(pi))
  813. const static real_t s_c5 = 0.54627421529; // (sqrt(15))/(4*sqrt(pi))
  814. const static real_t s_c_scale = 1.0 / 0.91529123286551084;
  815. const static real_t s_c_scale_inv = 0.91529123286551084;
  816. const static real_t s_rc2 = 1.5853309190550713 * s_c_scale;
  817. const static real_t s_c4_div_c3 = s_c4 / s_c3;
  818. const static real_t s_c4_div_c3_x2 = (s_c4 / s_c3) * 2.0;
  819. const static real_t s_scale_dst2 = s_c3 * s_c_scale_inv;
  820. const static real_t s_scale_dst4 = s_c5 * s_c_scale_inv;
  821. const real_t src[9] = { p_values[0], p_values[1], p_values[2], p_values[3], p_values[4], p_values[5], p_values[6], p_values[7], p_values[8] };
  822. real_t m00 = rows[0][0];
  823. real_t m01 = rows[0][1];
  824. real_t m02 = rows[0][2];
  825. real_t m10 = rows[1][0];
  826. real_t m11 = rows[1][1];
  827. real_t m12 = rows[1][2];
  828. real_t m20 = rows[2][0];
  829. real_t m21 = rows[2][1];
  830. real_t m22 = rows[2][2];
  831. p_values[0] = src[0];
  832. p_values[1] = m11 * src[1] - m12 * src[2] + m10 * src[3];
  833. p_values[2] = -m21 * src[1] + m22 * src[2] - m20 * src[3];
  834. p_values[3] = m01 * src[1] - m02 * src[2] + m00 * src[3];
  835. real_t sh0 = src[7] + src[8] + src[8] - src[5];
  836. real_t sh1 = src[4] + s_rc2 * src[6] + src[7] + src[8];
  837. real_t sh2 = src[4];
  838. real_t sh3 = -src[7];
  839. real_t sh4 = -src[5];
  840. // Rotations. R0 and R1 just use the raw matrix columns
  841. real_t r2x = m00 + m01;
  842. real_t r2y = m10 + m11;
  843. real_t r2z = m20 + m21;
  844. real_t r3x = m00 + m02;
  845. real_t r3y = m10 + m12;
  846. real_t r3z = m20 + m22;
  847. real_t r4x = m01 + m02;
  848. real_t r4y = m11 + m12;
  849. real_t r4z = m21 + m22;
  850. // dense matrix multiplication one column at a time
  851. // column 0
  852. real_t sh0_x = sh0 * m00;
  853. real_t sh0_y = sh0 * m10;
  854. real_t d0 = sh0_x * m10;
  855. real_t d1 = sh0_y * m20;
  856. real_t d2 = sh0 * (m20 * m20 + s_c4_div_c3);
  857. real_t d3 = sh0_x * m20;
  858. real_t d4 = sh0_x * m00 - sh0_y * m10;
  859. // column 1
  860. real_t sh1_x = sh1 * m02;
  861. real_t sh1_y = sh1 * m12;
  862. d0 += sh1_x * m12;
  863. d1 += sh1_y * m22;
  864. d2 += sh1 * (m22 * m22 + s_c4_div_c3);
  865. d3 += sh1_x * m22;
  866. d4 += sh1_x * m02 - sh1_y * m12;
  867. // column 2
  868. real_t sh2_x = sh2 * r2x;
  869. real_t sh2_y = sh2 * r2y;
  870. d0 += sh2_x * r2y;
  871. d1 += sh2_y * r2z;
  872. d2 += sh2 * (r2z * r2z + s_c4_div_c3_x2);
  873. d3 += sh2_x * r2z;
  874. d4 += sh2_x * r2x - sh2_y * r2y;
  875. // column 3
  876. real_t sh3_x = sh3 * r3x;
  877. real_t sh3_y = sh3 * r3y;
  878. d0 += sh3_x * r3y;
  879. d1 += sh3_y * r3z;
  880. d2 += sh3 * (r3z * r3z + s_c4_div_c3_x2);
  881. d3 += sh3_x * r3z;
  882. d4 += sh3_x * r3x - sh3_y * r3y;
  883. // column 4
  884. real_t sh4_x = sh4 * r4x;
  885. real_t sh4_y = sh4 * r4y;
  886. d0 += sh4_x * r4y;
  887. d1 += sh4_y * r4z;
  888. d2 += sh4 * (r4z * r4z + s_c4_div_c3_x2);
  889. d3 += sh4_x * r4z;
  890. d4 += sh4_x * r4x - sh4_y * r4y;
  891. // extra multipliers
  892. p_values[4] = d0;
  893. p_values[5] = -d1;
  894. p_values[6] = d2 * s_scale_dst2;
  895. p_values[7] = -d3;
  896. p_values[8] = d4 * s_scale_dst4;
  897. }
  898. Basis Basis::looking_at(const Vector3 &p_target, const Vector3 &p_up, bool p_use_model_front) {
  899. #ifdef MATH_CHECKS
  900. ERR_FAIL_COND_V_MSG(p_target.is_zero_approx(), Basis(), "The target vector can't be zero.");
  901. ERR_FAIL_COND_V_MSG(p_up.is_zero_approx(), Basis(), "The up vector can't be zero.");
  902. #endif
  903. Vector3 v_z = p_target.normalized();
  904. if (!p_use_model_front) {
  905. v_z = -v_z;
  906. }
  907. Vector3 v_x = p_up.cross(v_z);
  908. #ifdef MATH_CHECKS
  909. ERR_FAIL_COND_V_MSG(v_x.is_zero_approx(), Basis(), "The target vector and up vector can't be parallel to each other.");
  910. #endif
  911. v_x.normalize();
  912. Vector3 v_y = v_z.cross(v_x);
  913. Basis basis;
  914. basis.set_columns(v_x, v_y, v_z);
  915. return basis;
  916. }