DistanceJoint.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Box2D.XNA port of Box2D:
  3. * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
  4. *
  5. * Original source Box2D:
  6. * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
  7. *
  8. * This software is provided 'as-is', without any express or implied
  9. * warranty. In no event will the authors be held liable for any damages
  10. * arising from the use of this software.
  11. * Permission is granted to anyone to use this software for any purpose,
  12. * including commercial applications, and to alter it and redistribute it
  13. * freely, subject to the following restrictions:
  14. * 1. The origin of this software must not be misrepresented; you must not
  15. * claim that you wrote the original software. If you use this software
  16. * in a product, an acknowledgment in the product documentation would be
  17. * appreciated but is not required.
  18. * 2. Altered source versions must be plainly marked as such, and must not be
  19. * misrepresented as being the original software.
  20. * 3. This notice may not be removed or altered from any source distribution.
  21. */
  22. using System;
  23. using System.Diagnostics;
  24. using Microsoft.Xna.Framework;
  25. namespace Box2D.XNA
  26. {
  27. /// Distance joint definition. This requires defining an
  28. /// anchor point on both bodies and the non-zero length of the
  29. /// distance joint. The definition uses local anchor points
  30. /// so that the initial configuration can violate the constraint
  31. /// slightly. This helps when saving and loading a game.
  32. /// @warning Do not use a zero or short length.
  33. public class DistanceJointDef : JointDef
  34. {
  35. public DistanceJointDef()
  36. {
  37. type = JointType.Distance;
  38. localAnchorA = new Vector2(0.0f, 0.0f);
  39. localAnchorB = new Vector2(0.0f, 0.0f);
  40. length = 1.0f;
  41. frequencyHz = 0.0f;
  42. dampingRatio = 0.0f;
  43. }
  44. /// Initialize the bodies, anchors, and length using the world
  45. /// anchors.
  46. // 1-D rained system
  47. // m (v2 - v1) = lambda
  48. // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
  49. // x2 = x1 + h * v2
  50. // 1-D mass-damper-spring system
  51. // m (v2 - v1) + h * d * v2 + h * k *
  52. // C = norm(p2 - p1) - L
  53. // u = (p2 - p1) / norm(p2 - p1)
  54. // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
  55. // J = [-u -cross(r1, u) u cross(r2, u)]
  56. // K = J * invM * JT
  57. // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
  58. public void Initialize(Body b1, Body b2,
  59. Vector2 anchor1, Vector2 anchor2)
  60. {
  61. bodyA = b1;
  62. bodyB = b2;
  63. localAnchorA = bodyA.GetLocalPoint(anchor1);
  64. localAnchorB = bodyB.GetLocalPoint(anchor2);
  65. Vector2 d = anchor2 - anchor1;
  66. length = d.Length();
  67. }
  68. /// The local anchor point relative to body1's origin.
  69. public Vector2 localAnchorA;
  70. /// The local anchor point relative to body2's origin.
  71. public Vector2 localAnchorB;
  72. /// The natural length between the anchor points.
  73. public float length;
  74. /// The mass-spring-damper frequency in Hertz.
  75. public float frequencyHz;
  76. /// The damping ratio. 0 = no damping, 1 = critical damping.
  77. public float dampingRatio;
  78. };
  79. /// A distance joint rains two points on two bodies
  80. /// to remain at a fixed distance from each other. You can view
  81. /// this as a massless, rigid rod.
  82. public class DistanceJoint : Joint
  83. {
  84. /// Set/get the natural length.
  85. /// Manipulating the length can lead to non-physical behavior when the frequency is zero.
  86. public void SetLength(float length)
  87. {
  88. _length = length;
  89. }
  90. public float GetLength()
  91. {
  92. return _length;
  93. }
  94. // Set/get frequency in Hz.
  95. public void SetFrequency(float hz)
  96. {
  97. _frequencyHz = hz;
  98. }
  99. public float GetFrequency()
  100. {
  101. return _frequencyHz;
  102. }
  103. // Set/get damping ratio.
  104. public void SetDampingRatio(float ratio)
  105. {
  106. _dampingRatio = ratio;
  107. }
  108. public float GetDampingRatio()
  109. {
  110. return _dampingRatio;
  111. }
  112. public override Vector2 GetAnchorA()
  113. {
  114. return _bodyA.GetWorldPoint(_localAnchor1);
  115. }
  116. public override Vector2 GetAnchorB()
  117. {
  118. return _bodyB.GetWorldPoint(_localAnchor2);
  119. }
  120. public override Vector2 GetReactionForce(float inv_dt)
  121. {
  122. Vector2 F = (inv_dt * _impulse) * _u;
  123. return F;
  124. }
  125. public override float GetReactionTorque(float inv_dt)
  126. {
  127. return 0.0f;
  128. }
  129. internal DistanceJoint(DistanceJointDef def)
  130. : base(def)
  131. {
  132. _localAnchor1 = def.localAnchorA;
  133. _localAnchor2 = def.localAnchorB;
  134. _length = def.length;
  135. _frequencyHz = def.frequencyHz;
  136. _dampingRatio = def.dampingRatio;
  137. _impulse = 0.0f;
  138. _gamma = 0.0f;
  139. _bias = 0.0f;
  140. }
  141. internal override void InitVelocityConstraints(ref TimeStep step)
  142. {
  143. Body b1 = _bodyA;
  144. Body b2 = _bodyB;
  145. Transform xf1, xf2;
  146. b1.GetTransform(out xf1);
  147. b2.GetTransform(out xf2);
  148. // Compute the effective mass matrix.
  149. Vector2 r1 = MathUtils.Multiply(ref xf1.R, _localAnchor1 - b1.GetLocalCenter());
  150. Vector2 r2 = MathUtils.Multiply(ref xf2.R, _localAnchor2 - b2.GetLocalCenter());
  151. _u = b2._sweep.c + r2 - b1._sweep.c - r1;
  152. // Handle singularity.
  153. float length = _u.Length();
  154. if (length > Settings.b2_linearSlop)
  155. {
  156. _u *= 1.0f / length;
  157. }
  158. else
  159. {
  160. _u = new Vector2(0.0f, 0.0f);
  161. }
  162. float cr1u = MathUtils.Cross(r1, _u);
  163. float cr2u = MathUtils.Cross(r2, _u);
  164. float invMass = b1._invMass + b1._invI * cr1u * cr1u + b2._invMass + b2._invI * cr2u * cr2u;
  165. Debug.Assert(invMass > Settings.b2_epsilon);
  166. _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
  167. if (_frequencyHz > 0.0f)
  168. {
  169. float C = length - _length;
  170. // Frequency
  171. float omega = 2.0f * Settings.b2_pi * _frequencyHz;
  172. // Damping coefficient
  173. float d = 2.0f * _mass * _dampingRatio * omega;
  174. // Spring stiffness
  175. float k = _mass * omega * omega;
  176. // magic formulas
  177. _gamma = step.dt * (d + step.dt * k);
  178. _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f;
  179. _bias = C * step.dt * k * _gamma;
  180. _mass = invMass + _gamma;
  181. _mass = _mass != 0.0f ? 1.0f / _mass : 0.0f;
  182. }
  183. if (step.warmStarting)
  184. {
  185. // Scale the impulse to support a variable time step.
  186. _impulse *= step.dtRatio;
  187. Vector2 P = _impulse * _u;
  188. b1._linearVelocity -= b1._invMass * P;
  189. b1._angularVelocity -= b1._invI * MathUtils.Cross(r1, P);
  190. b2._linearVelocity += b2._invMass * P;
  191. b2._angularVelocity += b2._invI * MathUtils.Cross(r2, P);
  192. }
  193. else
  194. {
  195. _impulse = 0.0f;
  196. }
  197. }
  198. internal override void SolveVelocityConstraints(ref TimeStep step)
  199. {
  200. Body b1 = _bodyA;
  201. Body b2 = _bodyB;
  202. Transform xf1, xf2;
  203. b1.GetTransform(out xf1);
  204. b2.GetTransform(out xf2);
  205. Vector2 r1 = MathUtils.Multiply(ref xf1.R, _localAnchor1 - b1.GetLocalCenter());
  206. Vector2 r2 = MathUtils.Multiply(ref xf2.R, _localAnchor2 - b2.GetLocalCenter());
  207. // Cdot = dot(u, v + cross(w, r))
  208. Vector2 v1 = b1._linearVelocity + MathUtils.Cross(b1._angularVelocity, r1);
  209. Vector2 v2 = b2._linearVelocity + MathUtils.Cross(b2._angularVelocity, r2);
  210. float Cdot = Vector2.Dot(_u, v2 - v1);
  211. float impulse = -_mass * (Cdot + _bias + _gamma * _impulse);
  212. _impulse += impulse;
  213. Vector2 P = impulse * _u;
  214. b1._linearVelocity -= b1._invMass * P;
  215. b1._angularVelocity -= b1._invI * MathUtils.Cross(r1, P);
  216. b2._linearVelocity += b2._invMass * P;
  217. b2._angularVelocity += b2._invI * MathUtils.Cross(r2, P);
  218. }
  219. internal override bool SolvePositionConstraints(float baumgarte)
  220. {
  221. if (_frequencyHz > 0.0f)
  222. {
  223. // There is no position correction for soft distance constraints.
  224. return true;
  225. }
  226. Body b1 = _bodyA;
  227. Body b2 = _bodyB;
  228. Transform xf1, xf2;
  229. b1.GetTransform(out xf1);
  230. b2.GetTransform(out xf2);
  231. Vector2 r1 = MathUtils.Multiply(ref xf1.R, _localAnchor1 - b1.GetLocalCenter());
  232. Vector2 r2 = MathUtils.Multiply(ref xf2.R, _localAnchor2 - b2.GetLocalCenter());
  233. Vector2 d = b2._sweep.c + r2 - b1._sweep.c - r1;
  234. float length = d.Length();
  235. if (length == 0.0f)
  236. return true;
  237. d /= length;
  238. float C = length - _length;
  239. C = MathUtils.Clamp(C, -Settings.b2_maxLinearCorrection, Settings.b2_maxLinearCorrection);
  240. float impulse = -_mass * C;
  241. _u = d;
  242. Vector2 P = impulse * _u;
  243. b1._sweep.c -= b1._invMass * P;
  244. b1._sweep.a -= b1._invI * MathUtils.Cross(r1, P);
  245. b2._sweep.c += b2._invMass * P;
  246. b2._sweep.a += b2._invI * MathUtils.Cross(r2, P);
  247. b1.SynchronizeTransform();
  248. b2.SynchronizeTransform();
  249. return Math.Abs(C) < Settings.b2_linearSlop;
  250. }
  251. internal Vector2 _localAnchor1;
  252. internal Vector2 _localAnchor2;
  253. internal Vector2 _u;
  254. internal float _frequencyHz;
  255. internal float _dampingRatio;
  256. internal float _gamma;
  257. internal float _bias;
  258. internal float _impulse;
  259. internal float _mass;
  260. internal float _length;
  261. };
  262. }