1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.commons.math.geometry; 19 20 import java.io.Serializable; 21 22 /** 23 * This class implements rotations in a three-dimensional space. 24 * 25 * <p>Rotations can be represented by several different mathematical 26 * entities (matrices, axe and angle, Cardan or Euler angles, 27 * quaternions). This class presents an higher level abstraction, more 28 * user-oriented and hiding this implementation details. Well, for the 29 * curious, we use quaternions for the internal representation. The 30 * user can build a rotation from any of these representations, and 31 * any of these representations can be retrieved from a 32 * <code>Rotation</code> instance (see the various constructors and 33 * getters). In addition, a rotation can also be built implicitely 34 * from a set of vectors and their image.</p> 35 * <p>This implies that this class can be used to convert from one 36 * representation to another one. For example, converting a rotation 37 * matrix into a set of Cardan angles from can be done using the 38 * followong single line of code:</p> 39 * <pre> 40 * double[] angles = new Rotation(matrix, 1.0e-10).getAngles(RotationOrder.XYZ); 41 * </pre> 42 * <p>Focus is oriented on what a rotation <em>do</em> rather than on its 43 * underlying representation. Once it has been built, and regardless of its 44 * internal representation, a rotation is an <em>operator</em> which basically 45 * transforms three dimensional {@link Vector3D vectors} into other three 46 * dimensional {@link Vector3D vectors}. Depending on the application, the 47 * meaning of these vectors may vary and the semantics of the rotation also.</p> 48 * <p>For example in an spacecraft attitude simulation tool, users will often 49 * consider the vectors are fixed (say the Earth direction for example) and the 50 * rotation transforms the coordinates coordinates of this vector in inertial 51 * frame into the coordinates of the same vector in satellite frame. In this 52 * case, the rotation implicitely defines the relation between the two frames. 53 * Another example could be a telescope control application, where the rotation 54 * would transform the sighting direction at rest into the desired observing 55 * direction when the telescope is pointed towards an object of interest. In this 56 * case the rotation transforms the directionf at rest in a topocentric frame 57 * into the sighting direction in the same topocentric frame. In many case, both 58 * approaches will be combined, in our telescope example, we will probably also 59 * need to transform the observing direction in the topocentric frame into the 60 * observing direction in inertial frame taking into account the observatory 61 * location and the Earth rotation.</p> 62 * 63 * <p>These examples show that a rotation is what the user wants it to be, so this 64 * class does not push the user towards one specific definition and hence does not 65 * provide methods like <code>projectVectorIntoDestinationFrame</code> or 66 * <code>computeTransformedDirection</code>. It provides simpler and more generic 67 * methods: {@link #applyTo(Vector3D) applyTo(Vector3D)} and {@link 68 * #applyInverseTo(Vector3D) applyInverseTo(Vector3D)}.</p> 69 * 70 * <p>Since a rotation is basically a vectorial operator, several rotations can be 71 * composed together and the composite operation <code>r = r<sub>1</sub> o 72 * r<sub>2</sub></code> (which means that for each vector <code>u</code>, 73 * <code>r(u) = r<sub>1</sub>(r<sub>2</sub>(u))</code>) is also a rotation. Hence 74 * we can consider that in addition to vectors, a rotation can be applied to other 75 * rotations as well (or to itself). With our previous notations, we would say we 76 * can apply <code>r<sub>1</sub></code> to <code>r<sub>2</sub></code> and the result 77 * we get is <code>r = r<sub>1</sub> o r<sub>2</sub></code>. For this purpose, the 78 * class provides the methods: {@link #applyTo(Rotation) applyTo(Rotation)} and 79 * {@link #applyInverseTo(Rotation) applyInverseTo(Rotation)}.</p> 80 * 81 * <p>Rotations are guaranteed to be immutable objects.</p> 82 * 83 * @version $Revision: 627994 $ $Date: 2008-02-15 03:16:05 -0700 (Fri, 15 Feb 2008) $ 84 * @see Vector3D 85 * @see RotationOrder 86 * @since 1.2 87 */ 88 89 public class Rotation implements Serializable { 90 91 /** Build the identity rotation. 92 */ 93 public Rotation() { 94 q0 = 1; 95 q1 = 0; 96 q2 = 0; 97 q3 = 0; 98 } 99 100 /** Build a rotation from the quaternion coordinates. 101 * <p>A rotation can be built from a <em>normalized</em> quaternion, 102 * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> + 103 * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> + 104 * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized, 105 * the constructor can normalize it in a preprocessing step.</p> 106 * @param q0 scalar part of the quaternion 107 * @param q1 first coordinate of the vectorial part of the quaternion 108 * @param q2 second coordinate of the vectorial part of the quaternion 109 * @param q3 third coordinate of the vectorial part of the quaternion 110 * @param needsNormalization if true, the coordinates are considered 111 * not to be normalized, a normalization preprocessing step is performed 112 * before using them 113 */ 114 public Rotation(double q0, double q1, double q2, double q3, 115 boolean needsNormalization) { 116 117 if (needsNormalization) { 118 // normalization preprocessing 119 double inv = 1.0 / Math.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); 120 q0 *= inv; 121 q1 *= inv; 122 q2 *= inv; 123 q3 *= inv; 124 } 125 126 this.q0 = q0; 127 this.q1 = q1; 128 this.q2 = q2; 129 this.q3 = q3; 130 131 } 132 133 /** Build a rotation from an axis and an angle. 134 * <p>We use the convention that angles are oriented according to 135 * the effect of the rotation on vectors around the axis. That means 136 * that if (i, j, k) is a direct frame and if we first provide +k as 137 * the axis and PI/2 as the angle to this constructor, and then 138 * {@link #applyTo(Vector3D) apply} the instance to +i, we will get 139 * +j.</p> 140 * @param axis axis around which to rotate 141 * @param angle rotation angle. 142 * @exception ArithmeticException if the axis norm is zero 143 */ 144 public Rotation(Vector3D axis, double angle) { 145 146 double norm = axis.getNorm(); 147 if (norm == 0) { 148 throw new ArithmeticException("zero norm for rotation axis"); 149 } 150 151 double halfAngle = -0.5 * angle; 152 double coeff = Math.sin(halfAngle) / norm; 153 154 q0 = Math.cos (halfAngle); 155 q1 = coeff * axis.getX(); 156 q2 = coeff * axis.getY(); 157 q3 = coeff * axis.getZ(); 158 159 } 160 161 /** Build a rotation from a 3X3 matrix. 162 163 * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices 164 * (which are matrices for which m.m<sup>T</sup> = I) with real 165 * coefficients. The module of the determinant of unit matrices is 166 * 1, among the orthogonal 3X3 matrices, only the ones having a 167 * positive determinant (+1) are rotation matrices.</p> 168 169 * <p>When a rotation is defined by a matrix with truncated values 170 * (typically when it is extracted from a technical sheet where only 171 * four to five significant digits are available), the matrix is not 172 * orthogonal anymore. This constructor handles this case 173 * transparently by using a copy of the given matrix and applying a 174 * correction to the copy in order to perfect its orthogonality. If 175 * the Frobenius norm of the correction needed is above the given 176 * threshold, then the matrix is considered to be too far from a 177 * true rotation matrix and an exception is thrown.<p> 178 179 * @param m rotation matrix 180 * @param threshold convergence threshold for the iterative 181 * orthogonality correction (convergence is reached when the 182 * difference between two steps of the Frobenius norm of the 183 * correction is below this threshold) 184 185 * @exception NotARotationMatrixException if the matrix is not a 3X3 186 * matrix, or if it cannot be transformed into an orthogonal matrix 187 * with the given threshold, or if the determinant of the resulting 188 * orthogonal matrix is negative 189 190 */ 191 public Rotation(double[][] m, double threshold) 192 throws NotARotationMatrixException { 193 194 // dimension check 195 if ((m.length != 3) || (m[0].length != 3) || 196 (m[1].length != 3) || (m[2].length != 3)) { 197 throw new NotARotationMatrixException("a {0}x{1} matrix" + 198 " cannot be a rotation matrix", 199 new Object[] { 200 Integer.toString(m.length), 201 Integer.toString(m[0].length) 202 }); 203 } 204 205 // compute a "close" orthogonal matrix 206 double[][] ort = orthogonalizeMatrix(m, threshold); 207 208 // check the sign of the determinant 209 double det = ort[0][0] * (ort[1][1] * ort[2][2] - ort[2][1] * ort[1][2]) - 210 ort[1][0] * (ort[0][1] * ort[2][2] - ort[2][1] * ort[0][2]) + 211 ort[2][0] * (ort[0][1] * ort[1][2] - ort[1][1] * ort[0][2]); 212 if (det < 0.0) { 213 throw new NotARotationMatrixException("the closest orthogonal matrix" + 214 " has a negative determinant {0}", 215 new Object[] { 216 Double.toString(det) 217 }); 218 } 219 220 // There are different ways to compute the quaternions elements 221 // from the matrix. They all involve computing one element from 222 // the diagonal of the matrix, and computing the three other ones 223 // using a formula involving a division by the first element, 224 // which unfortunately can be zero. Since the norm of the 225 // quaternion is 1, we know at least one element has an absolute 226 // value greater or equal to 0.5, so it is always possible to 227 // select the right formula and avoid division by zero and even 228 // numerical inaccuracy. Checking the elements in turn and using 229 // the first one greater than 0.45 is safe (this leads to a simple 230 // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19) 231 double s = ort[0][0] + ort[1][1] + ort[2][2]; 232 if (s > -0.19) { 233 // compute q0 and deduce q1, q2 and q3 234 q0 = 0.5 * Math.sqrt(s + 1.0); 235 double inv = 0.25 / q0; 236 q1 = inv * (ort[1][2] - ort[2][1]); 237 q2 = inv * (ort[2][0] - ort[0][2]); 238 q3 = inv * (ort[0][1] - ort[1][0]); 239 } else { 240 s = ort[0][0] - ort[1][1] - ort[2][2]; 241 if (s > -0.19) { 242 // compute q1 and deduce q0, q2 and q3 243 q1 = 0.5 * Math.sqrt(s + 1.0); 244 double inv = 0.25 / q1; 245 q0 = inv * (ort[1][2] - ort[2][1]); 246 q2 = inv * (ort[0][1] + ort[1][0]); 247 q3 = inv * (ort[0][2] + ort[2][0]); 248 } else { 249 s = ort[1][1] - ort[0][0] - ort[2][2]; 250 if (s > -0.19) { 251 // compute q2 and deduce q0, q1 and q3 252 q2 = 0.5 * Math.sqrt(s + 1.0); 253 double inv = 0.25 / q2; 254 q0 = inv * (ort[2][0] - ort[0][2]); 255 q1 = inv * (ort[0][1] + ort[1][0]); 256 q3 = inv * (ort[2][1] + ort[1][2]); 257 } else { 258 // compute q3 and deduce q0, q1 and q2 259 s = ort[2][2] - ort[0][0] - ort[1][1]; 260 q3 = 0.5 * Math.sqrt(s + 1.0); 261 double inv = 0.25 / q3; 262 q0 = inv * (ort[0][1] - ort[1][0]); 263 q1 = inv * (ort[0][2] + ort[2][0]); 264 q2 = inv * (ort[2][1] + ort[1][2]); 265 } 266 } 267 } 268 269 } 270 271 /** Build the rotation that transforms a pair of vector into another pair. 272 273 * <p>Except for possible scale factors, if the instance were applied to 274 * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair 275 * (v<sub>1</sub>, v<sub>2</sub>).</p> 276 277 * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is 278 * not the same as the angular separation between v<sub>1</sub> and 279 * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than 280 * v<sub>2</sub>, the corrected vector will be in the (v<sub>1</sub>, 281 * v<sub>2</sub>) plane.</p> 282 283 * @param u1 first vector of the origin pair 284 * @param u2 second vector of the origin pair 285 * @param v1 desired image of u1 by the rotation 286 * @param v2 desired image of u2 by the rotation 287 * @exception IllegalArgumentException if the norm of one of the vectors is zero 288 */ 289 public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) { 290 291 // norms computation 292 double u1u1 = Vector3D.dotProduct(u1, u1); 293 double u2u2 = Vector3D.dotProduct(u2, u2); 294 double v1v1 = Vector3D.dotProduct(v1, v1); 295 double v2v2 = Vector3D.dotProduct(v2, v2); 296 if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) { 297 throw new IllegalArgumentException("zero norm for rotation defining vector"); 298 } 299 300 double u1x = u1.getX(); 301 double u1y = u1.getY(); 302 double u1z = u1.getZ(); 303 304 double u2x = u2.getX(); 305 double u2y = u2.getY(); 306 double u2z = u2.getZ(); 307 308 // normalize v1 in order to have (v1'|v1') = (u1|u1) 309 double coeff = Math.sqrt (u1u1 / v1v1); 310 double v1x = coeff * v1.getX(); 311 double v1y = coeff * v1.getY(); 312 double v1z = coeff * v1.getZ(); 313 v1 = new Vector3D(v1x, v1y, v1z); 314 315 // adjust v2 in order to have (u1|u2) = (v1|v2) and (v2'|v2') = (u2|u2) 316 double u1u2 = Vector3D.dotProduct(u1, u2); 317 double v1v2 = Vector3D.dotProduct(v1, v2); 318 double coeffU = u1u2 / u1u1; 319 double coeffV = v1v2 / u1u1; 320 double beta = Math.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV)); 321 double alpha = coeffU - beta * coeffV; 322 double v2x = alpha * v1x + beta * v2.getX(); 323 double v2y = alpha * v1y + beta * v2.getY(); 324 double v2z = alpha * v1z + beta * v2.getZ(); 325 v2 = new Vector3D(v2x, v2y, v2z); 326 327 // preliminary computation (we use explicit formulation instead 328 // of relying on the Vector3D class in order to avoid building lots 329 // of temporary objects) 330 Vector3D uRef = u1; 331 Vector3D vRef = v1; 332 double dx1 = v1x - u1.getX(); 333 double dy1 = v1y - u1.getY(); 334 double dz1 = v1z - u1.getZ(); 335 double dx2 = v2x - u2.getX(); 336 double dy2 = v2y - u2.getY(); 337 double dz2 = v2z - u2.getZ(); 338 Vector3D k = new Vector3D(dy1 * dz2 - dz1 * dy2, 339 dz1 * dx2 - dx1 * dz2, 340 dx1 * dy2 - dy1 * dx2); 341 double c = k.getX() * (u1y * u2z - u1z * u2y) + 342 k.getY() * (u1z * u2x - u1x * u2z) + 343 k.getZ() * (u1x * u2y - u1y * u2x); 344 345 if (c == 0) { 346 // the (q1, q2, q3) vector is in the (u1, u2) plane 347 // we try other vectors 348 Vector3D u3 = Vector3D.crossProduct(u1, u2); 349 Vector3D v3 = Vector3D.crossProduct(v1, v2); 350 double u3x = u3.getX(); 351 double u3y = u3.getY(); 352 double u3z = u3.getZ(); 353 double v3x = v3.getX(); 354 double v3y = v3.getY(); 355 double v3z = v3.getZ(); 356 357 double dx3 = v3x - u3x; 358 double dy3 = v3y - u3y; 359 double dz3 = v3z - u3z; 360 k = new Vector3D(dy1 * dz3 - dz1 * dy3, 361 dz1 * dx3 - dx1 * dz3, 362 dx1 * dy3 - dy1 * dx3); 363 c = k.getX() * (u1y * u3z - u1z * u3y) + 364 k.getY() * (u1z * u3x - u1x * u3z) + 365 k.getZ() * (u1x * u3y - u1y * u3x); 366 367 if (c == 0) { 368 // the (q1, q2, q3) vector is aligned with u1: 369 // we try (u2, u3) and (v2, v3) 370 k = new Vector3D(dy2 * dz3 - dz2 * dy3, 371 dz2 * dx3 - dx2 * dz3, 372 dx2 * dy3 - dy2 * dx3); 373 c = k.getX() * (u2y * u3z - u2z * u3y) + 374 k.getY() * (u2z * u3x - u2x * u3z) + 375 k.getZ() * (u2x * u3y - u2y * u3x); 376 377 if (c == 0) { 378 // the (q1, q2, q3) vector is aligned with everything 379 // this is really the identity rotation 380 q0 = 1.0; 381 q1 = 0.0; 382 q2 = 0.0; 383 q3 = 0.0; 384 return; 385 } 386 387 // we will have to use u2 and v2 to compute the scalar part 388 uRef = u2; 389 vRef = v2; 390 391 } 392 393 } 394 395 // compute the vectorial part 396 c = Math.sqrt(c); 397 double inv = 1.0 / (c + c); 398 q1 = inv * k.getX(); 399 q2 = inv * k.getY(); 400 q3 = inv * k.getZ(); 401 402 // compute the scalar part 403 k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2, 404 uRef.getZ() * q1 - uRef.getX() * q3, 405 uRef.getX() * q2 - uRef.getY() * q1); 406 c = Vector3D.dotProduct(k, k); 407 q0 = Vector3D.dotProduct(vRef, k) / (c + c); 408 409 } 410 411 /** Build one of the rotations that transform one vector into another one. 412 413 * <p>Except for a possible scale factor, if the instance were 414 * applied to the vector u it will produce the vector v. There is an 415 * infinite number of such rotations, this constructor choose the 416 * one with the smallest associated angle (i.e. the one whose axis 417 * is orthogonal to the (u, v) plane). If u and v are colinear, an 418 * arbitrary rotation axis is chosen.</p> 419 420 * @param u origin vector 421 * @param v desired image of u by the rotation 422 * @exception IllegalArgumentException if the norm of one of the vectors is zero 423 */ 424 public Rotation(Vector3D u, Vector3D v) { 425 426 double normProduct = u.getNorm() * v.getNorm(); 427 if (normProduct == 0) { 428 throw new IllegalArgumentException("zero norm for rotation defining vector"); 429 } 430 431 double dot = Vector3D.dotProduct(u, v); 432 433 if (dot < ((2.0e-15 - 1.0) * normProduct)) { 434 // special case u = -v: we select a PI angle rotation around 435 // an arbitrary vector orthogonal to u 436 Vector3D w = u.orthogonal(); 437 q0 = 0.0; 438 q1 = -w.getX(); 439 q2 = -w.getY(); 440 q3 = -w.getZ(); 441 } else { 442 // general case: (u, v) defines a plane, we select 443 // the shortest possible rotation: axis orthogonal to this plane 444 q0 = Math.sqrt(0.5 * (1.0 + dot / normProduct)); 445 double coeff = 1.0 / (2.0 * q0 * normProduct); 446 q1 = coeff * (v.getY() * u.getZ() - v.getZ() * u.getY()); 447 q2 = coeff * (v.getZ() * u.getX() - v.getX() * u.getZ()); 448 q3 = coeff * (v.getX() * u.getY() - v.getY() * u.getX()); 449 } 450 451 } 452 453 /** Build a rotation from three Cardan or Euler elementary rotations. 454 455 * <p>Cardan rotations are three successive rotations around the 456 * canonical axes X, Y and Z, each axis beeing used once. There are 457 * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler 458 * rotations are three successive rotations around the canonical 459 * axes X, Y and Z, the first and last rotations beeing around the 460 * same axis. There are 6 such sets of rotations (XYX, XZX, YXY, 461 * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p> 462 * <p>Beware that many people routinely use the term Euler angles even 463 * for what really are Cardan angles (this confusion is especially 464 * widespread in the aerospace business where Roll, Pitch and Yaw angles 465 * are often wrongly tagged as Euler angles).</p> 466 467 * @param order order of rotations to use 468 * @param alpha1 angle of the first elementary rotation 469 * @param alpha2 angle of the second elementary rotation 470 * @param alpha3 angle of the third elementary rotation 471 */ 472 public Rotation(RotationOrder order, 473 double alpha1, double alpha2, double alpha3) { 474 Rotation r1 = new Rotation(order.getA1(), alpha1); 475 Rotation r2 = new Rotation(order.getA2(), alpha2); 476 Rotation r3 = new Rotation(order.getA3(), alpha3); 477 Rotation composed = r1.applyTo(r2.applyTo(r3)); 478 q0 = composed.q0; 479 q1 = composed.q1; 480 q2 = composed.q2; 481 q3 = composed.q3; 482 } 483 484 /** Revert a rotation. 485 * Build a rotation which reverse the effect of another 486 * rotation. This means that if r(u) = v, then r.revert(v) = u. The 487 * instance is not changed. 488 * @return a new rotation whose effect is the reverse of the effect 489 * of the instance 490 */ 491 public Rotation revert() { 492 return new Rotation(-q0, q1, q2, q3, false); 493 } 494 495 /** Get the scalar coordinate of the quaternion. 496 * @return scalar coordinate of the quaternion 497 */ 498 public double getQ0() { 499 return q0; 500 } 501 502 /** Get the first coordinate of the vectorial part of the quaternion. 503 * @return first coordinate of the vectorial part of the quaternion 504 */ 505 public double getQ1() { 506 return q1; 507 } 508 509 /** Get the second coordinate of the vectorial part of the quaternion. 510 * @return second coordinate of the vectorial part of the quaternion 511 */ 512 public double getQ2() { 513 return q2; 514 } 515 516 /** Get the third coordinate of the vectorial part of the quaternion. 517 * @return third coordinate of the vectorial part of the quaternion 518 */ 519 public double getQ3() { 520 return q3; 521 } 522 523 /** Get the normalized axis of the rotation. 524 * @return normalized axis of the rotation 525 */ 526 public Vector3D getAxis() { 527 double squaredSine = q1 * q1 + q2 * q2 + q3 * q3; 528 if (squaredSine == 0) { 529 return new Vector3D(1, 0, 0); 530 } else if (q0 < 0) { 531 double inverse = 1 / Math.sqrt(squaredSine); 532 return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse); 533 } 534 double inverse = -1 / Math.sqrt(squaredSine); 535 return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse); 536 } 537 538 /** Get the angle of the rotation. 539 * @return angle of the rotation (between 0 and π) 540 */ 541 public double getAngle() { 542 if ((q0 < -0.1) || (q0 > 0.1)) { 543 return 2 * Math.asin(Math.sqrt(q1 * q1 + q2 * q2 + q3 * q3)); 544 } else if (q0 < 0) { 545 return 2 * Math.acos(-q0); 546 } 547 return 2 * Math.acos(q0); 548 } 549 550 /** Get the Cardan or Euler angles corresponding to the instance. 551 552 * <p>The equations show that each rotation can be defined by two 553 * different values of the Cardan or Euler angles set. For example 554 * if Cardan angles are used, the rotation defined by the angles 555 * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as 556 * the rotation defined by the angles π + a<sub>1</sub>, π 557 * - a<sub>2</sub> and π + a<sub>3</sub>. This method implements 558 * the following arbitrary choices:</p> 559 * <ul> 560 * <li>for Cardan angles, the chosen set is the one for which the 561 * second angle is between -π/2 and π/2 (i.e its cosine is 562 * positive),</li> 563 * <li>for Euler angles, the chosen set is the one for which the 564 * second angle is between 0 and π (i.e its sine is positive).</li> 565 * </ul> 566 567 * <p>Cardan and Euler angle have a very disappointing drawback: all 568 * of them have singularities. This means that if the instance is 569 * too close to the singularities corresponding to the given 570 * rotation order, it will be impossible to retrieve the angles. For 571 * Cardan angles, this is often called gimbal lock. There is 572 * <em>nothing</em> to do to prevent this, it is an intrinsic problem 573 * with Cardan and Euler representation (but not a problem with the 574 * rotation itself, which is perfectly well defined). For Cardan 575 * angles, singularities occur when the second angle is close to 576 * -π/2 or +π/2, for Euler angle singularities occur when the 577 * second angle is close to 0 or π, this implies that the identity 578 * rotation is always singular for Euler angles!</p> 579 580 * @param order rotation order to use 581 * @return an array of three angles, in the order specified by the set 582 * @exception CardanEulerSingularityException if the rotation is 583 * singular with respect to the angles set specified 584 */ 585 public double[] getAngles(RotationOrder order) 586 throws CardanEulerSingularityException { 587 588 if (order == RotationOrder.XYZ) { 589 590 // r (Vector3D.plusK) coordinates are : 591 // sin (theta), -cos (theta) sin (phi), cos (theta) cos (phi) 592 // (-r) (Vector3D.plusI) coordinates are : 593 // cos (psi) cos (theta), -sin (psi) cos (theta), sin (theta) 594 // and we can choose to have theta in the interval [-PI/2 ; +PI/2] 595 Vector3D v1 = applyTo(Vector3D.plusK); 596 Vector3D v2 = applyInverseTo(Vector3D.plusI); 597 if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) { 598 throw new CardanEulerSingularityException(true); 599 } 600 return new double[] { 601 Math.atan2(-(v1.getY()), v1.getZ()), 602 Math.asin(v2.getZ()), 603 Math.atan2(-(v2.getY()), v2.getX()) 604 }; 605 606 } else if (order == RotationOrder.XZY) { 607 608 // r (Vector3D.plusJ) coordinates are : 609 // -sin (psi), cos (psi) cos (phi), cos (psi) sin (phi) 610 // (-r) (Vector3D.plusI) coordinates are : 611 // cos (theta) cos (psi), -sin (psi), sin (theta) cos (psi) 612 // and we can choose to have psi in the interval [-PI/2 ; +PI/2] 613 Vector3D v1 = applyTo(Vector3D.plusJ); 614 Vector3D v2 = applyInverseTo(Vector3D.plusI); 615 if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) { 616 throw new CardanEulerSingularityException(true); 617 } 618 return new double[] { 619 Math.atan2(v1.getZ(), v1.getY()), 620 -Math.asin(v2.getY()), 621 Math.atan2(v2.getZ(), v2.getX()) 622 }; 623 624 } else if (order == RotationOrder.YXZ) { 625 626 // r (Vector3D.plusK) coordinates are : 627 // cos (phi) sin (theta), -sin (phi), cos (phi) cos (theta) 628 // (-r) (Vector3D.plusJ) coordinates are : 629 // sin (psi) cos (phi), cos (psi) cos (phi), -sin (phi) 630 // and we can choose to have phi in the interval [-PI/2 ; +PI/2] 631 Vector3D v1 = applyTo(Vector3D.plusK); 632 Vector3D v2 = applyInverseTo(Vector3D.plusJ); 633 if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) { 634 throw new CardanEulerSingularityException(true); 635 } 636 return new double[] { 637 Math.atan2(v1.getX(), v1.getZ()), 638 -Math.asin(v2.getZ()), 639 Math.atan2(v2.getX(), v2.getY()) 640 }; 641 642 } else if (order == RotationOrder.YZX) { 643 644 // r (Vector3D.plusI) coordinates are : 645 // cos (psi) cos (theta), sin (psi), -cos (psi) sin (theta) 646 // (-r) (Vector3D.plusJ) coordinates are : 647 // sin (psi), cos (phi) cos (psi), -sin (phi) cos (psi) 648 // and we can choose to have psi in the interval [-PI/2 ; +PI/2] 649 Vector3D v1 = applyTo(Vector3D.plusI); 650 Vector3D v2 = applyInverseTo(Vector3D.plusJ); 651 if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) { 652 throw new CardanEulerSingularityException(true); 653 } 654 return new double[] { 655 Math.atan2(-(v1.getZ()), v1.getX()), 656 Math.asin(v2.getX()), 657 Math.atan2(-(v2.getZ()), v2.getY()) 658 }; 659 660 } else if (order == RotationOrder.ZXY) { 661 662 // r (Vector3D.plusJ) coordinates are : 663 // -cos (phi) sin (psi), cos (phi) cos (psi), sin (phi) 664 // (-r) (Vector3D.plusK) coordinates are : 665 // -sin (theta) cos (phi), sin (phi), cos (theta) cos (phi) 666 // and we can choose to have phi in the interval [-PI/2 ; +PI/2] 667 Vector3D v1 = applyTo(Vector3D.plusJ); 668 Vector3D v2 = applyInverseTo(Vector3D.plusK); 669 if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) { 670 throw new CardanEulerSingularityException(true); 671 } 672 return new double[] { 673 Math.atan2(-(v1.getX()), v1.getY()), 674 Math.asin(v2.getY()), 675 Math.atan2(-(v2.getX()), v2.getZ()) 676 }; 677 678 } else if (order == RotationOrder.ZYX) { 679 680 // r (Vector3D.plusI) coordinates are : 681 // cos (theta) cos (psi), cos (theta) sin (psi), -sin (theta) 682 // (-r) (Vector3D.plusK) coordinates are : 683 // -sin (theta), sin (phi) cos (theta), cos (phi) cos (theta) 684 // and we can choose to have theta in the interval [-PI/2 ; +PI/2] 685 Vector3D v1 = applyTo(Vector3D.plusI); 686 Vector3D v2 = applyInverseTo(Vector3D.plusK); 687 if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) { 688 throw new CardanEulerSingularityException(true); 689 } 690 return new double[] { 691 Math.atan2(v1.getY(), v1.getX()), 692 -Math.asin(v2.getX()), 693 Math.atan2(v2.getY(), v2.getZ()) 694 }; 695 696 } else if (order == RotationOrder.XYX) { 697 698 // r (Vector3D.plusI) coordinates are : 699 // cos (theta), sin (phi1) sin (theta), -cos (phi1) sin (theta) 700 // (-r) (Vector3D.plusI) coordinates are : 701 // cos (theta), sin (theta) sin (phi2), sin (theta) cos (phi2) 702 // and we can choose to have theta in the interval [0 ; PI] 703 Vector3D v1 = applyTo(Vector3D.plusI); 704 Vector3D v2 = applyInverseTo(Vector3D.plusI); 705 if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) { 706 throw new CardanEulerSingularityException(false); 707 } 708 return new double[] { 709 Math.atan2(v1.getY(), -v1.getZ()), 710 Math.acos(v2.getX()), 711 Math.atan2(v2.getY(), v2.getZ()) 712 }; 713 714 } else if (order == RotationOrder.XZX) { 715 716 // r (Vector3D.plusI) coordinates are : 717 // cos (psi), cos (phi1) sin (psi), sin (phi1) sin (psi) 718 // (-r) (Vector3D.plusI) coordinates are : 719 // cos (psi), -sin (psi) cos (phi2), sin (psi) sin (phi2) 720 // and we can choose to have psi in the interval [0 ; PI] 721 Vector3D v1 = applyTo(Vector3D.plusI); 722 Vector3D v2 = applyInverseTo(Vector3D.plusI); 723 if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) { 724 throw new CardanEulerSingularityException(false); 725 } 726 return new double[] { 727 Math.atan2(v1.getZ(), v1.getY()), 728 Math.acos(v2.getX()), 729 Math.atan2(v2.getZ(), -v2.getY()) 730 }; 731 732 } else if (order == RotationOrder.YXY) { 733 734 // r (Vector3D.plusJ) coordinates are : 735 // sin (theta1) sin (phi), cos (phi), cos (theta1) sin (phi) 736 // (-r) (Vector3D.plusJ) coordinates are : 737 // sin (phi) sin (theta2), cos (phi), -sin (phi) cos (theta2) 738 // and we can choose to have phi in the interval [0 ; PI] 739 Vector3D v1 = applyTo(Vector3D.plusJ); 740 Vector3D v2 = applyInverseTo(Vector3D.plusJ); 741 if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) { 742 throw new CardanEulerSingularityException(false); 743 } 744 return new double[] { 745 Math.atan2(v1.getX(), v1.getZ()), 746 Math.acos(v2.getY()), 747 Math.atan2(v2.getX(), -v2.getZ()) 748 }; 749 750 } else if (order == RotationOrder.YZY) { 751 752 // r (Vector3D.plusJ) coordinates are : 753 // -cos (theta1) sin (psi), cos (psi), sin (theta1) sin (psi) 754 // (-r) (Vector3D.plusJ) coordinates are : 755 // sin (psi) cos (theta2), cos (psi), sin (psi) sin (theta2) 756 // and we can choose to have psi in the interval [0 ; PI] 757 Vector3D v1 = applyTo(Vector3D.plusJ); 758 Vector3D v2 = applyInverseTo(Vector3D.plusJ); 759 if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) { 760 throw new CardanEulerSingularityException(false); 761 } 762 return new double[] { 763 Math.atan2(v1.getZ(), -v1.getX()), 764 Math.acos(v2.getY()), 765 Math.atan2(v2.getZ(), v2.getX()) 766 }; 767 768 } else if (order == RotationOrder.ZXZ) { 769 770 // r (Vector3D.plusK) coordinates are : 771 // sin (psi1) sin (phi), -cos (psi1) sin (phi), cos (phi) 772 // (-r) (Vector3D.plusK) coordinates are : 773 // sin (phi) sin (psi2), sin (phi) cos (psi2), cos (phi) 774 // and we can choose to have phi in the interval [0 ; PI] 775 Vector3D v1 = applyTo(Vector3D.plusK); 776 Vector3D v2 = applyInverseTo(Vector3D.plusK); 777 if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) { 778 throw new CardanEulerSingularityException(false); 779 } 780 return new double[] { 781 Math.atan2(v1.getX(), -v1.getY()), 782 Math.acos(v2.getZ()), 783 Math.atan2(v2.getX(), v2.getY()) 784 }; 785 786 } else { // last possibility is ZYZ 787 788 // r (Vector3D.plusK) coordinates are : 789 // cos (psi1) sin (theta), sin (psi1) sin (theta), cos (theta) 790 // (-r) (Vector3D.plusK) coordinates are : 791 // -sin (theta) cos (psi2), sin (theta) sin (psi2), cos (theta) 792 // and we can choose to have theta in the interval [0 ; PI] 793 Vector3D v1 = applyTo(Vector3D.plusK); 794 Vector3D v2 = applyInverseTo(Vector3D.plusK); 795 if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) { 796 throw new CardanEulerSingularityException(false); 797 } 798 return new double[] { 799 Math.atan2(v1.getY(), v1.getX()), 800 Math.acos(v2.getZ()), 801 Math.atan2(v2.getY(), -v2.getX()) 802 }; 803 804 } 805 806 } 807 808 /** Get the 3X3 matrix corresponding to the instance 809 * @return the matrix corresponding to the instance 810 */ 811 public double[][] getMatrix() { 812 813 // products 814 double q0q0 = q0 * q0; 815 double q0q1 = q0 * q1; 816 double q0q2 = q0 * q2; 817 double q0q3 = q0 * q3; 818 double q1q1 = q1 * q1; 819 double q1q2 = q1 * q2; 820 double q1q3 = q1 * q3; 821 double q2q2 = q2 * q2; 822 double q2q3 = q2 * q3; 823 double q3q3 = q3 * q3; 824 825 // create the matrix 826 double[][] m = new double[3][]; 827 m[0] = new double[3]; 828 m[1] = new double[3]; 829 m[2] = new double[3]; 830 831 m [0][0] = 2.0 * (q0q0 + q1q1) - 1.0; 832 m [1][0] = 2.0 * (q1q2 - q0q3); 833 m [2][0] = 2.0 * (q1q3 + q0q2); 834 835 m [0][1] = 2.0 * (q1q2 + q0q3); 836 m [1][1] = 2.0 * (q0q0 + q2q2) - 1.0; 837 m [2][1] = 2.0 * (q2q3 - q0q1); 838 839 m [0][2] = 2.0 * (q1q3 - q0q2); 840 m [1][2] = 2.0 * (q2q3 + q0q1); 841 m [2][2] = 2.0 * (q0q0 + q3q3) - 1.0; 842 843 return m; 844 845 } 846 847 /** Apply the rotation to a vector. 848 * @param u vector to apply the rotation to 849 * @return a new vector which is the image of u by the rotation 850 */ 851 public Vector3D applyTo(Vector3D u) { 852 853 double x = u.getX(); 854 double y = u.getY(); 855 double z = u.getZ(); 856 857 double s = q1 * x + q2 * y + q3 * z; 858 859 return new Vector3D(2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x, 860 2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y, 861 2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z); 862 863 } 864 865 /** Apply the inverse of the rotation to a vector. 866 * @param u vector to apply the inverse of the rotation to 867 * @return a new vector which such that u is its image by the rotation 868 */ 869 public Vector3D applyInverseTo(Vector3D u) { 870 871 double x = u.getX(); 872 double y = u.getY(); 873 double z = u.getZ(); 874 875 double s = q1 * x + q2 * y + q3 * z; 876 double m0 = -q0; 877 878 return new Vector3D(2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x, 879 2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y, 880 2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z); 881 882 } 883 884 /** Apply the instance to another rotation. 885 * Applying the instance to a rotation is computing the composition 886 * in an order compliant with the following rule : let u be any 887 * vector and v its image by r (i.e. r.applyTo(u) = v), let w be the image 888 * of v by the instance (i.e. applyTo(v) = w), then w = comp.applyTo(u), 889 * where comp = applyTo(r). 890 * @param r rotation to apply the rotation to 891 * @return a new rotation which is the composition of r by the instance 892 */ 893 public Rotation applyTo(Rotation r) { 894 return new Rotation(r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3), 895 r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2), 896 r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3), 897 r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1), 898 false); 899 } 900 901 /** Apply the inverse of the instance to another rotation. 902 * Applying the inverse of the instance to a rotation is computing 903 * the composition in an order compliant with the following rule : 904 * let u be any vector and v its image by r (i.e. r.applyTo(u) = v), 905 * let w be the inverse image of v by the instance 906 * (i.e. applyInverseTo(v) = w), then w = comp.applyTo(u), where 907 * comp = applyInverseTo(r). 908 * @param r rotation to apply the rotation to 909 * @return a new rotation which is the composition of r by the inverse 910 * of the instance 911 */ 912 public Rotation applyInverseTo(Rotation r) { 913 return new Rotation(-r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3), 914 -r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2), 915 -r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3), 916 -r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1), 917 false); 918 } 919 920 /** Perfect orthogonality on a 3X3 matrix. 921 * @param m initial matrix (not exactly orthogonal) 922 * @param threshold convergence threshold for the iterative 923 * orthogonality correction (convergence is reached when the 924 * difference between two steps of the Frobenius norm of the 925 * correction is below this threshold) 926 * @return an orthogonal matrix close to m 927 * @exception NotARotationMatrixException if the matrix cannot be 928 * orthogonalized with the given threshold after 10 iterations 929 */ 930 private double[][] orthogonalizeMatrix(double[][] m, double threshold) 931 throws NotARotationMatrixException { 932 double[] m0 = m[0]; 933 double[] m1 = m[1]; 934 double[] m2 = m[2]; 935 double x00 = m0[0]; 936 double x01 = m0[1]; 937 double x02 = m0[2]; 938 double x10 = m1[0]; 939 double x11 = m1[1]; 940 double x12 = m1[2]; 941 double x20 = m2[0]; 942 double x21 = m2[1]; 943 double x22 = m2[2]; 944 double fn = 0; 945 double fn1; 946 947 double[][] o = new double[3][3]; 948 double[] o0 = o[0]; 949 double[] o1 = o[1]; 950 double[] o2 = o[2]; 951 952 // iterative correction: Xn+1 = Xn - 0.5 * (Xn.Mt.Xn - M) 953 int i = 0; 954 while (++i < 11) { 955 956 // Mt.Xn 957 double mx00 = m0[0] * x00 + m1[0] * x10 + m2[0] * x20; 958 double mx10 = m0[1] * x00 + m1[1] * x10 + m2[1] * x20; 959 double mx20 = m0[2] * x00 + m1[2] * x10 + m2[2] * x20; 960 double mx01 = m0[0] * x01 + m1[0] * x11 + m2[0] * x21; 961 double mx11 = m0[1] * x01 + m1[1] * x11 + m2[1] * x21; 962 double mx21 = m0[2] * x01 + m1[2] * x11 + m2[2] * x21; 963 double mx02 = m0[0] * x02 + m1[0] * x12 + m2[0] * x22; 964 double mx12 = m0[1] * x02 + m1[1] * x12 + m2[1] * x22; 965 double mx22 = m0[2] * x02 + m1[2] * x12 + m2[2] * x22; 966 967 // Xn+1 968 o0[0] = x00 - 0.5 * (x00 * mx00 + x01 * mx10 + x02 * mx20 - m0[0]); 969 o0[1] = x01 - 0.5 * (x00 * mx01 + x01 * mx11 + x02 * mx21 - m0[1]); 970 o0[2] = x02 - 0.5 * (x00 * mx02 + x01 * mx12 + x02 * mx22 - m0[2]); 971 o1[0] = x10 - 0.5 * (x10 * mx00 + x11 * mx10 + x12 * mx20 - m1[0]); 972 o1[1] = x11 - 0.5 * (x10 * mx01 + x11 * mx11 + x12 * mx21 - m1[1]); 973 o1[2] = x12 - 0.5 * (x10 * mx02 + x11 * mx12 + x12 * mx22 - m1[2]); 974 o2[0] = x20 - 0.5 * (x20 * mx00 + x21 * mx10 + x22 * mx20 - m2[0]); 975 o2[1] = x21 - 0.5 * (x20 * mx01 + x21 * mx11 + x22 * mx21 - m2[1]); 976 o2[2] = x22 - 0.5 * (x20 * mx02 + x21 * mx12 + x22 * mx22 - m2[2]); 977 978 // correction on each elements 979 double corr00 = o0[0] - m0[0]; 980 double corr01 = o0[1] - m0[1]; 981 double corr02 = o0[2] - m0[2]; 982 double corr10 = o1[0] - m1[0]; 983 double corr11 = o1[1] - m1[1]; 984 double corr12 = o1[2] - m1[2]; 985 double corr20 = o2[0] - m2[0]; 986 double corr21 = o2[1] - m2[1]; 987 double corr22 = o2[2] - m2[2]; 988 989 // Frobenius norm of the correction 990 fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 + 991 corr10 * corr10 + corr11 * corr11 + corr12 * corr12 + 992 corr20 * corr20 + corr21 * corr21 + corr22 * corr22; 993 994 // convergence test 995 if (Math.abs(fn1 - fn) <= threshold) 996 return o; 997 998 // prepare next iteration 999 x00 = o0[0]; 1000 x01 = o0[1]; 1001 x02 = o0[2]; 1002 x10 = o1[0]; 1003 x11 = o1[1]; 1004 x12 = o1[2]; 1005 x20 = o2[0]; 1006 x21 = o2[1]; 1007 x22 = o2[2]; 1008 fn = fn1; 1009 1010 } 1011 1012 // the algorithm did not converge after 10 iterations 1013 throw new NotARotationMatrixException("unable to orthogonalize matrix" + 1014 " in {0} iterations", 1015 new Object[] { 1016 Integer.toString(i - 1) 1017 }); 1018 } 1019 1020 /** Scalar coordinate of the quaternion. */ 1021 private final double q0; 1022 1023 /** First coordinate of the vectorial part of the quaternion. */ 1024 private final double q1; 1025 1026 /** Second coordinate of the vectorial part of the quaternion. */ 1027 private final double q2; 1028 1029 /** Third coordinate of the vectorial part of the quaternion. */ 1030 private final double q3; 1031 1032 /** Serializable version identifier */ 1033 private static final long serialVersionUID = 8225864499430109352L; 1034 1035 }