RigidBody.cpp 23 KB

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