hinge_joint_sw.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*************************************************************************/
  2. /* hinge_joint_sw.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. /*
  31. Adapted to Godot from the Bullet library.
  32. */
  33. /*
  34. Bullet Continuous Collision Detection and Physics Library
  35. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  36. This software is provided 'as-is', without any express or implied warranty.
  37. In no event will the authors be held liable for any damages arising from the use of this software.
  38. Permission is granted to anyone to use this software for any purpose,
  39. including commercial applications, and to alter it and redistribute it freely,
  40. subject to the following restrictions:
  41. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  42. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  43. 3. This notice may not be removed or altered from any source distribution.
  44. */
  45. #include "hinge_joint_sw.h"
  46. static void plane_space(const Vector3 &n, Vector3 &p, Vector3 &q) {
  47. if (Math::abs(n.z) > 0.707106781186547524400844362) {
  48. // choose p in y-z plane
  49. real_t a = n[1] * n[1] + n[2] * n[2];
  50. real_t k = 1.0 / Math::sqrt(a);
  51. p = Vector3(0, -n[2] * k, n[1] * k);
  52. // set q = n x p
  53. q = Vector3(a * k, -n[0] * p[2], n[0] * p[1]);
  54. } else {
  55. // choose p in x-y plane
  56. real_t a = n.x * n.x + n.y * n.y;
  57. real_t k = 1.0 / Math::sqrt(a);
  58. p = Vector3(-n.y * k, n.x * k, 0);
  59. // set q = n x p
  60. q = Vector3(-n.z * p.y, n.z * p.x, a * k);
  61. }
  62. }
  63. HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameA, const Transform &frameB) :
  64. JointSW(_arr, 2) {
  65. A = rbA;
  66. B = rbB;
  67. m_rbAFrame = frameA;
  68. m_rbBFrame = frameB;
  69. // flip axis
  70. m_rbBFrame.basis[0][2] *= real_t(-1.);
  71. m_rbBFrame.basis[1][2] *= real_t(-1.);
  72. m_rbBFrame.basis[2][2] *= real_t(-1.);
  73. //start with free
  74. m_lowerLimit = Math_PI;
  75. m_upperLimit = -Math_PI;
  76. m_useLimit = false;
  77. m_biasFactor = 0.3f;
  78. m_relaxationFactor = 1.0f;
  79. m_limitSoftness = 0.9f;
  80. m_solveLimit = false;
  81. tau = 0.3;
  82. m_angularOnly = false;
  83. m_enableAngularMotor = false;
  84. A->add_constraint(this, 0);
  85. B->add_constraint(this, 1);
  86. }
  87. HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB,
  88. const Vector3 &axisInA, const Vector3 &axisInB) :
  89. JointSW(_arr, 2) {
  90. A = rbA;
  91. B = rbB;
  92. m_rbAFrame.origin = pivotInA;
  93. // since no frame is given, assume this to be zero angle and just pick rb transform axis
  94. Vector3 rbAxisA1 = rbA->get_transform().basis.get_axis(0);
  95. Vector3 rbAxisA2;
  96. real_t projection = axisInA.dot(rbAxisA1);
  97. if (projection >= 1.0f - CMP_EPSILON) {
  98. rbAxisA1 = -rbA->get_transform().basis.get_axis(2);
  99. rbAxisA2 = rbA->get_transform().basis.get_axis(1);
  100. } else if (projection <= -1.0f + CMP_EPSILON) {
  101. rbAxisA1 = rbA->get_transform().basis.get_axis(2);
  102. rbAxisA2 = rbA->get_transform().basis.get_axis(1);
  103. } else {
  104. rbAxisA2 = axisInA.cross(rbAxisA1);
  105. rbAxisA1 = rbAxisA2.cross(axisInA);
  106. }
  107. m_rbAFrame.basis = Basis(rbAxisA1.x, rbAxisA2.x, axisInA.x,
  108. rbAxisA1.y, rbAxisA2.y, axisInA.y,
  109. rbAxisA1.z, rbAxisA2.z, axisInA.z);
  110. Quat rotationArc = Quat(axisInA, axisInB);
  111. Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1);
  112. Vector3 rbAxisB2 = axisInB.cross(rbAxisB1);
  113. m_rbBFrame.origin = pivotInB;
  114. m_rbBFrame.basis = Basis(rbAxisB1.x, rbAxisB2.x, -axisInB.x,
  115. rbAxisB1.y, rbAxisB2.y, -axisInB.y,
  116. rbAxisB1.z, rbAxisB2.z, -axisInB.z);
  117. //start with free
  118. m_lowerLimit = Math_PI;
  119. m_upperLimit = -Math_PI;
  120. m_useLimit = false;
  121. m_biasFactor = 0.3f;
  122. m_relaxationFactor = 1.0f;
  123. m_limitSoftness = 0.9f;
  124. m_solveLimit = false;
  125. tau = 0.3;
  126. m_angularOnly = false;
  127. m_enableAngularMotor = false;
  128. A->add_constraint(this, 0);
  129. B->add_constraint(this, 1);
  130. }
  131. bool HingeJointSW::setup(real_t p_step) {
  132. m_appliedImpulse = real_t(0.);
  133. if (!m_angularOnly) {
  134. Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
  135. Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
  136. Vector3 relPos = pivotBInW - pivotAInW;
  137. Vector3 normal[3];
  138. if (relPos.length_squared() > CMP_EPSILON) {
  139. normal[0] = relPos.normalized();
  140. } else {
  141. normal[0] = Vector3(real_t(1.0), 0, 0);
  142. }
  143. plane_space(normal[0], normal[1], normal[2]);
  144. for (int i = 0; i < 3; i++) {
  145. memnew_placement(&m_jac[i], JacobianEntrySW(
  146. A->get_principal_inertia_axes().transposed(),
  147. B->get_principal_inertia_axes().transposed(),
  148. pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
  149. pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
  150. normal[i],
  151. A->get_inv_inertia(),
  152. A->get_inv_mass(),
  153. B->get_inv_inertia(),
  154. B->get_inv_mass()));
  155. }
  156. }
  157. //calculate two perpendicular jointAxis, orthogonal to hingeAxis
  158. //these two jointAxis require equal angular velocities for both bodies
  159. //this is unused for now, it's a todo
  160. Vector3 jointAxis0local;
  161. Vector3 jointAxis1local;
  162. plane_space(m_rbAFrame.basis.get_axis(2), jointAxis0local, jointAxis1local);
  163. A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
  164. Vector3 jointAxis0 = A->get_transform().basis.xform(jointAxis0local);
  165. Vector3 jointAxis1 = A->get_transform().basis.xform(jointAxis1local);
  166. Vector3 hingeAxisWorld = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
  167. memnew_placement(&m_jacAng[0], JacobianEntrySW(jointAxis0,
  168. A->get_principal_inertia_axes().transposed(),
  169. B->get_principal_inertia_axes().transposed(),
  170. A->get_inv_inertia(),
  171. B->get_inv_inertia()));
  172. memnew_placement(&m_jacAng[1], JacobianEntrySW(jointAxis1,
  173. A->get_principal_inertia_axes().transposed(),
  174. B->get_principal_inertia_axes().transposed(),
  175. A->get_inv_inertia(),
  176. B->get_inv_inertia()));
  177. memnew_placement(&m_jacAng[2], JacobianEntrySW(hingeAxisWorld,
  178. A->get_principal_inertia_axes().transposed(),
  179. B->get_principal_inertia_axes().transposed(),
  180. A->get_inv_inertia(),
  181. B->get_inv_inertia()));
  182. // Compute limit information
  183. real_t hingeAngle = get_hinge_angle();
  184. //set bias, sign, clear accumulator
  185. m_correction = real_t(0.);
  186. m_limitSign = real_t(0.);
  187. m_solveLimit = false;
  188. m_accLimitImpulse = real_t(0.);
  189. //if (m_lowerLimit < m_upperLimit)
  190. if (m_useLimit && m_lowerLimit <= m_upperLimit) {
  191. //if (hingeAngle <= m_lowerLimit*m_limitSoftness)
  192. if (hingeAngle <= m_lowerLimit) {
  193. m_correction = (m_lowerLimit - hingeAngle);
  194. m_limitSign = 1.0f;
  195. m_solveLimit = true;
  196. }
  197. //else if (hingeAngle >= m_upperLimit*m_limitSoftness)
  198. else if (hingeAngle >= m_upperLimit) {
  199. m_correction = m_upperLimit - hingeAngle;
  200. m_limitSign = -1.0f;
  201. m_solveLimit = true;
  202. }
  203. }
  204. //Compute K = J*W*J' for hinge axis
  205. Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
  206. m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) +
  207. B->compute_angular_impulse_denominator(axisA));
  208. return true;
  209. }
  210. void HingeJointSW::solve(real_t p_step) {
  211. Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
  212. Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
  213. //real_t tau = real_t(0.3);
  214. //linear part
  215. if (!m_angularOnly) {
  216. Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
  217. Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
  218. Vector3 vel1 = A->get_velocity_in_local_point(rel_pos1);
  219. Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2);
  220. Vector3 vel = vel1 - vel2;
  221. for (int i = 0; i < 3; i++) {
  222. const Vector3 &normal = m_jac[i].m_linearJointAxis;
  223. real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal();
  224. real_t rel_vel;
  225. rel_vel = normal.dot(vel);
  226. //positional error (zeroth order error)
  227. real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
  228. real_t impulse = depth * tau / p_step * jacDiagABInv - rel_vel * jacDiagABInv;
  229. m_appliedImpulse += impulse;
  230. Vector3 impulse_vector = normal * impulse;
  231. A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector);
  232. B->apply_impulse(pivotBInW - B->get_transform().origin, -impulse_vector);
  233. }
  234. }
  235. {
  236. ///solve angular part
  237. // get axes in world space
  238. Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
  239. Vector3 axisB = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(2));
  240. const Vector3 &angVelA = A->get_angular_velocity();
  241. const Vector3 &angVelB = B->get_angular_velocity();
  242. Vector3 angVelAroundHingeAxisA = axisA * axisA.dot(angVelA);
  243. Vector3 angVelAroundHingeAxisB = axisB * axisB.dot(angVelB);
  244. Vector3 angAorthog = angVelA - angVelAroundHingeAxisA;
  245. Vector3 angBorthog = angVelB - angVelAroundHingeAxisB;
  246. Vector3 velrelOrthog = angAorthog - angBorthog;
  247. {
  248. //solve orthogonal angular velocity correction
  249. real_t relaxation = real_t(1.);
  250. real_t len = velrelOrthog.length();
  251. if (len > real_t(0.00001)) {
  252. Vector3 normal = velrelOrthog.normalized();
  253. real_t denom = A->compute_angular_impulse_denominator(normal) +
  254. B->compute_angular_impulse_denominator(normal);
  255. // scale for mass and relaxation
  256. velrelOrthog *= (real_t(1.) / denom) * m_relaxationFactor;
  257. }
  258. //solve angular positional correction
  259. Vector3 angularError = -axisA.cross(axisB) * (real_t(1.) / p_step);
  260. real_t len2 = angularError.length();
  261. if (len2 > real_t(0.00001)) {
  262. Vector3 normal2 = angularError.normalized();
  263. real_t denom2 = A->compute_angular_impulse_denominator(normal2) +
  264. B->compute_angular_impulse_denominator(normal2);
  265. angularError *= (real_t(1.) / denom2) * relaxation;
  266. }
  267. A->apply_torque_impulse(-velrelOrthog + angularError);
  268. B->apply_torque_impulse(velrelOrthog - angularError);
  269. // solve limit
  270. if (m_solveLimit) {
  271. real_t amplitude = ((angVelB - angVelA).dot(axisA) * m_relaxationFactor + m_correction * (real_t(1.) / p_step) * m_biasFactor) * m_limitSign;
  272. real_t impulseMag = amplitude * m_kHinge;
  273. // Clamp the accumulated impulse
  274. real_t temp = m_accLimitImpulse;
  275. m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0));
  276. impulseMag = m_accLimitImpulse - temp;
  277. Vector3 impulse = axisA * impulseMag * m_limitSign;
  278. A->apply_torque_impulse(impulse);
  279. B->apply_torque_impulse(-impulse);
  280. }
  281. }
  282. //apply motor
  283. if (m_enableAngularMotor) {
  284. //todo: add limits too
  285. Vector3 angularLimit(0, 0, 0);
  286. Vector3 velrel = angVelAroundHingeAxisA - angVelAroundHingeAxisB;
  287. real_t projRelVel = velrel.dot(axisA);
  288. real_t desiredMotorVel = m_motorTargetVelocity;
  289. real_t motor_relvel = desiredMotorVel - projRelVel;
  290. real_t unclippedMotorImpulse = m_kHinge * motor_relvel;
  291. //todo: should clip against accumulated impulse
  292. real_t clippedMotorImpulse = unclippedMotorImpulse > m_maxMotorImpulse ? m_maxMotorImpulse : unclippedMotorImpulse;
  293. clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse;
  294. Vector3 motorImp = clippedMotorImpulse * axisA;
  295. A->apply_torque_impulse(motorImp + angularLimit);
  296. B->apply_torque_impulse(-motorImp - angularLimit);
  297. }
  298. }
  299. }
  300. /*
  301. void HingeJointSW::updateRHS(real_t timeStep)
  302. {
  303. (void)timeStep;
  304. }
  305. */
  306. static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) {
  307. real_t coeff_1 = Math_PI / 4.0f;
  308. real_t coeff_2 = 3.0f * coeff_1;
  309. real_t abs_y = Math::abs(y);
  310. real_t angle;
  311. if (x >= 0.0f) {
  312. real_t r = (x - abs_y) / (x + abs_y);
  313. angle = coeff_1 - coeff_1 * r;
  314. } else {
  315. real_t r = (x + abs_y) / (abs_y - x);
  316. angle = coeff_2 - coeff_1 * r;
  317. }
  318. return (y < 0.0f) ? -angle : angle;
  319. }
  320. real_t HingeJointSW::get_hinge_angle() {
  321. const Vector3 refAxis0 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(0));
  322. const Vector3 refAxis1 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(1));
  323. const Vector3 swingAxis = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(1));
  324. return atan2fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
  325. }
  326. void HingeJointSW::set_param(PhysicsServer::HingeJointParam p_param, real_t p_value) {
  327. switch (p_param) {
  328. case PhysicsServer::HINGE_JOINT_BIAS: tau = p_value; break;
  329. case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: m_upperLimit = p_value; break;
  330. case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: m_lowerLimit = p_value; break;
  331. case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: m_biasFactor = p_value; break;
  332. case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: m_limitSoftness = p_value; break;
  333. case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: m_relaxationFactor = p_value; break;
  334. case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: m_motorTargetVelocity = p_value; break;
  335. case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: m_maxMotorImpulse = p_value; break;
  336. case PhysicsServer::HINGE_JOINT_MAX: break; // Can't happen, but silences warning
  337. }
  338. }
  339. real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const {
  340. switch (p_param) {
  341. case PhysicsServer::HINGE_JOINT_BIAS: return tau;
  342. case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: return m_upperLimit;
  343. case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: return m_lowerLimit;
  344. case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: return m_biasFactor;
  345. case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: return m_limitSoftness;
  346. case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: return m_relaxationFactor;
  347. case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: return m_motorTargetVelocity;
  348. case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: return m_maxMotorImpulse;
  349. case PhysicsServer::HINGE_JOINT_MAX: break; // Can't happen, but silences warning
  350. }
  351. return 0;
  352. }
  353. void HingeJointSW::set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value) {
  354. switch (p_flag) {
  355. case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: m_useLimit = p_value; break;
  356. case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: m_enableAngularMotor = p_value; break;
  357. case PhysicsServer::HINGE_JOINT_FLAG_MAX: break; // Can't happen, but silences warning
  358. }
  359. }
  360. bool HingeJointSW::get_flag(PhysicsServer::HingeJointFlag p_flag) const {
  361. switch (p_flag) {
  362. case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: return m_useLimit;
  363. case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: return m_enableAngularMotor;
  364. case PhysicsServer::HINGE_JOINT_FLAG_MAX: break; // Can't happen, but silences warning
  365. }
  366. return false;
  367. }