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