RigidBody.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "PhysicsUtils.h"
  29. #include "PhysicsWorld.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "ResourceEvents.h"
  33. #include "RigidBody.h"
  34. #include "Scene.h"
  35. #include "SceneEvents.h"
  36. #include "SmoothedTransform.h"
  37. #include "XMLElement.h"
  38. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  39. #include <BulletDynamics/Dynamics/btRigidBody.h>
  40. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  41. static const float DEFAULT_MASS = 0.0f;
  42. static const float DEFAULT_FRICTION = 0.5f;
  43. static const float DEFAULT_RESTITUTION = 0.0f;
  44. static const float DEFAULT_LINEAR_REST_THRESHOLD = 0.8f;
  45. static const float DEFAULT_ANGULAR_REST_THRESHOLD = 1.0f;
  46. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  47. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  48. static const String collisionEventModeNames[] =
  49. {
  50. "Never",
  51. "When Active",
  52. "Always",
  53. ""
  54. };
  55. OBJECTTYPESTATIC(RigidBody);
  56. RigidBody::RigidBody(Context* context) :
  57. Component(context),
  58. body_(0),
  59. compoundShape_(0),
  60. mass_(DEFAULT_MASS),
  61. collisionLayer_(DEFAULT_COLLISION_LAYER),
  62. collisionMask_(DEFAULT_COLLISION_MASK),
  63. collisionEventMode_(COLLISION_ACTIVE),
  64. lastPosition_(Vector3::ZERO),
  65. lastRotation_(Quaternion::IDENTITY),
  66. kinematic_(false),
  67. phantom_(false),
  68. inSetTransform_(false),
  69. hasSmoothedTransform_(false),
  70. dirty_(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. dirty_ = true;
  112. }
  113. void RigidBody::ApplyAttributes()
  114. {
  115. if (dirty_)
  116. {
  117. AddBodyToWorld();
  118. dirty_ = false;
  119. }
  120. }
  121. void RigidBody::getWorldTransform(btTransform &worldTrans) const
  122. {
  123. lastPosition_ = node_->GetWorldPosition();
  124. lastRotation_ = node_->GetWorldRotation();
  125. worldTrans.setOrigin(ToBtVector3(lastPosition_));
  126. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  127. }
  128. void RigidBody::setWorldTransform(const btTransform &worldTrans)
  129. {
  130. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin());
  131. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  132. RigidBody* parentRigidBody = 0;
  133. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  134. // In that case store it to PhysicsWorld for delayed assignment
  135. Node* parent = node_->GetParent();
  136. if (parent && parent != GetScene())
  137. parentRigidBody = parent->GetComponent<RigidBody>();
  138. if (!parentRigidBody)
  139. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  140. else
  141. {
  142. DelayedWorldTransform delayed;
  143. delayed.rigidBody_ = this;
  144. delayed.parentRigidBody_ = parentRigidBody;
  145. delayed.worldPosition_ = newWorldPosition;
  146. delayed.worldRotation_ = newWorldRotation;
  147. physicsWorld_->AddDelayedWorldTransform(delayed);
  148. }
  149. MarkNetworkUpdate();
  150. }
  151. void RigidBody::SetMass(float mass)
  152. {
  153. mass = Max(mass, 0.0f);
  154. if (mass != mass_)
  155. {
  156. mass_ = mass;
  157. AddBodyToWorld();
  158. MarkNetworkUpdate();
  159. }
  160. }
  161. void RigidBody::SetPosition(Vector3 position)
  162. {
  163. if (body_)
  164. {
  165. btTransform& worldTrans = body_->getWorldTransform();
  166. worldTrans.setOrigin(ToBtVector3(position));
  167. // When forcing the physics position, set also interpolated position so that there is no jitter
  168. btTransform interpTrans = body_->getInterpolationWorldTransform();
  169. interpTrans.setOrigin(worldTrans.getOrigin());
  170. body_->setInterpolationWorldTransform(interpTrans);
  171. MarkNetworkUpdate();
  172. }
  173. }
  174. void RigidBody::SetRotation(Quaternion rotation)
  175. {
  176. if (body_)
  177. {
  178. btTransform& worldTrans = body_->getWorldTransform();
  179. worldTrans.setRotation(ToBtQuaternion(rotation));
  180. // When forcing the physics position, set also interpolated position so that there is no jitter
  181. btTransform interpTrans = body_->getInterpolationWorldTransform();
  182. interpTrans.setRotation(worldTrans.getRotation());
  183. body_->setInterpolationWorldTransform(interpTrans);
  184. MarkNetworkUpdate();
  185. }
  186. }
  187. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  188. {
  189. if (body_)
  190. {
  191. btTransform& worldTrans = body_->getWorldTransform();
  192. worldTrans.setOrigin(ToBtVector3(position));
  193. worldTrans.setRotation(ToBtQuaternion(rotation));
  194. // When forcing the physics position, set also interpolated position so that there is no jitter
  195. btTransform interpTrans = body_->getInterpolationWorldTransform();
  196. interpTrans.setOrigin(worldTrans.getOrigin());
  197. interpTrans.setRotation(worldTrans.getRotation());
  198. body_->setInterpolationWorldTransform(interpTrans);
  199. MarkNetworkUpdate();
  200. }
  201. }
  202. void RigidBody::SetLinearVelocity(Vector3 velocity)
  203. {
  204. if (body_)
  205. {
  206. body_->setLinearVelocity(ToBtVector3(velocity));
  207. if (velocity != Vector3::ZERO)
  208. Activate();
  209. MarkNetworkUpdate();
  210. }
  211. }
  212. void RigidBody::SetLinearFactor(Vector3 factor)
  213. {
  214. if (body_)
  215. {
  216. body_->setLinearFactor(ToBtVector3(factor));
  217. MarkNetworkUpdate();
  218. }
  219. }
  220. void RigidBody::SetLinearRestThreshold(float threshold)
  221. {
  222. if (body_)
  223. {
  224. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  225. MarkNetworkUpdate();
  226. }
  227. }
  228. void RigidBody::SetLinearDamping(float damping)
  229. {
  230. if (body_)
  231. {
  232. body_->setDamping(damping, body_->getAngularDamping());
  233. MarkNetworkUpdate();
  234. }
  235. }
  236. void RigidBody::SetAngularVelocity(Vector3 velocity)
  237. {
  238. if (body_)
  239. {
  240. body_->setAngularVelocity(ToBtVector3(velocity));
  241. if (velocity != Vector3::ZERO)
  242. Activate();
  243. MarkNetworkUpdate();
  244. }
  245. }
  246. void RigidBody::SetAngularFactor(Vector3 factor)
  247. {
  248. if (body_)
  249. {
  250. body_->setAngularFactor(ToBtVector3(factor));
  251. MarkNetworkUpdate();
  252. }
  253. }
  254. void RigidBody::SetAngularRestThreshold(float threshold)
  255. {
  256. if (body_)
  257. {
  258. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  259. MarkNetworkUpdate();
  260. }
  261. }
  262. void RigidBody::SetAngularDamping(float damping)
  263. {
  264. if (body_)
  265. {
  266. body_->setDamping(body_->getLinearDamping(), damping);
  267. MarkNetworkUpdate();
  268. }
  269. }
  270. void RigidBody::SetFriction(float friction)
  271. {
  272. if (body_)
  273. {
  274. body_->setFriction(friction);
  275. MarkNetworkUpdate();
  276. }
  277. }
  278. void RigidBody::SetRestitution(float restitution)
  279. {
  280. if (body_)
  281. {
  282. body_->setRestitution(restitution);
  283. MarkNetworkUpdate();
  284. }
  285. }
  286. void RigidBody::SetCcdRadius(float radius)
  287. {
  288. radius = Max(radius, 0.0f);
  289. if (body_)
  290. {
  291. body_->setCcdSweptSphereRadius(radius);
  292. MarkNetworkUpdate();
  293. }
  294. }
  295. void RigidBody::SetCcdMotionThreshold(float threshold)
  296. {
  297. threshold = Max(threshold, 0.0f);
  298. if (body_)
  299. {
  300. body_->setCcdMotionThreshold(threshold);
  301. MarkNetworkUpdate();
  302. }
  303. }
  304. void RigidBody::SetUseGravity(bool enable)
  305. {
  306. if (physicsWorld_ && body_ && enable != GetUseGravity())
  307. {
  308. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  309. int flags = body_->getFlags();
  310. if (enable)
  311. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  312. else
  313. flags |= BT_DISABLE_WORLD_GRAVITY;
  314. body_->setFlags(flags);
  315. if (enable)
  316. body_->setGravity(world->getGravity());
  317. else
  318. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  319. MarkNetworkUpdate();
  320. }
  321. }
  322. void RigidBody::SetKinematic(bool enable)
  323. {
  324. if (enable != kinematic_)
  325. {
  326. kinematic_ = enable;
  327. AddBodyToWorld();
  328. MarkNetworkUpdate();
  329. }
  330. }
  331. void RigidBody::SetPhantom(bool enable)
  332. {
  333. if (enable != phantom_)
  334. {
  335. phantom_ = enable;
  336. AddBodyToWorld();
  337. MarkNetworkUpdate();
  338. }
  339. }
  340. void RigidBody::SetCollisionLayer(unsigned layer)
  341. {
  342. if (layer != collisionLayer_)
  343. {
  344. collisionLayer_ = layer;
  345. AddBodyToWorld();
  346. MarkNetworkUpdate();
  347. }
  348. }
  349. void RigidBody::SetCollisionMask(unsigned mask)
  350. {
  351. if (mask != collisionMask_)
  352. {
  353. collisionMask_ = mask;
  354. AddBodyToWorld();
  355. MarkNetworkUpdate();
  356. }
  357. }
  358. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  359. {
  360. if (layer != collisionLayer_ || mask != collisionMask_)
  361. {
  362. collisionLayer_ = layer;
  363. collisionMask_ = mask;
  364. AddBodyToWorld();
  365. MarkNetworkUpdate();
  366. }
  367. }
  368. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  369. {
  370. collisionEventMode_ = mode;
  371. MarkNetworkUpdate();
  372. }
  373. void RigidBody::ApplyForce(const Vector3& force)
  374. {
  375. if (body_ && force != Vector3::ZERO)
  376. {
  377. Activate();
  378. body_->applyCentralForce(ToBtVector3(force));
  379. }
  380. }
  381. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  382. {
  383. if (body_ && force != Vector3::ZERO)
  384. {
  385. Activate();
  386. body_->applyForce(ToBtVector3(force), ToBtVector3(position));
  387. }
  388. }
  389. void RigidBody::ApplyTorque(const Vector3& torque)
  390. {
  391. if (body_ && torque != Vector3::ZERO)
  392. {
  393. Activate();
  394. body_->applyTorque(ToBtVector3(torque));
  395. }
  396. }
  397. void RigidBody::ApplyImpulse(const Vector3& impulse)
  398. {
  399. if (body_ && impulse != Vector3::ZERO)
  400. {
  401. Activate();
  402. body_->applyCentralImpulse(ToBtVector3(impulse));
  403. }
  404. }
  405. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  406. {
  407. if (body_ && impulse != Vector3::ZERO)
  408. {
  409. Activate();
  410. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position));
  411. }
  412. }
  413. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  414. {
  415. if (body_ && torque != Vector3::ZERO)
  416. {
  417. Activate();
  418. body_->applyTorqueImpulse(ToBtVector3(torque));
  419. }
  420. }
  421. void RigidBody::ResetForces()
  422. {
  423. if (body_)
  424. body_->clearForces();
  425. }
  426. void RigidBody::Activate()
  427. {
  428. if (body_ && !body_->isActive())
  429. body_->activate();
  430. }
  431. Vector3 RigidBody::GetPosition() const
  432. {
  433. if (body_)
  434. return ToVector3(body_->getWorldTransform().getOrigin());
  435. else
  436. return Vector3::ZERO;
  437. }
  438. Quaternion RigidBody::GetRotation() const
  439. {
  440. if (body_)
  441. return ToQuaternion(body_->getWorldTransform().getRotation());
  442. else
  443. return Quaternion::IDENTITY;
  444. }
  445. Vector3 RigidBody::GetLinearVelocity() const
  446. {
  447. if (body_)
  448. return ToVector3(body_->getLinearVelocity());
  449. else
  450. return Vector3::ZERO;
  451. }
  452. Vector3 RigidBody::GetLinearFactor() const
  453. {
  454. if (body_)
  455. return ToVector3(body_->getLinearFactor());
  456. else
  457. return Vector3::ZERO;
  458. }
  459. float RigidBody::GetLinearRestThreshold() const
  460. {
  461. if (body_)
  462. return body_->getLinearSleepingThreshold();
  463. else
  464. return 0.0f;
  465. }
  466. float RigidBody::GetLinearDamping() const
  467. {
  468. if (body_)
  469. return body_->getLinearDamping();
  470. else
  471. return 0.0f;
  472. }
  473. Vector3 RigidBody::GetAngularVelocity() const
  474. {
  475. if (body_)
  476. return ToVector3(body_->getAngularVelocity());
  477. else
  478. return Vector3::ZERO;
  479. }
  480. Vector3 RigidBody::GetAngularFactor() const
  481. {
  482. if (body_)
  483. return ToVector3(body_->getAngularFactor());
  484. else
  485. return Vector3::ZERO;
  486. }
  487. float RigidBody::GetAngularRestThreshold() const
  488. {
  489. if (body_)
  490. return body_->getAngularSleepingThreshold();
  491. else
  492. return 0.0f;
  493. }
  494. float RigidBody::GetAngularDamping() const
  495. {
  496. if (body_)
  497. return body_->getAngularDamping();
  498. else
  499. return 0.0f;
  500. }
  501. float RigidBody::GetFriction() const
  502. {
  503. if (body_)
  504. return body_->getFriction();
  505. else
  506. return 0.0f;
  507. }
  508. float RigidBody::GetRestitution() const
  509. {
  510. if (body_)
  511. return body_->getRestitution();
  512. else
  513. return 0.0f;
  514. }
  515. float RigidBody::GetCcdRadius() const
  516. {
  517. if (body_)
  518. return body_->getCcdSweptSphereRadius();
  519. else
  520. return 0.0f;
  521. }
  522. float RigidBody::GetCcdMotionThreshold() const
  523. {
  524. if (body_)
  525. return body_->getCcdMotionThreshold();
  526. else
  527. return 0.0f;
  528. }
  529. bool RigidBody::GetUseGravity() const
  530. {
  531. if (body_)
  532. return (body_->getFlags() & BT_DISABLE_WORLD_GRAVITY) == 0;
  533. else
  534. return true;
  535. }
  536. bool RigidBody::IsActive() const
  537. {
  538. if (body_)
  539. return body_->isActive();
  540. else
  541. return false;
  542. }
  543. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  544. {
  545. inSetTransform_ = true;
  546. // Apply transform to the SmoothedTransform component instead of node transform if available
  547. SmoothedTransform* transform = 0;
  548. if (hasSmoothedTransform_)
  549. transform = GetComponent<SmoothedTransform>();
  550. if (transform)
  551. {
  552. transform->SetTargetWorldPosition(newWorldPosition);
  553. transform->SetTargetWorldRotation(newWorldRotation);
  554. lastPosition_ = newWorldPosition;
  555. lastRotation_ = newWorldRotation;
  556. }
  557. else
  558. {
  559. node_->SetWorldPosition(newWorldPosition);
  560. node_->SetWorldRotation(newWorldRotation);
  561. lastPosition_ = node_->GetWorldPosition();
  562. lastRotation_ = node_->GetWorldRotation();
  563. }
  564. inSetTransform_ = false;
  565. }
  566. void RigidBody::UpdateMass()
  567. {
  568. if (body_)
  569. {
  570. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  571. if (mass_ > 0.0f)
  572. compoundShape_->calculateLocalInertia(mass_, localInertia);
  573. body_->setMassProps(mass_, localInertia);
  574. }
  575. }
  576. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  577. {
  578. if (debug && physicsWorld_ && body_)
  579. {
  580. physicsWorld_->SetDebugRenderer(debug);
  581. physicsWorld_->SetDebugDepthTest(depthTest);
  582. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  583. world->debugDrawObject(body_->getWorldTransform(), compoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  584. btVector3(0.0f, 1.0f, 0.0f));
  585. physicsWorld_->SetDebugRenderer(0);
  586. }
  587. }
  588. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  589. {
  590. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  591. MemoryBuffer buf(value);
  592. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  593. }
  594. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  595. {
  596. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  597. attrBuffer_.Clear();
  598. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  599. return attrBuffer_.GetBuffer();
  600. }
  601. void RigidBody::OnMarkedDirty(Node* node)
  602. {
  603. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  604. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  605. // states; rather follow the SmoothedTransform target transform directly
  606. if (!inSetTransform_ && !hasSmoothedTransform_)
  607. {
  608. // Physics operations are not safe from worker threads
  609. Scene* scene = GetScene();
  610. if (scene && scene->IsThreadedUpdate())
  611. {
  612. scene->DelayedMarkedDirty(this);
  613. return;
  614. }
  615. // Check if transform has changed from the last one set in ApplyWorldTransform()
  616. Vector3 newPosition = node_->GetWorldPosition();
  617. Quaternion newRotation = node_->GetWorldRotation();
  618. if (!newPosition.Equals(lastPosition_))
  619. {
  620. lastPosition_ = newPosition;
  621. SetPosition(newPosition);
  622. }
  623. if (!newRotation.Equals(lastRotation_))
  624. {
  625. lastRotation_ = newRotation;
  626. SetRotation(newRotation);
  627. }
  628. }
  629. }
  630. void RigidBody::OnNodeSet(Node* node)
  631. {
  632. if (node)
  633. {
  634. Scene* scene = GetScene();
  635. if (scene)
  636. {
  637. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  638. if (physicsWorld_)
  639. physicsWorld_->AddRigidBody(this);
  640. else
  641. LOGERROR("Null physics world, can not create rigid body");
  642. AddBodyToWorld();
  643. }
  644. node->AddListener(this);
  645. }
  646. }
  647. void RigidBody::AddBodyToWorld()
  648. {
  649. if (!physicsWorld_)
  650. return;
  651. PROFILE(AddBodyToWorld);
  652. if (mass_ < 0.0f)
  653. mass_ = 0.0f;
  654. bool massUpdated = false;
  655. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  656. if (body_)
  657. world->removeRigidBody(body_);
  658. else
  659. {
  660. // Correct inertia will be calculated below
  661. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  662. body_ = new btRigidBody(mass_, this, compoundShape_, localInertia);
  663. body_->setUserPointer(this);
  664. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  665. // If it exists, subscribe to its change events
  666. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  667. if (transform)
  668. {
  669. hasSmoothedTransform_ = true;
  670. SubscribeToEvent(transform, E_TARGETPOSITION, HANDLER(RigidBody, HandleTargetPosition));
  671. SubscribeToEvent(transform, E_TARGETROTATION, HANDLER(RigidBody, HandleTargetRotation));
  672. }
  673. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  674. // Note: NotifyRigidBody() will cause mass to be updated
  675. PODVector<CollisionShape*> shapes;
  676. node_->GetDerivedComponents<CollisionShape>(shapes);
  677. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  678. {
  679. massUpdated = true;
  680. (*i)->NotifyRigidBody();
  681. }
  682. }
  683. if (!massUpdated)
  684. UpdateMass();
  685. int flags = body_->getCollisionFlags();
  686. if (phantom_)
  687. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  688. else
  689. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  690. if (kinematic_)
  691. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  692. else
  693. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  694. body_->setCollisionFlags(flags);
  695. world->addRigidBody(body_, collisionLayer_, collisionMask_);
  696. if (mass_ > 0.0f)
  697. Activate();
  698. else
  699. {
  700. SetLinearVelocity(Vector3::ZERO);
  701. SetAngularVelocity(Vector3::ZERO);
  702. }
  703. }
  704. void RigidBody::ReleaseBody()
  705. {
  706. if (body_)
  707. {
  708. if (physicsWorld_)
  709. {
  710. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  711. world->removeRigidBody(body_);
  712. }
  713. delete body_;
  714. body_ = 0;
  715. }
  716. }
  717. void RigidBody::HandleTargetPosition(StringHash eventType, VariantMap& eventData)
  718. {
  719. // Copy the smoothing target position to the rigid body
  720. if (!inSetTransform_)
  721. SetPosition(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldPosition());
  722. }
  723. void RigidBody::HandleTargetRotation(StringHash eventType, VariantMap& eventData)
  724. {
  725. // Copy the smoothing target rotation to the rigid body
  726. if (!inSetTransform_)
  727. SetRotation(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldRotation());
  728. }