Quaternion.cs 27 KB

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