btGeneric6DofConstraint.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 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.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. /*
  14. 2007-09-09
  15. Refactored by Francisco Le?n
  16. email: [email protected]
  17. http://gimpact.sf.net
  18. */
  19. #include "btGeneric6DofConstraint.h"
  20. #include "BulletDynamics/Dynamics/btRigidBody.h"
  21. #include "LinearMath/btTransformUtil.h"
  22. #include "LinearMath/btTransformUtil.h"
  23. #include <new>
  24. #define D6_USE_OBSOLETE_METHOD false
  25. #define D6_USE_FRAME_OFFSET true
  26. btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
  27. : btTypedConstraint(D6_CONSTRAINT_TYPE, rbA, rbB), m_frameInA(frameInA), m_frameInB(frameInB), m_useLinearReferenceFrameA(useLinearReferenceFrameA), m_useOffsetForConstraintFrame(D6_USE_FRAME_OFFSET), m_flags(0), m_useSolveConstraintObsolete(D6_USE_OBSOLETE_METHOD)
  28. {
  29. calculateTransforms();
  30. }
  31. btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB)
  32. : btTypedConstraint(D6_CONSTRAINT_TYPE, getFixedBody(), rbB),
  33. m_frameInB(frameInB),
  34. m_useLinearReferenceFrameA(useLinearReferenceFrameB),
  35. m_useOffsetForConstraintFrame(D6_USE_FRAME_OFFSET),
  36. m_flags(0),
  37. m_useSolveConstraintObsolete(false)
  38. {
  39. ///not providing rigidbody A means implicitly using worldspace for body A
  40. m_frameInA = rbB.getCenterOfMassTransform() * m_frameInB;
  41. calculateTransforms();
  42. }
  43. #define GENERIC_D6_DISABLE_WARMSTARTING 1
  44. btScalar btGetMatrixElem(const btMatrix3x3& mat, int index);
  45. btScalar btGetMatrixElem(const btMatrix3x3& mat, int index)
  46. {
  47. int i = index % 3;
  48. int j = index / 3;
  49. return mat[i][j];
  50. }
  51. ///MatrixToEulerXYZ from http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Matrix3.inl.html
  52. bool matrixToEulerXYZ(const btMatrix3x3& mat, btVector3& xyz);
  53. bool matrixToEulerXYZ(const btMatrix3x3& mat, btVector3& xyz)
  54. {
  55. // // rot = cy*cz -cy*sz sy
  56. // // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
  57. // // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
  58. //
  59. btScalar fi = btGetMatrixElem(mat, 2);
  60. if (fi < btScalar(1.0f))
  61. {
  62. if (fi > btScalar(-1.0f))
  63. {
  64. xyz[0] = btAtan2(-btGetMatrixElem(mat, 5), btGetMatrixElem(mat, 8));
  65. xyz[1] = btAsin(btGetMatrixElem(mat, 2));
  66. xyz[2] = btAtan2(-btGetMatrixElem(mat, 1), btGetMatrixElem(mat, 0));
  67. return true;
  68. }
  69. else
  70. {
  71. // WARNING. Not unique. XA - ZA = -atan2(r10,r11)
  72. xyz[0] = -btAtan2(btGetMatrixElem(mat, 3), btGetMatrixElem(mat, 4));
  73. xyz[1] = -SIMD_HALF_PI;
  74. xyz[2] = btScalar(0.0);
  75. return false;
  76. }
  77. }
  78. else
  79. {
  80. // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11)
  81. xyz[0] = btAtan2(btGetMatrixElem(mat, 3), btGetMatrixElem(mat, 4));
  82. xyz[1] = SIMD_HALF_PI;
  83. xyz[2] = 0.0;
  84. }
  85. return false;
  86. }
  87. //////////////////////////// btRotationalLimitMotor ////////////////////////////////////
  88. int btRotationalLimitMotor::testLimitValue(btScalar test_value)
  89. {
  90. if (m_loLimit > m_hiLimit)
  91. {
  92. m_currentLimit = 0; //Free from violation
  93. return 0;
  94. }
  95. if (test_value < m_loLimit)
  96. {
  97. m_currentLimit = 1; //low limit violation
  98. m_currentLimitError = test_value - m_loLimit;
  99. if (m_currentLimitError > SIMD_PI)
  100. m_currentLimitError -= SIMD_2_PI;
  101. else if (m_currentLimitError < -SIMD_PI)
  102. m_currentLimitError += SIMD_2_PI;
  103. return 1;
  104. }
  105. else if (test_value > m_hiLimit)
  106. {
  107. m_currentLimit = 2; //High limit violation
  108. m_currentLimitError = test_value - m_hiLimit;
  109. if (m_currentLimitError > SIMD_PI)
  110. m_currentLimitError -= SIMD_2_PI;
  111. else if (m_currentLimitError < -SIMD_PI)
  112. m_currentLimitError += SIMD_2_PI;
  113. return 2;
  114. };
  115. m_currentLimit = 0; //Free from violation
  116. return 0;
  117. }
  118. btScalar btRotationalLimitMotor::solveAngularLimits(
  119. btScalar timeStep, btVector3& axis, btScalar jacDiagABInv,
  120. btRigidBody* body0, btRigidBody* body1)
  121. {
  122. if (needApplyTorques() == false) return 0.0f;
  123. btScalar target_velocity = m_targetVelocity;
  124. btScalar maxMotorForce = m_maxMotorForce;
  125. //current error correction
  126. if (m_currentLimit != 0)
  127. {
  128. target_velocity = -m_stopERP * m_currentLimitError / (timeStep);
  129. maxMotorForce = m_maxLimitForce;
  130. }
  131. maxMotorForce *= timeStep;
  132. // current velocity difference
  133. btVector3 angVelA = body0->getAngularVelocity();
  134. btVector3 angVelB = body1->getAngularVelocity();
  135. btVector3 vel_diff;
  136. vel_diff = angVelA - angVelB;
  137. btScalar rel_vel = axis.dot(vel_diff);
  138. // correction velocity
  139. btScalar motor_relvel = m_limitSoftness * (target_velocity - m_damping * rel_vel);
  140. if (motor_relvel < SIMD_EPSILON && motor_relvel > -SIMD_EPSILON)
  141. {
  142. return 0.0f; //no need for applying force
  143. }
  144. // correction impulse
  145. btScalar unclippedMotorImpulse = (1 + m_bounce) * motor_relvel * jacDiagABInv;
  146. // clip correction impulse
  147. btScalar clippedMotorImpulse;
  148. ///@todo: should clip against accumulated impulse
  149. if (unclippedMotorImpulse > 0.0f)
  150. {
  151. clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce ? maxMotorForce : unclippedMotorImpulse;
  152. }
  153. else
  154. {
  155. clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce : unclippedMotorImpulse;
  156. }
  157. // sort with accumulated impulses
  158. btScalar lo = btScalar(-BT_LARGE_FLOAT);
  159. btScalar hi = btScalar(BT_LARGE_FLOAT);
  160. btScalar oldaccumImpulse = m_accumulatedImpulse;
  161. btScalar sum = oldaccumImpulse + clippedMotorImpulse;
  162. m_accumulatedImpulse = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum;
  163. clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse;
  164. btVector3 motorImp = clippedMotorImpulse * axis;
  165. body0->applyTorqueImpulse(motorImp);
  166. body1->applyTorqueImpulse(-motorImp);
  167. return clippedMotorImpulse;
  168. }
  169. //////////////////////////// End btRotationalLimitMotor ////////////////////////////////////
  170. //////////////////////////// btTranslationalLimitMotor ////////////////////////////////////
  171. int btTranslationalLimitMotor::testLimitValue(int limitIndex, btScalar test_value)
  172. {
  173. btScalar loLimit = m_lowerLimit[limitIndex];
  174. btScalar hiLimit = m_upperLimit[limitIndex];
  175. if (loLimit > hiLimit)
  176. {
  177. m_currentLimit[limitIndex] = 0; //Free from violation
  178. m_currentLimitError[limitIndex] = btScalar(0.f);
  179. return 0;
  180. }
  181. if (test_value < loLimit)
  182. {
  183. m_currentLimit[limitIndex] = 2; //low limit violation
  184. m_currentLimitError[limitIndex] = test_value - loLimit;
  185. return 2;
  186. }
  187. else if (test_value > hiLimit)
  188. {
  189. m_currentLimit[limitIndex] = 1; //High limit violation
  190. m_currentLimitError[limitIndex] = test_value - hiLimit;
  191. return 1;
  192. };
  193. m_currentLimit[limitIndex] = 0; //Free from violation
  194. m_currentLimitError[limitIndex] = btScalar(0.f);
  195. return 0;
  196. }
  197. btScalar btTranslationalLimitMotor::solveLinearAxis(
  198. btScalar timeStep,
  199. btScalar jacDiagABInv,
  200. btRigidBody& body1, const btVector3& pointInA,
  201. btRigidBody& body2, const btVector3& pointInB,
  202. int limit_index,
  203. const btVector3& axis_normal_on_a,
  204. const btVector3& anchorPos)
  205. {
  206. ///find relative velocity
  207. // btVector3 rel_pos1 = pointInA - body1.getCenterOfMassPosition();
  208. // btVector3 rel_pos2 = pointInB - body2.getCenterOfMassPosition();
  209. btVector3 rel_pos1 = anchorPos - body1.getCenterOfMassPosition();
  210. btVector3 rel_pos2 = anchorPos - body2.getCenterOfMassPosition();
  211. btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
  212. btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
  213. btVector3 vel = vel1 - vel2;
  214. btScalar rel_vel = axis_normal_on_a.dot(vel);
  215. /// apply displacement correction
  216. //positional error (zeroth order error)
  217. btScalar depth = -(pointInA - pointInB).dot(axis_normal_on_a);
  218. btScalar lo = btScalar(-BT_LARGE_FLOAT);
  219. btScalar hi = btScalar(BT_LARGE_FLOAT);
  220. btScalar minLimit = m_lowerLimit[limit_index];
  221. btScalar maxLimit = m_upperLimit[limit_index];
  222. //handle the limits
  223. if (minLimit < maxLimit)
  224. {
  225. {
  226. if (depth > maxLimit)
  227. {
  228. depth -= maxLimit;
  229. lo = btScalar(0.);
  230. }
  231. else
  232. {
  233. if (depth < minLimit)
  234. {
  235. depth -= minLimit;
  236. hi = btScalar(0.);
  237. }
  238. else
  239. {
  240. return 0.0f;
  241. }
  242. }
  243. }
  244. }
  245. btScalar normalImpulse = m_limitSoftness * (m_restitution * depth / timeStep - m_damping * rel_vel) * jacDiagABInv;
  246. btScalar oldNormalImpulse = m_accumulatedImpulse[limit_index];
  247. btScalar sum = oldNormalImpulse + normalImpulse;
  248. m_accumulatedImpulse[limit_index] = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum;
  249. normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse;
  250. btVector3 impulse_vector = axis_normal_on_a * normalImpulse;
  251. body1.applyImpulse(impulse_vector, rel_pos1);
  252. body2.applyImpulse(-impulse_vector, rel_pos2);
  253. return normalImpulse;
  254. }
  255. //////////////////////////// btTranslationalLimitMotor ////////////////////////////////////
  256. void btGeneric6DofConstraint::calculateAngleInfo()
  257. {
  258. btMatrix3x3 relative_frame = m_calculatedTransformA.getBasis().inverse() * m_calculatedTransformB.getBasis();
  259. matrixToEulerXYZ(relative_frame, m_calculatedAxisAngleDiff);
  260. // in euler angle mode we do not actually constrain the angular velocity
  261. // along the axes axis[0] and axis[2] (although we do use axis[1]) :
  262. //
  263. // to get constrain w2-w1 along ...not
  264. // ------ --------------------- ------
  265. // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0]
  266. // d(angle[1])/dt = 0 ax[1]
  267. // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2]
  268. //
  269. // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0.
  270. // to prove the result for angle[0], write the expression for angle[0] from
  271. // GetInfo1 then take the derivative. to prove this for angle[2] it is
  272. // easier to take the euler rate expression for d(angle[2])/dt with respect
  273. // to the components of w and set that to 0.
  274. btVector3 axis0 = m_calculatedTransformB.getBasis().getColumn(0);
  275. btVector3 axis2 = m_calculatedTransformA.getBasis().getColumn(2);
  276. m_calculatedAxis[1] = axis2.cross(axis0);
  277. m_calculatedAxis[0] = m_calculatedAxis[1].cross(axis2);
  278. m_calculatedAxis[2] = axis0.cross(m_calculatedAxis[1]);
  279. m_calculatedAxis[0].normalize();
  280. m_calculatedAxis[1].normalize();
  281. m_calculatedAxis[2].normalize();
  282. }
  283. void btGeneric6DofConstraint::calculateTransforms()
  284. {
  285. calculateTransforms(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform());
  286. }
  287. void btGeneric6DofConstraint::calculateTransforms(const btTransform& transA, const btTransform& transB)
  288. {
  289. m_calculatedTransformA = transA * m_frameInA;
  290. m_calculatedTransformB = transB * m_frameInB;
  291. calculateLinearInfo();
  292. calculateAngleInfo();
  293. if (m_useOffsetForConstraintFrame)
  294. { // get weight factors depending on masses
  295. btScalar miA = getRigidBodyA().getInvMass();
  296. btScalar miB = getRigidBodyB().getInvMass();
  297. m_hasStaticBody = (miA < SIMD_EPSILON) || (miB < SIMD_EPSILON);
  298. btScalar miS = miA + miB;
  299. if (miS > btScalar(0.f))
  300. {
  301. m_factA = miB / miS;
  302. }
  303. else
  304. {
  305. m_factA = btScalar(0.5f);
  306. }
  307. m_factB = btScalar(1.0f) - m_factA;
  308. }
  309. }
  310. void btGeneric6DofConstraint::buildLinearJacobian(
  311. btJacobianEntry& jacLinear, const btVector3& normalWorld,
  312. const btVector3& pivotAInW, const btVector3& pivotBInW)
  313. {
  314. new (&jacLinear) btJacobianEntry(
  315. m_rbA.getCenterOfMassTransform().getBasis().transpose(),
  316. m_rbB.getCenterOfMassTransform().getBasis().transpose(),
  317. pivotAInW - m_rbA.getCenterOfMassPosition(),
  318. pivotBInW - m_rbB.getCenterOfMassPosition(),
  319. normalWorld,
  320. m_rbA.getInvInertiaDiagLocal(),
  321. m_rbA.getInvMass(),
  322. m_rbB.getInvInertiaDiagLocal(),
  323. m_rbB.getInvMass());
  324. }
  325. void btGeneric6DofConstraint::buildAngularJacobian(
  326. btJacobianEntry& jacAngular, const btVector3& jointAxisW)
  327. {
  328. new (&jacAngular) btJacobianEntry(jointAxisW,
  329. m_rbA.getCenterOfMassTransform().getBasis().transpose(),
  330. m_rbB.getCenterOfMassTransform().getBasis().transpose(),
  331. m_rbA.getInvInertiaDiagLocal(),
  332. m_rbB.getInvInertiaDiagLocal());
  333. }
  334. bool btGeneric6DofConstraint::testAngularLimitMotor(int axis_index)
  335. {
  336. btScalar angle = m_calculatedAxisAngleDiff[axis_index];
  337. angle = btAdjustAngleToLimits(angle, m_angularLimits[axis_index].m_loLimit, m_angularLimits[axis_index].m_hiLimit);
  338. m_angularLimits[axis_index].m_currentPosition = angle;
  339. //test limits
  340. m_angularLimits[axis_index].testLimitValue(angle);
  341. return m_angularLimits[axis_index].needApplyTorques();
  342. }
  343. void btGeneric6DofConstraint::buildJacobian()
  344. {
  345. #ifndef __SPU__
  346. if (m_useSolveConstraintObsolete)
  347. {
  348. // Clear accumulated impulses for the next simulation step
  349. m_linearLimits.m_accumulatedImpulse.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
  350. int i;
  351. for (i = 0; i < 3; i++)
  352. {
  353. m_angularLimits[i].m_accumulatedImpulse = btScalar(0.);
  354. }
  355. //calculates transform
  356. calculateTransforms(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform());
  357. // const btVector3& pivotAInW = m_calculatedTransformA.getOrigin();
  358. // const btVector3& pivotBInW = m_calculatedTransformB.getOrigin();
  359. calcAnchorPos();
  360. btVector3 pivotAInW = m_AnchorPos;
  361. btVector3 pivotBInW = m_AnchorPos;
  362. // not used here
  363. // btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition();
  364. // btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition();
  365. btVector3 normalWorld;
  366. //linear part
  367. for (i = 0; i < 3; i++)
  368. {
  369. if (m_linearLimits.isLimited(i))
  370. {
  371. if (m_useLinearReferenceFrameA)
  372. normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
  373. else
  374. normalWorld = m_calculatedTransformB.getBasis().getColumn(i);
  375. buildLinearJacobian(
  376. m_jacLinear[i], normalWorld,
  377. pivotAInW, pivotBInW);
  378. }
  379. }
  380. // angular part
  381. for (i = 0; i < 3; i++)
  382. {
  383. //calculates error angle
  384. if (testAngularLimitMotor(i))
  385. {
  386. normalWorld = this->getAxis(i);
  387. // Create angular atom
  388. buildAngularJacobian(m_jacAng[i], normalWorld);
  389. }
  390. }
  391. }
  392. #endif //__SPU__
  393. }
  394. void btGeneric6DofConstraint::getInfo1(btConstraintInfo1* info)
  395. {
  396. if (m_useSolveConstraintObsolete)
  397. {
  398. info->m_numConstraintRows = 0;
  399. info->nub = 0;
  400. }
  401. else
  402. {
  403. //prepare constraint
  404. calculateTransforms(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform());
  405. info->m_numConstraintRows = 0;
  406. info->nub = 6;
  407. int i;
  408. //test linear limits
  409. for (i = 0; i < 3; i++)
  410. {
  411. if (m_linearLimits.needApplyForce(i))
  412. {
  413. info->m_numConstraintRows++;
  414. info->nub--;
  415. }
  416. }
  417. //test angular limits
  418. for (i = 0; i < 3; i++)
  419. {
  420. if (testAngularLimitMotor(i))
  421. {
  422. info->m_numConstraintRows++;
  423. info->nub--;
  424. }
  425. }
  426. }
  427. }
  428. void btGeneric6DofConstraint::getInfo1NonVirtual(btConstraintInfo1* info)
  429. {
  430. if (m_useSolveConstraintObsolete)
  431. {
  432. info->m_numConstraintRows = 0;
  433. info->nub = 0;
  434. }
  435. else
  436. {
  437. //pre-allocate all 6
  438. info->m_numConstraintRows = 6;
  439. info->nub = 0;
  440. }
  441. }
  442. void btGeneric6DofConstraint::getInfo2(btConstraintInfo2* info)
  443. {
  444. btAssert(!m_useSolveConstraintObsolete);
  445. const btTransform& transA = m_rbA.getCenterOfMassTransform();
  446. const btTransform& transB = m_rbB.getCenterOfMassTransform();
  447. const btVector3& linVelA = m_rbA.getLinearVelocity();
  448. const btVector3& linVelB = m_rbB.getLinearVelocity();
  449. const btVector3& angVelA = m_rbA.getAngularVelocity();
  450. const btVector3& angVelB = m_rbB.getAngularVelocity();
  451. if (m_useOffsetForConstraintFrame)
  452. { // for stability better to solve angular limits first
  453. int row = setAngularLimits(info, 0, transA, transB, linVelA, linVelB, angVelA, angVelB);
  454. setLinearLimits(info, row, transA, transB, linVelA, linVelB, angVelA, angVelB);
  455. }
  456. else
  457. { // leave old version for compatibility
  458. int row = setLinearLimits(info, 0, transA, transB, linVelA, linVelB, angVelA, angVelB);
  459. setAngularLimits(info, row, transA, transB, linVelA, linVelB, angVelA, angVelB);
  460. }
  461. }
  462. void btGeneric6DofConstraint::getInfo2NonVirtual(btConstraintInfo2* info, const btTransform& transA, const btTransform& transB, const btVector3& linVelA, const btVector3& linVelB, const btVector3& angVelA, const btVector3& angVelB)
  463. {
  464. btAssert(!m_useSolveConstraintObsolete);
  465. //prepare constraint
  466. calculateTransforms(transA, transB);
  467. int i;
  468. for (i = 0; i < 3; i++)
  469. {
  470. testAngularLimitMotor(i);
  471. }
  472. if (m_useOffsetForConstraintFrame)
  473. { // for stability better to solve angular limits first
  474. int row = setAngularLimits(info, 0, transA, transB, linVelA, linVelB, angVelA, angVelB);
  475. setLinearLimits(info, row, transA, transB, linVelA, linVelB, angVelA, angVelB);
  476. }
  477. else
  478. { // leave old version for compatibility
  479. int row = setLinearLimits(info, 0, transA, transB, linVelA, linVelB, angVelA, angVelB);
  480. setAngularLimits(info, row, transA, transB, linVelA, linVelB, angVelA, angVelB);
  481. }
  482. }
  483. int btGeneric6DofConstraint::setLinearLimits(btConstraintInfo2* info, int row, const btTransform& transA, const btTransform& transB, const btVector3& linVelA, const btVector3& linVelB, const btVector3& angVelA, const btVector3& angVelB)
  484. {
  485. // int row = 0;
  486. //solve linear limits
  487. btRotationalLimitMotor limot;
  488. for (int i = 0; i < 3; i++)
  489. {
  490. if (m_linearLimits.needApplyForce(i))
  491. { // re-use rotational motor code
  492. limot.m_bounce = btScalar(0.f);
  493. limot.m_currentLimit = m_linearLimits.m_currentLimit[i];
  494. limot.m_currentPosition = m_linearLimits.m_currentLinearDiff[i];
  495. limot.m_currentLimitError = m_linearLimits.m_currentLimitError[i];
  496. limot.m_damping = m_linearLimits.m_damping;
  497. limot.m_enableMotor = m_linearLimits.m_enableMotor[i];
  498. limot.m_hiLimit = m_linearLimits.m_upperLimit[i];
  499. limot.m_limitSoftness = m_linearLimits.m_limitSoftness;
  500. limot.m_loLimit = m_linearLimits.m_lowerLimit[i];
  501. limot.m_maxLimitForce = btScalar(0.f);
  502. limot.m_maxMotorForce = m_linearLimits.m_maxMotorForce[i];
  503. limot.m_targetVelocity = m_linearLimits.m_targetVelocity[i];
  504. btVector3 axis = m_calculatedTransformA.getBasis().getColumn(i);
  505. int flags = m_flags >> (i * BT_6DOF_FLAGS_AXIS_SHIFT);
  506. limot.m_normalCFM = (flags & BT_6DOF_FLAGS_CFM_NORM) ? m_linearLimits.m_normalCFM[i] : info->cfm[0];
  507. limot.m_stopCFM = (flags & BT_6DOF_FLAGS_CFM_STOP) ? m_linearLimits.m_stopCFM[i] : info->cfm[0];
  508. limot.m_stopERP = (flags & BT_6DOF_FLAGS_ERP_STOP) ? m_linearLimits.m_stopERP[i] : info->erp;
  509. if (m_useOffsetForConstraintFrame)
  510. {
  511. int indx1 = (i + 1) % 3;
  512. int indx2 = (i + 2) % 3;
  513. int rotAllowed = 1; // rotations around orthos to current axis
  514. if (m_angularLimits[indx1].m_currentLimit && m_angularLimits[indx2].m_currentLimit)
  515. {
  516. rotAllowed = 0;
  517. }
  518. row += get_limit_motor_info2(&limot, transA, transB, linVelA, linVelB, angVelA, angVelB, info, row, axis, 0, rotAllowed);
  519. }
  520. else
  521. {
  522. row += get_limit_motor_info2(&limot, transA, transB, linVelA, linVelB, angVelA, angVelB, info, row, axis, 0);
  523. }
  524. }
  525. }
  526. return row;
  527. }
  528. int btGeneric6DofConstraint::setAngularLimits(btConstraintInfo2* info, int row_offset, const btTransform& transA, const btTransform& transB, const btVector3& linVelA, const btVector3& linVelB, const btVector3& angVelA, const btVector3& angVelB)
  529. {
  530. btGeneric6DofConstraint* d6constraint = this;
  531. int row = row_offset;
  532. //solve angular limits
  533. for (int i = 0; i < 3; i++)
  534. {
  535. if (d6constraint->getRotationalLimitMotor(i)->needApplyTorques())
  536. {
  537. btVector3 axis = d6constraint->getAxis(i);
  538. int flags = m_flags >> ((i + 3) * BT_6DOF_FLAGS_AXIS_SHIFT);
  539. if (!(flags & BT_6DOF_FLAGS_CFM_NORM))
  540. {
  541. m_angularLimits[i].m_normalCFM = info->cfm[0];
  542. }
  543. if (!(flags & BT_6DOF_FLAGS_CFM_STOP))
  544. {
  545. m_angularLimits[i].m_stopCFM = info->cfm[0];
  546. }
  547. if (!(flags & BT_6DOF_FLAGS_ERP_STOP))
  548. {
  549. m_angularLimits[i].m_stopERP = info->erp;
  550. }
  551. row += get_limit_motor_info2(d6constraint->getRotationalLimitMotor(i),
  552. transA, transB, linVelA, linVelB, angVelA, angVelB, info, row, axis, 1);
  553. }
  554. }
  555. return row;
  556. }
  557. void btGeneric6DofConstraint::updateRHS(btScalar timeStep)
  558. {
  559. (void)timeStep;
  560. }
  561. void btGeneric6DofConstraint::setFrames(const btTransform& frameA, const btTransform& frameB)
  562. {
  563. m_frameInA = frameA;
  564. m_frameInB = frameB;
  565. buildJacobian();
  566. calculateTransforms();
  567. }
  568. btVector3 btGeneric6DofConstraint::getAxis(int axis_index) const
  569. {
  570. return m_calculatedAxis[axis_index];
  571. }
  572. btScalar btGeneric6DofConstraint::getRelativePivotPosition(int axisIndex) const
  573. {
  574. return m_calculatedLinearDiff[axisIndex];
  575. }
  576. btScalar btGeneric6DofConstraint::getAngle(int axisIndex) const
  577. {
  578. return m_calculatedAxisAngleDiff[axisIndex];
  579. }
  580. void btGeneric6DofConstraint::calcAnchorPos(void)
  581. {
  582. btScalar imA = m_rbA.getInvMass();
  583. btScalar imB = m_rbB.getInvMass();
  584. btScalar weight;
  585. if (imB == btScalar(0.0))
  586. {
  587. weight = btScalar(1.0);
  588. }
  589. else
  590. {
  591. weight = imA / (imA + imB);
  592. }
  593. const btVector3& pA = m_calculatedTransformA.getOrigin();
  594. const btVector3& pB = m_calculatedTransformB.getOrigin();
  595. m_AnchorPos = pA * weight + pB * (btScalar(1.0) - weight);
  596. return;
  597. }
  598. void btGeneric6DofConstraint::calculateLinearInfo()
  599. {
  600. m_calculatedLinearDiff = m_calculatedTransformB.getOrigin() - m_calculatedTransformA.getOrigin();
  601. m_calculatedLinearDiff = m_calculatedTransformA.getBasis().inverse() * m_calculatedLinearDiff;
  602. for (int i = 0; i < 3; i++)
  603. {
  604. m_linearLimits.m_currentLinearDiff[i] = m_calculatedLinearDiff[i];
  605. m_linearLimits.testLimitValue(i, m_calculatedLinearDiff[i]);
  606. }
  607. }
  608. int btGeneric6DofConstraint::get_limit_motor_info2(
  609. btRotationalLimitMotor* limot,
  610. const btTransform& transA, const btTransform& transB, const btVector3& linVelA, const btVector3& linVelB, const btVector3& angVelA, const btVector3& angVelB,
  611. btConstraintInfo2* info, int row, btVector3& ax1, int rotational, int rotAllowed)
  612. {
  613. int srow = row * info->rowskip;
  614. bool powered = limot->m_enableMotor;
  615. int limit = limot->m_currentLimit;
  616. if (powered || limit)
  617. { // if the joint is powered, or has joint limits, add in the extra row
  618. btScalar* J1 = rotational ? info->m_J1angularAxis : info->m_J1linearAxis;
  619. btScalar* J2 = rotational ? info->m_J2angularAxis : info->m_J2linearAxis;
  620. J1[srow + 0] = ax1[0];
  621. J1[srow + 1] = ax1[1];
  622. J1[srow + 2] = ax1[2];
  623. J2[srow + 0] = -ax1[0];
  624. J2[srow + 1] = -ax1[1];
  625. J2[srow + 2] = -ax1[2];
  626. if ((!rotational))
  627. {
  628. if (m_useOffsetForConstraintFrame)
  629. {
  630. btVector3 tmpA, tmpB, relA, relB;
  631. // get vector from bodyB to frameB in WCS
  632. relB = m_calculatedTransformB.getOrigin() - transB.getOrigin();
  633. // get its projection to constraint axis
  634. btVector3 projB = ax1 * relB.dot(ax1);
  635. // get vector directed from bodyB to constraint axis (and orthogonal to it)
  636. btVector3 orthoB = relB - projB;
  637. // same for bodyA
  638. relA = m_calculatedTransformA.getOrigin() - transA.getOrigin();
  639. btVector3 projA = ax1 * relA.dot(ax1);
  640. btVector3 orthoA = relA - projA;
  641. // get desired offset between frames A and B along constraint axis
  642. btScalar desiredOffs = limot->m_currentPosition - limot->m_currentLimitError;
  643. // desired vector from projection of center of bodyA to projection of center of bodyB to constraint axis
  644. btVector3 totalDist = projA + ax1 * desiredOffs - projB;
  645. // get offset vectors relA and relB
  646. relA = orthoA + totalDist * m_factA;
  647. relB = orthoB - totalDist * m_factB;
  648. tmpA = relA.cross(ax1);
  649. tmpB = relB.cross(ax1);
  650. if (m_hasStaticBody && (!rotAllowed))
  651. {
  652. tmpA *= m_factA;
  653. tmpB *= m_factB;
  654. }
  655. int i;
  656. for (i = 0; i < 3; i++) info->m_J1angularAxis[srow + i] = tmpA[i];
  657. for (i = 0; i < 3; i++) info->m_J2angularAxis[srow + i] = -tmpB[i];
  658. }
  659. else
  660. {
  661. btVector3 ltd; // Linear Torque Decoupling vector
  662. btVector3 c = m_calculatedTransformB.getOrigin() - transA.getOrigin();
  663. ltd = c.cross(ax1);
  664. info->m_J1angularAxis[srow + 0] = ltd[0];
  665. info->m_J1angularAxis[srow + 1] = ltd[1];
  666. info->m_J1angularAxis[srow + 2] = ltd[2];
  667. c = m_calculatedTransformB.getOrigin() - transB.getOrigin();
  668. ltd = -c.cross(ax1);
  669. info->m_J2angularAxis[srow + 0] = ltd[0];
  670. info->m_J2angularAxis[srow + 1] = ltd[1];
  671. info->m_J2angularAxis[srow + 2] = ltd[2];
  672. }
  673. }
  674. // if we're limited low and high simultaneously, the joint motor is
  675. // ineffective
  676. if (limit && (limot->m_loLimit == limot->m_hiLimit)) powered = false;
  677. info->m_constraintError[srow] = btScalar(0.f);
  678. if (powered)
  679. {
  680. info->cfm[srow] = limot->m_normalCFM;
  681. if (!limit)
  682. {
  683. btScalar tag_vel = rotational ? limot->m_targetVelocity : -limot->m_targetVelocity;
  684. btScalar mot_fact = getMotorFactor(limot->m_currentPosition,
  685. limot->m_loLimit,
  686. limot->m_hiLimit,
  687. tag_vel,
  688. info->fps * limot->m_stopERP);
  689. info->m_constraintError[srow] += mot_fact * limot->m_targetVelocity;
  690. info->m_lowerLimit[srow] = -limot->m_maxMotorForce / info->fps;
  691. info->m_upperLimit[srow] = limot->m_maxMotorForce / info->fps;
  692. }
  693. }
  694. if (limit)
  695. {
  696. btScalar k = info->fps * limot->m_stopERP;
  697. if (!rotational)
  698. {
  699. info->m_constraintError[srow] += k * limot->m_currentLimitError;
  700. }
  701. else
  702. {
  703. info->m_constraintError[srow] += -k * limot->m_currentLimitError;
  704. }
  705. info->cfm[srow] = limot->m_stopCFM;
  706. if (limot->m_loLimit == limot->m_hiLimit)
  707. { // limited low and high simultaneously
  708. info->m_lowerLimit[srow] = -SIMD_INFINITY;
  709. info->m_upperLimit[srow] = SIMD_INFINITY;
  710. }
  711. else
  712. {
  713. if (limit == 1)
  714. {
  715. info->m_lowerLimit[srow] = 0;
  716. info->m_upperLimit[srow] = SIMD_INFINITY;
  717. }
  718. else
  719. {
  720. info->m_lowerLimit[srow] = -SIMD_INFINITY;
  721. info->m_upperLimit[srow] = 0;
  722. }
  723. // deal with bounce
  724. if (limot->m_bounce > 0)
  725. {
  726. // calculate joint velocity
  727. btScalar vel;
  728. if (rotational)
  729. {
  730. vel = angVelA.dot(ax1);
  731. //make sure that if no body -> angVelB == zero vec
  732. // if (body1)
  733. vel -= angVelB.dot(ax1);
  734. }
  735. else
  736. {
  737. vel = linVelA.dot(ax1);
  738. //make sure that if no body -> angVelB == zero vec
  739. // if (body1)
  740. vel -= linVelB.dot(ax1);
  741. }
  742. // only apply bounce if the velocity is incoming, and if the
  743. // resulting c[] exceeds what we already have.
  744. if (limit == 1)
  745. {
  746. if (vel < 0)
  747. {
  748. btScalar newc = -limot->m_bounce * vel;
  749. if (newc > info->m_constraintError[srow])
  750. info->m_constraintError[srow] = newc;
  751. }
  752. }
  753. else
  754. {
  755. if (vel > 0)
  756. {
  757. btScalar newc = -limot->m_bounce * vel;
  758. if (newc < info->m_constraintError[srow])
  759. info->m_constraintError[srow] = newc;
  760. }
  761. }
  762. }
  763. }
  764. }
  765. return 1;
  766. }
  767. else
  768. return 0;
  769. }
  770. ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
  771. ///If no axis is provided, it uses the default axis for this constraint.
  772. void btGeneric6DofConstraint::setParam(int num, btScalar value, int axis)
  773. {
  774. if ((axis >= 0) && (axis < 3))
  775. {
  776. switch (num)
  777. {
  778. case BT_CONSTRAINT_STOP_ERP:
  779. m_linearLimits.m_stopERP[axis] = value;
  780. m_flags |= BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  781. break;
  782. case BT_CONSTRAINT_STOP_CFM:
  783. m_linearLimits.m_stopCFM[axis] = value;
  784. m_flags |= BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  785. break;
  786. case BT_CONSTRAINT_CFM:
  787. m_linearLimits.m_normalCFM[axis] = value;
  788. m_flags |= BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  789. break;
  790. default:
  791. btAssertConstrParams(0);
  792. }
  793. }
  794. else if ((axis >= 3) && (axis < 6))
  795. {
  796. switch (num)
  797. {
  798. case BT_CONSTRAINT_STOP_ERP:
  799. m_angularLimits[axis - 3].m_stopERP = value;
  800. m_flags |= BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  801. break;
  802. case BT_CONSTRAINT_STOP_CFM:
  803. m_angularLimits[axis - 3].m_stopCFM = value;
  804. m_flags |= BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  805. break;
  806. case BT_CONSTRAINT_CFM:
  807. m_angularLimits[axis - 3].m_normalCFM = value;
  808. m_flags |= BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
  809. break;
  810. default:
  811. btAssertConstrParams(0);
  812. }
  813. }
  814. else
  815. {
  816. btAssertConstrParams(0);
  817. }
  818. }
  819. ///return the local value of parameter
  820. btScalar btGeneric6DofConstraint::getParam(int num, int axis) const
  821. {
  822. btScalar retVal = 0;
  823. if ((axis >= 0) && (axis < 3))
  824. {
  825. switch (num)
  826. {
  827. case BT_CONSTRAINT_STOP_ERP:
  828. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  829. retVal = m_linearLimits.m_stopERP[axis];
  830. break;
  831. case BT_CONSTRAINT_STOP_CFM:
  832. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  833. retVal = m_linearLimits.m_stopCFM[axis];
  834. break;
  835. case BT_CONSTRAINT_CFM:
  836. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  837. retVal = m_linearLimits.m_normalCFM[axis];
  838. break;
  839. default:
  840. btAssertConstrParams(0);
  841. }
  842. }
  843. else if ((axis >= 3) && (axis < 6))
  844. {
  845. switch (num)
  846. {
  847. case BT_CONSTRAINT_STOP_ERP:
  848. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  849. retVal = m_angularLimits[axis - 3].m_stopERP;
  850. break;
  851. case BT_CONSTRAINT_STOP_CFM:
  852. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  853. retVal = m_angularLimits[axis - 3].m_stopCFM;
  854. break;
  855. case BT_CONSTRAINT_CFM:
  856. btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
  857. retVal = m_angularLimits[axis - 3].m_normalCFM;
  858. break;
  859. default:
  860. btAssertConstrParams(0);
  861. }
  862. }
  863. else
  864. {
  865. btAssertConstrParams(0);
  866. }
  867. return retVal;
  868. }
  869. void btGeneric6DofConstraint::setAxis(const btVector3& axis1, const btVector3& axis2)
  870. {
  871. btVector3 zAxis = axis1.normalized();
  872. btVector3 yAxis = axis2.normalized();
  873. btVector3 xAxis = yAxis.cross(zAxis); // we want right coordinate system
  874. btTransform frameInW;
  875. frameInW.setIdentity();
  876. frameInW.getBasis().setValue(xAxis[0], yAxis[0], zAxis[0],
  877. xAxis[1], yAxis[1], zAxis[1],
  878. xAxis[2], yAxis[2], zAxis[2]);
  879. // now get constraint frame in local coordinate systems
  880. m_frameInA = m_rbA.getCenterOfMassTransform().inverse() * frameInW;
  881. m_frameInB = m_rbB.getCenterOfMassTransform().inverse() * frameInW;
  882. calculateTransforms();
  883. }