RigidBody.cpp 27 KB

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