Quaternion.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Runtime.InteropServices;
  5. namespace BansheeEngine
  6. {
  7. /** @addtogroup Math
  8. * @{
  9. */
  10. /// <summary>
  11. /// Quaternion used for representing rotations.
  12. /// </summary>
  13. [StructLayout(LayoutKind.Sequential), SerializeObject]
  14. public struct Quaternion // Note: Must match C++ class Quaternion
  15. {
  16. /// <summary>
  17. /// Contains constant data that is used when calculating euler angles in a certain order.
  18. /// </summary>
  19. private struct EulerAngleOrderData
  20. {
  21. public EulerAngleOrderData(int a, int b, int c)
  22. {
  23. this.a = a;
  24. this.b = b;
  25. this.c = c;
  26. }
  27. public int a, b, c;
  28. };
  29. /// <summary>
  30. /// Quaternion with all zero elements.
  31. /// </summary>
  32. public static readonly Quaternion Zero = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
  33. /// <summary>
  34. /// Quaternion representing no rotation.
  35. /// </summary>
  36. public static readonly Quaternion Identity = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
  37. private static readonly float epsilon = 1e-03f;
  38. private static readonly EulerAngleOrderData[] EA_LOOKUP = new EulerAngleOrderData[6]
  39. { new EulerAngleOrderData(0, 1, 2), new EulerAngleOrderData(0, 2, 1), new EulerAngleOrderData(1, 0, 2),
  40. new EulerAngleOrderData(1, 2, 0), new EulerAngleOrderData(2, 0, 1), new EulerAngleOrderData(2, 1, 0) };
  41. public float x;
  42. public float y;
  43. public float z;
  44. public float w;
  45. /// <summary>
  46. /// Accesses a specific component of the quaternion.
  47. /// </summary>
  48. /// <param name="index">Index of the component (0 - x, 1 - y, 2 - z, 3 - w).</param>
  49. /// <returns>Value of the specific component.</returns>
  50. public float this[int index]
  51. {
  52. get
  53. {
  54. switch (index)
  55. {
  56. case 0:
  57. return x;
  58. case 1:
  59. return y;
  60. case 2:
  61. return z;
  62. case 3:
  63. return w;
  64. default:
  65. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  66. }
  67. }
  68. set
  69. {
  70. switch (index)
  71. {
  72. case 0:
  73. x = value;
  74. break;
  75. case 1:
  76. y = value;
  77. break;
  78. case 2:
  79. z = value;
  80. break;
  81. case 3:
  82. w = value;
  83. break;
  84. default:
  85. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  86. }
  87. }
  88. }
  89. /// <summary>
  90. /// Gets the positive x-axis of the coordinate system transformed by this quaternion.
  91. /// </summary>
  92. public Vector3 Right
  93. {
  94. get
  95. {
  96. float fTy = 2.0f*y;
  97. float fTz = 2.0f*z;
  98. float fTwy = fTy*w;
  99. float fTwz = fTz*w;
  100. float fTxy = fTy*x;
  101. float fTxz = fTz*x;
  102. float fTyy = fTy*y;
  103. float fTzz = fTz*z;
  104. return new Vector3(1.0f - (fTyy + fTzz), fTxy + fTwz, fTxz - fTwy);
  105. }
  106. }
  107. /// <summary>
  108. /// Gets the positive y-axis of the coordinate system transformed by this quaternion.
  109. /// </summary>
  110. public Vector3 Up
  111. {
  112. get
  113. {
  114. float fTx = 2.0f * x;
  115. float fTy = 2.0f * y;
  116. float fTz = 2.0f * z;
  117. float fTwx = fTx * w;
  118. float fTwz = fTz * w;
  119. float fTxx = fTx * x;
  120. float fTxy = fTy * x;
  121. float fTyz = fTz * y;
  122. float fTzz = fTz * z;
  123. return new Vector3(fTxy - fTwz, 1.0f - (fTxx + fTzz), fTyz + fTwx);
  124. }
  125. }
  126. /// <summary>
  127. /// Gets the positive z-axis of the coordinate system transformed by this quaternion.
  128. /// </summary>
  129. public Vector3 Forward
  130. {
  131. get
  132. {
  133. float fTx = 2.0f * x;
  134. float fTy = 2.0f * y;
  135. float fTz = 2.0f * z;
  136. float fTwx = fTx * w;
  137. float fTwy = fTy * w;
  138. float fTxx = fTx * x;
  139. float fTxz = fTz * x;
  140. float fTyy = fTy * y;
  141. float fTyz = fTz * y;
  142. return new Vector3(fTxz + fTwy, fTyz - fTwx, 1.0f - (fTxx + fTyy));
  143. }
  144. }
  145. /// <summary>
  146. /// Returns the inverse of the quaternion. Quaternion must be non-zero. Inverse quaternion has the opposite
  147. /// rotation of the original.
  148. /// </summary>
  149. public Quaternion Inverse
  150. {
  151. get
  152. {
  153. Quaternion copy = this;
  154. copy.Invert();
  155. return copy;
  156. }
  157. }
  158. /// <summary>
  159. /// Returns a normalized copy of the quaternion.
  160. /// </summary>
  161. public Quaternion Normalized
  162. {
  163. get
  164. {
  165. Quaternion copy = this;
  166. copy.Normalize();
  167. return copy;
  168. }
  169. }
  170. /// <summary>
  171. /// Constructs a new quaternion with the specified components.
  172. /// </summary>
  173. public Quaternion(float x, float y, float z, float w)
  174. {
  175. this.x = x;
  176. this.y = y;
  177. this.z = z;
  178. this.w = w;
  179. }
  180. public static Quaternion operator* (Quaternion lhs, Quaternion rhs)
  181. {
  182. return new Quaternion((lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y),
  183. (lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z),
  184. (lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x),
  185. (lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z));
  186. }
  187. public static Quaternion operator* (float lhs, Quaternion rhs)
  188. {
  189. return new Quaternion(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w);
  190. }
  191. public static Quaternion operator+ (Quaternion lhs, Quaternion rhs)
  192. {
  193. return new Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
  194. }
  195. public static Quaternion operator- (Quaternion lhs, Quaternion rhs)
  196. {
  197. return new Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
  198. }
  199. public static Quaternion operator- (Quaternion quat)
  200. {
  201. return new Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  202. }
  203. public static bool operator== (Quaternion lhs, Quaternion rhs)
  204. {
  205. return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
  206. }
  207. public static bool operator!= (Quaternion lhs, Quaternion rhs)
  208. {
  209. return !(lhs == rhs);
  210. }
  211. /// <summary>
  212. /// Calculates a dot product between two quaternions.
  213. /// </summary>
  214. /// <param name="a">First quaternion.</param>
  215. /// <param name="b">Second quaternion.</param>
  216. /// <returns>Dot product between the two quaternions.</returns>
  217. public static float Dot(Quaternion a, Quaternion b)
  218. {
  219. return (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
  220. }
  221. /// <summary>
  222. /// Applies quaternion rotation to the specified point.
  223. /// </summary>
  224. /// <param name="point">Point to rotate.</param>
  225. /// <returns>Point rotated by the quaternion.</returns>
  226. public Vector3 Rotate(Vector3 point)
  227. {
  228. return ToRotationMatrix().Transform(point);
  229. }
  230. /// <summary>
  231. /// Initializes the quaternion with rotation that rotates from one direction to another.
  232. /// </summary>
  233. /// <param name="fromDirection">Rotation to start at.</param>
  234. /// <param name="toDirection">Rotation to end at.</param>
  235. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection)
  236. {
  237. SetFromToRotation(fromDirection, toDirection, Vector3.Zero);
  238. }
  239. /// <summary>
  240. /// Initializes the quaternion with rotation that rotates from one direction to another.
  241. /// </summary>
  242. /// <param name="fromDirection">Rotation to start at.</param>
  243. /// <param name="toDirection">Rotation to end at.</param>
  244. /// <param name="fallbackAxis">Fallback axis to use if the from/to vectors are almost completely opposite.
  245. /// Fallback axis should be perpendicular to both vectors.</param>
  246. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  247. {
  248. fromDirection.Normalize();
  249. toDirection.Normalize();
  250. float d = Vector3.Dot(fromDirection, toDirection);
  251. // If dot == 1, vectors are the same
  252. if (d >= 1.0f)
  253. {
  254. this = Identity;
  255. return;
  256. }
  257. if (d < (1e-6f - 1.0f))
  258. {
  259. if (fallbackAxis != Vector3.Zero)
  260. {
  261. // Rotate 180 degrees about the fallback axis
  262. this = FromAxisAngle(fallbackAxis, MathEx.Pi);
  263. }
  264. else
  265. {
  266. // Generate an axis
  267. Vector3 axis = Vector3.Cross(Vector3.XAxis, fromDirection);
  268. if (axis.SqrdLength < ((1e-06f * 1e-06f))) // Pick another if collinear
  269. axis = Vector3.Cross(Vector3.YAxis, fromDirection);
  270. axis.Normalize();
  271. this = FromAxisAngle(axis, MathEx.Pi);
  272. }
  273. }
  274. else
  275. {
  276. float s = MathEx.Sqrt((1+d)*2);
  277. float invs = 1 / s;
  278. Vector3 c = Vector3.Cross(fromDirection, toDirection);
  279. x = c.x * invs;
  280. y = c.y * invs;
  281. z = c.z * invs;
  282. w = s * 0.5f;
  283. Normalize();
  284. }
  285. }
  286. /// <summary>
  287. /// Normalizes the quaternion.
  288. /// </summary>
  289. /// <returns>Length of the quaternion prior to normalization.</returns>
  290. public float Normalize()
  291. {
  292. float len = w*w+x*x+y*y+z*z;
  293. float factor = 1.0f / (float)MathEx.Sqrt(len);
  294. x *= factor;
  295. y *= factor;
  296. z *= factor;
  297. w *= factor;
  298. return len;
  299. }
  300. /// <summary>
  301. /// Calculates the inverse of the quaternion. Inverse quaternion has the opposite rotation of the original.
  302. /// </summary>
  303. public void Invert()
  304. {
  305. float fNorm = w * w + x * x + y * y + z * z;
  306. if (fNorm > 0.0f)
  307. {
  308. float fInvNorm = 1.0f / fNorm;
  309. x *= -fInvNorm;
  310. y *= -fInvNorm;
  311. z *= -fInvNorm;
  312. w *= fInvNorm;
  313. }
  314. else
  315. {
  316. this = Zero;
  317. }
  318. }
  319. /// <summary>
  320. /// Initializes the quaternion so that it orients an object so it faces in te provided direction.
  321. /// </summary>
  322. /// <param name="forward">Direction to orient the object towards.</param>
  323. public void SetLookRotation(Vector3 forward)
  324. {
  325. FromToRotation(-Vector3.ZAxis, forward);
  326. }
  327. /// <summary>
  328. /// Initializes the quaternion so that it orients an object so it faces in te provided direction.
  329. /// </summary>
  330. /// <param name="forward">Direction to orient the object towards.</param>
  331. /// <param name="up">Axis that determines the upward direction of the object.</param>
  332. public void SetLookRotation(Vector3 forward, Vector3 up)
  333. {
  334. Vector3 forwardNrm = Vector3.Normalize(forward);
  335. Vector3 upNrm = Vector3.Normalize(up);
  336. if (MathEx.ApproxEquals(Vector3.Dot(forwardNrm, upNrm), 1.0f))
  337. {
  338. SetLookRotation(forwardNrm);
  339. return;
  340. }
  341. Vector3 x = Vector3.Cross(forwardNrm, upNrm);
  342. Vector3 y = Vector3.Cross(x, forwardNrm);
  343. x.Normalize();
  344. y.Normalize();
  345. this = Quaternion.FromAxes(x, y, -forwardNrm);
  346. }
  347. /// <summary>
  348. /// Performs spherical interpolation between two quaternions. Spherical interpolation neatly interpolates between
  349. /// two rotations without modifying the size of the vector it is applied to (unlike linear interpolation).
  350. /// </summary>
  351. /// <param name="from">Start quaternion.</param>
  352. /// <param name="to">End quaternion.</param>
  353. /// <param name="t">Interpolation factor in range [0, 1] that determines how much to interpolate between
  354. /// <paramref name="from"/> and <paramref name="to"/>.</param>
  355. /// <param name="shortestPath">Should the interpolation be performed between the shortest or longest path between
  356. /// the two quaternions.</param>
  357. /// <returns>Interpolated quaternion representing a rotation between <paramref name="from"/> and
  358. /// <paramref name="to"/>.</returns>
  359. public static Quaternion Slerp(Quaternion from, Quaternion to, float t, bool shortestPath = true)
  360. {
  361. float dot = Dot(from, to);
  362. Quaternion quat;
  363. if (dot < 0.0f && shortestPath)
  364. {
  365. dot = -dot;
  366. quat = -to;
  367. }
  368. else
  369. {
  370. quat = to;
  371. }
  372. if (MathEx.Abs(dot) < (1 - epsilon))
  373. {
  374. float sin = MathEx.Sqrt(1 - (dot*dot));
  375. Radian angle = MathEx.Atan2(sin, dot);
  376. float invSin = 1.0f / sin;
  377. float a = MathEx.Sin((1.0f - t) * angle) * invSin;
  378. float b = MathEx.Sin(t * angle) * invSin;
  379. return a * from + b * quat;
  380. }
  381. else
  382. {
  383. Quaternion ret = (1.0f - t) * from + t * quat;
  384. ret.Normalize();
  385. return ret;
  386. }
  387. }
  388. /// <summary>
  389. /// Returns the inverse of the quaternion. Quaternion must be non-zero. Inverse quaternion has the opposite
  390. /// rotation of the original.
  391. /// </summary>
  392. /// <param name="rotation">Quaternion to calculate the inverse for.</param>
  393. /// <returns>Inverse of the provided quaternion.</returns>
  394. public static Quaternion Invert(Quaternion rotation)
  395. {
  396. Quaternion copy = rotation;
  397. copy.Invert();
  398. return copy;
  399. }
  400. /// <summary>
  401. /// Calculates an angle between two rotations.
  402. /// </summary>
  403. /// <param name="a">First rotation.</param>
  404. /// <param name="b">Second rotation.</param>
  405. /// <returns>Angle between the rotations, in degrees.</returns>
  406. public static Degree Angle(Quaternion a, Quaternion b)
  407. {
  408. return (MathEx.Acos(MathEx.Min(MathEx.Abs(Dot(a, b)), 1.0f)) * 2.0f);
  409. }
  410. /// <summary>
  411. /// Converts the quaternion rotation into axis/angle rotation.
  412. /// </summary>
  413. /// <param name="axis">Axis around which the rotation is performed.</param>
  414. /// <param name="angle">Amount of rotation.</param>
  415. public void ToAxisAngle(out Vector3 axis, out Degree angle)
  416. {
  417. float fSqrLength = x*x+y*y+z*z;
  418. if (fSqrLength > 0.0f)
  419. {
  420. angle = 2.0f * MathEx.Acos(w);
  421. float fInvLength = MathEx.InvSqrt(fSqrLength);
  422. axis.x = x*fInvLength;
  423. axis.y = y*fInvLength;
  424. axis.z = z*fInvLength;
  425. }
  426. else
  427. {
  428. // Angle is 0, so any axis will do
  429. angle = (Degree)0.0f;
  430. axis.x = 1.0f;
  431. axis.y = 0.0f;
  432. axis.z = 0.0f;
  433. }
  434. }
  435. /// <summary>
  436. /// Converts a quaternion into an orthonormal set of axes.
  437. /// </summary>
  438. /// <param name="xAxis">Output normalized x axis.</param>
  439. /// <param name="yAxis">Output normalized y axis.</param>
  440. /// <param name="zAxis">Output normalized z axis.</param>
  441. public void ToAxes(ref Vector3 xAxis, ref Vector3 yAxis, ref Vector3 zAxis)
  442. {
  443. Matrix3 matRot = ToRotationMatrix();
  444. xAxis.x = matRot[0, 0];
  445. xAxis.y = matRot[1, 0];
  446. xAxis.z = matRot[2, 0];
  447. yAxis.x = matRot[0, 1];
  448. yAxis.y = matRot[1, 1];
  449. yAxis.z = matRot[2, 1];
  450. zAxis.x = matRot[0, 2];
  451. zAxis.y = matRot[1, 2];
  452. zAxis.z = matRot[2, 2];
  453. }
  454. /// <summary>
  455. /// Converts the quaternion rotation into euler angle (pitch/yaw/roll) rotation.
  456. /// </summary>
  457. /// <returns>Rotation as euler angles, in degrees.</returns>
  458. public Vector3 ToEuler()
  459. {
  460. Matrix3 matRot = ToRotationMatrix();
  461. return matRot.ToEulerAngles();
  462. }
  463. /// <summary>
  464. /// Converts a quaternion rotation into a rotation matrix.
  465. /// </summary>
  466. /// <returns>Matrix representing the rotation.</returns>
  467. public Matrix3 ToRotationMatrix()
  468. {
  469. Matrix3 mat = new Matrix3();
  470. float tx = x + x;
  471. float ty = y + y;
  472. float fTz = z + z;
  473. float twx = tx * w;
  474. float twy = ty * w;
  475. float twz = fTz * w;
  476. float txx = tx * x;
  477. float txy = ty * x;
  478. float txz = fTz * x;
  479. float tyy = ty * y;
  480. float tyz = fTz * y;
  481. float tzz = fTz * z;
  482. mat[0, 0] = 1.0f - (tyy + tzz);
  483. mat[0, 1] = txy - twz;
  484. mat[0, 2] = txz + twy;
  485. mat[1, 0] = txy + twz;
  486. mat[1, 1] = 1.0f - (txx + tzz);
  487. mat[1, 2] = tyz - twx;
  488. mat[2, 0] = txz - twy;
  489. mat[2, 1] = tyz + twx;
  490. mat[2, 2] = 1.0f - (txx + tyy);
  491. return mat;
  492. }
  493. /// <summary>
  494. /// Creates a quaternion with rotation that rotates from one direction to another.
  495. /// </summary>
  496. /// <param name="fromDirection">Rotation to start at.</param>
  497. /// <param name="toDirection">Rotation to end at.</param>
  498. /// <returns>Quaternion that rotates an object from <paramref name="fromDirection"/> to
  499. /// <paramref name="toDirection"/></returns>
  500. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection)
  501. {
  502. Quaternion q = new Quaternion();
  503. q.SetFromToRotation(fromDirection, toDirection);
  504. return q;
  505. }
  506. /// <summary>
  507. /// Creates a quaternion with rotation that rotates from one direction to another.
  508. /// </summary>
  509. /// <param name="fromDirection">Rotation to start at.</param>
  510. /// <param name="toDirection">Rotation to end at.</param>
  511. /// <param name="fallbackAxis">Fallback axis to use if the from/to vectors are almost completely opposite.
  512. /// Fallback axis should be perpendicular to both vectors.</param>
  513. /// <returns>Quaternion that rotates an object from <paramref name="fromDirection"/> to
  514. /// <paramref name="toDirection"/></returns>
  515. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  516. {
  517. Quaternion q = new Quaternion();
  518. q.SetFromToRotation(fromDirection, toDirection, fallbackAxis);
  519. return q;
  520. }
  521. /// <summary>
  522. /// Creates a quaternion that orients an object so it faces in te provided direction.
  523. /// </summary>
  524. /// <param name="forward">Direction to orient the object towards.</param>
  525. public static Quaternion LookRotation(Vector3 forward)
  526. {
  527. Quaternion quat = new Quaternion();
  528. quat.SetLookRotation(forward);
  529. return quat;
  530. }
  531. /// <summary>
  532. /// Creates a quaternion that orients an object so it faces in the provided direction.
  533. /// </summary>
  534. /// <param name="forward">Direction to orient the object towards.</param>
  535. /// <param name="up">Axis that determines the upward direction of the object.</param>
  536. public static Quaternion LookRotation(Vector3 forward, Vector3 up)
  537. {
  538. Quaternion quat = new Quaternion();
  539. quat.SetLookRotation(forward, up);
  540. return quat;
  541. }
  542. /// <summary>
  543. /// Converts the quaternion rotation into euler angle (pitch/yaw/roll) rotation.
  544. /// </summary>
  545. /// <param name="rotation">Quaternion to convert.</param>
  546. /// <returns>Rotation as euler angles, in degrees.</returns>
  547. public static Vector3 ToEuler(Quaternion rotation)
  548. {
  549. return rotation.ToEuler();
  550. }
  551. /// <summary>
  552. /// Converts the quaternion rotation into axis/angle rotation.
  553. /// </summary>
  554. /// <param name="rotation">Quaternion to convert.</param>
  555. /// <param name="axis">Axis around which the rotation is performed.</param>
  556. /// <param name="angle">Amount of rotation.</param>
  557. public static void ToAxisAngle(Quaternion rotation, out Vector3 axis, out Degree angle)
  558. {
  559. rotation.ToAxisAngle(out axis, out angle);
  560. }
  561. /// <summary>
  562. /// Creates a quaternion from a rotation matrix.
  563. /// </summary>
  564. /// <param name="rotMatrix">Rotation matrix to convert to quaternion.</param>
  565. /// <returns>Newly created quaternion that has equivalent rotation as the provided rotation matrix.</returns>
  566. public static Quaternion FromRotationMatrix(Matrix3 rotMatrix)
  567. {
  568. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  569. // article "Quaternion Calculus and Fast Animation".
  570. Quaternion quat = new Quaternion();
  571. float trace = rotMatrix.m00 + rotMatrix.m11 + rotMatrix.m22;
  572. float root;
  573. if (trace > 0.0f)
  574. {
  575. // |w| > 1/2, may as well choose w > 1/2
  576. root = MathEx.Sqrt(trace + 1.0f); // 2w
  577. quat.w = 0.5f*root;
  578. root = 0.5f/root; // 1/(4w)
  579. quat.x = (rotMatrix.m21 - rotMatrix.m12) * root;
  580. quat.y = (rotMatrix.m02 - rotMatrix.m20) * root;
  581. quat.z = (rotMatrix.m10 - rotMatrix.m01) * root;
  582. }
  583. else
  584. {
  585. // |w| <= 1/2
  586. int[] nextLookup = { 1, 2, 0 };
  587. int i = 0;
  588. if (rotMatrix.m11 > rotMatrix.m00)
  589. i = 1;
  590. if (rotMatrix.m22 > rotMatrix[i, i])
  591. i = 2;
  592. int j = nextLookup[i];
  593. int k = nextLookup[j];
  594. root = MathEx.Sqrt(rotMatrix[i,i] - rotMatrix[j, j] - rotMatrix[k, k] + 1.0f);
  595. quat[i] = 0.5f*root;
  596. root = 0.5f/root;
  597. quat.w = (rotMatrix[k, j] - rotMatrix[j, k]) * root;
  598. quat[j] = (rotMatrix[j, i] + rotMatrix[i, j]) * root;
  599. quat[k] = (rotMatrix[k, i] + rotMatrix[i, k]) * root;
  600. }
  601. quat.Normalize();
  602. return quat;
  603. }
  604. /// <summary>
  605. /// Creates a quaternion from axis/angle rotation.
  606. /// </summary>
  607. /// <param name="axis">Axis around which the rotation is performed.</param>
  608. /// <param name="angle">Amount of rotation.</param>
  609. /// <returns>Quaternion that rotates an object around the specified axis for the specified amount.</returns>
  610. public static Quaternion FromAxisAngle(Vector3 axis, Degree angle)
  611. {
  612. Quaternion quat;
  613. float halfAngle = (float)(0.5f*angle.Radians);
  614. float sin = (float)MathEx.Sin(halfAngle);
  615. quat.w = (float)MathEx.Cos(halfAngle);
  616. quat.x = sin * axis.x;
  617. quat.y = sin * axis.y;
  618. quat.z = sin * axis.z;
  619. return quat;
  620. }
  621. /// <summary>
  622. /// Initializes the quaternion from orthonormal set of axes.
  623. /// </summary>
  624. /// <param name="xAxis">Normalized x axis.</param>
  625. /// <param name="yAxis">Normalized y axis.</param>
  626. /// <param name="zAxis">Normalized z axis.</param>
  627. /// <returns>Quaternion that represents a rotation from base axes to the specified set of axes.</returns>
  628. public static Quaternion FromAxes(Vector3 xAxis, Vector3 yAxis, Vector3 zAxis)
  629. {
  630. Matrix3 mat;
  631. mat.m00 = xAxis.x;
  632. mat.m10 = xAxis.y;
  633. mat.m20 = xAxis.z;
  634. mat.m01 = yAxis.x;
  635. mat.m11 = yAxis.y;
  636. mat.m21 = yAxis.z;
  637. mat.m02 = zAxis.x;
  638. mat.m12 = zAxis.y;
  639. mat.m22 = zAxis.z;
  640. return FromRotationMatrix(mat);
  641. }
  642. /// <summary>
  643. /// Creates a quaternion from the provided euler angle (pitch/yaw/roll) rotation.
  644. /// </summary>
  645. /// <param name="xAngle">Pitch angle of rotation.</param>
  646. /// <param name="yAngle">Yar angle of rotation.</param>
  647. /// <param name="zAngle">Roll angle of rotation.</param>
  648. /// <param name="order">The order in which rotations will be applied. Different rotations can be created depending
  649. /// on the order.</param>
  650. /// <returns>Quaternion that can rotate an object to the specified angles.</returns>
  651. public static Quaternion FromEuler(Degree xAngle, Degree yAngle, Degree zAngle,
  652. EulerAngleOrder order = EulerAngleOrder.YXZ)
  653. {
  654. EulerAngleOrderData l = EA_LOOKUP[(int)order];
  655. Radian halfXAngle = xAngle * 0.5f;
  656. Radian halfYAngle = yAngle * 0.5f;
  657. Radian halfZAngle = zAngle * 0.5f;
  658. float cx = MathEx.Cos(halfXAngle);
  659. float sx = MathEx.Sin(halfXAngle);
  660. float cy = MathEx.Cos(halfYAngle);
  661. float sy = MathEx.Sin(halfYAngle);
  662. float cz = MathEx.Cos(halfZAngle);
  663. float sz = MathEx.Sin(halfZAngle);
  664. Quaternion[] quats = new Quaternion[3];
  665. quats[0] = new Quaternion(sx, 0.0f, 0.0f, cx);
  666. quats[1] = new Quaternion(0.0f, sy, 0.0f, cy);
  667. quats[2] = new Quaternion(0.0f, 0.0f, sz, cz);
  668. return (quats[l.a] * quats[l.b]) * quats[l.c];
  669. }
  670. /// <summary>
  671. /// Creates a quaternion from the provided euler angle (pitch/yaw/roll) rotation.
  672. /// </summary>
  673. /// <param name="euler">Euler angles in degrees.</param>
  674. /// <param name="order">The order in which rotations will be applied. Different rotations can be created depending
  675. /// on the order.</param>
  676. /// <returns>Quaternion that can rotate an object to the specified angles.</returns>
  677. public static Quaternion FromEuler(Vector3 euler, EulerAngleOrder order = EulerAngleOrder.YXZ)
  678. {
  679. return FromEuler((Degree)euler.x, (Degree)euler.y, (Degree)euler.z, order);
  680. }
  681. /// <inheritdoc/>
  682. public override int GetHashCode()
  683. {
  684. return x.GetHashCode() ^ y.GetHashCode() << 2 ^ z.GetHashCode() >> 2 ^ w.GetHashCode() >> 1;
  685. }
  686. /// <inheritdoc/>
  687. public override bool Equals(object other)
  688. {
  689. if (!(other is Quaternion))
  690. return false;
  691. Quaternion quat = (Quaternion)other;
  692. if (x.Equals(quat.x) && y.Equals(quat.y) && z.Equals(quat.z) && w.Equals(quat.w))
  693. return true;
  694. return false;
  695. }
  696. /// <inheritdoc/>
  697. public override string ToString()
  698. {
  699. return String.Format("({0}, {1}, {2}, {3})", x, y, z, w);
  700. }
  701. }
  702. /** @} */
  703. }