RigidBody.cpp 26 KB

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