PhysicsRigidBody.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #include "Base.h"
  2. #include "PhysicsRigidBody.h"
  3. #include "PhysicsController.h"
  4. #include "Game.h"
  5. #include "Image.h"
  6. #include "MeshPart.h"
  7. #include "Node.h"
  8. namespace gameplay
  9. {
  10. PhysicsRigidBody::PhysicsRigidBody(Node* node, const PhysicsCollisionShape::Definition& shape, const Parameters& parameters)
  11. : PhysicsCollisionObject(node), _body(NULL), _mass(parameters.mass), _constraints(NULL), _inDestructor(false)
  12. {
  13. GP_ASSERT(Game::getInstance()->getPhysicsController());
  14. GP_ASSERT(_node);
  15. // Create our collision shape.
  16. Vector3 centerOfMassOffset;
  17. _collisionShape = Game::getInstance()->getPhysicsController()->createShape(node, shape, &centerOfMassOffset);
  18. GP_ASSERT(_collisionShape && _collisionShape->getShape());
  19. // Create motion state object.
  20. _motionState = new PhysicsMotionState(node, (centerOfMassOffset.lengthSquared() > MATH_EPSILON) ? &centerOfMassOffset : NULL);
  21. // If the mass is non-zero, then the object is dynamic so we calculate the local
  22. // inertia. However, if the collision shape is a triangle mesh, we don't calculate
  23. // inertia since Bullet doesn't currently support this.
  24. btVector3 localInertia(0.0, 0.0, 0.0);
  25. if (parameters.mass != 0.0 && _collisionShape->getType() != PhysicsCollisionShape::SHAPE_MESH)
  26. _collisionShape->getShape()->calculateLocalInertia(parameters.mass, localInertia);
  27. // Create the Bullet physics rigid body object.
  28. btRigidBody::btRigidBodyConstructionInfo rbInfo(parameters.mass, _motionState, _collisionShape->getShape(), localInertia);
  29. rbInfo.m_friction = parameters.friction;
  30. rbInfo.m_restitution = parameters.restitution;
  31. rbInfo.m_linearDamping = parameters.linearDamping;
  32. rbInfo.m_angularDamping = parameters.angularDamping;
  33. // Create + assign the new bullet rigid body object.
  34. _body = bullet_new<btRigidBody>(rbInfo);
  35. // Set other initially defined properties.
  36. setKinematic(parameters.kinematic);
  37. setAnisotropicFriction(parameters.anisotropicFriction);
  38. // Add ourself to the physics world.
  39. Game::getInstance()->getPhysicsController()->addCollisionObject(this);
  40. if (_collisionShape->getType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  41. {
  42. // Add a listener on the node's transform so we can track dirty changes to calculate
  43. // an inverse matrix for transforming heightfield points between world and local space.
  44. _node->addListener(this);
  45. }
  46. }
  47. PhysicsRigidBody::~PhysicsRigidBody()
  48. {
  49. GP_ASSERT(Game::getInstance()->getPhysicsController());
  50. GP_ASSERT(_collisionShape);
  51. GP_ASSERT(_node);
  52. // Clean up all constraints linked to this rigid body.
  53. _inDestructor = true;
  54. if (_constraints)
  55. {
  56. for (unsigned int i = 0; i < _constraints->size(); ++i)
  57. {
  58. SAFE_DELETE((*_constraints)[i]);
  59. }
  60. SAFE_DELETE(_constraints);
  61. }
  62. // Remove collision object from physics controller.
  63. Game::getInstance()->getPhysicsController()->removeCollisionObject(this);
  64. // Clean up the rigid body and its related objects.
  65. SAFE_DELETE(_body);
  66. // Unregister node listener (only registered for heihgtfield collision shape types).
  67. if (_collisionShape->getType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  68. {
  69. _node->removeListener(this);
  70. }
  71. }
  72. PhysicsCollisionObject::Type PhysicsRigidBody::getType() const
  73. {
  74. return PhysicsCollisionObject::RIGID_BODY;
  75. }
  76. btCollisionObject* PhysicsRigidBody::getCollisionObject() const
  77. {
  78. return _body;
  79. }
  80. void PhysicsRigidBody::applyForce(const Vector3& force, const Vector3* relativePosition)
  81. {
  82. // If the force is significant enough, activate the rigid body
  83. // to make sure that it isn't sleeping and apply the force.
  84. if (force.lengthSquared() > MATH_EPSILON)
  85. {
  86. GP_ASSERT(_body);
  87. _body->activate();
  88. if (relativePosition)
  89. _body->applyForce(BV(force), BV(*relativePosition));
  90. else
  91. _body->applyCentralForce(BV(force));
  92. }
  93. }
  94. void PhysicsRigidBody::applyImpulse(const Vector3& impulse, const Vector3* relativePosition)
  95. {
  96. // If the impulse is significant enough, activate the rigid body
  97. // to make sure that it isn't sleeping and apply the impulse.
  98. if (impulse.lengthSquared() > MATH_EPSILON)
  99. {
  100. GP_ASSERT(_body);
  101. _body->activate();
  102. if (relativePosition)
  103. {
  104. _body->applyImpulse(BV(impulse), BV(*relativePosition));
  105. }
  106. else
  107. _body->applyCentralImpulse(BV(impulse));
  108. }
  109. }
  110. void PhysicsRigidBody::applyTorque(const Vector3& torque)
  111. {
  112. // If the torque is significant enough, activate the rigid body
  113. // to make sure that it isn't sleeping and apply the torque.
  114. if (torque.lengthSquared() > MATH_EPSILON)
  115. {
  116. GP_ASSERT(_body);
  117. _body->activate();
  118. _body->applyTorque(BV(torque));
  119. }
  120. }
  121. void PhysicsRigidBody::applyTorqueImpulse(const Vector3& torque)
  122. {
  123. // If the torque impulse is significant enough, activate the rigid body
  124. // to make sure that it isn't sleeping and apply the torque impulse.
  125. if (torque.lengthSquared() > MATH_EPSILON)
  126. {
  127. GP_ASSERT(_body);
  128. _body->activate();
  129. _body->applyTorqueImpulse(BV(torque));
  130. }
  131. }
  132. PhysicsRigidBody* PhysicsRigidBody::create(Node* node, Properties* properties)
  133. {
  134. // Check if the properties is valid and has a valid namespace.
  135. if (!properties || !(strcmp(properties->getNamespace(), "collisionObject") == 0))
  136. {
  137. GP_ERROR("Failed to load rigid body from properties object: must be non-null object and have namespace equal to 'collisionObject'.");
  138. return NULL;
  139. }
  140. // Check that the type is specified and correct.
  141. const char* type = properties->getString("type");
  142. if (!type)
  143. {
  144. GP_ERROR("Failed to load physics rigid body from properties object; required attribute 'type' is missing.");
  145. return NULL;
  146. }
  147. if (strcmp(type, "RIGID_BODY") != 0)
  148. {
  149. GP_ERROR("Failed to load physics rigid body from properties object; attribute 'type' must be equal to 'RIGID_BODY'.");
  150. return NULL;
  151. }
  152. // Load the physics collision shape definition.
  153. PhysicsCollisionShape::Definition* shape = PhysicsCollisionShape::Definition::create(node, properties);
  154. if (shape == NULL)
  155. {
  156. GP_ERROR("Failed to create collision shape during rigid body creation.");
  157. return NULL;
  158. }
  159. // Set the rigid body parameters to their defaults.
  160. Parameters parameters;
  161. Vector3* gravity = NULL;
  162. // Load the defined rigid body parameters.
  163. properties->rewind();
  164. const char* name;
  165. while ((name = properties->getNextProperty()) != NULL)
  166. {
  167. if (strcmp(name, "mass") == 0)
  168. {
  169. parameters.mass = properties->getFloat();
  170. }
  171. else if (strcmp(name, "friction") == 0)
  172. {
  173. parameters.friction = properties->getFloat();
  174. }
  175. else if (strcmp(name, "restitution") == 0)
  176. {
  177. parameters.restitution = properties->getFloat();
  178. }
  179. else if (strcmp(name, "linearDamping") == 0)
  180. {
  181. parameters.linearDamping = properties->getFloat();
  182. }
  183. else if (strcmp(name, "angularDamping") == 0)
  184. {
  185. parameters.angularDamping = properties->getFloat();
  186. }
  187. else if (strcmp(name, "kinematic") == 0)
  188. {
  189. parameters.kinematic = properties->getBool();
  190. }
  191. else if (strcmp(name, "anisotropicFriction") == 0)
  192. {
  193. properties->getVector3(NULL, &parameters.anisotropicFriction);
  194. }
  195. else if (strcmp(name, "gravity") == 0)
  196. {
  197. gravity = new Vector3();
  198. properties->getVector3(NULL, gravity);
  199. }
  200. else
  201. {
  202. // Ignore this case (the attributes for the rigid body's collision shape would end up here).
  203. }
  204. }
  205. // Create the rigid body.
  206. PhysicsRigidBody* body = new PhysicsRigidBody(node, *shape, parameters);
  207. SAFE_DELETE(shape);
  208. if (gravity)
  209. {
  210. body->setGravity(*gravity);
  211. SAFE_DELETE(gravity);
  212. }
  213. return body;
  214. }
  215. void PhysicsRigidBody::setKinematic(bool kinematic)
  216. {
  217. GP_ASSERT(_body);
  218. if (kinematic)
  219. {
  220. _body->setCollisionFlags(_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
  221. _body->setActivationState(DISABLE_DEACTIVATION);
  222. }
  223. else
  224. {
  225. _body->setCollisionFlags(_body->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
  226. _body->setActivationState(ACTIVE_TAG);
  227. }
  228. }
  229. float PhysicsRigidBody::getHeight(float x, float y, Vector3* normal /*=NULL*/) const
  230. {
  231. GP_ASSERT(_collisionShape);
  232. // This function is only supported for heightfield rigid bodies.
  233. if (_collisionShape->getType() != PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  234. {
  235. GP_ERROR("Attempting to get the height of a non-heightfield rigid body.");
  236. return 0.0f;
  237. }
  238. GP_ASSERT(_collisionShape->_shapeData.heightfieldData);
  239. GP_ASSERT(_node);
  240. // Calculate the correct x, y position relative to the heightfield data.
  241. if (_collisionShape->_shapeData.heightfieldData->inverseIsDirty)
  242. {
  243. _node->getWorldMatrix().invert(&_collisionShape->_shapeData.heightfieldData->inverse);
  244. _collisionShape->_shapeData.heightfieldData->inverseIsDirty = false;
  245. }
  246. float w = _collisionShape->_shapeData.heightfieldData->width;
  247. float h = _collisionShape->_shapeData.heightfieldData->height;
  248. GP_ASSERT(w - 1);
  249. GP_ASSERT(h - 1);
  250. Vector3 v = _collisionShape->_shapeData.heightfieldData->inverse * Vector3(x, 0.0f, y);
  251. x = (v.x + (0.5f * (w - 1))) * w / (w - 1);
  252. y = (v.z + (0.5f * (h - 1))) * h / (h - 1);
  253. // Check that the x, y position is within the bounds.
  254. if (x < 0.0f || x > w || y < 0.0f || y > h)
  255. {
  256. GP_ERROR("Attempting to get height at point '%f, %f', which is outside the range of the heightfield with width %d and height %d.", x, y, w, h);
  257. return 0.0f;
  258. }
  259. return PhysicsController::calculateHeight(_collisionShape->_shapeData.heightfieldData->heightData, w, h, x, y,
  260. &_node->getWorldMatrix(), _collisionShape->_shapeData.heightfieldData->normalData, normal);
  261. }
  262. void PhysicsRigidBody::addConstraint(PhysicsConstraint* constraint)
  263. {
  264. GP_ASSERT(constraint);
  265. if (_constraints == NULL)
  266. _constraints = new std::vector<PhysicsConstraint*>();
  267. _constraints->push_back(constraint);
  268. }
  269. void PhysicsRigidBody::removeConstraint(PhysicsConstraint* constraint)
  270. {
  271. // Ensure that the rigid body has constraints and that we are
  272. // not currently in the rigid body's destructor (in this case,
  273. // the constraints will be destroyed from there).
  274. if (_constraints && !_inDestructor)
  275. {
  276. for (unsigned int i = 0; i < _constraints->size(); ++i)
  277. {
  278. if ((*_constraints)[i] == constraint)
  279. {
  280. _constraints->erase(_constraints->begin() + i);
  281. break;
  282. }
  283. }
  284. }
  285. }
  286. bool PhysicsRigidBody::supportsConstraints()
  287. {
  288. return (getShapeType() != PhysicsCollisionShape::SHAPE_HEIGHTFIELD && getShapeType() != PhysicsCollisionShape::SHAPE_MESH);
  289. }
  290. void PhysicsRigidBody::transformChanged(Transform* transform, long cookie)
  291. {
  292. if (getShapeType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  293. {
  294. GP_ASSERT(_collisionShape && _collisionShape->_shapeData.heightfieldData);
  295. _collisionShape->_shapeData.heightfieldData->inverseIsDirty = true;
  296. }
  297. }
  298. }