RigidBody.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Physics/CollisionShape.h"
  28. #include "../Physics/Constraint.h"
  29. #include "../Physics/PhysicsUtils.h"
  30. #include "../Physics/PhysicsWorld.h"
  31. #include "../Physics/RigidBody.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Resource/ResourceEvents.h"
  34. #include "../Scene/Scene.h"
  35. #include "../Scene/SceneEvents.h"
  36. #include "../Scene/SmoothedTransform.h"
  37. #include <Bullet/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  38. #include <Bullet/BulletDynamics/Dynamics/btRigidBody.h>
  39. #include <Bullet/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_ROLLING_FRICTION = 0.0f;
  46. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  47. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  48. static const char* collisionEventModeNames[] =
  49. {
  50. "Never",
  51. "When Active",
  52. "Always",
  53. 0
  54. };
  55. extern const char* PHYSICS_CATEGORY;
  56. RigidBody::RigidBody(Context* context) :
  57. Component(context),
  58. body_(0),
  59. compoundShape_(0),
  60. shiftedCompoundShape_(0),
  61. gravityOverride_(Vector3::ZERO),
  62. centerOfMass_(Vector3::ZERO),
  63. mass_(DEFAULT_MASS),
  64. collisionLayer_(DEFAULT_COLLISION_LAYER),
  65. collisionMask_(DEFAULT_COLLISION_MASK),
  66. collisionEventMode_(COLLISION_ACTIVE),
  67. lastPosition_(Vector3::ZERO),
  68. lastRotation_(Quaternion::IDENTITY),
  69. kinematic_(false),
  70. trigger_(false),
  71. useGravity_(true),
  72. readdBody_(false),
  73. inWorld_(false),
  74. enableMassUpdate_(true),
  75. hasSimulated_(false)
  76. {
  77. compoundShape_ = new btCompoundShape();
  78. shiftedCompoundShape_ = new btCompoundShape();
  79. }
  80. RigidBody::~RigidBody()
  81. {
  82. ReleaseBody();
  83. if (physicsWorld_)
  84. physicsWorld_->RemoveRigidBody(this);
  85. delete compoundShape_;
  86. compoundShape_ = 0;
  87. delete shiftedCompoundShape_;
  88. shiftedCompoundShape_ = 0;
  89. }
  90. void RigidBody::RegisterObject(Context* context)
  91. {
  92. context->RegisterFactory<RigidBody>(PHYSICS_CATEGORY);
  93. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  94. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Physics Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE | AM_NOEDIT);
  95. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Physics Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE | AM_NOEDIT);
  96. URHO3D_ATTRIBUTE("Mass", float, mass_, DEFAULT_MASS, AM_DEFAULT);
  97. URHO3D_ACCESSOR_ATTRIBUTE("Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  98. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Anisotropic Friction", GetAnisotropicFriction, SetAnisotropicFriction, Vector3, Vector3::ONE,
  99. AM_DEFAULT);
  100. URHO3D_ACCESSOR_ATTRIBUTE("Rolling Friction", GetRollingFriction, SetRollingFriction, float, DEFAULT_ROLLING_FRICTION, AM_DEFAULT);
  101. URHO3D_ACCESSOR_ATTRIBUTE("Restitution", GetRestitution, SetRestitution, float, DEFAULT_RESTITUTION, AM_DEFAULT);
  102. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector3, Vector3::ZERO,
  103. AM_DEFAULT | AM_LATESTDATA);
  104. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Angular Velocity", GetAngularVelocity, SetAngularVelocity, Vector3, Vector3::ZERO, AM_FILE);
  105. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Linear Factor", GetLinearFactor, SetLinearFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  106. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Angular Factor", GetAngularFactor, SetAngularFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  107. URHO3D_ACCESSOR_ATTRIBUTE("Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  108. URHO3D_ACCESSOR_ATTRIBUTE("Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  109. URHO3D_ACCESSOR_ATTRIBUTE("Linear Rest Threshold", GetLinearRestThreshold, SetLinearRestThreshold, float, 0.8f, AM_DEFAULT);
  110. URHO3D_ACCESSOR_ATTRIBUTE("Angular Rest Threshold", GetAngularRestThreshold, SetAngularRestThreshold, float, 1.0f, AM_DEFAULT);
  111. URHO3D_ATTRIBUTE("Collision Layer", int, collisionLayer_, DEFAULT_COLLISION_LAYER, AM_DEFAULT);
  112. URHO3D_ATTRIBUTE("Collision Mask", int, collisionMask_, DEFAULT_COLLISION_MASK, AM_DEFAULT);
  113. URHO3D_ACCESSOR_ATTRIBUTE("Contact Threshold", GetContactProcessingThreshold, SetContactProcessingThreshold, float, BT_LARGE_FLOAT,
  114. AM_DEFAULT);
  115. URHO3D_ACCESSOR_ATTRIBUTE("CCD Radius", GetCcdRadius, SetCcdRadius, float, 0.0f, AM_DEFAULT);
  116. URHO3D_ACCESSOR_ATTRIBUTE("CCD Motion Threshold", GetCcdMotionThreshold, SetCcdMotionThreshold, float, 0.0f, AM_DEFAULT);
  117. URHO3D_ACCESSOR_ATTRIBUTE("Network Angular Velocity", GetNetAngularVelocityAttr, SetNetAngularVelocityAttr, PODVector<unsigned char>,
  118. Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  119. URHO3D_ENUM_ATTRIBUTE("Collision Event Mode", collisionEventMode_, collisionEventModeNames, COLLISION_ACTIVE, AM_DEFAULT);
  120. URHO3D_ACCESSOR_ATTRIBUTE("Use Gravity", GetUseGravity, SetUseGravity, bool, true, AM_DEFAULT);
  121. URHO3D_ATTRIBUTE("Is Kinematic", bool, kinematic_, false, AM_DEFAULT);
  122. URHO3D_ATTRIBUTE("Is Trigger", bool, trigger_, false, AM_DEFAULT);
  123. URHO3D_ACCESSOR_ATTRIBUTE("Gravity Override", GetGravityOverride, SetGravityOverride, Vector3, Vector3::ZERO, AM_DEFAULT);
  124. }
  125. void RigidBody::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  126. {
  127. Serializable::OnSetAttribute(attr, src);
  128. // Change of any non-accessor attribute requires the rigid body to be re-added to the physics world
  129. if (!attr.accessor_)
  130. readdBody_ = true;
  131. }
  132. void RigidBody::ApplyAttributes()
  133. {
  134. if (readdBody_)
  135. AddBodyToWorld();
  136. }
  137. void RigidBody::OnSetEnabled()
  138. {
  139. bool enabled = IsEnabledEffective();
  140. if (enabled && !inWorld_)
  141. AddBodyToWorld();
  142. else if (!enabled && inWorld_)
  143. RemoveBodyFromWorld();
  144. }
  145. void RigidBody::getWorldTransform(btTransform& worldTrans) const
  146. {
  147. // We may be in a pathological state where a RigidBody exists without a scene node when this callback is fired,
  148. // so check to be sure
  149. if (node_)
  150. {
  151. lastPosition_ = node_->GetWorldPosition();
  152. lastRotation_ = node_->GetWorldRotation();
  153. worldTrans.setOrigin(ToBtVector3(lastPosition_ + lastRotation_ * centerOfMass_));
  154. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  155. }
  156. hasSimulated_ = true;
  157. }
  158. void RigidBody::setWorldTransform(const btTransform& worldTrans)
  159. {
  160. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  161. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin()) - newWorldRotation * centerOfMass_;
  162. RigidBody* parentRigidBody = 0;
  163. // It is possible that the RigidBody component has been kept alive via a shared pointer,
  164. // while its scene node has already been destroyed
  165. if (node_)
  166. {
  167. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  168. // In that case store it to PhysicsWorld for delayed assignment
  169. Node* parent = node_->GetParent();
  170. if (parent != GetScene() && parent)
  171. parentRigidBody = parent->GetComponent<RigidBody>();
  172. if (!parentRigidBody)
  173. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  174. else
  175. {
  176. DelayedWorldTransform delayed;
  177. delayed.rigidBody_ = this;
  178. delayed.parentRigidBody_ = parentRigidBody;
  179. delayed.worldPosition_ = newWorldPosition;
  180. delayed.worldRotation_ = newWorldRotation;
  181. physicsWorld_->AddDelayedWorldTransform(delayed);
  182. }
  183. MarkNetworkUpdate();
  184. }
  185. hasSimulated_ = true;
  186. }
  187. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  188. {
  189. if (debug && physicsWorld_ && body_ && IsEnabledEffective())
  190. {
  191. physicsWorld_->SetDebugRenderer(debug);
  192. physicsWorld_->SetDebugDepthTest(depthTest);
  193. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  194. world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  195. btVector3(0.0f, 1.0f, 0.0f));
  196. physicsWorld_->SetDebugRenderer(0);
  197. }
  198. }
  199. void RigidBody::SetMass(float mass)
  200. {
  201. mass = Max(mass, 0.0f);
  202. if (mass != mass_)
  203. {
  204. mass_ = mass;
  205. AddBodyToWorld();
  206. MarkNetworkUpdate();
  207. }
  208. }
  209. void RigidBody::SetPosition(const Vector3& position)
  210. {
  211. if (body_)
  212. {
  213. btTransform& worldTrans = body_->getWorldTransform();
  214. worldTrans.setOrigin(ToBtVector3(position + ToQuaternion(worldTrans.getRotation()) * centerOfMass_));
  215. // When forcing the physics position, set also interpolated position so that there is no jitter
  216. // When not inside the simulation loop, this may lead to erratic movement of parented rigidbodies
  217. // so skip in that case. Exception made before first simulation tick so that interpolation position
  218. // of e.g. instantiated prefabs will be correct from the start
  219. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  220. {
  221. btTransform interpTrans = body_->getInterpolationWorldTransform();
  222. interpTrans.setOrigin(worldTrans.getOrigin());
  223. body_->setInterpolationWorldTransform(interpTrans);
  224. }
  225. Activate();
  226. MarkNetworkUpdate();
  227. }
  228. }
  229. void RigidBody::SetRotation(const Quaternion& rotation)
  230. {
  231. if (body_)
  232. {
  233. Vector3 oldPosition = GetPosition();
  234. btTransform& worldTrans = body_->getWorldTransform();
  235. worldTrans.setRotation(ToBtQuaternion(rotation));
  236. if (!centerOfMass_.Equals(Vector3::ZERO))
  237. worldTrans.setOrigin(ToBtVector3(oldPosition + rotation * centerOfMass_));
  238. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  239. {
  240. btTransform interpTrans = body_->getInterpolationWorldTransform();
  241. interpTrans.setRotation(worldTrans.getRotation());
  242. if (!centerOfMass_.Equals(Vector3::ZERO))
  243. interpTrans.setOrigin(worldTrans.getOrigin());
  244. body_->setInterpolationWorldTransform(interpTrans);
  245. }
  246. body_->updateInertiaTensor();
  247. Activate();
  248. MarkNetworkUpdate();
  249. }
  250. }
  251. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  252. {
  253. if (body_)
  254. {
  255. btTransform& worldTrans = body_->getWorldTransform();
  256. worldTrans.setRotation(ToBtQuaternion(rotation));
  257. worldTrans.setOrigin(ToBtVector3(position + rotation * centerOfMass_));
  258. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  259. {
  260. btTransform interpTrans = body_->getInterpolationWorldTransform();
  261. interpTrans.setOrigin(worldTrans.getOrigin());
  262. interpTrans.setRotation(worldTrans.getRotation());
  263. body_->setInterpolationWorldTransform(interpTrans);
  264. }
  265. body_->updateInertiaTensor();
  266. Activate();
  267. MarkNetworkUpdate();
  268. }
  269. }
  270. void RigidBody::SetLinearVelocity(const Vector3& velocity)
  271. {
  272. if (body_)
  273. {
  274. body_->setLinearVelocity(ToBtVector3(velocity));
  275. if (velocity != Vector3::ZERO)
  276. Activate();
  277. MarkNetworkUpdate();
  278. }
  279. }
  280. void RigidBody::SetLinearFactor(const Vector3& factor)
  281. {
  282. if (body_)
  283. {
  284. body_->setLinearFactor(ToBtVector3(factor));
  285. MarkNetworkUpdate();
  286. }
  287. }
  288. void RigidBody::SetLinearRestThreshold(float threshold)
  289. {
  290. if (body_)
  291. {
  292. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  293. MarkNetworkUpdate();
  294. }
  295. }
  296. void RigidBody::SetLinearDamping(float damping)
  297. {
  298. if (body_)
  299. {
  300. body_->setDamping(damping, body_->getAngularDamping());
  301. MarkNetworkUpdate();
  302. }
  303. }
  304. void RigidBody::SetAngularVelocity(const Vector3& velocity)
  305. {
  306. if (body_)
  307. {
  308. body_->setAngularVelocity(ToBtVector3(velocity));
  309. if (velocity != Vector3::ZERO)
  310. Activate();
  311. MarkNetworkUpdate();
  312. }
  313. }
  314. void RigidBody::SetAngularFactor(const Vector3& factor)
  315. {
  316. if (body_)
  317. {
  318. body_->setAngularFactor(ToBtVector3(factor));
  319. MarkNetworkUpdate();
  320. }
  321. }
  322. void RigidBody::SetAngularRestThreshold(float threshold)
  323. {
  324. if (body_)
  325. {
  326. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  327. MarkNetworkUpdate();
  328. }
  329. }
  330. void RigidBody::SetAngularDamping(float damping)
  331. {
  332. if (body_)
  333. {
  334. body_->setDamping(body_->getLinearDamping(), damping);
  335. MarkNetworkUpdate();
  336. }
  337. }
  338. void RigidBody::SetFriction(float friction)
  339. {
  340. if (body_)
  341. {
  342. body_->setFriction(friction);
  343. MarkNetworkUpdate();
  344. }
  345. }
  346. void RigidBody::SetAnisotropicFriction(const Vector3& friction)
  347. {
  348. if (body_)
  349. {
  350. body_->setAnisotropicFriction(ToBtVector3(friction));
  351. MarkNetworkUpdate();
  352. }
  353. }
  354. void RigidBody::SetRollingFriction(float friction)
  355. {
  356. if (body_)
  357. {
  358. body_->setRollingFriction(friction);
  359. MarkNetworkUpdate();
  360. }
  361. }
  362. void RigidBody::SetRestitution(float restitution)
  363. {
  364. if (body_)
  365. {
  366. body_->setRestitution(restitution);
  367. MarkNetworkUpdate();
  368. }
  369. }
  370. void RigidBody::SetContactProcessingThreshold(float threshold)
  371. {
  372. if (body_)
  373. {
  374. body_->setContactProcessingThreshold(threshold);
  375. MarkNetworkUpdate();
  376. }
  377. }
  378. void RigidBody::SetCcdRadius(float radius)
  379. {
  380. radius = Max(radius, 0.0f);
  381. if (body_)
  382. {
  383. body_->setCcdSweptSphereRadius(radius);
  384. MarkNetworkUpdate();
  385. }
  386. }
  387. void RigidBody::SetCcdMotionThreshold(float threshold)
  388. {
  389. threshold = Max(threshold, 0.0f);
  390. if (body_)
  391. {
  392. body_->setCcdMotionThreshold(threshold);
  393. MarkNetworkUpdate();
  394. }
  395. }
  396. void RigidBody::SetUseGravity(bool enable)
  397. {
  398. if (enable != useGravity_)
  399. {
  400. useGravity_ = enable;
  401. UpdateGravity();
  402. MarkNetworkUpdate();
  403. }
  404. }
  405. void RigidBody::SetGravityOverride(const Vector3& gravity)
  406. {
  407. if (gravity != gravityOverride_)
  408. {
  409. gravityOverride_ = gravity;
  410. UpdateGravity();
  411. MarkNetworkUpdate();
  412. }
  413. }
  414. void RigidBody::SetKinematic(bool enable)
  415. {
  416. if (enable != kinematic_)
  417. {
  418. kinematic_ = enable;
  419. AddBodyToWorld();
  420. MarkNetworkUpdate();
  421. }
  422. }
  423. void RigidBody::SetTrigger(bool enable)
  424. {
  425. if (enable != trigger_)
  426. {
  427. trigger_ = enable;
  428. AddBodyToWorld();
  429. MarkNetworkUpdate();
  430. }
  431. }
  432. void RigidBody::SetCollisionLayer(unsigned layer)
  433. {
  434. if (layer != collisionLayer_)
  435. {
  436. collisionLayer_ = layer;
  437. AddBodyToWorld();
  438. MarkNetworkUpdate();
  439. }
  440. }
  441. void RigidBody::SetCollisionMask(unsigned mask)
  442. {
  443. if (mask != collisionMask_)
  444. {
  445. collisionMask_ = mask;
  446. AddBodyToWorld();
  447. MarkNetworkUpdate();
  448. }
  449. }
  450. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  451. {
  452. if (layer != collisionLayer_ || mask != collisionMask_)
  453. {
  454. collisionLayer_ = layer;
  455. collisionMask_ = mask;
  456. AddBodyToWorld();
  457. MarkNetworkUpdate();
  458. }
  459. }
  460. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  461. {
  462. collisionEventMode_ = mode;
  463. MarkNetworkUpdate();
  464. }
  465. void RigidBody::ApplyForce(const Vector3& force)
  466. {
  467. if (body_ && force != Vector3::ZERO)
  468. {
  469. Activate();
  470. body_->applyCentralForce(ToBtVector3(force));
  471. }
  472. }
  473. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  474. {
  475. if (body_ && force != Vector3::ZERO)
  476. {
  477. Activate();
  478. body_->applyForce(ToBtVector3(force), ToBtVector3(position - centerOfMass_));
  479. }
  480. }
  481. void RigidBody::ApplyTorque(const Vector3& torque)
  482. {
  483. if (body_ && torque != Vector3::ZERO)
  484. {
  485. Activate();
  486. body_->applyTorque(ToBtVector3(torque));
  487. }
  488. }
  489. void RigidBody::ApplyImpulse(const Vector3& impulse)
  490. {
  491. if (body_ && impulse != Vector3::ZERO)
  492. {
  493. Activate();
  494. body_->applyCentralImpulse(ToBtVector3(impulse));
  495. }
  496. }
  497. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  498. {
  499. if (body_ && impulse != Vector3::ZERO)
  500. {
  501. Activate();
  502. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position - centerOfMass_));
  503. }
  504. }
  505. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  506. {
  507. if (body_ && torque != Vector3::ZERO)
  508. {
  509. Activate();
  510. body_->applyTorqueImpulse(ToBtVector3(torque));
  511. }
  512. }
  513. void RigidBody::ResetForces()
  514. {
  515. if (body_)
  516. body_->clearForces();
  517. }
  518. void RigidBody::Activate()
  519. {
  520. if (body_ && mass_ > 0.0f)
  521. body_->activate(true);
  522. }
  523. void RigidBody::ReAddBodyToWorld()
  524. {
  525. if (body_ && inWorld_)
  526. AddBodyToWorld();
  527. }
  528. void RigidBody::DisableMassUpdate()
  529. {
  530. enableMassUpdate_ = false;
  531. }
  532. void RigidBody::EnableMassUpdate()
  533. {
  534. if (!enableMassUpdate_)
  535. {
  536. enableMassUpdate_ = true;
  537. UpdateMass();
  538. }
  539. }
  540. Vector3 RigidBody::GetPosition() const
  541. {
  542. if (body_)
  543. {
  544. const btTransform& transform = body_->getWorldTransform();
  545. return ToVector3(transform.getOrigin()) - ToQuaternion(transform.getRotation()) * centerOfMass_;
  546. }
  547. else
  548. return Vector3::ZERO;
  549. }
  550. Quaternion RigidBody::GetRotation() const
  551. {
  552. return body_ ? ToQuaternion(body_->getWorldTransform().getRotation()) : Quaternion::IDENTITY;
  553. }
  554. Vector3 RigidBody::GetLinearVelocity() const
  555. {
  556. return body_ ? ToVector3(body_->getLinearVelocity()) : Vector3::ZERO;
  557. }
  558. Vector3 RigidBody::GetLinearFactor() const
  559. {
  560. return body_ ? ToVector3(body_->getLinearFactor()) : Vector3::ZERO;
  561. }
  562. Vector3 RigidBody::GetVelocityAtPoint(const Vector3& position) const
  563. {
  564. return body_ ? ToVector3(body_->getVelocityInLocalPoint(ToBtVector3(position - centerOfMass_))) : Vector3::ZERO;
  565. }
  566. float RigidBody::GetLinearRestThreshold() const
  567. {
  568. return body_ ? body_->getLinearSleepingThreshold() : 0.0f;
  569. }
  570. float RigidBody::GetLinearDamping() const
  571. {
  572. return body_ ? body_->getLinearDamping() : 0.0f;
  573. }
  574. Vector3 RigidBody::GetAngularVelocity() const
  575. {
  576. return body_ ? ToVector3(body_->getAngularVelocity()) : Vector3::ZERO;
  577. }
  578. Vector3 RigidBody::GetAngularFactor() const
  579. {
  580. return body_ ? ToVector3(body_->getAngularFactor()) : Vector3::ZERO;
  581. }
  582. float RigidBody::GetAngularRestThreshold() const
  583. {
  584. return body_ ? body_->getAngularSleepingThreshold() : 0.0f;
  585. }
  586. float RigidBody::GetAngularDamping() const
  587. {
  588. return body_ ? body_->getAngularDamping() : 0.0f;
  589. }
  590. float RigidBody::GetFriction() const
  591. {
  592. return body_ ? body_->getFriction() : 0.0f;
  593. }
  594. Vector3 RigidBody::GetAnisotropicFriction() const
  595. {
  596. return body_ ? ToVector3(body_->getAnisotropicFriction()) : Vector3::ZERO;
  597. }
  598. float RigidBody::GetRollingFriction() const
  599. {
  600. return body_ ? body_->getRollingFriction() : 0.0f;
  601. }
  602. float RigidBody::GetRestitution() const
  603. {
  604. return body_ ? body_->getRestitution() : 0.0f;
  605. }
  606. float RigidBody::GetContactProcessingThreshold() const
  607. {
  608. return body_ ? body_->getContactProcessingThreshold() : 0.0f;
  609. }
  610. float RigidBody::GetCcdRadius() const
  611. {
  612. return body_ ? body_->getCcdSweptSphereRadius() : 0.0f;
  613. }
  614. float RigidBody::GetCcdMotionThreshold() const
  615. {
  616. return body_ ? body_->getCcdMotionThreshold() : 0.0f;
  617. }
  618. bool RigidBody::IsActive() const
  619. {
  620. return body_ ? body_->isActive() : false;
  621. }
  622. void RigidBody::GetCollidingBodies(PODVector<RigidBody*>& result) const
  623. {
  624. if (physicsWorld_)
  625. physicsWorld_->GetCollidingBodies(result, this);
  626. else
  627. result.Clear();
  628. }
  629. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  630. {
  631. // In case of holding an extra reference to the RigidBody, this could be called in a situation
  632. // where node is already null
  633. if (!node_ || !physicsWorld_)
  634. return;
  635. physicsWorld_->SetApplyingTransforms(true);
  636. // Apply transform to the SmoothedTransform component instead of node transform if available
  637. if (smoothedTransform_)
  638. {
  639. smoothedTransform_->SetTargetWorldPosition(newWorldPosition);
  640. smoothedTransform_->SetTargetWorldRotation(newWorldRotation);
  641. lastPosition_ = newWorldPosition;
  642. lastRotation_ = newWorldRotation;
  643. }
  644. else
  645. {
  646. node_->SetWorldPosition(newWorldPosition);
  647. node_->SetWorldRotation(newWorldRotation);
  648. lastPosition_ = node_->GetWorldPosition();
  649. lastRotation_ = node_->GetWorldRotation();
  650. }
  651. physicsWorld_->SetApplyingTransforms(false);
  652. }
  653. void RigidBody::UpdateMass()
  654. {
  655. if (!body_ || !enableMassUpdate_)
  656. return;
  657. btTransform principal;
  658. principal.setRotation(btQuaternion::getIdentity());
  659. principal.setOrigin(btVector3(0.0f, 0.0f, 0.0f));
  660. // Calculate center of mass shift from all the collision shapes
  661. unsigned numShapes = (unsigned)compoundShape_->getNumChildShapes();
  662. if (numShapes)
  663. {
  664. PODVector<float> masses(numShapes);
  665. for (unsigned i = 0; i < numShapes; ++i)
  666. {
  667. // The actual mass does not matter, divide evenly between child shapes
  668. masses[i] = 1.0f;
  669. }
  670. btVector3 inertia(0.0f, 0.0f, 0.0f);
  671. compoundShape_->calculatePrincipalAxisTransform(&masses[0], principal, inertia);
  672. }
  673. // Add child shapes to shifted compound shape with adjusted offset
  674. while (shiftedCompoundShape_->getNumChildShapes())
  675. shiftedCompoundShape_->removeChildShapeByIndex(shiftedCompoundShape_->getNumChildShapes() - 1);
  676. for (unsigned i = 0; i < numShapes; ++i)
  677. {
  678. btTransform adjusted = compoundShape_->getChildTransform(i);
  679. adjusted.setOrigin(adjusted.getOrigin() - principal.getOrigin());
  680. shiftedCompoundShape_->addChildShape(adjusted, compoundShape_->getChildShape(i));
  681. }
  682. // If shifted compound shape has only one child with no offset/rotation, use the child shape
  683. // directly as the rigid body collision shape for better collision detection performance
  684. bool useCompound = !numShapes || numShapes > 1;
  685. if (!useCompound)
  686. {
  687. const btTransform& childTransform = shiftedCompoundShape_->getChildTransform(0);
  688. if (!ToVector3(childTransform.getOrigin()).Equals(Vector3::ZERO) ||
  689. !ToQuaternion(childTransform.getRotation()).Equals(Quaternion::IDENTITY))
  690. useCompound = true;
  691. }
  692. body_->setCollisionShape(useCompound ? shiftedCompoundShape_ : shiftedCompoundShape_->getChildShape(0));
  693. // If we have one shape and this is a triangle mesh, we use a custom material callback in order to adjust internal edges
  694. if (!useCompound && body_->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE &&
  695. physicsWorld_->GetInternalEdge())
  696. body_->setCollisionFlags(body_->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  697. else
  698. body_->setCollisionFlags(body_->getCollisionFlags() & ~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  699. // Reapply rigid body position with new center of mass shift
  700. Vector3 oldPosition = GetPosition();
  701. centerOfMass_ = ToVector3(principal.getOrigin());
  702. SetPosition(oldPosition);
  703. // Calculate final inertia
  704. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  705. if (mass_ > 0.0f)
  706. shiftedCompoundShape_->calculateLocalInertia(mass_, localInertia);
  707. body_->setMassProps(mass_, localInertia);
  708. body_->updateInertiaTensor();
  709. // Reapply constraint positions for new center of mass shift
  710. if (node_)
  711. {
  712. for (PODVector<Constraint*>::Iterator i = constraints_.Begin(); i != constraints_.End(); ++i)
  713. (*i)->ApplyFrames();
  714. }
  715. }
  716. void RigidBody::UpdateGravity()
  717. {
  718. if (physicsWorld_ && body_)
  719. {
  720. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  721. int flags = body_->getFlags();
  722. if (useGravity_ && gravityOverride_ == Vector3::ZERO)
  723. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  724. else
  725. flags |= BT_DISABLE_WORLD_GRAVITY;
  726. body_->setFlags(flags);
  727. if (useGravity_)
  728. {
  729. // If override vector is zero, use world's gravity
  730. if (gravityOverride_ == Vector3::ZERO)
  731. body_->setGravity(world->getGravity());
  732. else
  733. body_->setGravity(ToBtVector3(gravityOverride_));
  734. }
  735. else
  736. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  737. }
  738. }
  739. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  740. {
  741. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  742. MemoryBuffer buf(value);
  743. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  744. }
  745. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  746. {
  747. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  748. attrBuffer_.Clear();
  749. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  750. return attrBuffer_.GetBuffer();
  751. }
  752. void RigidBody::AddConstraint(Constraint* constraint)
  753. {
  754. constraints_.Push(constraint);
  755. }
  756. void RigidBody::RemoveConstraint(Constraint* constraint)
  757. {
  758. constraints_.Remove(constraint);
  759. // A constraint being removed should possibly cause the object to eg. start falling, so activate
  760. Activate();
  761. }
  762. void RigidBody::ReleaseBody()
  763. {
  764. if (body_)
  765. {
  766. // Release all constraints which refer to this body
  767. // Make a copy for iteration
  768. PODVector<Constraint*> constraints = constraints_;
  769. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  770. (*i)->ReleaseConstraint();
  771. RemoveBodyFromWorld();
  772. delete body_;
  773. body_ = 0;
  774. }
  775. }
  776. void RigidBody::OnMarkedDirty(Node* node)
  777. {
  778. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  779. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  780. // states; rather follow the SmoothedTransform target transform directly
  781. // Also, for kinematic objects Bullet asks the position from us, so we do not need to apply ourselves
  782. // (exception: initial setting of transform)
  783. if ((!kinematic_ || !hasSimulated_) && (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms()) && !smoothedTransform_)
  784. {
  785. // Physics operations are not safe from worker threads
  786. Scene* scene = GetScene();
  787. if (scene && scene->IsThreadedUpdate())
  788. {
  789. scene->DelayedMarkedDirty(this);
  790. return;
  791. }
  792. // Check if transform has changed from the last one set in ApplyWorldTransform()
  793. Vector3 newPosition = node_->GetWorldPosition();
  794. Quaternion newRotation = node_->GetWorldRotation();
  795. if (!newRotation.Equals(lastRotation_))
  796. {
  797. lastRotation_ = newRotation;
  798. SetRotation(newRotation);
  799. }
  800. if (!newPosition.Equals(lastPosition_))
  801. {
  802. lastPosition_ = newPosition;
  803. SetPosition(newPosition);
  804. }
  805. }
  806. }
  807. void RigidBody::OnNodeSet(Node* node)
  808. {
  809. if (node)
  810. node->AddListener(this);
  811. }
  812. void RigidBody::OnSceneSet(Scene* scene)
  813. {
  814. if (scene)
  815. {
  816. if (scene == node_)
  817. URHO3D_LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  818. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  819. physicsWorld_->AddRigidBody(this);
  820. AddBodyToWorld();
  821. }
  822. else
  823. {
  824. ReleaseBody();
  825. if (physicsWorld_)
  826. physicsWorld_->RemoveRigidBody(this);
  827. }
  828. }
  829. void RigidBody::AddBodyToWorld()
  830. {
  831. if (!physicsWorld_)
  832. return;
  833. URHO3D_PROFILE(AddBodyToWorld);
  834. if (mass_ < 0.0f)
  835. mass_ = 0.0f;
  836. if (body_)
  837. RemoveBodyFromWorld();
  838. else
  839. {
  840. // Correct inertia will be calculated below
  841. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  842. body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
  843. body_->setUserPointer(this);
  844. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  845. // If it exists, subscribe to its change events
  846. smoothedTransform_ = GetComponent<SmoothedTransform>();
  847. if (smoothedTransform_)
  848. {
  849. SubscribeToEvent(smoothedTransform_, E_TARGETPOSITION, URHO3D_HANDLER(RigidBody, HandleTargetPosition));
  850. SubscribeToEvent(smoothedTransform_, E_TARGETROTATION, URHO3D_HANDLER(RigidBody, HandleTargetRotation));
  851. }
  852. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  853. // Do not update mass yet, but do it once all shapes have been added
  854. PODVector<CollisionShape*> shapes;
  855. node_->GetComponents<CollisionShape>(shapes);
  856. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  857. (*i)->NotifyRigidBody(false);
  858. // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
  859. // to create themselves now
  860. PODVector<Constraint*> constraints;
  861. node_->GetComponents<Constraint>(constraints);
  862. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  863. (*i)->CreateConstraint();
  864. }
  865. UpdateMass();
  866. UpdateGravity();
  867. int flags = body_->getCollisionFlags();
  868. if (trigger_)
  869. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  870. else
  871. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  872. if (kinematic_)
  873. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  874. else
  875. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  876. body_->setCollisionFlags(flags);
  877. body_->forceActivationState(kinematic_ ? DISABLE_DEACTIVATION : ISLAND_SLEEPING);
  878. if (!IsEnabledEffective())
  879. return;
  880. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  881. world->addRigidBody(body_, (short)collisionLayer_, (short)collisionMask_);
  882. inWorld_ = true;
  883. readdBody_ = false;
  884. hasSimulated_ = false;
  885. if (mass_ > 0.0f)
  886. Activate();
  887. else
  888. {
  889. SetLinearVelocity(Vector3::ZERO);
  890. SetAngularVelocity(Vector3::ZERO);
  891. }
  892. }
  893. void RigidBody::RemoveBodyFromWorld()
  894. {
  895. if (physicsWorld_ && body_ && inWorld_)
  896. {
  897. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  898. world->removeRigidBody(body_);
  899. inWorld_ = false;
  900. }
  901. }
  902. void RigidBody::HandleTargetPosition(StringHash eventType, VariantMap& eventData)
  903. {
  904. // Copy the smoothing target position to the rigid body
  905. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  906. SetPosition(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldPosition());
  907. }
  908. void RigidBody::HandleTargetRotation(StringHash eventType, VariantMap& eventData)
  909. {
  910. // Copy the smoothing target rotation to the rigid body
  911. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  912. SetRotation(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldRotation());
  913. }
  914. }