RigidBody.cpp 27 KB

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