btDiscreteDynamicsWorld.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
  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. #include "btDiscreteDynamicsWorld.h"
  14. //collision detection
  15. #include "bullet/BulletCollision//CollisionDispatch/btCollisionDispatcher.h"
  16. #include "bullet/BulletCollision//BroadphaseCollision/btSimpleBroadphase.h"
  17. #include "bullet/BulletCollision//BroadphaseCollision/btCollisionAlgorithm.h"
  18. #include "bullet/BulletCollision//CollisionShapes/btCollisionShape.h"
  19. #include "bullet/BulletCollision//CollisionDispatch/btSimulationIslandManager.h"
  20. #include "bullet/LinearMath/btTransformUtil.h"
  21. #include "bullet/LinearMath/btQuickprof.h"
  22. //rigidbody & constraints
  23. #include "bullet/BulletDynamics/Dynamics/btRigidBody.h"
  24. #include "bullet/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h"
  25. #include "bullet/BulletDynamics/ConstraintSolver/btContactSolverInfo.h"
  26. #include "bullet/BulletDynamics/ConstraintSolver/btTypedConstraint.h"
  27. #include "bullet/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h"
  28. #include "bullet/BulletDynamics/ConstraintSolver/btHingeConstraint.h"
  29. #include "bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h"
  30. #include "bullet/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h"
  31. #include "bullet/BulletDynamics/ConstraintSolver/btSliderConstraint.h"
  32. #include "bullet/BulletDynamics/ConstraintSolver/btContactConstraint.h"
  33. #include "bullet/LinearMath/btIDebugDraw.h"
  34. #include "bullet/BulletCollision//CollisionShapes/btSphereShape.h"
  35. #include "bullet/BulletDynamics/Dynamics/btActionInterface.h"
  36. #include "bullet/LinearMath/btQuickprof.h"
  37. #include "bullet/LinearMath/btMotionState.h"
  38. #include "bullet/LinearMath/btSerializer.h"
  39. #if 0
  40. btAlignedObjectArray<btVector3> debugContacts;
  41. btAlignedObjectArray<btVector3> debugNormals;
  42. int startHit=2;
  43. int firstHit=startHit;
  44. #endif
  45. SIMD_FORCE_INLINE int btGetConstraintIslandId(const btTypedConstraint* lhs)
  46. {
  47. int islandId;
  48. const btCollisionObject& rcolObj0 = lhs->getRigidBodyA();
  49. const btCollisionObject& rcolObj1 = lhs->getRigidBodyB();
  50. islandId= rcolObj0.getIslandTag()>=0?rcolObj0.getIslandTag():rcolObj1.getIslandTag();
  51. return islandId;
  52. }
  53. class btSortConstraintOnIslandPredicate
  54. {
  55. public:
  56. bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) const
  57. {
  58. int rIslandId0,lIslandId0;
  59. rIslandId0 = btGetConstraintIslandId(rhs);
  60. lIslandId0 = btGetConstraintIslandId(lhs);
  61. return lIslandId0 < rIslandId0;
  62. }
  63. };
  64. struct InplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback
  65. {
  66. btContactSolverInfo* m_solverInfo;
  67. btConstraintSolver* m_solver;
  68. btTypedConstraint** m_sortedConstraints;
  69. int m_numConstraints;
  70. btIDebugDraw* m_debugDrawer;
  71. btDispatcher* m_dispatcher;
  72. btAlignedObjectArray<btCollisionObject*> m_bodies;
  73. btAlignedObjectArray<btPersistentManifold*> m_manifolds;
  74. btAlignedObjectArray<btTypedConstraint*> m_constraints;
  75. InplaceSolverIslandCallback(
  76. btConstraintSolver* solver,
  77. btStackAlloc* stackAlloc,
  78. btDispatcher* dispatcher)
  79. :m_solverInfo(NULL),
  80. m_solver(solver),
  81. m_sortedConstraints(NULL),
  82. m_numConstraints(0),
  83. m_debugDrawer(NULL),
  84. m_dispatcher(dispatcher)
  85. {
  86. }
  87. InplaceSolverIslandCallback& operator=(InplaceSolverIslandCallback& other)
  88. {
  89. btAssert(0);
  90. (void)other;
  91. return *this;
  92. }
  93. SIMD_FORCE_INLINE void setup ( btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btIDebugDraw* debugDrawer)
  94. {
  95. btAssert(solverInfo);
  96. m_solverInfo = solverInfo;
  97. m_sortedConstraints = sortedConstraints;
  98. m_numConstraints = numConstraints;
  99. m_debugDrawer = debugDrawer;
  100. m_bodies.resize (0);
  101. m_manifolds.resize (0);
  102. m_constraints.resize (0);
  103. }
  104. virtual void processIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId)
  105. {
  106. if (islandId<0)
  107. {
  108. ///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id
  109. m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,&m_sortedConstraints[0],m_numConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher);
  110. } else
  111. {
  112. //also add all non-contact constraints/joints for this island
  113. btTypedConstraint** startConstraint = 0;
  114. int numCurConstraints = 0;
  115. int i;
  116. //find the first constraint for this island
  117. for (i=0;i<m_numConstraints;i++)
  118. {
  119. if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId)
  120. {
  121. startConstraint = &m_sortedConstraints[i];
  122. break;
  123. }
  124. }
  125. //count the number of constraints in this island
  126. for (;i<m_numConstraints;i++)
  127. {
  128. if (btGetConstraintIslandId(m_sortedConstraints[i]) == islandId)
  129. {
  130. numCurConstraints++;
  131. }
  132. }
  133. if (m_solverInfo->m_minimumSolverBatchSize<=1)
  134. {
  135. m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher);
  136. } else
  137. {
  138. for (i=0;i<numBodies;i++)
  139. m_bodies.push_back(bodies[i]);
  140. for (i=0;i<numManifolds;i++)
  141. m_manifolds.push_back(manifolds[i]);
  142. for (i=0;i<numCurConstraints;i++)
  143. m_constraints.push_back(startConstraint[i]);
  144. if ((m_constraints.size()+m_manifolds.size())>m_solverInfo->m_minimumSolverBatchSize)
  145. {
  146. processConstraints();
  147. } else
  148. {
  149. //printf("deferred\n");
  150. }
  151. }
  152. }
  153. }
  154. void processConstraints()
  155. {
  156. btCollisionObject** bodies = m_bodies.size()? &m_bodies[0]:0;
  157. btPersistentManifold** manifold = m_manifolds.size()?&m_manifolds[0]:0;
  158. btTypedConstraint** constraints = m_constraints.size()?&m_constraints[0]:0;
  159. m_solver->solveGroup( bodies,m_bodies.size(),manifold, m_manifolds.size(),constraints, m_constraints.size() ,*m_solverInfo,m_debugDrawer,m_dispatcher);
  160. m_bodies.resize(0);
  161. m_manifolds.resize(0);
  162. m_constraints.resize(0);
  163. }
  164. };
  165. btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration)
  166. :btDynamicsWorld(dispatcher,pairCache,collisionConfiguration),
  167. m_sortedConstraints (),
  168. m_solverIslandCallback ( NULL ),
  169. m_constraintSolver(constraintSolver),
  170. m_gravity(0,-10,0),
  171. m_localTime(0),
  172. m_synchronizeAllMotionStates(false),
  173. m_applySpeculativeContactRestitution(false),
  174. m_profileTimings(0),
  175. m_fixedTimeStep(0),
  176. m_latencyMotionStateInterpolation(true)
  177. {
  178. if (!m_constraintSolver)
  179. {
  180. void* mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16);
  181. m_constraintSolver = new (mem) btSequentialImpulseConstraintSolver;
  182. m_ownsConstraintSolver = true;
  183. } else
  184. {
  185. m_ownsConstraintSolver = false;
  186. }
  187. {
  188. void* mem = btAlignedAlloc(sizeof(btSimulationIslandManager),16);
  189. m_islandManager = new (mem) btSimulationIslandManager();
  190. }
  191. m_ownsIslandManager = true;
  192. {
  193. void* mem = btAlignedAlloc(sizeof(InplaceSolverIslandCallback),16);
  194. m_solverIslandCallback = new (mem) InplaceSolverIslandCallback (m_constraintSolver, 0, dispatcher);
  195. }
  196. }
  197. btDiscreteDynamicsWorld::~btDiscreteDynamicsWorld()
  198. {
  199. //only delete it when we created it
  200. if (m_ownsIslandManager)
  201. {
  202. m_islandManager->~btSimulationIslandManager();
  203. btAlignedFree( m_islandManager);
  204. }
  205. if (m_solverIslandCallback)
  206. {
  207. m_solverIslandCallback->~InplaceSolverIslandCallback();
  208. btAlignedFree(m_solverIslandCallback);
  209. }
  210. if (m_ownsConstraintSolver)
  211. {
  212. m_constraintSolver->~btConstraintSolver();
  213. btAlignedFree(m_constraintSolver);
  214. }
  215. }
  216. void btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep)
  217. {
  218. ///would like to iterate over m_nonStaticRigidBodies, but unfortunately old API allows
  219. ///to switch status _after_ adding kinematic objects to the world
  220. ///fix it for Bullet 3.x release
  221. for (int i=0;i<m_collisionObjects.size();i++)
  222. {
  223. btCollisionObject* colObj = m_collisionObjects[i];
  224. btRigidBody* body = btRigidBody::upcast(colObj);
  225. if (body && body->getActivationState() != ISLAND_SLEEPING)
  226. {
  227. if (body->isKinematicObject())
  228. {
  229. //to calculate velocities next frame
  230. body->saveKinematicState(timeStep);
  231. }
  232. }
  233. }
  234. }
  235. void btDiscreteDynamicsWorld::debugDrawWorld()
  236. {
  237. BT_PROFILE("debugDrawWorld");
  238. btCollisionWorld::debugDrawWorld();
  239. bool drawConstraints = false;
  240. if (getDebugDrawer())
  241. {
  242. int mode = getDebugDrawer()->getDebugMode();
  243. if(mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits))
  244. {
  245. drawConstraints = true;
  246. }
  247. }
  248. if(drawConstraints)
  249. {
  250. for(int i = getNumConstraints()-1; i>=0 ;i--)
  251. {
  252. btTypedConstraint* constraint = getConstraint(i);
  253. debugDrawConstraint(constraint);
  254. }
  255. }
  256. if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawNormals)))
  257. {
  258. int i;
  259. if (getDebugDrawer() && getDebugDrawer()->getDebugMode())
  260. {
  261. for (i=0;i<m_actions.size();i++)
  262. {
  263. m_actions[i]->debugDraw(m_debugDrawer);
  264. }
  265. }
  266. }
  267. }
  268. void btDiscreteDynamicsWorld::clearForces()
  269. {
  270. ///@todo: iterate over awake simulation islands!
  271. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  272. {
  273. btRigidBody* body = m_nonStaticRigidBodies[i];
  274. //need to check if next line is ok
  275. //it might break backward compatibility (people applying forces on sleeping objects get never cleared and accumulate on wake-up
  276. body->clearForces();
  277. }
  278. }
  279. ///apply gravity, call this once per timestep
  280. void btDiscreteDynamicsWorld::applyGravity()
  281. {
  282. ///@todo: iterate over awake simulation islands!
  283. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  284. {
  285. btRigidBody* body = m_nonStaticRigidBodies[i];
  286. if (body->isActive())
  287. {
  288. body->applyGravity();
  289. }
  290. }
  291. }
  292. void btDiscreteDynamicsWorld::synchronizeSingleMotionState(btRigidBody* body)
  293. {
  294. btAssert(body);
  295. if (body->getMotionState() && !body->isStaticOrKinematicObject())
  296. {
  297. //we need to call the update at least once, even for sleeping objects
  298. //otherwise the 'graphics' transform never updates properly
  299. ///@todo: add 'dirty' flag
  300. //if (body->getActivationState() != ISLAND_SLEEPING)
  301. {
  302. btTransform interpolatedTransform;
  303. btTransformUtil::integrateTransform(body->getInterpolationWorldTransform(),
  304. body->getInterpolationLinearVelocity(),body->getInterpolationAngularVelocity(),
  305. (m_latencyMotionStateInterpolation && m_fixedTimeStep) ? m_localTime - m_fixedTimeStep : m_localTime*body->getHitFraction(),
  306. interpolatedTransform);
  307. body->getMotionState()->setWorldTransform(interpolatedTransform);
  308. }
  309. }
  310. }
  311. void btDiscreteDynamicsWorld::synchronizeMotionStates()
  312. {
  313. BT_PROFILE("synchronizeMotionStates");
  314. if (m_synchronizeAllMotionStates)
  315. {
  316. //iterate over all collision objects
  317. for ( int i=0;i<m_collisionObjects.size();i++)
  318. {
  319. btCollisionObject* colObj = m_collisionObjects[i];
  320. btRigidBody* body = btRigidBody::upcast(colObj);
  321. if (body)
  322. synchronizeSingleMotionState(body);
  323. }
  324. } else
  325. {
  326. //iterate over all active rigid bodies
  327. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  328. {
  329. btRigidBody* body = m_nonStaticRigidBodies[i];
  330. if (body->isActive())
  331. synchronizeSingleMotionState(body);
  332. }
  333. }
  334. }
  335. int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep)
  336. {
  337. startProfiling(timeStep);
  338. BT_PROFILE("stepSimulation");
  339. int numSimulationSubSteps = 0;
  340. if (maxSubSteps)
  341. {
  342. //fixed timestep with interpolation
  343. m_fixedTimeStep = fixedTimeStep;
  344. m_localTime += timeStep;
  345. if (m_localTime >= fixedTimeStep)
  346. {
  347. numSimulationSubSteps = int( m_localTime / fixedTimeStep);
  348. m_localTime -= numSimulationSubSteps * fixedTimeStep;
  349. }
  350. } else
  351. {
  352. //variable timestep
  353. fixedTimeStep = timeStep;
  354. m_localTime = m_latencyMotionStateInterpolation ? 0 : timeStep;
  355. m_fixedTimeStep = 0;
  356. if (btFuzzyZero(timeStep))
  357. {
  358. numSimulationSubSteps = 0;
  359. maxSubSteps = 0;
  360. } else
  361. {
  362. numSimulationSubSteps = 1;
  363. maxSubSteps = 1;
  364. }
  365. }
  366. //process some debugging flags
  367. if (getDebugDrawer())
  368. {
  369. btIDebugDraw* debugDrawer = getDebugDrawer ();
  370. gDisableDeactivation = (debugDrawer->getDebugMode() & btIDebugDraw::DBG_NoDeactivation) != 0;
  371. }
  372. if (numSimulationSubSteps)
  373. {
  374. //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt
  375. int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps)? maxSubSteps : numSimulationSubSteps;
  376. saveKinematicState(fixedTimeStep*clampedSimulationSteps);
  377. applyGravity();
  378. for (int i=0;i<clampedSimulationSteps;i++)
  379. {
  380. internalSingleStepSimulation(fixedTimeStep);
  381. synchronizeMotionStates();
  382. }
  383. } else
  384. {
  385. synchronizeMotionStates();
  386. }
  387. clearForces();
  388. #ifndef BT_NO_PROFILE
  389. CProfileManager::Increment_Frame_Counter();
  390. #endif //BT_NO_PROFILE
  391. return numSimulationSubSteps;
  392. }
  393. void btDiscreteDynamicsWorld::internalSingleStepSimulation(btScalar timeStep)
  394. {
  395. BT_PROFILE("internalSingleStepSimulation");
  396. if(0 != m_internalPreTickCallback) {
  397. (*m_internalPreTickCallback)(this, timeStep);
  398. }
  399. ///apply gravity, predict motion
  400. predictUnconstraintMotion(timeStep);
  401. btDispatcherInfo& dispatchInfo = getDispatchInfo();
  402. dispatchInfo.m_timeStep = timeStep;
  403. dispatchInfo.m_stepCount = 0;
  404. dispatchInfo.m_debugDraw = getDebugDrawer();
  405. createPredictiveContacts(timeStep);
  406. ///perform collision detection
  407. performDiscreteCollisionDetection();
  408. calculateSimulationIslands();
  409. getSolverInfo().m_timeStep = timeStep;
  410. ///solve contact and other joint constraints
  411. solveConstraints(getSolverInfo());
  412. ///CallbackTriggers();
  413. ///integrate transforms
  414. integrateTransforms(timeStep);
  415. ///update vehicle simulation
  416. updateActions(timeStep);
  417. updateActivationState( timeStep );
  418. if(0 != m_internalTickCallback) {
  419. (*m_internalTickCallback)(this, timeStep);
  420. }
  421. }
  422. void btDiscreteDynamicsWorld::setGravity(const btVector3& gravity)
  423. {
  424. m_gravity = gravity;
  425. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  426. {
  427. btRigidBody* body = m_nonStaticRigidBodies[i];
  428. if (body->isActive() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
  429. {
  430. body->setGravity(gravity);
  431. }
  432. }
  433. }
  434. btVector3 btDiscreteDynamicsWorld::getGravity () const
  435. {
  436. return m_gravity;
  437. }
  438. void btDiscreteDynamicsWorld::addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup,short int collisionFilterMask)
  439. {
  440. btCollisionWorld::addCollisionObject(collisionObject,collisionFilterGroup,collisionFilterMask);
  441. }
  442. void btDiscreteDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject)
  443. {
  444. btRigidBody* body = btRigidBody::upcast(collisionObject);
  445. if (body)
  446. removeRigidBody(body);
  447. else
  448. btCollisionWorld::removeCollisionObject(collisionObject);
  449. }
  450. void btDiscreteDynamicsWorld::removeRigidBody(btRigidBody* body)
  451. {
  452. m_nonStaticRigidBodies.remove(body);
  453. btCollisionWorld::removeCollisionObject(body);
  454. }
  455. void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body)
  456. {
  457. if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
  458. {
  459. body->setGravity(m_gravity);
  460. }
  461. if (body->getCollisionShape())
  462. {
  463. if (!body->isStaticObject())
  464. {
  465. m_nonStaticRigidBodies.push_back(body);
  466. } else
  467. {
  468. body->setActivationState(ISLAND_SLEEPING);
  469. }
  470. bool isDynamic = !(body->isStaticObject() || body->isKinematicObject());
  471. short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
  472. short collisionFilterMask = isDynamic? short(btBroadphaseProxy::AllFilter) : short(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
  473. addCollisionObject(body,collisionFilterGroup,collisionFilterMask);
  474. }
  475. }
  476. void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body, short group, short mask)
  477. {
  478. if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
  479. {
  480. body->setGravity(m_gravity);
  481. }
  482. if (body->getCollisionShape())
  483. {
  484. if (!body->isStaticObject())
  485. {
  486. m_nonStaticRigidBodies.push_back(body);
  487. }
  488. else
  489. {
  490. body->setActivationState(ISLAND_SLEEPING);
  491. }
  492. addCollisionObject(body,group,mask);
  493. }
  494. }
  495. void btDiscreteDynamicsWorld::updateActions(btScalar timeStep)
  496. {
  497. BT_PROFILE("updateActions");
  498. for ( int i=0;i<m_actions.size();i++)
  499. {
  500. m_actions[i]->updateAction( this, timeStep);
  501. }
  502. }
  503. void btDiscreteDynamicsWorld::updateActivationState(btScalar timeStep)
  504. {
  505. BT_PROFILE("updateActivationState");
  506. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  507. {
  508. btRigidBody* body = m_nonStaticRigidBodies[i];
  509. if (body)
  510. {
  511. body->updateDeactivation(timeStep);
  512. if (body->wantsSleeping())
  513. {
  514. if (body->isStaticOrKinematicObject())
  515. {
  516. body->setActivationState(ISLAND_SLEEPING);
  517. } else
  518. {
  519. if (body->getActivationState() == ACTIVE_TAG)
  520. body->setActivationState( WANTS_DEACTIVATION );
  521. if (body->getActivationState() == ISLAND_SLEEPING)
  522. {
  523. body->setAngularVelocity(btVector3(0,0,0));
  524. body->setLinearVelocity(btVector3(0,0,0));
  525. }
  526. }
  527. } else
  528. {
  529. if (body->getActivationState() != DISABLE_DEACTIVATION)
  530. body->setActivationState( ACTIVE_TAG );
  531. }
  532. }
  533. }
  534. }
  535. void btDiscreteDynamicsWorld::addConstraint(btTypedConstraint* constraint,bool disableCollisionsBetweenLinkedBodies)
  536. {
  537. m_constraints.push_back(constraint);
  538. if (disableCollisionsBetweenLinkedBodies)
  539. {
  540. constraint->getRigidBodyA().addConstraintRef(constraint);
  541. constraint->getRigidBodyB().addConstraintRef(constraint);
  542. }
  543. }
  544. void btDiscreteDynamicsWorld::removeConstraint(btTypedConstraint* constraint)
  545. {
  546. m_constraints.remove(constraint);
  547. constraint->getRigidBodyA().removeConstraintRef(constraint);
  548. constraint->getRigidBodyB().removeConstraintRef(constraint);
  549. }
  550. void btDiscreteDynamicsWorld::addAction(btActionInterface* action)
  551. {
  552. m_actions.push_back(action);
  553. }
  554. void btDiscreteDynamicsWorld::removeAction(btActionInterface* action)
  555. {
  556. m_actions.remove(action);
  557. }
  558. void btDiscreteDynamicsWorld::addVehicle(btActionInterface* vehicle)
  559. {
  560. addAction(vehicle);
  561. }
  562. void btDiscreteDynamicsWorld::removeVehicle(btActionInterface* vehicle)
  563. {
  564. removeAction(vehicle);
  565. }
  566. void btDiscreteDynamicsWorld::addCharacter(btActionInterface* character)
  567. {
  568. addAction(character);
  569. }
  570. void btDiscreteDynamicsWorld::removeCharacter(btActionInterface* character)
  571. {
  572. removeAction(character);
  573. }
  574. void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo)
  575. {
  576. BT_PROFILE("solveConstraints");
  577. m_sortedConstraints.resize( m_constraints.size());
  578. int i;
  579. for (i=0;i<getNumConstraints();i++)
  580. {
  581. m_sortedConstraints[i] = m_constraints[i];
  582. }
  583. // btAssert(0);
  584. m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate());
  585. btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0;
  586. m_solverIslandCallback->setup(&solverInfo,constraintsPtr,m_sortedConstraints.size(),getDebugDrawer());
  587. m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds());
  588. /// solve all the constraints for this island
  589. m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),m_solverIslandCallback);
  590. m_solverIslandCallback->processConstraints();
  591. m_constraintSolver->allSolved(solverInfo, m_debugDrawer);
  592. }
  593. void btDiscreteDynamicsWorld::calculateSimulationIslands()
  594. {
  595. BT_PROFILE("calculateSimulationIslands");
  596. getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher());
  597. {
  598. //merge islands based on speculative contact manifolds too
  599. for (int i=0;i<this->m_predictiveManifolds.size();i++)
  600. {
  601. btPersistentManifold* manifold = m_predictiveManifolds[i];
  602. const btCollisionObject* colObj0 = manifold->getBody0();
  603. const btCollisionObject* colObj1 = manifold->getBody1();
  604. if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
  605. ((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
  606. {
  607. getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
  608. }
  609. }
  610. }
  611. {
  612. int i;
  613. int numConstraints = int(m_constraints.size());
  614. for (i=0;i< numConstraints ; i++ )
  615. {
  616. btTypedConstraint* constraint = m_constraints[i];
  617. if (constraint->isEnabled())
  618. {
  619. const btRigidBody* colObj0 = &constraint->getRigidBodyA();
  620. const btRigidBody* colObj1 = &constraint->getRigidBodyB();
  621. if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
  622. ((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
  623. {
  624. getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
  625. }
  626. }
  627. }
  628. }
  629. //Store the island id in each body
  630. getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld());
  631. }
  632. class btClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  633. {
  634. public:
  635. btCollisionObject* m_me;
  636. btScalar m_allowedPenetration;
  637. btOverlappingPairCache* m_pairCache;
  638. btDispatcher* m_dispatcher;
  639. public:
  640. btClosestNotMeConvexResultCallback (btCollisionObject* me,const btVector3& fromA,const btVector3& toA,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) :
  641. btCollisionWorld::ClosestConvexResultCallback(fromA,toA),
  642. m_me(me),
  643. m_allowedPenetration(0.0f),
  644. m_pairCache(pairCache),
  645. m_dispatcher(dispatcher)
  646. {
  647. }
  648. virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)
  649. {
  650. if (convexResult.m_hitCollisionObject == m_me)
  651. return 1.0f;
  652. //ignore result if there is no contact response
  653. if(!convexResult.m_hitCollisionObject->hasContactResponse())
  654. return 1.0f;
  655. btVector3 linVelA,linVelB;
  656. linVelA = m_convexToWorld-m_convexFromWorld;
  657. linVelB = btVector3(0,0,0);//toB.getOrigin()-fromB.getOrigin();
  658. btVector3 relativeVelocity = (linVelA-linVelB);
  659. //don't report time of impact for motion away from the contact normal (or causes minor penetration)
  660. if (convexResult.m_hitNormalLocal.dot(relativeVelocity)>=-m_allowedPenetration)
  661. return 1.f;
  662. return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);
  663. }
  664. virtual bool needsCollision(btBroadphaseProxy* proxy0) const
  665. {
  666. //don't collide with itself
  667. if (proxy0->m_clientObject == m_me)
  668. return false;
  669. ///don't do CCD when the collision filters are not matching
  670. if (!ClosestConvexResultCallback::needsCollision(proxy0))
  671. return false;
  672. btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject;
  673. //call needsResponse, see http://code.google.com/p/bullet/issues/detail?id=179
  674. if (m_dispatcher->needsResponse(m_me,otherObj))
  675. {
  676. #if 0
  677. ///don't do CCD when there are already contact points (touching contact/penetration)
  678. btAlignedObjectArray<btPersistentManifold*> manifoldArray;
  679. btBroadphasePair* collisionPair = m_pairCache->findPair(m_me->getBroadphaseHandle(),proxy0);
  680. if (collisionPair)
  681. {
  682. if (collisionPair->m_algorithm)
  683. {
  684. manifoldArray.resize(0);
  685. collisionPair->m_algorithm->getAllContactManifolds(manifoldArray);
  686. for (int j=0;j<manifoldArray.size();j++)
  687. {
  688. btPersistentManifold* manifold = manifoldArray[j];
  689. if (manifold->getNumContacts()>0)
  690. return false;
  691. }
  692. }
  693. }
  694. #endif
  695. return true;
  696. }
  697. return false;
  698. }
  699. };
  700. ///internal debugging variable. this value shouldn't be too high
  701. int gNumClampedCcdMotions=0;
  702. void btDiscreteDynamicsWorld::createPredictiveContacts(btScalar timeStep)
  703. {
  704. BT_PROFILE("createPredictiveContacts");
  705. {
  706. BT_PROFILE("release predictive contact manifolds");
  707. for (int i=0;i<m_predictiveManifolds.size();i++)
  708. {
  709. btPersistentManifold* manifold = m_predictiveManifolds[i];
  710. this->m_dispatcher1->releaseManifold(manifold);
  711. }
  712. m_predictiveManifolds.clear();
  713. }
  714. btTransform predictedTrans;
  715. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  716. {
  717. btRigidBody* body = m_nonStaticRigidBodies[i];
  718. body->setHitFraction(1.f);
  719. if (body->isActive() && (!body->isStaticOrKinematicObject()))
  720. {
  721. body->predictIntegratedTransform(timeStep, predictedTrans);
  722. btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2();
  723. if (getDispatchInfo().m_useContinuous && body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion)
  724. {
  725. BT_PROFILE("predictive convexSweepTest");
  726. if (body->getCollisionShape()->isConvex())
  727. {
  728. gNumClampedCcdMotions++;
  729. #ifdef PREDICTIVE_CONTACT_USE_STATIC_ONLY
  730. class StaticOnlyCallback : public btClosestNotMeConvexResultCallback
  731. {
  732. public:
  733. StaticOnlyCallback (btCollisionObject* me,const btVector3& fromA,const btVector3& toA,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) :
  734. btClosestNotMeConvexResultCallback(me,fromA,toA,pairCache,dispatcher)
  735. {
  736. }
  737. virtual bool needsCollision(btBroadphaseProxy* proxy0) const
  738. {
  739. btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject;
  740. if (!otherObj->isStaticOrKinematicObject())
  741. return false;
  742. return btClosestNotMeConvexResultCallback::needsCollision(proxy0);
  743. }
  744. };
  745. StaticOnlyCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
  746. #else
  747. btClosestNotMeConvexResultCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
  748. #endif
  749. //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
  750. btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
  751. sweepResults.m_allowedPenetration=getDispatchInfo().m_allowedCcdPenetration;
  752. sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup;
  753. sweepResults.m_collisionFilterMask = body->getBroadphaseProxy()->m_collisionFilterMask;
  754. btTransform modifiedPredictedTrans = predictedTrans;
  755. modifiedPredictedTrans.setBasis(body->getWorldTransform().getBasis());
  756. convexSweepTest(&tmpSphere,body->getWorldTransform(),modifiedPredictedTrans,sweepResults);
  757. if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f))
  758. {
  759. btVector3 distVec = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin())*sweepResults.m_closestHitFraction;
  760. btScalar distance = distVec.dot(-sweepResults.m_hitNormalWorld);
  761. btPersistentManifold* manifold = m_dispatcher1->getNewManifold(body,sweepResults.m_hitCollisionObject);
  762. m_predictiveManifolds.push_back(manifold);
  763. btVector3 worldPointB = body->getWorldTransform().getOrigin()+distVec;
  764. btVector3 localPointB = sweepResults.m_hitCollisionObject->getWorldTransform().inverse()*worldPointB;
  765. btManifoldPoint newPoint(btVector3(0,0,0), localPointB,sweepResults.m_hitNormalWorld,distance);
  766. bool isPredictive = true;
  767. int index = manifold->addManifoldPoint(newPoint, isPredictive);
  768. btManifoldPoint& pt = manifold->getContactPoint(index);
  769. pt.m_combinedRestitution = 0;
  770. pt.m_combinedFriction = btManifoldResult::calculateCombinedFriction(body,sweepResults.m_hitCollisionObject);
  771. pt.m_positionWorldOnA = body->getWorldTransform().getOrigin();
  772. pt.m_positionWorldOnB = worldPointB;
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. void btDiscreteDynamicsWorld::integrateTransforms(btScalar timeStep)
  780. {
  781. BT_PROFILE("integrateTransforms");
  782. btTransform predictedTrans;
  783. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  784. {
  785. btRigidBody* body = m_nonStaticRigidBodies[i];
  786. body->setHitFraction(1.f);
  787. if (body->isActive() && (!body->isStaticOrKinematicObject()))
  788. {
  789. body->predictIntegratedTransform(timeStep, predictedTrans);
  790. btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2();
  791. if (getDispatchInfo().m_useContinuous && body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion)
  792. {
  793. BT_PROFILE("CCD motion clamping");
  794. if (body->getCollisionShape()->isConvex())
  795. {
  796. gNumClampedCcdMotions++;
  797. #ifdef USE_STATIC_ONLY
  798. class StaticOnlyCallback : public btClosestNotMeConvexResultCallback
  799. {
  800. public:
  801. StaticOnlyCallback (btCollisionObject* me,const btVector3& fromA,const btVector3& toA,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) :
  802. btClosestNotMeConvexResultCallback(me,fromA,toA,pairCache,dispatcher)
  803. {
  804. }
  805. virtual bool needsCollision(btBroadphaseProxy* proxy0) const
  806. {
  807. btCollisionObject* otherObj = (btCollisionObject*) proxy0->m_clientObject;
  808. if (!otherObj->isStaticOrKinematicObject())
  809. return false;
  810. return btClosestNotMeConvexResultCallback::needsCollision(proxy0);
  811. }
  812. };
  813. StaticOnlyCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
  814. #else
  815. btClosestNotMeConvexResultCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
  816. #endif
  817. //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
  818. btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
  819. sweepResults.m_allowedPenetration=getDispatchInfo().m_allowedCcdPenetration;
  820. sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup;
  821. sweepResults.m_collisionFilterMask = body->getBroadphaseProxy()->m_collisionFilterMask;
  822. btTransform modifiedPredictedTrans = predictedTrans;
  823. modifiedPredictedTrans.setBasis(body->getWorldTransform().getBasis());
  824. convexSweepTest(&tmpSphere,body->getWorldTransform(),modifiedPredictedTrans,sweepResults);
  825. if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f))
  826. {
  827. //printf("clamped integration to hit fraction = %f\n",fraction);
  828. body->setHitFraction(sweepResults.m_closestHitFraction);
  829. body->predictIntegratedTransform(timeStep*body->getHitFraction(), predictedTrans);
  830. body->setHitFraction(0.f);
  831. body->proceedToTransform( predictedTrans);
  832. #if 0
  833. btVector3 linVel = body->getLinearVelocity();
  834. btScalar maxSpeed = body->getCcdMotionThreshold()/getSolverInfo().m_timeStep;
  835. btScalar maxSpeedSqr = maxSpeed*maxSpeed;
  836. if (linVel.length2()>maxSpeedSqr)
  837. {
  838. linVel.normalize();
  839. linVel*= maxSpeed;
  840. body->setLinearVelocity(linVel);
  841. btScalar ms2 = body->getLinearVelocity().length2();
  842. body->predictIntegratedTransform(timeStep, predictedTrans);
  843. btScalar sm2 = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2();
  844. btScalar smt = body->getCcdSquareMotionThreshold();
  845. printf("sm2=%f\n",sm2);
  846. }
  847. #else
  848. //don't apply the collision response right now, it will happen next frame
  849. //if you really need to, you can uncomment next 3 lines. Note that is uses zero restitution.
  850. //btScalar appliedImpulse = 0.f;
  851. //btScalar depth = 0.f;
  852. //appliedImpulse = resolveSingleCollision(body,(btCollisionObject*)sweepResults.m_hitCollisionObject,sweepResults.m_hitPointWorld,sweepResults.m_hitNormalWorld,getSolverInfo(), depth);
  853. #endif
  854. continue;
  855. }
  856. }
  857. }
  858. body->proceedToTransform( predictedTrans);
  859. }
  860. }
  861. ///this should probably be switched on by default, but it is not well tested yet
  862. if (m_applySpeculativeContactRestitution)
  863. {
  864. BT_PROFILE("apply speculative contact restitution");
  865. for (int i=0;i<m_predictiveManifolds.size();i++)
  866. {
  867. btPersistentManifold* manifold = m_predictiveManifolds[i];
  868. btRigidBody* body0 = btRigidBody::upcast((btCollisionObject*)manifold->getBody0());
  869. btRigidBody* body1 = btRigidBody::upcast((btCollisionObject*)manifold->getBody1());
  870. for (int p=0;p<manifold->getNumContacts();p++)
  871. {
  872. const btManifoldPoint& pt = manifold->getContactPoint(p);
  873. btScalar combinedRestitution = btManifoldResult::calculateCombinedRestitution(body0, body1);
  874. if (combinedRestitution>0 && pt.m_appliedImpulse != 0.f)
  875. //if (pt.getDistance()>0 && combinedRestitution>0 && pt.m_appliedImpulse != 0.f)
  876. {
  877. btVector3 imp = -pt.m_normalWorldOnB * pt.m_appliedImpulse* combinedRestitution;
  878. const btVector3& pos1 = pt.getPositionWorldOnA();
  879. const btVector3& pos2 = pt.getPositionWorldOnB();
  880. btVector3 rel_pos0 = pos1 - body0->getWorldTransform().getOrigin();
  881. btVector3 rel_pos1 = pos2 - body1->getWorldTransform().getOrigin();
  882. if (body0)
  883. body0->applyImpulse(imp,rel_pos0);
  884. if (body1)
  885. body1->applyImpulse(-imp,rel_pos1);
  886. }
  887. }
  888. }
  889. }
  890. }
  891. void btDiscreteDynamicsWorld::predictUnconstraintMotion(btScalar timeStep)
  892. {
  893. BT_PROFILE("predictUnconstraintMotion");
  894. for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
  895. {
  896. btRigidBody* body = m_nonStaticRigidBodies[i];
  897. if (!body->isStaticOrKinematicObject())
  898. {
  899. //don't integrate/update velocities here, it happens in the constraint solver
  900. body->applyDamping(timeStep);
  901. body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform());
  902. }
  903. }
  904. }
  905. void btDiscreteDynamicsWorld::startProfiling(btScalar timeStep)
  906. {
  907. (void)timeStep;
  908. #ifndef BT_NO_PROFILE
  909. CProfileManager::Reset();
  910. #endif //BT_NO_PROFILE
  911. }
  912. void btDiscreteDynamicsWorld::debugDrawConstraint(btTypedConstraint* constraint)
  913. {
  914. bool drawFrames = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraints) != 0;
  915. bool drawLimits = (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawConstraintLimits) != 0;
  916. btScalar dbgDrawSize = constraint->getDbgDrawSize();
  917. if(dbgDrawSize <= btScalar(0.f))
  918. {
  919. return;
  920. }
  921. switch(constraint->getConstraintType())
  922. {
  923. case POINT2POINT_CONSTRAINT_TYPE:
  924. {
  925. btPoint2PointConstraint* p2pC = (btPoint2PointConstraint*)constraint;
  926. btTransform tr;
  927. tr.setIdentity();
  928. btVector3 pivot = p2pC->getPivotInA();
  929. pivot = p2pC->getRigidBodyA().getCenterOfMassTransform() * pivot;
  930. tr.setOrigin(pivot);
  931. getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  932. // that ideally should draw the same frame
  933. pivot = p2pC->getPivotInB();
  934. pivot = p2pC->getRigidBodyB().getCenterOfMassTransform() * pivot;
  935. tr.setOrigin(pivot);
  936. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  937. }
  938. break;
  939. case HINGE_CONSTRAINT_TYPE:
  940. {
  941. btHingeConstraint* pHinge = (btHingeConstraint*)constraint;
  942. btTransform tr = pHinge->getRigidBodyA().getCenterOfMassTransform() * pHinge->getAFrame();
  943. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  944. tr = pHinge->getRigidBodyB().getCenterOfMassTransform() * pHinge->getBFrame();
  945. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  946. btScalar minAng = pHinge->getLowerLimit();
  947. btScalar maxAng = pHinge->getUpperLimit();
  948. if(minAng == maxAng)
  949. {
  950. break;
  951. }
  952. bool drawSect = true;
  953. if(minAng > maxAng)
  954. {
  955. minAng = btScalar(0.f);
  956. maxAng = SIMD_2_PI;
  957. drawSect = false;
  958. }
  959. if(drawLimits)
  960. {
  961. btVector3& center = tr.getOrigin();
  962. btVector3 normal = tr.getBasis().getColumn(2);
  963. btVector3 axis = tr.getBasis().getColumn(0);
  964. getDebugDrawer()->drawArc(center, normal, axis, dbgDrawSize, dbgDrawSize, minAng, maxAng, btVector3(0,0,0), drawSect);
  965. }
  966. }
  967. break;
  968. case CONETWIST_CONSTRAINT_TYPE:
  969. {
  970. btConeTwistConstraint* pCT = (btConeTwistConstraint*)constraint;
  971. btTransform tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame();
  972. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  973. tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame();
  974. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  975. if(drawLimits)
  976. {
  977. //const btScalar length = btScalar(5);
  978. const btScalar length = dbgDrawSize;
  979. static int nSegments = 8*4;
  980. btScalar fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)(nSegments-1)/btScalar(nSegments);
  981. btVector3 pPrev = pCT->GetPointForAngle(fAngleInRadians, length);
  982. pPrev = tr * pPrev;
  983. for (int i=0; i<nSegments; i++)
  984. {
  985. fAngleInRadians = btScalar(2.*3.1415926) * (btScalar)i/btScalar(nSegments);
  986. btVector3 pCur = pCT->GetPointForAngle(fAngleInRadians, length);
  987. pCur = tr * pCur;
  988. getDebugDrawer()->drawLine(pPrev, pCur, btVector3(0,0,0));
  989. if (i%(nSegments/8) == 0)
  990. getDebugDrawer()->drawLine(tr.getOrigin(), pCur, btVector3(0,0,0));
  991. pPrev = pCur;
  992. }
  993. btScalar tws = pCT->getTwistSpan();
  994. btScalar twa = pCT->getTwistAngle();
  995. bool useFrameB = (pCT->getRigidBodyB().getInvMass() > btScalar(0.f));
  996. if(useFrameB)
  997. {
  998. tr = pCT->getRigidBodyB().getCenterOfMassTransform() * pCT->getBFrame();
  999. }
  1000. else
  1001. {
  1002. tr = pCT->getRigidBodyA().getCenterOfMassTransform() * pCT->getAFrame();
  1003. }
  1004. btVector3 pivot = tr.getOrigin();
  1005. btVector3 normal = tr.getBasis().getColumn(0);
  1006. btVector3 axis1 = tr.getBasis().getColumn(1);
  1007. getDebugDrawer()->drawArc(pivot, normal, axis1, dbgDrawSize, dbgDrawSize, -twa-tws, -twa+tws, btVector3(0,0,0), true);
  1008. }
  1009. }
  1010. break;
  1011. case D6_SPRING_CONSTRAINT_TYPE:
  1012. case D6_CONSTRAINT_TYPE:
  1013. {
  1014. btGeneric6DofConstraint* p6DOF = (btGeneric6DofConstraint*)constraint;
  1015. btTransform tr = p6DOF->getCalculatedTransformA();
  1016. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  1017. tr = p6DOF->getCalculatedTransformB();
  1018. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  1019. if(drawLimits)
  1020. {
  1021. tr = p6DOF->getCalculatedTransformA();
  1022. const btVector3& center = p6DOF->getCalculatedTransformB().getOrigin();
  1023. btVector3 up = tr.getBasis().getColumn(2);
  1024. btVector3 axis = tr.getBasis().getColumn(0);
  1025. btScalar minTh = p6DOF->getRotationalLimitMotor(1)->m_loLimit;
  1026. btScalar maxTh = p6DOF->getRotationalLimitMotor(1)->m_hiLimit;
  1027. btScalar minPs = p6DOF->getRotationalLimitMotor(2)->m_loLimit;
  1028. btScalar maxPs = p6DOF->getRotationalLimitMotor(2)->m_hiLimit;
  1029. getDebugDrawer()->drawSpherePatch(center, up, axis, dbgDrawSize * btScalar(.9f), minTh, maxTh, minPs, maxPs, btVector3(0,0,0));
  1030. axis = tr.getBasis().getColumn(1);
  1031. btScalar ay = p6DOF->getAngle(1);
  1032. btScalar az = p6DOF->getAngle(2);
  1033. btScalar cy = btCos(ay);
  1034. btScalar sy = btSin(ay);
  1035. btScalar cz = btCos(az);
  1036. btScalar sz = btSin(az);
  1037. btVector3 ref;
  1038. ref[0] = cy*cz*axis[0] + cy*sz*axis[1] - sy*axis[2];
  1039. ref[1] = -sz*axis[0] + cz*axis[1];
  1040. ref[2] = cz*sy*axis[0] + sz*sy*axis[1] + cy*axis[2];
  1041. tr = p6DOF->getCalculatedTransformB();
  1042. btVector3 normal = -tr.getBasis().getColumn(0);
  1043. btScalar minFi = p6DOF->getRotationalLimitMotor(0)->m_loLimit;
  1044. btScalar maxFi = p6DOF->getRotationalLimitMotor(0)->m_hiLimit;
  1045. if(minFi > maxFi)
  1046. {
  1047. getDebugDrawer()->drawArc(center, normal, ref, dbgDrawSize, dbgDrawSize, -SIMD_PI, SIMD_PI, btVector3(0,0,0), false);
  1048. }
  1049. else if(minFi < maxFi)
  1050. {
  1051. getDebugDrawer()->drawArc(center, normal, ref, dbgDrawSize, dbgDrawSize, minFi, maxFi, btVector3(0,0,0), true);
  1052. }
  1053. tr = p6DOF->getCalculatedTransformA();
  1054. btVector3 bbMin = p6DOF->getTranslationalLimitMotor()->m_lowerLimit;
  1055. btVector3 bbMax = p6DOF->getTranslationalLimitMotor()->m_upperLimit;
  1056. getDebugDrawer()->drawBox(bbMin, bbMax, tr, btVector3(0,0,0));
  1057. }
  1058. }
  1059. break;
  1060. case SLIDER_CONSTRAINT_TYPE:
  1061. {
  1062. btSliderConstraint* pSlider = (btSliderConstraint*)constraint;
  1063. btTransform tr = pSlider->getCalculatedTransformA();
  1064. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  1065. tr = pSlider->getCalculatedTransformB();
  1066. if(drawFrames) getDebugDrawer()->drawTransform(tr, dbgDrawSize);
  1067. if(drawLimits)
  1068. {
  1069. btTransform tr = pSlider->getUseLinearReferenceFrameA() ? pSlider->getCalculatedTransformA() : pSlider->getCalculatedTransformB();
  1070. btVector3 li_min = tr * btVector3(pSlider->getLowerLinLimit(), 0.f, 0.f);
  1071. btVector3 li_max = tr * btVector3(pSlider->getUpperLinLimit(), 0.f, 0.f);
  1072. getDebugDrawer()->drawLine(li_min, li_max, btVector3(0, 0, 0));
  1073. btVector3 normal = tr.getBasis().getColumn(0);
  1074. btVector3 axis = tr.getBasis().getColumn(1);
  1075. btScalar a_min = pSlider->getLowerAngLimit();
  1076. btScalar a_max = pSlider->getUpperAngLimit();
  1077. const btVector3& center = pSlider->getCalculatedTransformB().getOrigin();
  1078. getDebugDrawer()->drawArc(center, normal, axis, dbgDrawSize, dbgDrawSize, a_min, a_max, btVector3(0,0,0), true);
  1079. }
  1080. }
  1081. break;
  1082. default :
  1083. break;
  1084. }
  1085. return;
  1086. }
  1087. void btDiscreteDynamicsWorld::setConstraintSolver(btConstraintSolver* solver)
  1088. {
  1089. if (m_ownsConstraintSolver)
  1090. {
  1091. btAlignedFree( m_constraintSolver);
  1092. }
  1093. m_ownsConstraintSolver = false;
  1094. m_constraintSolver = solver;
  1095. m_solverIslandCallback->m_solver = solver;
  1096. }
  1097. btConstraintSolver* btDiscreteDynamicsWorld::getConstraintSolver()
  1098. {
  1099. return m_constraintSolver;
  1100. }
  1101. int btDiscreteDynamicsWorld::getNumConstraints() const
  1102. {
  1103. return int(m_constraints.size());
  1104. }
  1105. btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index)
  1106. {
  1107. return m_constraints[index];
  1108. }
  1109. const btTypedConstraint* btDiscreteDynamicsWorld::getConstraint(int index) const
  1110. {
  1111. return m_constraints[index];
  1112. }
  1113. void btDiscreteDynamicsWorld::serializeRigidBodies(btSerializer* serializer)
  1114. {
  1115. int i;
  1116. //serialize all collision objects
  1117. for (i=0;i<m_collisionObjects.size();i++)
  1118. {
  1119. btCollisionObject* colObj = m_collisionObjects[i];
  1120. if (colObj->getInternalType() & btCollisionObject::CO_RIGID_BODY)
  1121. {
  1122. int len = colObj->calculateSerializeBufferSize();
  1123. btChunk* chunk = serializer->allocate(len,1);
  1124. const char* structType = colObj->serialize(chunk->m_oldPtr, serializer);
  1125. serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,colObj);
  1126. }
  1127. }
  1128. for (i=0;i<m_constraints.size();i++)
  1129. {
  1130. btTypedConstraint* constraint = m_constraints[i];
  1131. int size = constraint->calculateSerializeBufferSize();
  1132. btChunk* chunk = serializer->allocate(size,1);
  1133. const char* structType = constraint->serialize(chunk->m_oldPtr,serializer);
  1134. serializer->finalizeChunk(chunk,structType,BT_CONSTRAINT_CODE,constraint);
  1135. }
  1136. }
  1137. void btDiscreteDynamicsWorld::serializeDynamicsWorldInfo(btSerializer* serializer)
  1138. {
  1139. #ifdef BT_USE_DOUBLE_PRECISION
  1140. int len = sizeof(btDynamicsWorldDoubleData);
  1141. btChunk* chunk = serializer->allocate(len,1);
  1142. btDynamicsWorldDoubleData* worldInfo = (btDynamicsWorldDoubleData*)chunk->m_oldPtr;
  1143. #else//BT_USE_DOUBLE_PRECISION
  1144. int len = sizeof(btDynamicsWorldFloatData);
  1145. btChunk* chunk = serializer->allocate(len,1);
  1146. btDynamicsWorldFloatData* worldInfo = (btDynamicsWorldFloatData*)chunk->m_oldPtr;
  1147. #endif//BT_USE_DOUBLE_PRECISION
  1148. memset(worldInfo ,0x00,len);
  1149. m_gravity.serialize(worldInfo->m_gravity);
  1150. worldInfo->m_solverInfo.m_tau = getSolverInfo().m_tau;
  1151. worldInfo->m_solverInfo.m_damping = getSolverInfo().m_damping;
  1152. worldInfo->m_solverInfo.m_friction = getSolverInfo().m_friction;
  1153. worldInfo->m_solverInfo.m_timeStep = getSolverInfo().m_timeStep;
  1154. worldInfo->m_solverInfo.m_restitution = getSolverInfo().m_restitution;
  1155. worldInfo->m_solverInfo.m_maxErrorReduction = getSolverInfo().m_maxErrorReduction;
  1156. worldInfo->m_solverInfo.m_sor = getSolverInfo().m_sor;
  1157. worldInfo->m_solverInfo.m_erp = getSolverInfo().m_erp;
  1158. worldInfo->m_solverInfo.m_erp2 = getSolverInfo().m_erp2;
  1159. worldInfo->m_solverInfo.m_globalCfm = getSolverInfo().m_globalCfm;
  1160. worldInfo->m_solverInfo.m_splitImpulsePenetrationThreshold = getSolverInfo().m_splitImpulsePenetrationThreshold;
  1161. worldInfo->m_solverInfo.m_splitImpulseTurnErp = getSolverInfo().m_splitImpulseTurnErp;
  1162. worldInfo->m_solverInfo.m_linearSlop = getSolverInfo().m_linearSlop;
  1163. worldInfo->m_solverInfo.m_warmstartingFactor = getSolverInfo().m_warmstartingFactor;
  1164. worldInfo->m_solverInfo.m_maxGyroscopicForce = getSolverInfo().m_maxGyroscopicForce;
  1165. worldInfo->m_solverInfo.m_singleAxisRollingFrictionThreshold = getSolverInfo().m_singleAxisRollingFrictionThreshold;
  1166. worldInfo->m_solverInfo.m_numIterations = getSolverInfo().m_numIterations;
  1167. worldInfo->m_solverInfo.m_solverMode = getSolverInfo().m_solverMode;
  1168. worldInfo->m_solverInfo.m_restingContactRestitutionThreshold = getSolverInfo().m_restingContactRestitutionThreshold;
  1169. worldInfo->m_solverInfo.m_minimumSolverBatchSize = getSolverInfo().m_minimumSolverBatchSize;
  1170. worldInfo->m_solverInfo.m_splitImpulse = getSolverInfo().m_splitImpulse;
  1171. #ifdef BT_USE_DOUBLE_PRECISION
  1172. const char* structType = "btDynamicsWorldDoubleData";
  1173. #else//BT_USE_DOUBLE_PRECISION
  1174. const char* structType = "btDynamicsWorldFloatData";
  1175. #endif//BT_USE_DOUBLE_PRECISION
  1176. serializer->finalizeChunk(chunk,structType,BT_DYNAMICSWORLD_CODE,worldInfo);
  1177. }
  1178. void btDiscreteDynamicsWorld::serialize(btSerializer* serializer)
  1179. {
  1180. serializer->startSerialization();
  1181. serializeDynamicsWorldInfo(serializer);
  1182. serializeRigidBodies(serializer);
  1183. serializeCollisionObjects(serializer);
  1184. serializer->finishSerialization();
  1185. }