PhysicsController.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "MeshPart.h"
  4. #include "PhysicsController.h"
  5. #include "PhysicsMotionState.h"
  6. #include "Package.h"
  7. #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
  8. // The initial capacity of the Bullet debug drawer's vertex batch.
  9. #define INITIAL_CAPACITY 280
  10. namespace gameplay
  11. {
  12. const int PhysicsController::DIRTY = 0x01;
  13. const int PhysicsController::COLLISION = 0x02;
  14. const int PhysicsController::REGISTERED = 0x04;
  15. const int PhysicsController::REMOVE = 0x08;
  16. PhysicsController::PhysicsController()
  17. : _collisionConfiguration(NULL), _dispatcher(NULL),
  18. _overlappingPairCache(NULL), _solver(NULL), _world(NULL), _ghostPairCallback(NULL),
  19. _debugDrawer(NULL), _status(PhysicsController::Listener::DEACTIVATED), _listeners(NULL),
  20. _gravity(btScalar(0.0), btScalar(-9.8), btScalar(0.0))
  21. {
  22. // Default gravity is 9.8 along the negative Y axis.
  23. }
  24. PhysicsController::~PhysicsController()
  25. {
  26. SAFE_DELETE(_ghostPairCallback);
  27. SAFE_DELETE(_debugDrawer);
  28. SAFE_DELETE(_listeners);
  29. }
  30. void PhysicsController::addStatusListener(Listener* listener)
  31. {
  32. if (!_listeners)
  33. _listeners = new std::vector<Listener*>();
  34. _listeners->push_back(listener);
  35. }
  36. PhysicsCharacter* PhysicsController::createCharacter(Node* node, float radius, float height, const Vector3& center)
  37. {
  38. return new PhysicsCharacter(node, radius, height, center);
  39. }
  40. void PhysicsController::destroyCharacter(PhysicsCharacter* character)
  41. {
  42. SAFE_DELETE(character);
  43. }
  44. PhysicsFixedConstraint* PhysicsController::createFixedConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  45. {
  46. checkConstraintRigidBodies(a, b);
  47. PhysicsFixedConstraint* constraint = new PhysicsFixedConstraint(a, b);
  48. addConstraint(a, b, constraint);
  49. return constraint;
  50. }
  51. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  52. {
  53. checkConstraintRigidBodies(a, b);
  54. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, b);
  55. addConstraint(a, b, constraint);
  56. return constraint;
  57. }
  58. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a,
  59. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  60. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  61. {
  62. checkConstraintRigidBodies(a, b);
  63. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  64. addConstraint(a, b, constraint);
  65. return constraint;
  66. }
  67. PhysicsHingeConstraint* PhysicsController::createHingeConstraint(PhysicsRigidBody* a,
  68. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  69. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  70. {
  71. checkConstraintRigidBodies(a, b);
  72. PhysicsHingeConstraint* constraint = new PhysicsHingeConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  73. addConstraint(a, b, constraint);
  74. return constraint;
  75. }
  76. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  77. {
  78. checkConstraintRigidBodies(a, b);
  79. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a, b);
  80. addConstraint(a, b, constraint);
  81. return constraint;
  82. }
  83. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a,
  84. const Vector3& translationOffsetA, PhysicsRigidBody* b, const Vector3& translationOffsetB)
  85. {
  86. checkConstraintRigidBodies(a, b);
  87. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a,translationOffsetA, b, translationOffsetB);
  88. addConstraint(a, b, constraint);
  89. return constraint;
  90. }
  91. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  92. {
  93. checkConstraintRigidBodies(a, b);
  94. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, b);
  95. addConstraint(a, b, constraint);
  96. return constraint;
  97. }
  98. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, const Quaternion& rotationOffsetA, const Vector3& translationOffsetA,
  99. PhysicsRigidBody* b, const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  100. {
  101. checkConstraintRigidBodies(a, b);
  102. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  103. addConstraint(a, b, constraint);
  104. return constraint;
  105. }
  106. const Vector3& PhysicsController::getGravity() const
  107. {
  108. return _gravity;
  109. }
  110. void PhysicsController::setGravity(const Vector3& gravity)
  111. {
  112. _gravity = gravity;
  113. if (_world)
  114. _world->setGravity(BV(_gravity));
  115. }
  116. void PhysicsController::drawDebug(const Matrix& viewProjection)
  117. {
  118. _debugDrawer->begin(viewProjection);
  119. _world->debugDrawWorld();
  120. _debugDrawer->end();
  121. }
  122. PhysicsCollisionObject* PhysicsController::rayTest(const Ray& ray, float distance, Vector3* hitPoint, float* hitFraction)
  123. {
  124. btCollisionWorld::ClosestRayResultCallback callback(BV(ray.getOrigin()), BV(distance * ray.getDirection()));
  125. _world->rayTest(BV(ray.getOrigin()), BV(distance * ray.getDirection()), callback);
  126. if (callback.hasHit())
  127. {
  128. if (hitPoint)
  129. hitPoint->set(callback.m_hitPointWorld.x(), callback.m_hitPointWorld.y(), callback.m_hitPointWorld.z());
  130. if (hitFraction)
  131. *hitFraction = callback.m_closestHitFraction;
  132. return getCollisionObject(callback.m_collisionObject);
  133. }
  134. return NULL;
  135. }
  136. btScalar PhysicsController::addSingleResult(btManifoldPoint& cp, const btCollisionObject* a, int partIdA, int indexA,
  137. const btCollisionObject* b, int partIdB, int indexB)
  138. {
  139. // Get pointers to the PhysicsRigidBody objects.
  140. PhysicsCollisionObject* rbA = Game::getInstance()->getPhysicsController()->getCollisionObject(a);
  141. PhysicsCollisionObject* rbB = Game::getInstance()->getPhysicsController()->getCollisionObject(b);
  142. // If the given rigid body pair has collided in the past, then
  143. // we notify the listeners only if the pair was not colliding
  144. // during the previous frame. Otherwise, it's a new pair, so add a
  145. // new entry to the cache with the appropriate listeners and notify them.
  146. PhysicsRigidBody::CollisionPair pair(rbA, rbB);
  147. CollisionInfo* collisionInfo;
  148. if (_collisionStatus.count(pair) > 0)
  149. {
  150. collisionInfo = &_collisionStatus[pair];
  151. }
  152. else
  153. {
  154. // Add a new collision pair for these objects
  155. collisionInfo = &_collisionStatus[pair];
  156. // Add the appropriate listeners.
  157. PhysicsRigidBody::CollisionPair p1(pair.objectA, NULL);
  158. if (_collisionStatus.count(p1) > 0)
  159. {
  160. const CollisionInfo& ci = _collisionStatus[p1];
  161. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  162. for (; iter != ci._listeners.end(); iter++)
  163. {
  164. collisionInfo->_listeners.push_back(*iter);
  165. }
  166. }
  167. PhysicsRigidBody::CollisionPair p2(pair.objectB, NULL);
  168. if (_collisionStatus.count(p2) > 0)
  169. {
  170. const CollisionInfo& ci = _collisionStatus[p2];
  171. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  172. for (; iter != ci._listeners.end(); iter++)
  173. {
  174. collisionInfo->_listeners.push_back(*iter);
  175. }
  176. }
  177. }
  178. // Fire collision event
  179. if ((collisionInfo->_status & COLLISION) == 0)
  180. {
  181. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = collisionInfo->_listeners.begin();
  182. for (; iter != collisionInfo->_listeners.end(); iter++)
  183. {
  184. if ((collisionInfo->_status & REMOVE) == 0)
  185. {
  186. (*iter)->collisionEvent(PhysicsCollisionObject::CollisionListener::COLLIDING, pair, Vector3(cp.getPositionWorldOnA().x(), cp.getPositionWorldOnA().y(), cp.getPositionWorldOnA().z()),
  187. Vector3(cp.getPositionWorldOnB().x(), cp.getPositionWorldOnB().y(), cp.getPositionWorldOnB().z()));
  188. }
  189. }
  190. }
  191. // Update the collision status cache (we remove the dirty bit
  192. // set in the controller's update so that this particular collision pair's
  193. // status is not reset to 'no collision' when the controller's update completes).
  194. collisionInfo->_status &= ~DIRTY;
  195. collisionInfo->_status |= COLLISION;
  196. return 0.0f;
  197. }
  198. void PhysicsController::initialize()
  199. {
  200. _collisionConfiguration = new btDefaultCollisionConfiguration();
  201. _dispatcher = new btCollisionDispatcher(_collisionConfiguration);
  202. _overlappingPairCache = new btDbvtBroadphase();
  203. _solver = new btSequentialImpulseConstraintSolver();
  204. // Create the world.
  205. _world = new btDiscreteDynamicsWorld(_dispatcher, _overlappingPairCache, _solver, _collisionConfiguration);
  206. _world->setGravity(BV(_gravity));
  207. // Register ghost pair callback so bullet detects collisions with ghost objects (used for character collisions).
  208. _ghostPairCallback = bullet_new<btGhostPairCallback>();
  209. _world->getPairCache()->setInternalGhostPairCallback(_ghostPairCallback);
  210. // Set up debug drawing.
  211. _debugDrawer = new DebugDrawer();
  212. _world->setDebugDrawer(_debugDrawer);
  213. }
  214. void PhysicsController::finalize()
  215. {
  216. // Clean up the world and its various components.
  217. SAFE_DELETE(_world);
  218. SAFE_DELETE(_ghostPairCallback);
  219. SAFE_DELETE(_solver);
  220. SAFE_DELETE(_overlappingPairCache);
  221. SAFE_DELETE(_dispatcher);
  222. SAFE_DELETE(_collisionConfiguration);
  223. }
  224. void PhysicsController::pause()
  225. {
  226. // Unused
  227. }
  228. void PhysicsController::resume()
  229. {
  230. // Unused
  231. }
  232. void PhysicsController::update(long elapsedTime)
  233. {
  234. // Update the physics simulation, with a maximum
  235. // of 10 simulation steps being performed in a given frame.
  236. //
  237. // Note that stepSimulation takes elapsed time in seconds
  238. // so we divide by 1000 to convert from milliseconds.
  239. _world->stepSimulation((float)elapsedTime * 0.001, 10);
  240. // If we have status listeners, then check if our status has changed.
  241. if (_listeners)
  242. {
  243. Listener::EventType oldStatus = _status;
  244. if (_status = Listener::DEACTIVATED)
  245. {
  246. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  247. {
  248. if (_world->getCollisionObjectArray()[i]->isActive())
  249. {
  250. _status = Listener::ACTIVATED;
  251. break;
  252. }
  253. }
  254. }
  255. else
  256. {
  257. bool allInactive = true;
  258. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  259. {
  260. if (_world->getCollisionObjectArray()[i]->isActive())
  261. {
  262. allInactive = false;
  263. break;
  264. }
  265. }
  266. if (allInactive)
  267. _status = Listener::DEACTIVATED;
  268. }
  269. // If the status has changed, notify our listeners.
  270. if (oldStatus != _status)
  271. {
  272. for (unsigned int k = 0; k < _listeners->size(); k++)
  273. {
  274. (*_listeners)[k]->statusEvent(_status);
  275. }
  276. }
  277. }
  278. // All statuses are set with the DIRTY bit before collision processing occurs.
  279. // During collision processing, if a collision occurs, the status is
  280. // set to COLLISION and the DIRTY bit is cleared. Then, after collision processing
  281. // is finished, if a given status is still dirty, the COLLISION bit is cleared.
  282. //
  283. // If an entry was marked for removal in the last frame, remove it now.
  284. // Dirty the collision status cache entries.
  285. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  286. for (; iter != _collisionStatus.end();)
  287. {
  288. if ((iter->second._status & REMOVE) != 0)
  289. {
  290. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator eraseIter = iter;
  291. iter++;
  292. _collisionStatus.erase(eraseIter);
  293. }
  294. else
  295. {
  296. iter->second._status |= DIRTY;
  297. iter++;
  298. }
  299. }
  300. // Go through the collision status cache and perform all registered collision tests.
  301. iter = _collisionStatus.begin();
  302. for (; iter != _collisionStatus.end(); iter++)
  303. {
  304. // If this collision pair was one that was registered for listening, then perform the collision test.
  305. // (In the case where we register for all collisions with a rigid body, there will be a lot
  306. // of collision pairs in the status cache that we did not explicitly register for.)
  307. if ((iter->second._status & REGISTERED) != 0 && (iter->second._status & REMOVE) == 0)
  308. {
  309. if (iter->first.objectB)
  310. _world->contactPairTest(iter->first.objectA->getCollisionObject(), iter->first.objectB->getCollisionObject(), *this);
  311. else
  312. _world->contactTest(iter->first.objectA->getCollisionObject(), *this);
  313. }
  314. }
  315. // Update all the collision status cache entries.
  316. iter = _collisionStatus.begin();
  317. for (; iter != _collisionStatus.end(); iter++)
  318. {
  319. if ((iter->second._status & DIRTY) != 0)
  320. {
  321. if ((iter->second._status & COLLISION) != 0 && iter->first.objectB)
  322. {
  323. unsigned int size = iter->second._listeners.size();
  324. for (unsigned int i = 0; i < size; i++)
  325. {
  326. iter->second._listeners[i]->collisionEvent(PhysicsCollisionObject::CollisionListener::NOT_COLLIDING, iter->first);
  327. }
  328. }
  329. iter->second._status &= ~COLLISION;
  330. }
  331. }
  332. }
  333. void PhysicsController::addCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  334. {
  335. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  336. // Add the listener and ensure the status includes that this collision pair is registered.
  337. CollisionInfo& info = _collisionStatus[pair];
  338. info._listeners.push_back(listener);
  339. info._status |= PhysicsController::REGISTERED;
  340. }
  341. void PhysicsController::removeCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  342. {
  343. // Mark the collision pair for these objects for removal
  344. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  345. if (_collisionStatus.count(pair) > 0)
  346. {
  347. _collisionStatus[pair]._status |= REMOVE;
  348. }
  349. }
  350. void PhysicsController::addCollisionObject(PhysicsCollisionObject* object)
  351. {
  352. // Assign user pointer for the bullet collision object to allow efficient
  353. // lookups of bullet objects -> gameplay objects.
  354. object->getCollisionObject()->setUserPointer(object);
  355. // Add the object to the physics world
  356. switch (object->getType())
  357. {
  358. case PhysicsCollisionObject::RIGID_BODY:
  359. _world->addRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()));
  360. break;
  361. case PhysicsCollisionObject::CHARACTER:
  362. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::DefaultFilter);
  363. break;
  364. case PhysicsCollisionObject::GHOST_OBJECT:
  365. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::AllFilter);
  366. break;
  367. default:
  368. assert(0); // unexpected (new type?)
  369. break;
  370. }
  371. }
  372. void PhysicsController::removeCollisionObject(PhysicsCollisionObject* object)
  373. {
  374. // Remove the collision object from the world
  375. if (object->getCollisionObject())
  376. {
  377. switch (object->getType())
  378. {
  379. case PhysicsCollisionObject::RIGID_BODY:
  380. _world->removeRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()));
  381. break;
  382. case PhysicsCollisionObject::CHARACTER:
  383. case PhysicsCollisionObject::GHOST_OBJECT:
  384. _world->removeCollisionObject(object->getCollisionObject());
  385. break;
  386. default:
  387. assert(0); // unexpected (new type?)
  388. break;
  389. }
  390. }
  391. // Release collision shape
  392. if (object->getCollisionShape())
  393. {
  394. PhysicsCollisionShape* shape = reinterpret_cast<PhysicsCollisionShape*>(object->getCollisionShape()->getUserPointer());
  395. if (shape)
  396. {
  397. if (shape->getRefCount() == 1)
  398. {
  399. std::vector<PhysicsCollisionShape*>::iterator shapeItr = std::find(_shapes.begin(), _shapes.end(), shape);
  400. shape->release();
  401. if (shapeItr != _shapes.end())
  402. _shapes.erase(shapeItr);
  403. }
  404. else
  405. {
  406. shape->release();
  407. }
  408. }
  409. }
  410. // Find all references to the object in the collision status cache and mark them for removal.
  411. std::map<PhysicsRigidBody::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  412. for (; iter != _collisionStatus.end(); iter++)
  413. {
  414. if (iter->first.objectA == object || iter->first.objectB == object)
  415. iter->second._status |= REMOVE;
  416. }
  417. }
  418. PhysicsCollisionObject* PhysicsController::getCollisionObject(const btCollisionObject* collisionObject) const
  419. {
  420. // Gameplay rigid bodies are stored in the userPointer data of bullet collision objects
  421. return reinterpret_cast<PhysicsCollisionObject*>(collisionObject->getUserPointer());
  422. }
  423. btCollisionShape* PhysicsController::createBox(const Vector3& min, const Vector3& max, const Vector3& scale)
  424. {
  425. btVector3 halfExtents(scale.x * 0.5 * abs(max.x - min.x), scale.y * 0.5 * abs(max.y - min.y), scale.z * 0.5 * abs(max.z - min.z));
  426. // Return the box shape from the cache if it already exists.
  427. for (unsigned int i = 0; i < _shapes.size(); i++)
  428. {
  429. if (_shapes[i]->_shape->getShapeType() == BOX_SHAPE_PROXYTYPE)
  430. {
  431. btBoxShape* box = static_cast<btBoxShape*>(_shapes[i]->_shape);
  432. if (box->getHalfExtentsWithMargin() == halfExtents)
  433. {
  434. _shapes[i]->addRef();
  435. return box;
  436. }
  437. }
  438. }
  439. // Create the box shape and add it to the cache.
  440. btBoxShape* box = bullet_new<btBoxShape>(halfExtents);
  441. _shapes.push_back(new PhysicsCollisionShape(box));
  442. return box;
  443. }
  444. btCollisionShape* PhysicsController::createCapsule(float radius, float height)
  445. {
  446. // Return the capsule shape from the cache if it already exists.
  447. for (unsigned int i = 0; i < _shapes.size(); i++)
  448. {
  449. if (_shapes[i]->_shape->getShapeType() == CAPSULE_SHAPE_PROXYTYPE)
  450. {
  451. btCapsuleShape* capsule = static_cast<btCapsuleShape*>(_shapes[i]->_shape);
  452. if (capsule->getRadius() == radius && capsule->getHalfHeight() == 0.5f * height)
  453. {
  454. _shapes[i]->addRef();
  455. return capsule;
  456. }
  457. }
  458. }
  459. // Create the capsule shape and add it to the cache.
  460. btCapsuleShape* capsule = bullet_new<btCapsuleShape>(radius, height);
  461. _shapes.push_back(new PhysicsCollisionShape(capsule));
  462. return capsule;
  463. }
  464. btCollisionShape* PhysicsController::createSphere(float radius, const Vector3& scale)
  465. {
  466. // Since sphere shapes depend only on the radius, the best we can do is take
  467. // the largest dimension and apply that as the uniform scale to the rigid body.
  468. float uniformScale = scale.x;
  469. if (uniformScale < scale.y)
  470. uniformScale = scale.y;
  471. if (uniformScale < scale.z)
  472. uniformScale = scale.z;
  473. // Return the sphere shape from the cache if it already exists.
  474. for (unsigned int i = 0; i < _shapes.size(); i++)
  475. {
  476. if (_shapes[i]->_shape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
  477. {
  478. btSphereShape* sphere = static_cast<btSphereShape*>(_shapes[i]->_shape);
  479. if (sphere->getRadius() == uniformScale * radius)
  480. {
  481. _shapes[i]->addRef();
  482. return sphere;
  483. }
  484. }
  485. }
  486. // Create the sphere shape and add it to the cache.
  487. btSphereShape* sphere = bullet_new<btSphereShape>(uniformScale * radius);
  488. _shapes.push_back(new PhysicsCollisionShape(sphere));
  489. return sphere;
  490. }
  491. btCollisionShape* PhysicsController::createMesh(PhysicsRigidBody* body, const Vector3& scale)
  492. {
  493. assert(body);
  494. // Retrieve the mesh rigid body data from the node's mesh.
  495. Model* model = body->_node ? body->_node->getModel() : NULL;
  496. Mesh* mesh = model ? model->getMesh() : NULL;
  497. if (mesh == NULL)
  498. {
  499. LOG_ERROR("Cannot create mesh rigid body for node without model/mesh.");
  500. return NULL;
  501. }
  502. // Only support meshes with triangle list primitive types
  503. if (mesh->getPrimitiveType() != Mesh::TRIANGLES)
  504. {
  505. LOG_ERROR("Cannot create mesh rigid body for mesh without TRIANGLES primitive type.");
  506. return NULL;
  507. }
  508. // The mesh must have a valid URL (i.e. it must have been loaded from a Package)
  509. // in order to fetch mesh data for computing mesh rigid body.
  510. if (strlen(mesh->getUrl()) == 0)
  511. {
  512. LOG_ERROR("Cannot create mesh rigid body for mesh without valid URL.");
  513. return NULL;
  514. }
  515. Package::MeshData* data = Package::readMeshData(mesh->getUrl());
  516. if (data == NULL)
  517. {
  518. return NULL;
  519. }
  520. // Copy the scaled vertex position data to the rigid body's local buffer.
  521. Matrix m;
  522. Matrix::createScale(scale, &m);
  523. unsigned int vertexCount = data->vertexCount;
  524. body->_vertexData = new float[vertexCount * 3];
  525. Vector3 v;
  526. int vertexStride = data->vertexFormat.getVertexSize();
  527. for (unsigned int i = 0; i < data->vertexCount; i++)
  528. {
  529. v.set(*((float*)&data->vertexData[i * vertexStride + 0 * sizeof(float)]),
  530. *((float*)&data->vertexData[i * vertexStride + 1 * sizeof(float)]),
  531. *((float*)&data->vertexData[i * vertexStride + 2 * sizeof(float)]));
  532. v *= m;
  533. memcpy(&(body->_vertexData[i * 3]), &v, sizeof(float) * 3);
  534. }
  535. btTriangleIndexVertexArray* meshInterface = bullet_new<btTriangleIndexVertexArray>();
  536. unsigned int partCount = data->parts.size();
  537. if (partCount > 0)
  538. {
  539. PHY_ScalarType indexType = PHY_UCHAR;
  540. int indexStride = 0;
  541. Package::MeshPartData* meshPart = NULL;
  542. for (unsigned int i = 0; i < partCount; i++)
  543. {
  544. meshPart = data->parts[i];
  545. switch (meshPart->indexFormat)
  546. {
  547. case Mesh::INDEX8:
  548. indexType = PHY_UCHAR;
  549. indexStride = 1;
  550. break;
  551. case Mesh::INDEX16:
  552. indexType = PHY_SHORT;
  553. indexStride = 2;
  554. break;
  555. case Mesh::INDEX32:
  556. indexType = PHY_INTEGER;
  557. indexStride = 4;
  558. break;
  559. }
  560. // Move the index data into the rigid body's local buffer.
  561. // Set it to NULL in the MeshPartData so it is not released when the data is freed.
  562. body->_indexData.push_back(meshPart->indexData);
  563. meshPart->indexData = NULL;
  564. // Create a btIndexedMesh object for the current mesh part.
  565. btIndexedMesh indexedMesh;
  566. indexedMesh.m_indexType = indexType;
  567. indexedMesh.m_numTriangles = meshPart->indexCount / 3; // assume TRIANGLES primitive type
  568. indexedMesh.m_numVertices = meshPart->indexCount;
  569. indexedMesh.m_triangleIndexBase = (const unsigned char*)body->_indexData[i];
  570. indexedMesh.m_triangleIndexStride = indexStride*3;
  571. indexedMesh.m_vertexBase = (const unsigned char*)body->_vertexData;
  572. indexedMesh.m_vertexStride = sizeof(float)*3;
  573. indexedMesh.m_vertexType = PHY_FLOAT;
  574. // Add the indexed mesh data to the mesh interface.
  575. meshInterface->addIndexedMesh(indexedMesh, indexType);
  576. }
  577. }
  578. else
  579. {
  580. // Generate index data for the mesh locally in the rigid body.
  581. unsigned int* indexData = new unsigned int[data->vertexCount];
  582. for (unsigned int i = 0; i < data->vertexCount; i++)
  583. {
  584. indexData[i] = i;
  585. }
  586. body->_indexData.push_back((unsigned char*)indexData);
  587. // Create a single btIndexedMesh object for the mesh interface.
  588. btIndexedMesh indexedMesh;
  589. indexedMesh.m_indexType = PHY_INTEGER;
  590. indexedMesh.m_numTriangles = data->vertexCount / 3; // assume TRIANGLES primitive type
  591. indexedMesh.m_numVertices = data->vertexCount;
  592. indexedMesh.m_triangleIndexBase = body->_indexData[0];
  593. indexedMesh.m_triangleIndexStride = sizeof(unsigned int);
  594. indexedMesh.m_vertexBase = (const unsigned char*)body->_vertexData;
  595. indexedMesh.m_vertexStride = sizeof(float)*3;
  596. indexedMesh.m_vertexType = PHY_FLOAT;
  597. // Set the data in the mesh interface.
  598. meshInterface->addIndexedMesh(indexedMesh, indexedMesh.m_indexType);
  599. }
  600. btBvhTriangleMeshShape* shape = bullet_new<btBvhTriangleMeshShape>(meshInterface, true);
  601. _shapes.push_back(new PhysicsCollisionShape(shape));
  602. // Free the temporary mesh data now that it's stored in physics system
  603. SAFE_DELETE(data);
  604. return shape;
  605. }
  606. btCollisionShape* PhysicsController::createHeightfield(int width, int height, void* heightfieldData, float minHeight, float maxHeight)
  607. {
  608. btCollisionShape* shape = bullet_new<btHeightfieldTerrainShape>(width, height, heightfieldData, 1.0f, minHeight, maxHeight, 1, PHY_FLOAT, false);
  609. _shapes.push_back(new PhysicsCollisionShape(shape));
  610. return shape;
  611. }
  612. void PhysicsController::addConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b, PhysicsConstraint* constraint)
  613. {
  614. a->addConstraint(constraint);
  615. if (b)
  616. {
  617. b->addConstraint(constraint);
  618. }
  619. _world->addConstraint(constraint->_constraint);
  620. }
  621. bool PhysicsController::checkConstraintRigidBodies(PhysicsRigidBody* a, PhysicsRigidBody* b)
  622. {
  623. if (!a->supportsConstraints())
  624. {
  625. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", a->_node->getId());
  626. return false;
  627. }
  628. if (b && !b->supportsConstraints())
  629. {
  630. WARN_VARG("Rigid body '%s' does not support constraints; unexpected behavior may occur.", b->_node->getId());
  631. return false;
  632. }
  633. return true;
  634. }
  635. void PhysicsController::removeConstraint(PhysicsConstraint* constraint)
  636. {
  637. // Find the constraint and remove it from the physics world.
  638. for (int i = _world->getNumConstraints() - 1; i >= 0; i--)
  639. {
  640. btTypedConstraint* currentConstraint = _world->getConstraint(i);
  641. if (constraint->_constraint == currentConstraint)
  642. {
  643. _world->removeConstraint(currentConstraint);
  644. break;
  645. }
  646. }
  647. }
  648. PhysicsController::DebugDrawer::DebugDrawer()
  649. : _mode(btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawConstraintLimits | btIDebugDraw::DBG_DrawConstraints |
  650. btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe), _viewProjection(NULL), _meshBatch(NULL)
  651. {
  652. // Vertex shader for drawing colored lines.
  653. const char* vs_str =
  654. {
  655. "uniform mat4 u_viewProjectionMatrix;\n"
  656. "attribute vec4 a_position;\n"
  657. "attribute vec4 a_color;\n"
  658. "varying vec4 v_color;\n"
  659. "void main(void) {\n"
  660. " v_color = a_color;\n"
  661. " gl_Position = u_viewProjectionMatrix * a_position;\n"
  662. "}"
  663. };
  664. // Fragment shader for drawing colored lines.
  665. const char* fs_str =
  666. {
  667. #ifdef OPENGL_ES
  668. "precision highp float;\n"
  669. #endif
  670. "varying vec4 v_color;\n"
  671. "void main(void) {\n"
  672. " gl_FragColor = v_color;\n"
  673. "}"
  674. };
  675. Effect* effect = Effect::createFromSource(vs_str, fs_str);
  676. Material* material = Material::create(effect);
  677. material->getStateBlock()->setDepthTest(true);
  678. VertexFormat::Element elements[] =
  679. {
  680. VertexFormat::Element(VertexFormat::POSITION, 3),
  681. VertexFormat::Element(VertexFormat::COLOR, 4),
  682. };
  683. _meshBatch = MeshBatch::create(VertexFormat(elements, 2), Mesh::LINES, material, false);
  684. SAFE_RELEASE(material);
  685. SAFE_RELEASE(effect);
  686. }
  687. PhysicsController::DebugDrawer::~DebugDrawer()
  688. {
  689. SAFE_DELETE(_meshBatch);
  690. }
  691. void PhysicsController::DebugDrawer::begin(const Matrix& viewProjection)
  692. {
  693. _viewProjection = &viewProjection;
  694. _meshBatch->begin();
  695. }
  696. void PhysicsController::DebugDrawer::end()
  697. {
  698. _meshBatch->end();
  699. _meshBatch->getMaterial()->getParameter("u_viewProjectionMatrix")->setValue(_viewProjection);
  700. _meshBatch->draw();
  701. }
  702. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
  703. {
  704. static DebugDrawer::DebugVertex fromVertex, toVertex;
  705. fromVertex.x = from.getX();
  706. fromVertex.y = from.getY();
  707. fromVertex.z = from.getZ();
  708. fromVertex.r = fromColor.getX();
  709. fromVertex.g = fromColor.getY();
  710. fromVertex.b = fromColor.getZ();
  711. fromVertex.a = 1.0f;
  712. toVertex.x = to.getX();
  713. toVertex.y = to.getY();
  714. toVertex.z = to.getZ();
  715. toVertex.r = toColor.getX();
  716. toVertex.g = toColor.getY();
  717. toVertex.b = toColor.getZ();
  718. toVertex.a = 1.0f;
  719. _meshBatch->add(&fromVertex, 1);
  720. _meshBatch->add(&toVertex, 1);
  721. }
  722. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
  723. {
  724. drawLine(from, to, color, color);
  725. }
  726. void PhysicsController::DebugDrawer::drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
  727. {
  728. drawLine(pointOnB, pointOnB + normalOnB, color);
  729. }
  730. void PhysicsController::DebugDrawer::reportErrorWarning(const char* warningString)
  731. {
  732. WARN(warningString);
  733. }
  734. void PhysicsController::DebugDrawer::draw3dText(const btVector3& location, const char* textString)
  735. {
  736. WARN("Physics debug drawing: 3D text is not supported.");
  737. }
  738. void PhysicsController::DebugDrawer::setDebugMode(int mode)
  739. {
  740. _mode = mode;
  741. }
  742. int PhysicsController::DebugDrawer::getDebugMode() const
  743. {
  744. return _mode;
  745. }
  746. PhysicsController::PhysicsCollisionShape::PhysicsCollisionShape(btCollisionShape* shape)
  747. : _shape(shape)
  748. {
  749. // Assign user pointer to allow efficient lookup of PhysicsCollisionShape from bullet object
  750. shape->setUserPointer(this);
  751. }
  752. PhysicsController::PhysicsCollisionShape::~PhysicsCollisionShape()
  753. {
  754. SAFE_DELETE(_shape);
  755. }
  756. }