RigidBody.cpp 27 KB

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