RigidBody.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "CollisionShape.h"
  25. #include "Constraint.h"
  26. #include "Context.h"
  27. #include "Log.h"
  28. #include "MemoryBuffer.h"
  29. #include "PhysicsUtils.h"
  30. #include "PhysicsWorld.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "ResourceEvents.h"
  34. #include "RigidBody.h"
  35. #include "Scene.h"
  36. #include "SceneEvents.h"
  37. #include "SmoothedTransform.h"
  38. #include "XMLElement.h"
  39. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  40. #include <BulletDynamics/Dynamics/btRigidBody.h>
  41. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  42. static const float DEFAULT_MASS = 0.0f;
  43. static const float DEFAULT_FRICTION = 0.5f;
  44. static const float DEFAULT_RESTITUTION = 0.0f;
  45. static const float DEFAULT_LINEAR_REST_THRESHOLD = 0.8f;
  46. static const float DEFAULT_ANGULAR_REST_THRESHOLD = 1.0f;
  47. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  48. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  49. static const String collisionEventModeNames[] =
  50. {
  51. "Never",
  52. "When Active",
  53. "Always",
  54. ""
  55. };
  56. OBJECTTYPESTATIC(RigidBody);
  57. RigidBody::RigidBody(Context* context) :
  58. Component(context),
  59. body_(0),
  60. compoundShape_(0),
  61. mass_(DEFAULT_MASS),
  62. collisionLayer_(DEFAULT_COLLISION_LAYER),
  63. collisionMask_(DEFAULT_COLLISION_MASK),
  64. collisionEventMode_(COLLISION_ACTIVE),
  65. lastPosition_(Vector3::ZERO),
  66. lastRotation_(Quaternion::IDENTITY),
  67. kinematic_(false),
  68. phantom_(false),
  69. hasSmoothedTransform_(false),
  70. readdBody_(false)
  71. {
  72. compoundShape_ = new btCompoundShape();
  73. }
  74. RigidBody::~RigidBody()
  75. {
  76. ReleaseBody();
  77. if (physicsWorld_)
  78. physicsWorld_->RemoveRigidBody(this);
  79. delete compoundShape_;
  80. compoundShape_ = 0;
  81. }
  82. void RigidBody::RegisterObject(Context* context)
  83. {
  84. context->RegisterFactory<RigidBody>();
  85. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Physics Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE | AM_NOEDIT);
  86. ACCESSOR_ATTRIBUTE(RigidBody, VAR_QUATERNION, "Physics Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE | AM_NOEDIT);
  87. ATTRIBUTE(RigidBody, VAR_FLOAT, "Mass", mass_, DEFAULT_MASS, AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Restitution", GetRestitution, SetRestitution, float, DEFAULT_RESTITUTION, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  91. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Velocity", GetAngularVelocity, SetAngularVelocity, Vector3, Vector3::ZERO, AM_FILE);
  92. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Factor", GetLinearFactor, SetLinearFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Factor", GetAngularFactor, SetAngularFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.01f, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Rest Threshold", GetLinearRestThreshold, SetLinearRestThreshold, float, 0.01f, AM_DEFAULT);
  97. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Rest Threshold", GetAngularRestThreshold, SetAngularRestThreshold, float, 0.01f, AM_DEFAULT);
  98. ATTRIBUTE(RigidBody, VAR_INT, "Collision Layer", collisionLayer_, DEFAULT_COLLISION_LAYER, AM_DEFAULT);
  99. ATTRIBUTE(RigidBody, VAR_INT, "Collision Mask", collisionMask_, DEFAULT_COLLISION_MASK, AM_DEFAULT);
  100. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Radius", GetCcdRadius, SetCcdRadius, float, 0.0f, AM_DEFAULT);
  101. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Motion Threshold", GetCcdMotionThreshold, SetCcdMotionThreshold, float, 0.0f, AM_DEFAULT);
  102. REF_ACCESSOR_ATTRIBUTE(RigidBody, VAR_BUFFER, "Network Angular Velocity", GetNetAngularVelocityAttr, SetNetAngularVelocityAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  103. ENUM_ATTRIBUTE(RigidBody, "Collision Event Mode", collisionEventMode_, collisionEventModeNames, COLLISION_ACTIVE, AM_DEFAULT);
  104. ACCESSOR_ATTRIBUTE(RigidBody, VAR_BOOL, "Use Gravity", GetUseGravity, SetUseGravity, bool, true, AM_DEFAULT);
  105. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Kinematic", kinematic_, false, AM_DEFAULT);
  106. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Phantom", phantom_, false, AM_DEFAULT);
  107. }
  108. void RigidBody::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  109. {
  110. Component::OnSetAttribute(attr, src);
  111. // Change of any non-accessor attribute requires the rigid body to be re-added to the physics world
  112. if (!attr.accessor_)
  113. readdBody_ = true;
  114. }
  115. void RigidBody::ApplyAttributes()
  116. {
  117. if (readdBody_)
  118. {
  119. AddBodyToWorld();
  120. readdBody_ = false;
  121. }
  122. }
  123. void RigidBody::getWorldTransform(btTransform &worldTrans) const
  124. {
  125. lastPosition_ = node_->GetWorldPosition();
  126. lastRotation_ = node_->GetWorldRotation();
  127. worldTrans.setOrigin(ToBtVector3(lastPosition_));
  128. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  129. }
  130. void RigidBody::setWorldTransform(const btTransform &worldTrans)
  131. {
  132. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin());
  133. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  134. RigidBody* parentRigidBody = 0;
  135. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  136. // In that case store it to PhysicsWorld for delayed assignment
  137. Node* parent = node_->GetParent();
  138. if (parent && parent != GetScene())
  139. parentRigidBody = parent->GetComponent<RigidBody>();
  140. if (!parentRigidBody)
  141. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  142. else
  143. {
  144. DelayedWorldTransform delayed;
  145. delayed.rigidBody_ = this;
  146. delayed.parentRigidBody_ = parentRigidBody;
  147. delayed.worldPosition_ = newWorldPosition;
  148. delayed.worldRotation_ = newWorldRotation;
  149. physicsWorld_->AddDelayedWorldTransform(delayed);
  150. }
  151. MarkNetworkUpdate();
  152. }
  153. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  154. {
  155. if (debug && physicsWorld_ && body_)
  156. {
  157. physicsWorld_->SetDebugRenderer(debug);
  158. physicsWorld_->SetDebugDepthTest(depthTest);
  159. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  160. world->debugDrawObject(body_->getWorldTransform(), compoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  161. btVector3(0.0f, 1.0f, 0.0f));
  162. physicsWorld_->SetDebugRenderer(0);
  163. }
  164. }
  165. void RigidBody::SetMass(float mass)
  166. {
  167. mass = Max(mass, 0.0f);
  168. if (mass != mass_)
  169. {
  170. mass_ = mass;
  171. AddBodyToWorld();
  172. MarkNetworkUpdate();
  173. }
  174. }
  175. void RigidBody::SetPosition(Vector3 position)
  176. {
  177. if (body_)
  178. {
  179. btTransform& worldTrans = body_->getWorldTransform();
  180. worldTrans.setOrigin(ToBtVector3(position));
  181. // When forcing the physics position, set also interpolated position so that there is no jitter
  182. btTransform interpTrans = body_->getInterpolationWorldTransform();
  183. interpTrans.setOrigin(worldTrans.getOrigin());
  184. body_->setInterpolationWorldTransform(interpTrans);
  185. body_->updateInertiaTensor();
  186. Activate();
  187. MarkNetworkUpdate();
  188. }
  189. }
  190. void RigidBody::SetRotation(Quaternion rotation)
  191. {
  192. if (body_)
  193. {
  194. btTransform& worldTrans = body_->getWorldTransform();
  195. worldTrans.setRotation(ToBtQuaternion(rotation));
  196. // When forcing the physics position, set also interpolated position so that there is no jitter
  197. btTransform interpTrans = body_->getInterpolationWorldTransform();
  198. interpTrans.setRotation(worldTrans.getRotation());
  199. body_->setInterpolationWorldTransform(interpTrans);
  200. body_->updateInertiaTensor();
  201. Activate();
  202. MarkNetworkUpdate();
  203. }
  204. }
  205. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  206. {
  207. if (body_)
  208. {
  209. btTransform& worldTrans = body_->getWorldTransform();
  210. worldTrans.setOrigin(ToBtVector3(position));
  211. worldTrans.setRotation(ToBtQuaternion(rotation));
  212. // When forcing the physics position, set also interpolated position so that there is no jitter
  213. btTransform interpTrans = body_->getInterpolationWorldTransform();
  214. interpTrans.setOrigin(worldTrans.getOrigin());
  215. interpTrans.setRotation(worldTrans.getRotation());
  216. body_->setInterpolationWorldTransform(interpTrans);
  217. body_->updateInertiaTensor();
  218. Activate();
  219. MarkNetworkUpdate();
  220. }
  221. }
  222. void RigidBody::SetLinearVelocity(Vector3 velocity)
  223. {
  224. if (body_)
  225. {
  226. body_->setLinearVelocity(ToBtVector3(velocity));
  227. if (velocity != Vector3::ZERO)
  228. Activate();
  229. MarkNetworkUpdate();
  230. }
  231. }
  232. void RigidBody::SetLinearFactor(Vector3 factor)
  233. {
  234. if (body_)
  235. {
  236. body_->setLinearFactor(ToBtVector3(factor));
  237. MarkNetworkUpdate();
  238. }
  239. }
  240. void RigidBody::SetLinearRestThreshold(float threshold)
  241. {
  242. if (body_)
  243. {
  244. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  245. MarkNetworkUpdate();
  246. }
  247. }
  248. void RigidBody::SetLinearDamping(float damping)
  249. {
  250. if (body_)
  251. {
  252. body_->setDamping(damping, body_->getAngularDamping());
  253. MarkNetworkUpdate();
  254. }
  255. }
  256. void RigidBody::SetAngularVelocity(Vector3 velocity)
  257. {
  258. if (body_)
  259. {
  260. body_->setAngularVelocity(ToBtVector3(velocity));
  261. if (velocity != Vector3::ZERO)
  262. Activate();
  263. MarkNetworkUpdate();
  264. }
  265. }
  266. void RigidBody::SetAngularFactor(Vector3 factor)
  267. {
  268. if (body_)
  269. {
  270. body_->setAngularFactor(ToBtVector3(factor));
  271. MarkNetworkUpdate();
  272. }
  273. }
  274. void RigidBody::SetAngularRestThreshold(float threshold)
  275. {
  276. if (body_)
  277. {
  278. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  279. MarkNetworkUpdate();
  280. }
  281. }
  282. void RigidBody::SetAngularDamping(float damping)
  283. {
  284. if (body_)
  285. {
  286. body_->setDamping(body_->getLinearDamping(), damping);
  287. MarkNetworkUpdate();
  288. }
  289. }
  290. void RigidBody::SetFriction(float friction)
  291. {
  292. if (body_)
  293. {
  294. body_->setFriction(friction);
  295. MarkNetworkUpdate();
  296. }
  297. }
  298. void RigidBody::SetRestitution(float restitution)
  299. {
  300. if (body_)
  301. {
  302. body_->setRestitution(restitution);
  303. MarkNetworkUpdate();
  304. }
  305. }
  306. void RigidBody::SetCcdRadius(float radius)
  307. {
  308. radius = Max(radius, 0.0f);
  309. if (body_)
  310. {
  311. body_->setCcdSweptSphereRadius(radius);
  312. MarkNetworkUpdate();
  313. }
  314. }
  315. void RigidBody::SetCcdMotionThreshold(float threshold)
  316. {
  317. threshold = Max(threshold, 0.0f);
  318. if (body_)
  319. {
  320. body_->setCcdMotionThreshold(threshold);
  321. MarkNetworkUpdate();
  322. }
  323. }
  324. void RigidBody::SetUseGravity(bool enable)
  325. {
  326. if (physicsWorld_ && body_ && enable != GetUseGravity())
  327. {
  328. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  329. int flags = body_->getFlags();
  330. if (enable)
  331. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  332. else
  333. flags |= BT_DISABLE_WORLD_GRAVITY;
  334. body_->setFlags(flags);
  335. if (enable)
  336. body_->setGravity(world->getGravity());
  337. else
  338. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  339. MarkNetworkUpdate();
  340. }
  341. }
  342. void RigidBody::SetKinematic(bool enable)
  343. {
  344. if (enable != kinematic_)
  345. {
  346. kinematic_ = enable;
  347. AddBodyToWorld();
  348. MarkNetworkUpdate();
  349. }
  350. }
  351. void RigidBody::SetPhantom(bool enable)
  352. {
  353. if (enable != phantom_)
  354. {
  355. phantom_ = enable;
  356. AddBodyToWorld();
  357. MarkNetworkUpdate();
  358. }
  359. }
  360. void RigidBody::SetCollisionLayer(unsigned layer)
  361. {
  362. if (layer != collisionLayer_)
  363. {
  364. collisionLayer_ = layer;
  365. AddBodyToWorld();
  366. MarkNetworkUpdate();
  367. }
  368. }
  369. void RigidBody::SetCollisionMask(unsigned mask)
  370. {
  371. if (mask != collisionMask_)
  372. {
  373. collisionMask_ = mask;
  374. AddBodyToWorld();
  375. MarkNetworkUpdate();
  376. }
  377. }
  378. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  379. {
  380. if (layer != collisionLayer_ || mask != collisionMask_)
  381. {
  382. collisionLayer_ = layer;
  383. collisionMask_ = mask;
  384. AddBodyToWorld();
  385. MarkNetworkUpdate();
  386. }
  387. }
  388. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  389. {
  390. collisionEventMode_ = mode;
  391. MarkNetworkUpdate();
  392. }
  393. void RigidBody::ApplyForce(const Vector3& force)
  394. {
  395. if (body_ && force != Vector3::ZERO)
  396. {
  397. Activate();
  398. body_->applyCentralForce(ToBtVector3(force));
  399. }
  400. }
  401. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  402. {
  403. if (body_ && force != Vector3::ZERO)
  404. {
  405. Activate();
  406. body_->applyForce(ToBtVector3(force), ToBtVector3(position));
  407. }
  408. }
  409. void RigidBody::ApplyTorque(const Vector3& torque)
  410. {
  411. if (body_ && torque != Vector3::ZERO)
  412. {
  413. Activate();
  414. body_->applyTorque(ToBtVector3(torque));
  415. }
  416. }
  417. void RigidBody::ApplyImpulse(const Vector3& impulse)
  418. {
  419. if (body_ && impulse != Vector3::ZERO)
  420. {
  421. Activate();
  422. body_->applyCentralImpulse(ToBtVector3(impulse));
  423. }
  424. }
  425. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  426. {
  427. if (body_ && impulse != Vector3::ZERO)
  428. {
  429. Activate();
  430. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position));
  431. }
  432. }
  433. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  434. {
  435. if (body_ && torque != Vector3::ZERO)
  436. {
  437. Activate();
  438. body_->applyTorqueImpulse(ToBtVector3(torque));
  439. }
  440. }
  441. void RigidBody::ResetForces()
  442. {
  443. if (body_)
  444. body_->clearForces();
  445. }
  446. void RigidBody::Activate()
  447. {
  448. if (mass_ > 0.0f && body_ && !body_->isActive())
  449. body_->activate();
  450. }
  451. Vector3 RigidBody::GetPosition() const
  452. {
  453. if (body_)
  454. return ToVector3(body_->getWorldTransform().getOrigin());
  455. else
  456. return Vector3::ZERO;
  457. }
  458. Quaternion RigidBody::GetRotation() const
  459. {
  460. if (body_)
  461. return ToQuaternion(body_->getWorldTransform().getRotation());
  462. else
  463. return Quaternion::IDENTITY;
  464. }
  465. Vector3 RigidBody::GetLinearVelocity() const
  466. {
  467. if (body_)
  468. return ToVector3(body_->getLinearVelocity());
  469. else
  470. return Vector3::ZERO;
  471. }
  472. Vector3 RigidBody::GetLinearFactor() const
  473. {
  474. if (body_)
  475. return ToVector3(body_->getLinearFactor());
  476. else
  477. return Vector3::ZERO;
  478. }
  479. float RigidBody::GetLinearRestThreshold() const
  480. {
  481. if (body_)
  482. return body_->getLinearSleepingThreshold();
  483. else
  484. return 0.0f;
  485. }
  486. float RigidBody::GetLinearDamping() const
  487. {
  488. if (body_)
  489. return body_->getLinearDamping();
  490. else
  491. return 0.0f;
  492. }
  493. Vector3 RigidBody::GetAngularVelocity() const
  494. {
  495. if (body_)
  496. return ToVector3(body_->getAngularVelocity());
  497. else
  498. return Vector3::ZERO;
  499. }
  500. Vector3 RigidBody::GetAngularFactor() const
  501. {
  502. if (body_)
  503. return ToVector3(body_->getAngularFactor());
  504. else
  505. return Vector3::ZERO;
  506. }
  507. float RigidBody::GetAngularRestThreshold() const
  508. {
  509. if (body_)
  510. return body_->getAngularSleepingThreshold();
  511. else
  512. return 0.0f;
  513. }
  514. float RigidBody::GetAngularDamping() const
  515. {
  516. if (body_)
  517. return body_->getAngularDamping();
  518. else
  519. return 0.0f;
  520. }
  521. float RigidBody::GetFriction() const
  522. {
  523. if (body_)
  524. return body_->getFriction();
  525. else
  526. return 0.0f;
  527. }
  528. float RigidBody::GetRestitution() const
  529. {
  530. if (body_)
  531. return body_->getRestitution();
  532. else
  533. return 0.0f;
  534. }
  535. float RigidBody::GetCcdRadius() const
  536. {
  537. if (body_)
  538. return body_->getCcdSweptSphereRadius();
  539. else
  540. return 0.0f;
  541. }
  542. float RigidBody::GetCcdMotionThreshold() const
  543. {
  544. if (body_)
  545. return body_->getCcdMotionThreshold();
  546. else
  547. return 0.0f;
  548. }
  549. bool RigidBody::GetUseGravity() const
  550. {
  551. if (body_)
  552. return (body_->getFlags() & BT_DISABLE_WORLD_GRAVITY) == 0;
  553. else
  554. return true;
  555. }
  556. bool RigidBody::IsActive() const
  557. {
  558. if (body_)
  559. return body_->isActive();
  560. else
  561. return false;
  562. }
  563. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  564. {
  565. physicsWorld_->SetApplyingTransforms(true);
  566. // Apply transform to the SmoothedTransform component instead of node transform if available
  567. SmoothedTransform* transform = 0;
  568. if (hasSmoothedTransform_)
  569. transform = GetComponent<SmoothedTransform>();
  570. if (transform)
  571. {
  572. transform->SetTargetWorldPosition(newWorldPosition);
  573. transform->SetTargetWorldRotation(newWorldRotation);
  574. lastPosition_ = newWorldPosition;
  575. lastRotation_ = newWorldRotation;
  576. }
  577. else
  578. {
  579. node_->SetWorldPosition(newWorldPosition);
  580. node_->SetWorldRotation(newWorldRotation);
  581. lastPosition_ = node_->GetWorldPosition();
  582. lastRotation_ = node_->GetWorldRotation();
  583. }
  584. physicsWorld_->SetApplyingTransforms(false);
  585. }
  586. void RigidBody::UpdateMass()
  587. {
  588. if (body_)
  589. {
  590. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  591. if (mass_ > 0.0f)
  592. compoundShape_->calculateLocalInertia(mass_, localInertia);
  593. body_->setMassProps(mass_, localInertia);
  594. body_->updateInertiaTensor();
  595. }
  596. }
  597. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  598. {
  599. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  600. MemoryBuffer buf(value);
  601. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  602. }
  603. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  604. {
  605. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  606. attrBuffer_.Clear();
  607. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  608. return attrBuffer_.GetBuffer();
  609. }
  610. void RigidBody::AddConstraint(Constraint* constraint)
  611. {
  612. constraints_.Push(constraint);
  613. }
  614. void RigidBody::RemoveConstraint(Constraint* constraint)
  615. {
  616. constraints_.Erase(constraints_.Find(constraint));
  617. }
  618. void RigidBody::ReleaseBody()
  619. {
  620. if (body_)
  621. {
  622. // Release all constraints which refer to this body
  623. // Make a copy for iteration
  624. PODVector<Constraint*> constraints = constraints_;
  625. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  626. (*i)->ReleaseConstraint();
  627. if (physicsWorld_)
  628. {
  629. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  630. world->removeRigidBody(body_);
  631. }
  632. delete body_;
  633. body_ = 0;
  634. }
  635. }
  636. void RigidBody::OnMarkedDirty(Node* node)
  637. {
  638. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  639. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  640. // states; rather follow the SmoothedTransform target transform directly
  641. if ((!physicsWorld_ || !physicsWorld_->IsApplyingTransforms()) && !hasSmoothedTransform_)
  642. {
  643. // Physics operations are not safe from worker threads
  644. Scene* scene = GetScene();
  645. if (scene && scene->IsThreadedUpdate())
  646. {
  647. scene->DelayedMarkedDirty(this);
  648. return;
  649. }
  650. // Check if transform has changed from the last one set in ApplyWorldTransform()
  651. Vector3 newPosition = node_->GetWorldPosition();
  652. Quaternion newRotation = node_->GetWorldRotation();
  653. if (!newPosition.Equals(lastPosition_))
  654. {
  655. lastPosition_ = newPosition;
  656. SetPosition(newPosition);
  657. }
  658. if (!newRotation.Equals(lastRotation_))
  659. {
  660. lastRotation_ = newRotation;
  661. SetRotation(newRotation);
  662. }
  663. }
  664. }
  665. void RigidBody::OnNodeSet(Node* node)
  666. {
  667. if (node)
  668. {
  669. Scene* scene = GetScene();
  670. if (scene)
  671. {
  672. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  673. if (physicsWorld_)
  674. physicsWorld_->AddRigidBody(this);
  675. else
  676. LOGERROR("No physics world component in scene, can not create rigid body");
  677. AddBodyToWorld();
  678. }
  679. node->AddListener(this);
  680. }
  681. }
  682. void RigidBody::AddBodyToWorld()
  683. {
  684. if (!physicsWorld_)
  685. return;
  686. PROFILE(AddBodyToWorld);
  687. if (mass_ < 0.0f)
  688. mass_ = 0.0f;
  689. bool massUpdated = false;
  690. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  691. if (body_)
  692. world->removeRigidBody(body_);
  693. else
  694. {
  695. // Correct inertia will be calculated below
  696. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  697. body_ = new btRigidBody(mass_, this, compoundShape_, localInertia);
  698. body_->setUserPointer(this);
  699. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  700. // If it exists, subscribe to its change events
  701. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  702. if (transform)
  703. {
  704. hasSmoothedTransform_ = true;
  705. SubscribeToEvent(transform, E_TARGETPOSITION, HANDLER(RigidBody, HandleTargetPosition));
  706. SubscribeToEvent(transform, E_TARGETROTATION, HANDLER(RigidBody, HandleTargetRotation));
  707. }
  708. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  709. // Note: NotifyRigidBody() will cause mass to be updated
  710. PODVector<CollisionShape*> shapes;
  711. node_->GetComponents<CollisionShape>(shapes);
  712. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  713. {
  714. massUpdated = true;
  715. (*i)->NotifyRigidBody();
  716. }
  717. // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
  718. // to create themselves now
  719. PODVector<Constraint*> constraints;
  720. node_->GetComponents<Constraint>(constraints);
  721. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  722. (*i)->CreateConstraint();
  723. }
  724. if (!massUpdated)
  725. UpdateMass();
  726. int flags = body_->getCollisionFlags();
  727. if (phantom_)
  728. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  729. else
  730. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  731. if (kinematic_)
  732. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  733. else
  734. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  735. body_->setCollisionFlags(flags);
  736. world->addRigidBody(body_, collisionLayer_, collisionMask_);
  737. if (mass_ > 0.0f)
  738. Activate();
  739. else
  740. {
  741. SetLinearVelocity(Vector3::ZERO);
  742. SetAngularVelocity(Vector3::ZERO);
  743. }
  744. }
  745. void RigidBody::HandleTargetPosition(StringHash eventType, VariantMap& eventData)
  746. {
  747. // Copy the smoothing target position to the rigid body
  748. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  749. SetPosition(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldPosition());
  750. }
  751. void RigidBody::HandleTargetRotation(StringHash eventType, VariantMap& eventData)
  752. {
  753. // Copy the smoothing target rotation to the rigid body
  754. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  755. SetRotation(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldRotation());
  756. }