btGeneric6DofConstraint.cpp 31 KB

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