btDiscreteDynamicsWorld.cpp 49 KB

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