PhysicsController.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  1. #include "Base.h"
  2. #include "PhysicsController.h"
  3. #include "PhysicsRigidBody.h"
  4. #include "PhysicsCharacter.h"
  5. #include "Game.h"
  6. #include "MeshPart.h"
  7. #include "Bundle.h"
  8. #include "ScriptListener.h"
  9. #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
  10. // The initial capacity of the Bullet debug drawer's vertex batch.
  11. #define INITIAL_CAPACITY 280
  12. namespace gameplay
  13. {
  14. const int PhysicsController::DIRTY = 0x01;
  15. const int PhysicsController::COLLISION = 0x02;
  16. const int PhysicsController::REGISTERED = 0x04;
  17. const int PhysicsController::REMOVE = 0x08;
  18. PhysicsController::PhysicsController()
  19. : _collisionConfiguration(NULL), _dispatcher(NULL),
  20. _overlappingPairCache(NULL), _solver(NULL), _world(NULL), _ghostPairCallback(NULL),
  21. _debugDrawer(NULL), _status(PhysicsController::Listener::DEACTIVATED), _listeners(NULL),
  22. _gravity(btScalar(0.0), btScalar(-9.8), btScalar(0.0)), _collisionCallback(NULL), _scriptListeners(NULL)
  23. {
  24. // Default gravity is 9.8 along the negative Y axis.
  25. _collisionCallback = new CollisionCallback(this);
  26. }
  27. PhysicsController::~PhysicsController()
  28. {
  29. SAFE_DELETE(_collisionCallback);
  30. SAFE_DELETE(_ghostPairCallback);
  31. SAFE_DELETE(_debugDrawer);
  32. SAFE_DELETE(_listeners);
  33. if (_scriptListeners)
  34. {
  35. for (unsigned int i = 0; i < _scriptListeners->size(); i++)
  36. {
  37. SAFE_DELETE((*_scriptListeners)[i]);
  38. }
  39. SAFE_DELETE(_scriptListeners);
  40. }
  41. }
  42. void PhysicsController::addStatusListener(Listener* listener)
  43. {
  44. GP_ASSERT(listener);
  45. if (!_listeners)
  46. _listeners = new std::vector<Listener*>();
  47. _listeners->push_back(listener);
  48. }
  49. void PhysicsController::removeStatusListener(Listener* listener)
  50. {
  51. GP_ASSERT(listener);
  52. if (!_listeners)
  53. return;
  54. for (std::vector<Listener*>::iterator iter = _listeners->begin(); iter != _listeners->end(); iter++)
  55. {
  56. if (*iter == listener)
  57. {
  58. _listeners->erase(iter);
  59. return;
  60. }
  61. }
  62. }
  63. void PhysicsController::addStatusListener(const char* function)
  64. {
  65. if (!_scriptListeners)
  66. _scriptListeners = new std::vector<ScriptListener*>();
  67. ScriptListener* listener = new ScriptListener(function);
  68. _scriptListeners->push_back(listener);
  69. addStatusListener(listener);
  70. }
  71. void PhysicsController::removeStatusListener(const char* function)
  72. {
  73. if (!_scriptListeners)
  74. return;
  75. std::string functionStr = function;
  76. for (unsigned int i = 0; i < _scriptListeners->size(); i++)
  77. {
  78. if ((*_scriptListeners)[i]->_function == functionStr)
  79. {
  80. removeStatusListener((*_scriptListeners)[i]);
  81. SAFE_DELETE((*_scriptListeners)[i]);
  82. _scriptListeners->erase(_scriptListeners->begin() + i);
  83. return;
  84. }
  85. }
  86. }
  87. PhysicsFixedConstraint* PhysicsController::createFixedConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  88. {
  89. checkConstraintRigidBodies(a, b);
  90. PhysicsFixedConstraint* constraint = new PhysicsFixedConstraint(a, b);
  91. addConstraint(a, b, constraint);
  92. return constraint;
  93. }
  94. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  95. {
  96. checkConstraintRigidBodies(a, b);
  97. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, b);
  98. addConstraint(a, b, constraint);
  99. return constraint;
  100. }
  101. PhysicsGenericConstraint* PhysicsController::createGenericConstraint(PhysicsRigidBody* a,
  102. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  103. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  104. {
  105. checkConstraintRigidBodies(a, b);
  106. PhysicsGenericConstraint* constraint = new PhysicsGenericConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  107. addConstraint(a, b, constraint);
  108. return constraint;
  109. }
  110. PhysicsHingeConstraint* PhysicsController::createHingeConstraint(PhysicsRigidBody* a,
  111. const Quaternion& rotationOffsetA, const Vector3& translationOffsetA, PhysicsRigidBody* b,
  112. const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  113. {
  114. checkConstraintRigidBodies(a, b);
  115. PhysicsHingeConstraint* constraint = new PhysicsHingeConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  116. addConstraint(a, b, constraint);
  117. return constraint;
  118. }
  119. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  120. {
  121. checkConstraintRigidBodies(a, b);
  122. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a, b);
  123. addConstraint(a, b, constraint);
  124. return constraint;
  125. }
  126. PhysicsSocketConstraint* PhysicsController::createSocketConstraint(PhysicsRigidBody* a,
  127. const Vector3& translationOffsetA, PhysicsRigidBody* b, const Vector3& translationOffsetB)
  128. {
  129. checkConstraintRigidBodies(a, b);
  130. PhysicsSocketConstraint* constraint = new PhysicsSocketConstraint(a,translationOffsetA, b, translationOffsetB);
  131. addConstraint(a, b, constraint);
  132. return constraint;
  133. }
  134. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
  135. {
  136. checkConstraintRigidBodies(a, b);
  137. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, b);
  138. addConstraint(a, b, constraint);
  139. return constraint;
  140. }
  141. PhysicsSpringConstraint* PhysicsController::createSpringConstraint(PhysicsRigidBody* a, const Quaternion& rotationOffsetA, const Vector3& translationOffsetA,
  142. PhysicsRigidBody* b, const Quaternion& rotationOffsetB, const Vector3& translationOffsetB)
  143. {
  144. checkConstraintRigidBodies(a, b);
  145. PhysicsSpringConstraint* constraint = new PhysicsSpringConstraint(a, rotationOffsetA, translationOffsetA, b, rotationOffsetB, translationOffsetB);
  146. addConstraint(a, b, constraint);
  147. return constraint;
  148. }
  149. const Vector3& PhysicsController::getGravity() const
  150. {
  151. return _gravity;
  152. }
  153. void PhysicsController::setGravity(const Vector3& gravity)
  154. {
  155. _gravity = gravity;
  156. if (_world)
  157. _world->setGravity(BV(_gravity));
  158. }
  159. void PhysicsController::drawDebug(const Matrix& viewProjection)
  160. {
  161. GP_ASSERT(_debugDrawer);
  162. GP_ASSERT(_world);
  163. _debugDrawer->begin(viewProjection);
  164. _world->debugDrawWorld();
  165. _debugDrawer->end();
  166. }
  167. bool PhysicsController::rayTest(const Ray& ray, float distance, PhysicsController::HitResult* result, PhysicsController::HitFilter* filter)
  168. {
  169. class RayTestCallback : public btCollisionWorld::ClosestRayResultCallback
  170. {
  171. private:
  172. HitFilter* filter;
  173. HitResult hitResult;
  174. public:
  175. RayTestCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, PhysicsController::HitFilter* filter)
  176. : btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld), filter(filter)
  177. {
  178. }
  179. virtual bool needsCollision(btBroadphaseProxy* proxy0) const
  180. {
  181. if (!btCollisionWorld::ClosestRayResultCallback::needsCollision(proxy0))
  182. return false;
  183. btCollisionObject* co = reinterpret_cast<btCollisionObject*>(proxy0->m_clientObject);
  184. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(co->getUserPointer());
  185. if (object == NULL)
  186. return false;
  187. return filter ? !filter->filter(object) : true;
  188. }
  189. btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
  190. {
  191. GP_ASSERT(rayResult.m_collisionObject);
  192. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(rayResult.m_collisionObject->getUserPointer());
  193. if (object == NULL)
  194. return 1.0f; // ignore
  195. float result = btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
  196. hitResult.object = object;
  197. hitResult.point.set(m_hitPointWorld.x(), m_hitPointWorld.y(), m_hitPointWorld.z());
  198. hitResult.fraction = m_closestHitFraction;
  199. hitResult.normal.set(m_hitNormalWorld.x(), m_hitNormalWorld.y(), m_hitNormalWorld.z());
  200. if (filter && !filter->hit(hitResult))
  201. return 1.0f; // process next collision
  202. return result; // continue normally
  203. }
  204. };
  205. GP_ASSERT(_world);
  206. btVector3 rayFromWorld(BV(ray.getOrigin()));
  207. btVector3 rayToWorld(rayFromWorld + BV(ray.getDirection() * distance));
  208. RayTestCallback callback(rayFromWorld, rayToWorld, filter);
  209. _world->rayTest(rayFromWorld, rayToWorld, callback);
  210. if (callback.hasHit())
  211. {
  212. if (result)
  213. {
  214. result->object = getCollisionObject(callback.m_collisionObject);
  215. result->point.set(callback.m_hitPointWorld.x(), callback.m_hitPointWorld.y(), callback.m_hitPointWorld.z());
  216. result->fraction = callback.m_closestHitFraction;
  217. result->normal.set(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  218. }
  219. return true;
  220. }
  221. return false;
  222. }
  223. bool PhysicsController::sweepTest(PhysicsCollisionObject* object, const Vector3& endPosition, PhysicsController::HitResult* result, PhysicsController::HitFilter* filter)
  224. {
  225. class SweepTestCallback : public btCollisionWorld::ClosestConvexResultCallback
  226. {
  227. private:
  228. PhysicsCollisionObject* me;
  229. PhysicsController::HitFilter* filter;
  230. PhysicsController::HitResult hitResult;
  231. public:
  232. SweepTestCallback(PhysicsCollisionObject* me, PhysicsController::HitFilter* filter)
  233. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), me(me), filter(filter)
  234. {
  235. }
  236. virtual bool needsCollision(btBroadphaseProxy* proxy0) const
  237. {
  238. if (!btCollisionWorld::ClosestConvexResultCallback::needsCollision(proxy0))
  239. return false;
  240. btCollisionObject* co = reinterpret_cast<btCollisionObject*>(proxy0->m_clientObject);
  241. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(co->getUserPointer());
  242. if (object == NULL || object == me)
  243. return false;
  244. return filter ? !filter->filter(object) : true;
  245. }
  246. btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
  247. {
  248. GP_ASSERT(convexResult.m_hitCollisionObject);
  249. PhysicsCollisionObject* object = reinterpret_cast<PhysicsCollisionObject*>(convexResult.m_hitCollisionObject->getUserPointer());
  250. if (object == NULL)
  251. return 1.0f;
  252. float result = ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
  253. hitResult.object = object;
  254. hitResult.point.set(m_hitPointWorld.x(), m_hitPointWorld.y(), m_hitPointWorld.z());
  255. hitResult.fraction = m_closestHitFraction;
  256. hitResult.normal.set(m_hitNormalWorld.x(), m_hitNormalWorld.y(), m_hitNormalWorld.z());
  257. if (filter && !filter->hit(hitResult))
  258. return 1.0f;
  259. return result;
  260. }
  261. };
  262. GP_ASSERT(object && object->getCollisionShape());
  263. PhysicsCollisionShape* shape = object->getCollisionShape();
  264. PhysicsCollisionShape::Type type = shape->getType();
  265. if (type != PhysicsCollisionShape::SHAPE_BOX && type != PhysicsCollisionShape::SHAPE_SPHERE && type != PhysicsCollisionShape::SHAPE_CAPSULE)
  266. return false; // unsupported type
  267. // Define the start transform.
  268. btTransform start;
  269. start.setIdentity();
  270. if (object->getNode())
  271. {
  272. Vector3 translation;
  273. Quaternion rotation;
  274. const Matrix& m = object->getNode()->getWorldMatrix();
  275. m.getTranslation(&translation);
  276. m.getRotation(&rotation);
  277. start.setIdentity();
  278. start.setOrigin(BV(translation));
  279. start.setRotation(BQ(rotation));
  280. }
  281. // Define the end transform.
  282. btTransform end(start);
  283. end.setOrigin(BV(endPosition));
  284. // Perform bullet convex sweep test.
  285. SweepTestCallback callback(object, filter);
  286. // If the object is represented by a ghost object, use the ghost object's convex sweep test
  287. // since it is much faster than the world's version.
  288. // NOTE: Unfortunately the ghost object sweep test does not seem reliable here currently, so using world's version instead.
  289. /*switch (object->getType())
  290. {
  291. case PhysicsCollisionObject::GHOST_OBJECT:
  292. case PhysicsCollisionObject::CHARACTER:
  293. static_cast<PhysicsGhostObject*>(object)->_ghostObject->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  294. break;
  295. default:
  296. _world->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  297. break;
  298. }*/
  299. GP_ASSERT(_world);
  300. _world->convexSweepTest(static_cast<btConvexShape*>(shape->getShape()), start, end, callback, _world->getDispatchInfo().m_allowedCcdPenetration);
  301. // Check for hits and store results.
  302. if (callback.hasHit())
  303. {
  304. if (result)
  305. {
  306. result->object = getCollisionObject(callback.m_hitCollisionObject);
  307. result->point.set(callback.m_hitPointWorld.x(), callback.m_hitPointWorld.y(), callback.m_hitPointWorld.z());
  308. result->fraction = callback.m_closestHitFraction;
  309. result->normal.set(callback.m_hitNormalWorld.x(), callback.m_hitNormalWorld.y(), callback.m_hitNormalWorld.z());
  310. }
  311. return true;
  312. }
  313. return false;
  314. }
  315. btScalar PhysicsController::CollisionCallback::addSingleResult(btManifoldPoint& cp, const btCollisionObject* a, int partIdA, int indexA,
  316. const btCollisionObject* b, int partIdB, int indexB)
  317. {
  318. GP_ASSERT(_pc);
  319. // Get pointers to the PhysicsCollisionObject objects.
  320. PhysicsCollisionObject* objectA = _pc->getCollisionObject(a);
  321. PhysicsCollisionObject* objectB = _pc->getCollisionObject(b);
  322. // If the given collision object pair has collided in the past, then
  323. // we notify the listeners only if the pair was not colliding
  324. // during the previous frame. Otherwise, it's a new pair, so add a
  325. // new entry to the cache with the appropriate listeners and notify them.
  326. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  327. CollisionInfo* collisionInfo;
  328. if (_pc->_collisionStatus.count(pair) > 0)
  329. {
  330. collisionInfo = &_pc->_collisionStatus[pair];
  331. }
  332. else
  333. {
  334. // Add a new collision pair for these objects.
  335. collisionInfo = &_pc->_collisionStatus[pair];
  336. // Add the appropriate listeners.
  337. PhysicsCollisionObject::CollisionPair p1(pair.objectA, NULL);
  338. if (_pc->_collisionStatus.count(p1) > 0)
  339. {
  340. const CollisionInfo& ci = _pc->_collisionStatus[p1];
  341. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  342. for (; iter != ci._listeners.end(); iter++)
  343. {
  344. GP_ASSERT(*iter);
  345. collisionInfo->_listeners.push_back(*iter);
  346. }
  347. }
  348. PhysicsCollisionObject::CollisionPair p2(pair.objectB, NULL);
  349. if (_pc->_collisionStatus.count(p2) > 0)
  350. {
  351. const CollisionInfo& ci = _pc->_collisionStatus[p2];
  352. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = ci._listeners.begin();
  353. for (; iter != ci._listeners.end(); iter++)
  354. {
  355. GP_ASSERT(*iter);
  356. collisionInfo->_listeners.push_back(*iter);
  357. }
  358. }
  359. }
  360. // Fire collision event.
  361. if ((collisionInfo->_status & COLLISION) == 0)
  362. {
  363. std::vector<PhysicsCollisionObject::CollisionListener*>::const_iterator iter = collisionInfo->_listeners.begin();
  364. for (; iter != collisionInfo->_listeners.end(); iter++)
  365. {
  366. GP_ASSERT(*iter);
  367. if ((collisionInfo->_status & REMOVE) == 0)
  368. {
  369. (*iter)->collisionEvent(PhysicsCollisionObject::CollisionListener::COLLIDING, pair, Vector3(cp.getPositionWorldOnA().x(), cp.getPositionWorldOnA().y(), cp.getPositionWorldOnA().z()),
  370. Vector3(cp.getPositionWorldOnB().x(), cp.getPositionWorldOnB().y(), cp.getPositionWorldOnB().z()));
  371. }
  372. }
  373. }
  374. // Update the collision status cache (we remove the dirty bit
  375. // set in the controller's update so that this particular collision pair's
  376. // status is not reset to 'no collision' when the controller's update completes).
  377. collisionInfo->_status &= ~DIRTY;
  378. collisionInfo->_status |= COLLISION;
  379. return 0.0f;
  380. }
  381. void PhysicsController::initialize()
  382. {
  383. _collisionConfiguration = new btDefaultCollisionConfiguration();
  384. _dispatcher = new btCollisionDispatcher(_collisionConfiguration);
  385. _overlappingPairCache = new btDbvtBroadphase();
  386. _solver = new btSequentialImpulseConstraintSolver();
  387. // Create the world.
  388. _world = new btDiscreteDynamicsWorld(_dispatcher, _overlappingPairCache, _solver, _collisionConfiguration);
  389. _world->setGravity(BV(_gravity));
  390. // Register ghost pair callback so bullet detects collisions with ghost objects (used for character collisions).
  391. GP_ASSERT(_world->getPairCache());
  392. _ghostPairCallback = bullet_new<btGhostPairCallback>();
  393. _world->getPairCache()->setInternalGhostPairCallback(_ghostPairCallback);
  394. _world->getDispatchInfo().m_allowedCcdPenetration = 0.0001f;
  395. // Set up debug drawing.
  396. _debugDrawer = new DebugDrawer();
  397. _world->setDebugDrawer(_debugDrawer);
  398. }
  399. void PhysicsController::finalize()
  400. {
  401. // Clean up the world and its various components.
  402. SAFE_DELETE(_world);
  403. SAFE_DELETE(_ghostPairCallback);
  404. SAFE_DELETE(_solver);
  405. SAFE_DELETE(_overlappingPairCache);
  406. SAFE_DELETE(_dispatcher);
  407. SAFE_DELETE(_collisionConfiguration);
  408. }
  409. void PhysicsController::pause()
  410. {
  411. // Unused
  412. }
  413. void PhysicsController::resume()
  414. {
  415. // Unused
  416. }
  417. void PhysicsController::update(float elapsedTime)
  418. {
  419. GP_ASSERT(_world);
  420. // Update the physics simulation, with a maximum
  421. // of 10 simulation steps being performed in a given frame.
  422. //
  423. // Note that stepSimulation takes elapsed time in seconds
  424. // so we divide by 1000 to convert from milliseconds.
  425. _world->stepSimulation(elapsedTime * 0.001f, 10);
  426. // If we have status listeners, then check if our status has changed.
  427. if (_listeners)
  428. {
  429. Listener::EventType oldStatus = _status;
  430. if (_status == Listener::DEACTIVATED)
  431. {
  432. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  433. {
  434. GP_ASSERT(_world->getCollisionObjectArray()[i]);
  435. if (_world->getCollisionObjectArray()[i]->isActive())
  436. {
  437. _status = Listener::ACTIVATED;
  438. break;
  439. }
  440. }
  441. }
  442. else
  443. {
  444. bool allInactive = true;
  445. for (int i = 0; i < _world->getNumCollisionObjects(); i++)
  446. {
  447. GP_ASSERT(_world->getCollisionObjectArray()[i]);
  448. if (_world->getCollisionObjectArray()[i]->isActive())
  449. {
  450. allInactive = false;
  451. break;
  452. }
  453. }
  454. if (allInactive)
  455. _status = Listener::DEACTIVATED;
  456. }
  457. // If the status has changed, notify our listeners.
  458. if (oldStatus != _status)
  459. {
  460. for (unsigned int k = 0; k < _listeners->size(); k++)
  461. {
  462. GP_ASSERT((*_listeners)[k]);
  463. (*_listeners)[k]->statusEvent(_status);
  464. }
  465. }
  466. }
  467. // All statuses are set with the DIRTY bit before collision processing occurs.
  468. // During collision processing, if a collision occurs, the status is
  469. // set to COLLISION and the DIRTY bit is cleared. Then, after collision processing
  470. // is finished, if a given status is still dirty, the COLLISION bit is cleared.
  471. //
  472. // If an entry was marked for removal in the last frame, remove it now.
  473. // Dirty the collision status cache entries.
  474. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  475. for (; iter != _collisionStatus.end();)
  476. {
  477. if ((iter->second._status & REMOVE) != 0)
  478. {
  479. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator eraseIter = iter;
  480. iter++;
  481. _collisionStatus.erase(eraseIter);
  482. }
  483. else
  484. {
  485. iter->second._status |= DIRTY;
  486. iter++;
  487. }
  488. }
  489. // Go through the collision status cache and perform all registered collision tests.
  490. iter = _collisionStatus.begin();
  491. for (; iter != _collisionStatus.end(); iter++)
  492. {
  493. // If this collision pair was one that was registered for listening, then perform the collision test.
  494. // (In the case where we register for all collisions with a rigid body, there will be a lot
  495. // of collision pairs in the status cache that we did not explicitly register for.)
  496. if ((iter->second._status & REGISTERED) != 0 && (iter->second._status & REMOVE) == 0)
  497. {
  498. if (iter->first.objectB)
  499. _world->contactPairTest(iter->first.objectA->getCollisionObject(), iter->first.objectB->getCollisionObject(), *_collisionCallback);
  500. else
  501. _world->contactTest(iter->first.objectA->getCollisionObject(), *_collisionCallback);
  502. }
  503. }
  504. // Update all the collision status cache entries.
  505. iter = _collisionStatus.begin();
  506. for (; iter != _collisionStatus.end(); iter++)
  507. {
  508. if ((iter->second._status & DIRTY) != 0)
  509. {
  510. if ((iter->second._status & COLLISION) != 0 && iter->first.objectB)
  511. {
  512. unsigned int size = iter->second._listeners.size();
  513. for (unsigned int i = 0; i < size; i++)
  514. {
  515. iter->second._listeners[i]->collisionEvent(PhysicsCollisionObject::CollisionListener::NOT_COLLIDING, iter->first);
  516. }
  517. }
  518. iter->second._status &= ~COLLISION;
  519. }
  520. }
  521. }
  522. void PhysicsController::addCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  523. {
  524. GP_ASSERT(listener);
  525. // One of the collision objects in the pair must be non-null.
  526. GP_ASSERT(objectA || objectB);
  527. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  528. // Add the listener and ensure the status includes that this collision pair is registered.
  529. CollisionInfo& info = _collisionStatus[pair];
  530. info._listeners.push_back(listener);
  531. info._status |= PhysicsController::REGISTERED;
  532. }
  533. void PhysicsController::removeCollisionListener(PhysicsCollisionObject::CollisionListener* listener, PhysicsCollisionObject* objectA, PhysicsCollisionObject* objectB)
  534. {
  535. // One of the collision objects in the pair must be non-null.
  536. GP_ASSERT(objectA || objectB);
  537. PhysicsCollisionObject::CollisionPair pair(objectA, objectB);
  538. // Mark the collision pair for these objects for removal.
  539. if (_collisionStatus.count(pair) > 0)
  540. {
  541. _collisionStatus[pair]._status |= REMOVE;
  542. }
  543. }
  544. void PhysicsController::addCollisionObject(PhysicsCollisionObject* object)
  545. {
  546. GP_ASSERT(object && object->getCollisionObject());
  547. GP_ASSERT(_world);
  548. // Assign user pointer for the bullet collision object to allow efficient
  549. // lookups of bullet objects -> gameplay objects.
  550. object->getCollisionObject()->setUserPointer(object);
  551. // Add the object to the physics world.
  552. switch (object->getType())
  553. {
  554. case PhysicsCollisionObject::RIGID_BODY:
  555. _world->addRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()), btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  556. break;
  557. case PhysicsCollisionObject::CHARACTER:
  558. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  559. break;
  560. case PhysicsCollisionObject::GHOST_OBJECT:
  561. _world->addCollisionObject(object->getCollisionObject(), btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::DefaultFilter | btBroadphaseProxy::StaticFilter | btBroadphaseProxy::CharacterFilter | btBroadphaseProxy::AllFilter);
  562. break;
  563. default:
  564. GP_ERROR("Unsupported collision object type (%d).", object->getType());
  565. break;
  566. }
  567. }
  568. void PhysicsController::removeCollisionObject(PhysicsCollisionObject* object)
  569. {
  570. GP_ASSERT(object);
  571. GP_ASSERT(_world);
  572. // Remove the collision object from the world.
  573. if (object->getCollisionObject())
  574. {
  575. switch (object->getType())
  576. {
  577. case PhysicsCollisionObject::RIGID_BODY:
  578. _world->removeRigidBody(static_cast<btRigidBody*>(object->getCollisionObject()));
  579. break;
  580. case PhysicsCollisionObject::CHARACTER:
  581. case PhysicsCollisionObject::GHOST_OBJECT:
  582. _world->removeCollisionObject(object->getCollisionObject());
  583. break;
  584. default:
  585. GP_ERROR("Unsupported collision object type (%d).", object->getType());
  586. break;
  587. }
  588. }
  589. // Find all references to the object in the collision status cache and mark them for removal.
  590. std::map<PhysicsCollisionObject::CollisionPair, CollisionInfo>::iterator iter = _collisionStatus.begin();
  591. for (; iter != _collisionStatus.end(); iter++)
  592. {
  593. if (iter->first.objectA == object || iter->first.objectB == object)
  594. iter->second._status |= REMOVE;
  595. }
  596. }
  597. PhysicsCollisionObject* PhysicsController::getCollisionObject(const btCollisionObject* collisionObject) const
  598. {
  599. // Gameplay collision objects are stored in the userPointer data of Bullet collision objects.
  600. GP_ASSERT(collisionObject);
  601. return reinterpret_cast<PhysicsCollisionObject*>(collisionObject->getUserPointer());
  602. }
  603. static void getBoundingBox(Node* node, BoundingBox* out, bool merge = false)
  604. {
  605. GP_ASSERT(node);
  606. GP_ASSERT(out);
  607. if (node->getModel())
  608. {
  609. GP_ASSERT(node->getModel()->getMesh());
  610. if (merge)
  611. out->merge(node->getModel()->getMesh()->getBoundingBox());
  612. else
  613. {
  614. out->set(node->getModel()->getMesh()->getBoundingBox());
  615. merge = true;
  616. }
  617. }
  618. Node* child = node->getFirstChild();
  619. while (child)
  620. {
  621. getBoundingBox(child, out, merge);
  622. child = child->getNextSibling();
  623. }
  624. }
  625. static void getBoundingSphere(Node* node, BoundingSphere* out, bool merge = false)
  626. {
  627. GP_ASSERT(node);
  628. GP_ASSERT(out);
  629. if (node->getModel())
  630. {
  631. GP_ASSERT(node->getModel()->getMesh());
  632. if (merge)
  633. out->merge(node->getModel()->getMesh()->getBoundingSphere());
  634. else
  635. {
  636. out->set(node->getModel()->getMesh()->getBoundingSphere());
  637. merge = true;
  638. }
  639. }
  640. Node* child = node->getFirstChild();
  641. while (child)
  642. {
  643. getBoundingSphere(child, out, merge);
  644. child = child->getNextSibling();
  645. }
  646. }
  647. static void computeCenterOfMass(const Vector3& center, const Vector3& scale, Vector3* centerOfMassOffset)
  648. {
  649. GP_ASSERT(centerOfMassOffset);
  650. // Update center of mass offset.
  651. *centerOfMassOffset = center;
  652. centerOfMassOffset->x *= scale.x;
  653. centerOfMassOffset->y *= scale.y;
  654. centerOfMassOffset->z *= scale.z;
  655. centerOfMassOffset->negate();
  656. }
  657. PhysicsCollisionShape* PhysicsController::createShape(Node* node, const PhysicsCollisionShape::Definition& shape, Vector3* centerOfMassOffset)
  658. {
  659. GP_ASSERT(node);
  660. PhysicsCollisionShape* collisionShape = NULL;
  661. // Get the node's world scale (we need to apply this during creation since rigid bodies don't scale dynamically).
  662. Vector3 scale;
  663. node->getWorldMatrix().getScale(&scale);
  664. switch (shape.type)
  665. {
  666. case PhysicsCollisionShape::SHAPE_BOX:
  667. {
  668. if (shape.isExplicit)
  669. {
  670. // Use the passed in box information.
  671. collisionShape = createBox(Vector3(shape.data.box.extents), Vector3::one());
  672. if (shape.centerAbsolute)
  673. {
  674. computeCenterOfMass(Vector3(shape.data.box.center), Vector3::one(), centerOfMassOffset);
  675. }
  676. else
  677. {
  678. BoundingBox box;
  679. getBoundingBox(node, &box);
  680. computeCenterOfMass(box.getCenter() + Vector3(shape.data.box.center), scale, centerOfMassOffset);
  681. }
  682. }
  683. else
  684. {
  685. // Automatically compute bounding box from mesh's bounding box.
  686. BoundingBox box;
  687. getBoundingBox(node, &box);
  688. collisionShape = createBox(Vector3(std::fabs(box.max.x - box.min.x), std::fabs(box.max.y - box.min.y), std::fabs(box.max.z - box.min.z)), scale);
  689. computeCenterOfMass(box.getCenter(), scale, centerOfMassOffset);
  690. }
  691. }
  692. break;
  693. case PhysicsCollisionShape::SHAPE_SPHERE:
  694. {
  695. if (shape.isExplicit)
  696. {
  697. // Use the passed in sphere information.
  698. collisionShape = createSphere(shape.data.sphere.radius, Vector3::one());
  699. if (shape.centerAbsolute)
  700. {
  701. computeCenterOfMass(Vector3(shape.data.sphere.center), Vector3::one(), centerOfMassOffset);
  702. }
  703. else
  704. {
  705. BoundingSphere sphere;
  706. getBoundingSphere(node, &sphere);
  707. computeCenterOfMass(sphere.center + Vector3(shape.data.sphere.center), scale, centerOfMassOffset);
  708. }
  709. }
  710. else
  711. {
  712. // Automatically compute bounding sphere from mesh's bounding sphere.
  713. BoundingSphere sphere;
  714. getBoundingSphere(node, &sphere);
  715. collisionShape = createSphere(sphere.radius, scale);
  716. computeCenterOfMass(sphere.center, scale, centerOfMassOffset);
  717. }
  718. }
  719. break;
  720. case PhysicsCollisionShape::SHAPE_CAPSULE:
  721. {
  722. if (shape.isExplicit)
  723. {
  724. // Use the passed in capsule information.
  725. collisionShape = createCapsule(shape.data.capsule.radius, shape.data.capsule.height, Vector3::one());
  726. if (shape.centerAbsolute)
  727. {
  728. computeCenterOfMass(Vector3(shape.data.capsule.center), Vector3::one(), centerOfMassOffset);
  729. }
  730. else
  731. {
  732. BoundingBox box;
  733. getBoundingBox(node, &box);
  734. computeCenterOfMass(box.getCenter() + Vector3(shape.data.capsule.center), scale, centerOfMassOffset);
  735. }
  736. }
  737. else
  738. {
  739. // Compute a capsule shape that roughly matches the bounding box of the mesh.
  740. BoundingBox box;
  741. getBoundingBox(node, &box);
  742. float radius = std::max((box.max.x - box.min.x) * 0.5f, (box.max.z - box.min.z) * 0.5f);
  743. float height = box.max.y - box.min.y;
  744. collisionShape = createCapsule(radius, height, scale);
  745. computeCenterOfMass(box.getCenter(), scale, centerOfMassOffset);
  746. }
  747. }
  748. break;
  749. case PhysicsCollisionShape::SHAPE_HEIGHTFIELD:
  750. {
  751. // Build heightfield rigid body from the passed in shape.
  752. collisionShape = createHeightfield(node, shape.data.heightfield, centerOfMassOffset);
  753. }
  754. break;
  755. case PhysicsCollisionShape::SHAPE_MESH:
  756. {
  757. // Build mesh from passed in shape.
  758. collisionShape = createMesh(shape.data.mesh, scale);
  759. }
  760. break;
  761. default:
  762. GP_ERROR("Unsupported collision shape type (%d).", shape.type);
  763. break;
  764. }
  765. return collisionShape;
  766. }
  767. PhysicsCollisionShape* PhysicsController::createBox(const Vector3& extents, const Vector3& scale)
  768. {
  769. btVector3 halfExtents(scale.x * 0.5 * extents.x, scale.y * 0.5 * extents.y, scale.z * 0.5 * extents.z);
  770. PhysicsCollisionShape* shape;
  771. // Return the box shape from the cache if it already exists.
  772. for (unsigned int i = 0; i < _shapes.size(); ++i)
  773. {
  774. shape = _shapes[i];
  775. GP_ASSERT(shape);
  776. if (shape->getType() == PhysicsCollisionShape::SHAPE_BOX)
  777. {
  778. btBoxShape* box = static_cast<btBoxShape*>(shape->_shape);
  779. if (box && box->getHalfExtentsWithMargin() == halfExtents)
  780. {
  781. shape->addRef();
  782. return shape;
  783. }
  784. }
  785. }
  786. // Create the box shape and add it to the cache.
  787. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_BOX, bullet_new<btBoxShape>(halfExtents));
  788. _shapes.push_back(shape);
  789. return shape;
  790. }
  791. PhysicsCollisionShape* PhysicsController::createSphere(float radius, const Vector3& scale)
  792. {
  793. // Since sphere shapes depend only on the radius, the best we can do is take
  794. // the largest dimension and apply that as the uniform scale to the rigid body.
  795. float uniformScale = scale.x;
  796. if (uniformScale < scale.y)
  797. uniformScale = scale.y;
  798. if (uniformScale < scale.z)
  799. uniformScale = scale.z;
  800. float scaledRadius = radius * uniformScale;
  801. PhysicsCollisionShape* shape;
  802. // Return the sphere shape from the cache if it already exists.
  803. for (unsigned int i = 0; i < _shapes.size(); ++i)
  804. {
  805. shape = _shapes[i];
  806. GP_ASSERT(shape);
  807. if (shape->getType() == PhysicsCollisionShape::SHAPE_SPHERE)
  808. {
  809. btSphereShape* sphere = static_cast<btSphereShape*>(shape->_shape);
  810. if (sphere && sphere->getRadius() == scaledRadius)
  811. {
  812. shape->addRef();
  813. return shape;
  814. }
  815. }
  816. }
  817. // Create the sphere shape and add it to the cache.
  818. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_SPHERE, bullet_new<btSphereShape>(scaledRadius));
  819. _shapes.push_back(shape);
  820. return shape;
  821. }
  822. PhysicsCollisionShape* PhysicsController::createCapsule(float radius, float height, const Vector3& scale)
  823. {
  824. float girthScale = scale.x;
  825. if (girthScale < scale.z)
  826. girthScale = scale.z;
  827. float scaledRadius = radius * girthScale;
  828. float scaledHeight = height * scale.y - radius * 2;
  829. PhysicsCollisionShape* shape;
  830. // Return the capsule shape from the cache if it already exists.
  831. for (unsigned int i = 0; i < _shapes.size(); i++)
  832. {
  833. shape = _shapes[i];
  834. GP_ASSERT(shape);
  835. if (shape->getType() == PhysicsCollisionShape::SHAPE_CAPSULE)
  836. {
  837. btCapsuleShape* capsule = static_cast<btCapsuleShape*>(shape->_shape);
  838. if (capsule && capsule->getRadius() == scaledRadius && capsule->getHalfHeight() == 0.5f * scaledHeight)
  839. {
  840. shape->addRef();
  841. return shape;
  842. }
  843. }
  844. }
  845. // Create the capsule shape and add it to the cache.
  846. shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_CAPSULE, bullet_new<btCapsuleShape>(scaledRadius, scaledHeight));
  847. _shapes.push_back(shape);
  848. return shape;
  849. }
  850. PhysicsCollisionShape* PhysicsController::createHeightfield(Node* node, Image* image, Vector3* centerOfMassOffset)
  851. {
  852. GP_ASSERT(node);
  853. GP_ASSERT(image);
  854. GP_ASSERT(centerOfMassOffset);
  855. // Get the dimensions of the heightfield.
  856. // If the node has a mesh defined, use the dimensions of the bounding box for the mesh.
  857. // Otherwise simply use the image dimensions (with a max height of 255).
  858. float width, length, minHeight, maxHeight;
  859. if (node->getModel() && node->getModel()->getMesh())
  860. {
  861. const BoundingBox& box = node->getModel()->getMesh()->getBoundingBox();
  862. width = box.max.x - box.min.x;
  863. length = box.max.z - box.min.z;
  864. minHeight = box.min.y;
  865. maxHeight = box.max.y;
  866. }
  867. else
  868. {
  869. width = image->getWidth();
  870. length = image->getHeight();
  871. minHeight = 0.0f;
  872. maxHeight = 255.0f;
  873. }
  874. // Get the size in bytes of a pixel (we ensure that the image's
  875. // pixel format is actually supported before calling this constructor).
  876. unsigned int pixelSize = 0;
  877. switch (image->getFormat())
  878. {
  879. case Image::RGB:
  880. pixelSize = 3;
  881. break;
  882. case Image::RGBA:
  883. pixelSize = 4;
  884. break;
  885. default:
  886. GP_ERROR("Unsupported pixel format for heightmap image (%d).", image->getFormat());
  887. return NULL;
  888. }
  889. // Calculate the heights for each pixel.
  890. float* heights = new float[image->getWidth() * image->getHeight()];
  891. unsigned char* data = image->getData();
  892. for (unsigned int x = 0, w = image->getWidth(); x < w; ++x)
  893. {
  894. for (unsigned int y = 0, h = image->getHeight(); y < h; ++y)
  895. {
  896. heights[x + y * w] = ((((float)data[(x + y * h) * pixelSize + 0]) +
  897. ((float)data[(x + y * h) * pixelSize + 1]) +
  898. ((float)data[(x + y * h) * pixelSize + 2])) / 768.0f) * (maxHeight - minHeight) + minHeight;
  899. }
  900. }
  901. PhysicsCollisionShape::HeightfieldData* heightfieldData = new PhysicsCollisionShape::HeightfieldData();
  902. heightfieldData->heightData = NULL;
  903. heightfieldData->normalData = NULL;
  904. heightfieldData->inverseIsDirty = true;
  905. unsigned int sizeWidth = width;
  906. unsigned int sizeHeight = length;
  907. GP_ASSERT(sizeWidth);
  908. GP_ASSERT(sizeHeight);
  909. // Generate the heightmap data needed for physics (one height per world unit).
  910. heightfieldData->width = sizeWidth + 1;
  911. heightfieldData->height = sizeHeight + 1;
  912. heightfieldData->heightData = new float[heightfieldData->width * heightfieldData->height];
  913. heightfieldData->normalData = new Vector3[heightfieldData->width * heightfieldData->height];
  914. unsigned int heightIndex = 0, prevRowIndex = 0, prevColIndex = 0;
  915. float widthImageFactor = (float)(image->getWidth() - 1) / sizeWidth;
  916. float heightImageFactor = (float)(image->getHeight() - 1) / sizeHeight;
  917. float x = 0.0f;
  918. float z = 0.0f;
  919. const float horizStepsize = 1.0f;
  920. for (unsigned int row = 0, z = 0.0f; row <= sizeHeight; row++, z += horizStepsize)
  921. {
  922. for (unsigned int col = 0, x = 0.0f; col <= sizeWidth; col++, x += horizStepsize)
  923. {
  924. heightIndex = row * heightfieldData->width + col;
  925. prevRowIndex = heightIndex - heightfieldData->width; // ignored if row<1
  926. prevColIndex = heightIndex - 1; // ignored if col<1
  927. heightfieldData->heightData[heightIndex] = calculateHeight(heights, image->getWidth(), image->getHeight(), x * widthImageFactor, (sizeHeight - z) * heightImageFactor);
  928. //
  929. // Normal calculation based on height data using a backward difference.
  930. //
  931. if (row == 0 || col == 0)
  932. {
  933. // This is just a safe default value.
  934. heightfieldData->normalData[heightIndex].set(Vector3::unitY());
  935. }
  936. else
  937. {
  938. heightfieldData->normalData[heightIndex].set(
  939. heightfieldData->heightData[prevColIndex] - heightfieldData->heightData[heightIndex],
  940. horizStepsize,
  941. heightfieldData->heightData[prevRowIndex] - heightfieldData->heightData[heightIndex]);
  942. heightfieldData->normalData[heightIndex].normalize();
  943. }
  944. // For the starting row, just copy from the second row (i.e., a forward difference).
  945. if (row == 1)
  946. {
  947. heightfieldData->normalData[prevRowIndex].set(heightfieldData->normalData[heightIndex]);
  948. }
  949. // For the starting column, just copy from the second column (i.e., a forward difference).
  950. // (We don't care which of the 2 valid sources heightfieldData->normalData[0] ultimately comes from).
  951. if (col == 1)
  952. {
  953. heightfieldData->normalData[prevColIndex].set(heightfieldData->normalData[heightIndex]);
  954. }
  955. }
  956. }
  957. SAFE_DELETE_ARRAY(heights);
  958. // Offset the heightmap's center of mass according to the way that Bullet calculates the origin
  959. // of its heightfield collision shape; see documentation for the btHeightfieldTerrainShape for more info.
  960. Vector3 s;
  961. node->getWorldMatrix().getScale(&s);
  962. GP_ASSERT(s.y);
  963. centerOfMassOffset->set(0.0f, -(maxHeight - (0.5f * (maxHeight - minHeight))) / s.y, 0.0f);
  964. // Create the bullet terrain shape.
  965. btHeightfieldTerrainShape* terrainShape = bullet_new<btHeightfieldTerrainShape>(
  966. heightfieldData->width, heightfieldData->height, heightfieldData->heightData, 1.0f, minHeight, maxHeight, 1, PHY_FLOAT, false);
  967. // Create our collision shape object and store heightfieldData in it.
  968. PhysicsCollisionShape* shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_HEIGHTFIELD, terrainShape);
  969. shape->_shapeData.heightfieldData = heightfieldData;
  970. _shapes.push_back(shape);
  971. return shape;
  972. }
  973. PhysicsCollisionShape* PhysicsController::createMesh(Mesh* mesh, const Vector3& scale)
  974. {
  975. GP_ASSERT(mesh);
  976. // Only support meshes with triangle list primitive types.
  977. bool triMesh = true;
  978. if (mesh->getPartCount() > 0)
  979. {
  980. for (unsigned int i = 0; i < mesh->getPartCount(); ++i)
  981. {
  982. if (mesh->getPart(i)->getPrimitiveType() != Mesh::TRIANGLES)
  983. {
  984. triMesh = false;
  985. break;
  986. }
  987. }
  988. }
  989. else
  990. {
  991. triMesh = mesh->getPrimitiveType() == Mesh::TRIANGLES;
  992. }
  993. if (!triMesh)
  994. {
  995. GP_ERROR("Mesh rigid bodies are currently only supported on meshes with TRIANGLES primitive type.");
  996. return NULL;
  997. }
  998. // The mesh must have a valid URL (i.e. it must have been loaded from a Bundle)
  999. // in order to fetch mesh data for computing mesh rigid body.
  1000. if (strlen(mesh->getUrl()) == 0)
  1001. {
  1002. GP_ERROR("Cannot create mesh rigid body for mesh without valid URL.");
  1003. return NULL;
  1004. }
  1005. Bundle::MeshData* data = Bundle::readMeshData(mesh->getUrl());
  1006. if (data == NULL)
  1007. {
  1008. GP_ERROR("Failed to load mesh data from url '%s'.", mesh->getUrl());
  1009. return NULL;
  1010. }
  1011. // Create mesh data to be populated and store in returned collision shape.
  1012. PhysicsCollisionShape::MeshData* shapeMeshData = new PhysicsCollisionShape::MeshData();
  1013. shapeMeshData->vertexData = NULL;
  1014. // Copy the scaled vertex position data to the rigid body's local buffer.
  1015. Matrix m;
  1016. Matrix::createScale(scale, &m);
  1017. unsigned int vertexCount = data->vertexCount;
  1018. shapeMeshData->vertexData = new float[vertexCount * 3];
  1019. Vector3 v;
  1020. int vertexStride = data->vertexFormat.getVertexSize();
  1021. for (unsigned int i = 0; i < data->vertexCount; i++)
  1022. {
  1023. v.set(*((float*)&data->vertexData[i * vertexStride + 0 * sizeof(float)]),
  1024. *((float*)&data->vertexData[i * vertexStride + 1 * sizeof(float)]),
  1025. *((float*)&data->vertexData[i * vertexStride + 2 * sizeof(float)]));
  1026. v *= m;
  1027. memcpy(&(shapeMeshData->vertexData[i * 3]), &v, sizeof(float) * 3);
  1028. }
  1029. btTriangleIndexVertexArray* meshInterface = bullet_new<btTriangleIndexVertexArray>();
  1030. unsigned int partCount = data->parts.size();
  1031. if (partCount > 0)
  1032. {
  1033. PHY_ScalarType indexType = PHY_UCHAR;
  1034. int indexStride = 0;
  1035. Bundle::MeshPartData* meshPart = NULL;
  1036. for (unsigned int i = 0; i < partCount; i++)
  1037. {
  1038. meshPart = data->parts[i];
  1039. GP_ASSERT(meshPart);
  1040. switch (meshPart->indexFormat)
  1041. {
  1042. case Mesh::INDEX8:
  1043. indexType = PHY_UCHAR;
  1044. indexStride = 1;
  1045. break;
  1046. case Mesh::INDEX16:
  1047. indexType = PHY_SHORT;
  1048. indexStride = 2;
  1049. break;
  1050. case Mesh::INDEX32:
  1051. indexType = PHY_INTEGER;
  1052. indexStride = 4;
  1053. break;
  1054. default:
  1055. GP_ERROR("Unsupported index format (%d).", meshPart->indexFormat);
  1056. SAFE_DELETE(meshInterface);
  1057. SAFE_DELETE_ARRAY(shapeMeshData->vertexData);
  1058. SAFE_DELETE(shapeMeshData);
  1059. SAFE_DELETE(data);
  1060. return NULL;
  1061. }
  1062. // Move the index data into the rigid body's local buffer.
  1063. // Set it to NULL in the MeshPartData so it is not released when the data is freed.
  1064. shapeMeshData->indexData.push_back(meshPart->indexData);
  1065. meshPart->indexData = NULL;
  1066. // Create a btIndexedMesh object for the current mesh part.
  1067. btIndexedMesh indexedMesh;
  1068. indexedMesh.m_indexType = indexType;
  1069. indexedMesh.m_numTriangles = meshPart->indexCount / 3; // assume TRIANGLES primitive type
  1070. indexedMesh.m_numVertices = meshPart->indexCount;
  1071. indexedMesh.m_triangleIndexBase = (const unsigned char*)shapeMeshData->indexData[i];
  1072. indexedMesh.m_triangleIndexStride = indexStride*3;
  1073. indexedMesh.m_vertexBase = (const unsigned char*)shapeMeshData->vertexData;
  1074. indexedMesh.m_vertexStride = sizeof(float)*3;
  1075. indexedMesh.m_vertexType = PHY_FLOAT;
  1076. // Add the indexed mesh data to the mesh interface.
  1077. meshInterface->addIndexedMesh(indexedMesh, indexType);
  1078. }
  1079. }
  1080. else
  1081. {
  1082. // Generate index data for the mesh locally in the rigid body.
  1083. unsigned int* indexData = new unsigned int[data->vertexCount];
  1084. for (unsigned int i = 0; i < data->vertexCount; i++)
  1085. {
  1086. indexData[i] = i;
  1087. }
  1088. shapeMeshData->indexData.push_back((unsigned char*)indexData);
  1089. // Create a single btIndexedMesh object for the mesh interface.
  1090. btIndexedMesh indexedMesh;
  1091. indexedMesh.m_indexType = PHY_INTEGER;
  1092. indexedMesh.m_numTriangles = data->vertexCount / 3; // assume TRIANGLES primitive type
  1093. indexedMesh.m_numVertices = data->vertexCount;
  1094. indexedMesh.m_triangleIndexBase = shapeMeshData->indexData[0];
  1095. indexedMesh.m_triangleIndexStride = sizeof(unsigned int);
  1096. indexedMesh.m_vertexBase = (const unsigned char*)shapeMeshData->vertexData;
  1097. indexedMesh.m_vertexStride = sizeof(float)*3;
  1098. indexedMesh.m_vertexType = PHY_FLOAT;
  1099. // Set the data in the mesh interface.
  1100. meshInterface->addIndexedMesh(indexedMesh, indexedMesh.m_indexType);
  1101. }
  1102. // Create our collision shape object and store shapeMeshData in it.
  1103. PhysicsCollisionShape* shape = new PhysicsCollisionShape(PhysicsCollisionShape::SHAPE_MESH, bullet_new<btBvhTriangleMeshShape>(meshInterface, true));
  1104. shape->_shapeData.meshData = shapeMeshData;
  1105. _shapes.push_back(shape);
  1106. // Free the temporary mesh data now that it's stored in physics system.
  1107. SAFE_DELETE(data);
  1108. return shape;
  1109. }
  1110. void PhysicsController::destroyShape(PhysicsCollisionShape* shape)
  1111. {
  1112. if (shape)
  1113. {
  1114. if (shape->getRefCount() == 1)
  1115. {
  1116. // Remove shape from shape cache.
  1117. std::vector<PhysicsCollisionShape*>::iterator shapeItr = std::find(_shapes.begin(), _shapes.end(), shape);
  1118. if (shapeItr != _shapes.end())
  1119. _shapes.erase(shapeItr);
  1120. }
  1121. // Release the shape.
  1122. shape->release();
  1123. }
  1124. }
  1125. float PhysicsController::calculateHeight(float* data, unsigned int width, unsigned int height, float x, float y,
  1126. const Matrix* worldMatrix, Vector3* normalData, Vector3* normalResult)
  1127. {
  1128. GP_ASSERT(data);
  1129. unsigned int x1 = x;
  1130. unsigned int y1 = y;
  1131. unsigned int x2 = x1 + 1;
  1132. unsigned int y2 = y1 + 1;
  1133. float tmp;
  1134. float xFactor = x2 >= width ? 0.0f : modf(x, &tmp);
  1135. float yFactor = y2 >= height ? 0.0f : modf(y, &tmp);
  1136. float xFactorI = 1.0f - xFactor;
  1137. float yFactorI = 1.0f - yFactor;
  1138. float a = xFactorI * yFactorI;
  1139. float b = xFactorI * yFactor;
  1140. float c = xFactor * yFactor;
  1141. float d = xFactor * yFactorI;
  1142. if (normalResult)
  1143. {
  1144. normalResult->set(normalData[x1 + y1 * width] * a + normalData[x1 + y2 * width] * b +
  1145. normalData[x2 + y2 * width] * c + normalData[x2 + y1 * width] * d);
  1146. normalResult->normalize();
  1147. worldMatrix->transformVector(normalResult);
  1148. }
  1149. return data[x1 + y1 * width] * a + data[x1 + y2 * width] * b +
  1150. data[x2 + y2 * width] * c + data[x2 + y1 * width] * d;
  1151. }
  1152. void PhysicsController::addConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b, PhysicsConstraint* constraint)
  1153. {
  1154. GP_ASSERT(a);
  1155. GP_ASSERT(constraint);
  1156. GP_ASSERT(_world);
  1157. a->addConstraint(constraint);
  1158. if (b)
  1159. {
  1160. b->addConstraint(constraint);
  1161. }
  1162. _world->addConstraint(constraint->_constraint);
  1163. }
  1164. bool PhysicsController::checkConstraintRigidBodies(PhysicsRigidBody* a, PhysicsRigidBody* b)
  1165. {
  1166. GP_ASSERT(a);
  1167. if (!a->supportsConstraints())
  1168. {
  1169. GP_ASSERT(a->_node);
  1170. GP_ERROR("Rigid body '%s' does not support constraints; unexpected behavior may occur.", a->_node->getId());
  1171. return false;
  1172. }
  1173. if (b && !b->supportsConstraints())
  1174. {
  1175. GP_ASSERT(b->_node);
  1176. GP_ERROR("Rigid body '%s' does not support constraints; unexpected behavior may occur.", b->_node->getId());
  1177. return false;
  1178. }
  1179. return true;
  1180. }
  1181. void PhysicsController::removeConstraint(PhysicsConstraint* constraint)
  1182. {
  1183. GP_ASSERT(constraint);
  1184. GP_ASSERT(_world);
  1185. // Find the constraint and remove it from the physics world.
  1186. for (int i = _world->getNumConstraints() - 1; i >= 0; i--)
  1187. {
  1188. btTypedConstraint* currentConstraint = _world->getConstraint(i);
  1189. if (constraint->_constraint == currentConstraint)
  1190. {
  1191. _world->removeConstraint(currentConstraint);
  1192. break;
  1193. }
  1194. }
  1195. }
  1196. PhysicsController::DebugDrawer::DebugDrawer()
  1197. : _mode(btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawConstraintLimits | btIDebugDraw::DBG_DrawConstraints |
  1198. btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe), _viewProjection(NULL), _meshBatch(NULL)
  1199. {
  1200. // Vertex shader for drawing colored lines.
  1201. const char* vs_str =
  1202. {
  1203. "uniform mat4 u_viewProjectionMatrix;\n"
  1204. "attribute vec4 a_position;\n"
  1205. "attribute vec4 a_color;\n"
  1206. "varying vec4 v_color;\n"
  1207. "void main(void) {\n"
  1208. " v_color = a_color;\n"
  1209. " gl_Position = u_viewProjectionMatrix * a_position;\n"
  1210. "}"
  1211. };
  1212. // Fragment shader for drawing colored lines.
  1213. const char* fs_str =
  1214. {
  1215. #ifdef OPENGL_ES
  1216. "precision highp float;\n"
  1217. #endif
  1218. "varying vec4 v_color;\n"
  1219. "void main(void) {\n"
  1220. " gl_FragColor = v_color;\n"
  1221. "}"
  1222. };
  1223. Effect* effect = Effect::createFromSource(vs_str, fs_str);
  1224. Material* material = Material::create(effect);
  1225. GP_ASSERT(material && material->getStateBlock());
  1226. material->getStateBlock()->setDepthTest(true);
  1227. VertexFormat::Element elements[] =
  1228. {
  1229. VertexFormat::Element(VertexFormat::POSITION, 3),
  1230. VertexFormat::Element(VertexFormat::COLOR, 4),
  1231. };
  1232. _meshBatch = MeshBatch::create(VertexFormat(elements, 2), Mesh::LINES, material, false);
  1233. SAFE_RELEASE(material);
  1234. SAFE_RELEASE(effect);
  1235. }
  1236. PhysicsController::DebugDrawer::~DebugDrawer()
  1237. {
  1238. SAFE_DELETE(_meshBatch);
  1239. }
  1240. void PhysicsController::DebugDrawer::begin(const Matrix& viewProjection)
  1241. {
  1242. GP_ASSERT(_meshBatch);
  1243. _viewProjection = &viewProjection;
  1244. _meshBatch->begin();
  1245. }
  1246. void PhysicsController::DebugDrawer::end()
  1247. {
  1248. GP_ASSERT(_meshBatch && _meshBatch->getMaterial() && _meshBatch->getMaterial()->getParameter("u_viewProjectionMatrix"));
  1249. _meshBatch->finish();
  1250. _meshBatch->getMaterial()->getParameter("u_viewProjectionMatrix")->setValue(_viewProjection);
  1251. _meshBatch->draw();
  1252. }
  1253. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
  1254. {
  1255. GP_ASSERT(_meshBatch);
  1256. static DebugDrawer::DebugVertex fromVertex, toVertex;
  1257. fromVertex.x = from.getX();
  1258. fromVertex.y = from.getY();
  1259. fromVertex.z = from.getZ();
  1260. fromVertex.r = fromColor.getX();
  1261. fromVertex.g = fromColor.getY();
  1262. fromVertex.b = fromColor.getZ();
  1263. fromVertex.a = 1.0f;
  1264. toVertex.x = to.getX();
  1265. toVertex.y = to.getY();
  1266. toVertex.z = to.getZ();
  1267. toVertex.r = toColor.getX();
  1268. toVertex.g = toColor.getY();
  1269. toVertex.b = toColor.getZ();
  1270. toVertex.a = 1.0f;
  1271. _meshBatch->add(&fromVertex, 1);
  1272. _meshBatch->add(&toVertex, 1);
  1273. }
  1274. void PhysicsController::DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
  1275. {
  1276. drawLine(from, to, color, color);
  1277. }
  1278. void PhysicsController::DebugDrawer::drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
  1279. {
  1280. drawLine(pointOnB, pointOnB + normalOnB, color);
  1281. }
  1282. void PhysicsController::DebugDrawer::reportErrorWarning(const char* warningString)
  1283. {
  1284. GP_WARN(warningString);
  1285. }
  1286. void PhysicsController::DebugDrawer::draw3dText(const btVector3& location, const char* textString)
  1287. {
  1288. GP_WARN("Physics debug drawing: 3D text is not supported.");
  1289. }
  1290. void PhysicsController::DebugDrawer::setDebugMode(int mode)
  1291. {
  1292. _mode = mode;
  1293. }
  1294. int PhysicsController::DebugDrawer::getDebugMode() const
  1295. {
  1296. return _mode;
  1297. }
  1298. PhysicsController::Listener::~Listener()
  1299. {
  1300. GP_ASSERT(Game::getInstance()->getPhysicsController());
  1301. Game::getInstance()->getPhysicsController()->removeStatusListener(this);
  1302. }
  1303. PhysicsController::HitFilter::HitFilter()
  1304. {
  1305. }
  1306. PhysicsController::HitFilter::~HitFilter()
  1307. {
  1308. }
  1309. bool PhysicsController::HitFilter::filter(PhysicsCollisionObject* object)
  1310. {
  1311. return false;
  1312. }
  1313. bool PhysicsController::HitFilter::hit(const PhysicsController::HitResult& result)
  1314. {
  1315. return true;
  1316. }
  1317. }