Math.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * Farseer Physics Engine based on Box2D.XNA port:
  3. * Copyright (c) 2010 Ian Qvist
  4. *
  5. * Box2D.XNA port of Box2D:
  6. * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
  7. *
  8. * Original source Box2D:
  9. * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
  10. *
  11. * This software is provided 'as-is', without any express or implied
  12. * warranty. In no event will the authors be held liable for any damages
  13. * arising from the use of this software.
  14. * Permission is granted to anyone to use this software for any purpose,
  15. * including commercial applications, and to alter it and redistribute it
  16. * freely, subject to the following restrictions:
  17. * 1. The origin of this software must not be misrepresented; you must not
  18. * claim that you wrote the original software. If you use this software
  19. * in a product, an acknowledgment in the product documentation would be
  20. * appreciated but is not required.
  21. * 2. Altered source versions must be plainly marked as such, and must not be
  22. * misrepresented as being the original software.
  23. * 3. This notice may not be removed or altered from any source distribution.
  24. */
  25. using System;
  26. using System.Diagnostics;
  27. using System.Runtime.InteropServices;
  28. using Microsoft.Xna.Framework;
  29. namespace FarseerPhysics.Common
  30. {
  31. public static class MathUtils
  32. {
  33. public static float Cross(Vector2 a, Vector2 b)
  34. {
  35. return a.X * b.Y - a.Y * b.X;
  36. }
  37. public static Vector2 Cross(Vector2 a, float s)
  38. {
  39. return new Vector2(s * a.Y, -s * a.X);
  40. }
  41. public static Vector2 Cross(float s, Vector2 a)
  42. {
  43. return new Vector2(-s * a.Y, s * a.X);
  44. }
  45. public static Vector2 Abs(Vector2 v)
  46. {
  47. return new Vector2(Math.Abs(v.X), Math.Abs(v.Y));
  48. }
  49. public static Vector2 Multiply(ref Mat22 A, Vector2 v)
  50. {
  51. return Multiply(ref A, ref v);
  52. }
  53. public static Vector2 Multiply(ref Mat22 A, ref Vector2 v)
  54. {
  55. return new Vector2(A.Col1.X * v.X + A.Col2.X * v.Y, A.Col1.Y * v.X + A.Col2.Y * v.Y);
  56. }
  57. public static Vector2 MultiplyT(ref Mat22 A, Vector2 v)
  58. {
  59. return MultiplyT(ref A, ref v);
  60. }
  61. public static Vector2 MultiplyT(ref Mat22 A, ref Vector2 v)
  62. {
  63. return new Vector2(v.X * A.Col1.X + v.Y * A.Col1.Y, v.X * A.Col2.X + v.Y * A.Col2.Y);
  64. }
  65. public static Vector2 Multiply(ref Transform T, Vector2 v)
  66. {
  67. return Multiply(ref T, ref v);
  68. }
  69. public static Vector2 Multiply(ref Transform T, ref Vector2 v)
  70. {
  71. return new Vector2(T.Position.X + T.R.Col1.X * v.X + T.R.Col2.X * v.Y,
  72. T.Position.Y + T.R.Col1.Y * v.X + T.R.Col2.Y * v.Y);
  73. }
  74. public static Vector2 MultiplyT(ref Transform T, Vector2 v)
  75. {
  76. return MultiplyT(ref T, ref v);
  77. }
  78. public static Vector2 MultiplyT(ref Transform T, ref Vector2 v)
  79. {
  80. Vector2 tmp = Vector2.Zero;
  81. tmp.X = v.X - T.Position.X;
  82. tmp.Y = v.Y - T.Position.Y;
  83. return MultiplyT(ref T.R, ref tmp);
  84. }
  85. // A^T * B
  86. public static void MultiplyT(ref Mat22 A, ref Mat22 B, out Mat22 C)
  87. {
  88. C = new Mat22();
  89. C.Col1.X = A.Col1.X * B.Col1.X + A.Col1.Y * B.Col1.Y;
  90. C.Col1.Y = A.Col2.X * B.Col1.X + A.Col2.Y * B.Col1.Y;
  91. C.Col2.X = A.Col1.X * B.Col2.X + A.Col1.Y * B.Col2.Y;
  92. C.Col2.Y = A.Col2.X * B.Col2.X + A.Col2.Y * B.Col2.Y;
  93. }
  94. // v2 = A.R' * (B.R * v1 + B.p - A.p) = (A.R' * B.R) * v1 + (B.p - A.p)
  95. public static void MultiplyT(ref Transform A, ref Transform B, out Transform C)
  96. {
  97. C = new Transform();
  98. MultiplyT(ref A.R, ref B.R, out C.R);
  99. C.Position.X = B.Position.X - A.Position.X;
  100. C.Position.Y = B.Position.Y - A.Position.Y;
  101. }
  102. public static void Swap<T>(ref T a, ref T b)
  103. {
  104. T tmp = a;
  105. a = b;
  106. b = tmp;
  107. }
  108. /// <summary>
  109. /// This function is used to ensure that a floating point number is
  110. /// not a NaN or infinity.
  111. /// </summary>
  112. /// <param name="x">The x.</param>
  113. /// <returns>
  114. /// <c>true</c> if the specified x is valid; otherwise, <c>false</c>.
  115. /// </returns>
  116. public static bool IsValid(float x)
  117. {
  118. if (float.IsNaN(x))
  119. {
  120. // NaN.
  121. return false;
  122. }
  123. return !float.IsInfinity(x);
  124. }
  125. public static bool IsValid(this Vector2 x)
  126. {
  127. return IsValid(x.X) && IsValid(x.Y);
  128. }
  129. /// <summary>
  130. /// This is a approximate yet fast inverse square-root.
  131. /// </summary>
  132. /// <param name="x">The x.</param>
  133. /// <returns></returns>
  134. public static float InvSqrt(float x)
  135. {
  136. FloatConverter convert = new FloatConverter();
  137. convert.x = x;
  138. float xhalf = 0.5f * x;
  139. convert.i = 0x5f3759df - (convert.i >> 1);
  140. x = convert.x;
  141. x = x * (1.5f - xhalf * x * x);
  142. return x;
  143. }
  144. public static int Clamp(int a, int low, int high)
  145. {
  146. return Math.Max(low, Math.Min(a, high));
  147. }
  148. public static float Clamp(float a, float low, float high)
  149. {
  150. return Math.Max(low, Math.Min(a, high));
  151. }
  152. public static Vector2 Clamp(Vector2 a, Vector2 low, Vector2 high)
  153. {
  154. return Vector2.Max(low, Vector2.Min(a, high));
  155. }
  156. public static void Cross(ref Vector2 a, ref Vector2 b, out float c)
  157. {
  158. c = a.X * b.Y - a.Y * b.X;
  159. }
  160. /// <summary>
  161. /// Return the angle between two vectors on a plane
  162. /// The angle is from vector 1 to vector 2, positive anticlockwise
  163. /// The result is between -pi -> pi
  164. /// </summary>
  165. public static double VectorAngle(ref Vector2 p1, ref Vector2 p2)
  166. {
  167. double theta1 = Math.Atan2(p1.Y, p1.X);
  168. double theta2 = Math.Atan2(p2.Y, p2.X);
  169. double dtheta = theta2 - theta1;
  170. while (dtheta > Math.PI)
  171. dtheta -= (2 * Math.PI);
  172. while (dtheta < -Math.PI)
  173. dtheta += (2 * Math.PI);
  174. return (dtheta);
  175. }
  176. public static double VectorAngle(Vector2 p1, Vector2 p2)
  177. {
  178. return VectorAngle(ref p1, ref p2);
  179. }
  180. /// <summary>
  181. /// Returns a positive number if c is to the left of the line going from a to b.
  182. /// </summary>
  183. /// <returns>Positive number if point is left, negative if point is right,
  184. /// and 0 if points are collinear.</returns>
  185. public static float Area(Vector2 a, Vector2 b, Vector2 c)
  186. {
  187. return Area(ref a, ref b, ref c);
  188. }
  189. /// <summary>
  190. /// Returns a positive number if c is to the left of the line going from a to b.
  191. /// </summary>
  192. /// <returns>Positive number if point is left, negative if point is right,
  193. /// and 0 if points are collinear.</returns>
  194. public static float Area(ref Vector2 a, ref Vector2 b, ref Vector2 c)
  195. {
  196. return a.X * (b.Y - c.Y) + b.X * (c.Y - a.Y) + c.X * (a.Y - b.Y);
  197. }
  198. /// <summary>
  199. /// Determines if three vertices are collinear (ie. on a straight line)
  200. /// </summary>
  201. /// <param name="a">First vertex</param>
  202. /// <param name="b">Second vertex</param>
  203. /// <param name="c">Third vertex</param>
  204. /// <returns></returns>
  205. public static bool Collinear(ref Vector2 a, ref Vector2 b, ref Vector2 c)
  206. {
  207. return Collinear(ref a, ref b, ref c, 0);
  208. }
  209. public static bool Collinear(ref Vector2 a, ref Vector2 b, ref Vector2 c, float tolerance)
  210. {
  211. return FloatInRange(Area(ref a, ref b, ref c), -tolerance, tolerance);
  212. }
  213. public static void Cross(float s, ref Vector2 a, out Vector2 b)
  214. {
  215. b = new Vector2(-s * a.Y, s * a.X);
  216. }
  217. public static bool FloatEquals(float value1, float value2)
  218. {
  219. return Math.Abs(value1 - value2) <= Settings.Epsilon;
  220. }
  221. /// <summary>
  222. /// Checks if a floating point Value is equal to another,
  223. /// within a certain tolerance.
  224. /// </summary>
  225. /// <param name="value1">The first floating point Value.</param>
  226. /// <param name="value2">The second floating point Value.</param>
  227. /// <param name="delta">The floating point tolerance.</param>
  228. /// <returns>True if the values are "equal", false otherwise.</returns>
  229. public static bool FloatEquals(float value1, float value2, float delta)
  230. {
  231. return FloatInRange(value1, value2 - delta, value2 + delta);
  232. }
  233. /// <summary>
  234. /// Checks if a floating point Value is within a specified
  235. /// range of values (inclusive).
  236. /// </summary>
  237. /// <param name="value">The Value to check.</param>
  238. /// <param name="min">The minimum Value.</param>
  239. /// <param name="max">The maximum Value.</param>
  240. /// <returns>True if the Value is within the range specified,
  241. /// false otherwise.</returns>
  242. public static bool FloatInRange(float value, float min, float max)
  243. {
  244. return (value >= min && value <= max);
  245. }
  246. #region Nested type: FloatConverter
  247. [StructLayout(LayoutKind.Explicit)]
  248. private struct FloatConverter
  249. {
  250. [FieldOffset(0)]
  251. public float x;
  252. [FieldOffset(0)]
  253. public int i;
  254. }
  255. #endregion
  256. }
  257. /// <summary>
  258. /// A 2-by-2 matrix. Stored in column-major order.
  259. /// </summary>
  260. public struct Mat22
  261. {
  262. public Vector2 Col1, Col2;
  263. /// <summary>
  264. /// Construct this matrix using columns.
  265. /// </summary>
  266. /// <param name="c1">The c1.</param>
  267. /// <param name="c2">The c2.</param>
  268. public Mat22(Vector2 c1, Vector2 c2)
  269. {
  270. Col1 = c1;
  271. Col2 = c2;
  272. }
  273. /// <summary>
  274. /// Construct this matrix using scalars.
  275. /// </summary>
  276. /// <param name="a11">The a11.</param>
  277. /// <param name="a12">The a12.</param>
  278. /// <param name="a21">The a21.</param>
  279. /// <param name="a22">The a22.</param>
  280. public Mat22(float a11, float a12, float a21, float a22)
  281. {
  282. Col1 = new Vector2(a11, a21);
  283. Col2 = new Vector2(a12, a22);
  284. }
  285. /// <summary>
  286. /// Construct this matrix using an angle. This matrix becomes
  287. /// an orthonormal rotation matrix.
  288. /// </summary>
  289. /// <param name="angle">The angle.</param>
  290. public Mat22(float angle)
  291. {
  292. // TODO_ERIN compute sin+cos together.
  293. float c = (float)Math.Cos(angle), s = (float)Math.Sin(angle);
  294. Col1 = new Vector2(c, s);
  295. Col2 = new Vector2(-s, c);
  296. }
  297. /// <summary>
  298. /// Extract the angle from this matrix (assumed to be
  299. /// a rotation matrix).
  300. /// </summary>
  301. /// <value></value>
  302. public float Angle
  303. {
  304. get { return (float)Math.Atan2(Col1.Y, Col1.X); }
  305. }
  306. public Mat22 Inverse
  307. {
  308. get
  309. {
  310. float a = Col1.X, b = Col2.X, c = Col1.Y, d = Col2.Y;
  311. float det = a * d - b * c;
  312. if (det != 0.0f)
  313. {
  314. det = 1.0f / det;
  315. }
  316. Mat22 result = new Mat22();
  317. result.Col1.X = det * d;
  318. result.Col1.Y = -det * c;
  319. result.Col2.X = -det * b;
  320. result.Col2.Y = det * a;
  321. return result;
  322. }
  323. }
  324. /// <summary>
  325. /// Initialize this matrix using columns.
  326. /// </summary>
  327. /// <param name="c1">The c1.</param>
  328. /// <param name="c2">The c2.</param>
  329. public void Set(Vector2 c1, Vector2 c2)
  330. {
  331. Col1 = c1;
  332. Col2 = c2;
  333. }
  334. /// <summary>
  335. /// Initialize this matrix using an angle. This matrix becomes
  336. /// an orthonormal rotation matrix.
  337. /// </summary>
  338. /// <param name="angle">The angle.</param>
  339. public void Set(float angle)
  340. {
  341. float c = (float)Math.Cos(angle), s = (float)Math.Sin(angle);
  342. Col1.X = c;
  343. Col2.X = -s;
  344. Col1.Y = s;
  345. Col2.Y = c;
  346. }
  347. /// <summary>
  348. /// Set this to the identity matrix.
  349. /// </summary>
  350. public void SetIdentity()
  351. {
  352. Col1.X = 1.0f;
  353. Col2.X = 0.0f;
  354. Col1.Y = 0.0f;
  355. Col2.Y = 1.0f;
  356. }
  357. /// <summary>
  358. /// Set this matrix to all zeros.
  359. /// </summary>
  360. public void SetZero()
  361. {
  362. Col1.X = 0.0f;
  363. Col2.X = 0.0f;
  364. Col1.Y = 0.0f;
  365. Col2.Y = 0.0f;
  366. }
  367. /// <summary>
  368. /// Solve A * x = b, where b is a column vector. This is more efficient
  369. /// than computing the inverse in one-shot cases.
  370. /// </summary>
  371. /// <param name="b">The b.</param>
  372. /// <returns></returns>
  373. public Vector2 Solve(Vector2 b)
  374. {
  375. float a11 = Col1.X, a12 = Col2.X, a21 = Col1.Y, a22 = Col2.Y;
  376. float det = a11 * a22 - a12 * a21;
  377. if (det != 0.0f)
  378. {
  379. det = 1.0f / det;
  380. }
  381. return new Vector2(det * (a22 * b.X - a12 * b.Y), det * (a11 * b.Y - a21 * b.X));
  382. }
  383. public static void Add(ref Mat22 A, ref Mat22 B, out Mat22 R)
  384. {
  385. R.Col1 = A.Col1 + B.Col1;
  386. R.Col2 = A.Col2 + B.Col2;
  387. }
  388. }
  389. /// <summary>
  390. /// A 3-by-3 matrix. Stored in column-major order.
  391. /// </summary>
  392. public struct Mat33
  393. {
  394. public Vector3 Col1, Col2, Col3;
  395. /// <summary>
  396. /// Construct this matrix using columns.
  397. /// </summary>
  398. /// <param name="c1">The c1.</param>
  399. /// <param name="c2">The c2.</param>
  400. /// <param name="c3">The c3.</param>
  401. public Mat33(Vector3 c1, Vector3 c2, Vector3 c3)
  402. {
  403. Col1 = c1;
  404. Col2 = c2;
  405. Col3 = c3;
  406. }
  407. /// <summary>
  408. /// Set this matrix to all zeros.
  409. /// </summary>
  410. public void SetZero()
  411. {
  412. Col1 = Vector3.Zero;
  413. Col2 = Vector3.Zero;
  414. Col3 = Vector3.Zero;
  415. }
  416. /// <summary>
  417. /// Solve A * x = b, where b is a column vector. This is more efficient
  418. /// than computing the inverse in one-shot cases.
  419. /// </summary>
  420. /// <param name="b">The b.</param>
  421. /// <returns></returns>
  422. public Vector3 Solve33(Vector3 b)
  423. {
  424. float det = Vector3.Dot(Col1, Vector3.Cross(Col2, Col3));
  425. if (det != 0.0f)
  426. {
  427. det = 1.0f / det;
  428. }
  429. return new Vector3(det * Vector3.Dot(b, Vector3.Cross(Col2, Col3)),
  430. det * Vector3.Dot(Col1, Vector3.Cross(b, Col3)),
  431. det * Vector3.Dot(Col1, Vector3.Cross(Col2, b)));
  432. }
  433. /// <summary>
  434. /// Solve A * x = b, where b is a column vector. This is more efficient
  435. /// than computing the inverse in one-shot cases. Solve only the upper
  436. /// 2-by-2 matrix equation.
  437. /// </summary>
  438. /// <param name="b">The b.</param>
  439. /// <returns></returns>
  440. public Vector2 Solve22(Vector2 b)
  441. {
  442. float a11 = Col1.X, a12 = Col2.X, a21 = Col1.Y, a22 = Col2.Y;
  443. float det = a11 * a22 - a12 * a21;
  444. if (det != 0.0f)
  445. {
  446. det = 1.0f / det;
  447. }
  448. return new Vector2(det * (a22 * b.X - a12 * b.Y), det * (a11 * b.Y - a21 * b.X));
  449. }
  450. }
  451. /// <summary>
  452. /// A transform contains translation and rotation. It is used to represent
  453. /// the position and orientation of rigid frames.
  454. /// </summary>
  455. public struct Transform
  456. {
  457. public Vector2 Position;
  458. public Mat22 R;
  459. /// <summary>
  460. /// Initialize using a position vector and a rotation matrix.
  461. /// </summary>
  462. /// <param name="position">The position.</param>
  463. /// <param name="r">The r.</param>
  464. public Transform(ref Vector2 position, ref Mat22 r)
  465. {
  466. Position = position;
  467. R = r;
  468. }
  469. /// <summary>
  470. /// Calculate the angle that the rotation matrix represents.
  471. /// </summary>
  472. /// <value></value>
  473. public float Angle
  474. {
  475. get { return (float)Math.Atan2(R.Col1.Y, R.Col1.X); }
  476. }
  477. /// <summary>
  478. /// Set this to the identity transform.
  479. /// </summary>
  480. public void SetIdentity()
  481. {
  482. Position = Vector2.Zero;
  483. R.SetIdentity();
  484. }
  485. /// <summary>
  486. /// Set this based on the position and angle.
  487. /// </summary>
  488. /// <param name="position">The position.</param>
  489. /// <param name="angle">The angle.</param>
  490. public void Set(Vector2 position, float angle)
  491. {
  492. Position = position;
  493. R.Set(angle);
  494. }
  495. }
  496. /// <summary>
  497. /// This describes the motion of a body/shape for TOI computation.
  498. /// Shapes are defined with respect to the body origin, which may
  499. /// no coincide with the center of mass. However, to support dynamics
  500. /// we must interpolate the center of mass position.
  501. /// </summary>
  502. public struct Sweep
  503. {
  504. /// <summary>
  505. /// World angles
  506. /// </summary>
  507. public float A;
  508. public float A0;
  509. /// <summary>
  510. /// Fraction of the current time step in the range [0,1]
  511. /// c0 and a0 are the positions at alpha0.
  512. /// </summary>
  513. public float Alpha0;
  514. /// <summary>
  515. /// Center world positions
  516. /// </summary>
  517. public Vector2 C;
  518. public Vector2 C0;
  519. /// <summary>
  520. /// Local center of mass position
  521. /// </summary>
  522. public Vector2 LocalCenter;
  523. /// <summary>
  524. /// Get the interpolated transform at a specific time.
  525. /// </summary>
  526. /// <param name="xf">The transform.</param>
  527. /// <param name="beta">beta is a factor in [0,1], where 0 indicates alpha0.</param>
  528. public void GetTransform(out Transform xf, float beta)
  529. {
  530. xf = new Transform();
  531. xf.Position.X = (1.0f - beta) * C0.X + beta * C.X;
  532. xf.Position.Y = (1.0f - beta) * C0.Y + beta * C.Y;
  533. float angle = (1.0f - beta) * A0 + beta * A;
  534. xf.R.Set(angle);
  535. // Shift to origin
  536. xf.Position -= MathUtils.Multiply(ref xf.R, ref LocalCenter);
  537. }
  538. /// <summary>
  539. /// Advance the sweep forward, yielding a new initial state.
  540. /// </summary>
  541. /// <param name="alpha">new initial time..</param>
  542. public void Advance(float alpha)
  543. {
  544. Debug.Assert(Alpha0 < 1.0f);
  545. float beta = (alpha - Alpha0) / (1.0f - Alpha0);
  546. C0.X = (1.0f - beta) * C0.X + beta * C.X;
  547. C0.Y = (1.0f - beta) * C0.Y + beta * C.Y;
  548. A0 = (1.0f - beta) * A0 + beta * A;
  549. Alpha0 = alpha;
  550. }
  551. /// <summary>
  552. /// Normalize the angles.
  553. /// </summary>
  554. public void Normalize()
  555. {
  556. float d = MathHelper.TwoPi * (float)Math.Floor(A0 / MathHelper.TwoPi);
  557. A0 -= d;
  558. A -= d;
  559. }
  560. }
  561. }