RigidBody2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. //
  2. // Copyright (c) 2008-2017 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 "../IO/Log.h"
  25. #include "../Scene/Scene.h"
  26. #include "../Atomic2D/CollisionShape2D.h"
  27. #include "../Atomic2D/Constraint2D.h"
  28. #include "../Atomic2D/PhysicsUtils2D.h"
  29. #include "../Atomic2D/PhysicsWorld2D.h"
  30. #include "../Atomic2D/RigidBody2D.h"
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. extern const char* ATOMIC2D_CATEGORY;
  35. static const BodyType2D DEFAULT_BODYTYPE = BT_STATIC;
  36. static const char* bodyTypeNames[] =
  37. {
  38. "Static",
  39. "Kinematic",
  40. "Dynamic",
  41. 0
  42. };
  43. RigidBody2D::RigidBody2D(Context* context) :
  44. Component(context),
  45. useFixtureMass_(true),
  46. body_(0),
  47. // ATOMIC BEGIN
  48. castShadows_(true)
  49. // ATOMIC END
  50. {
  51. // Make sure the massData members are zero-initialized.
  52. massData_.mass = 0.0f;
  53. massData_.I = 0.0f;
  54. massData_.center.SetZero();
  55. }
  56. RigidBody2D::~RigidBody2D()
  57. {
  58. if (physicsWorld_)
  59. {
  60. ReleaseBody();
  61. physicsWorld_->RemoveRigidBody(this);
  62. }
  63. }
  64. void RigidBody2D::RegisterObject(Context* context)
  65. {
  66. context->RegisterFactory<RigidBody2D>(ATOMIC2D_CATEGORY);
  67. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  68. ATOMIC_ENUM_ACCESSOR_ATTRIBUTE("Body Type", GetBodyType, SetBodyType, BodyType2D, bodyTypeNames, DEFAULT_BODYTYPE, AM_DEFAULT);
  69. ATOMIC_ACCESSOR_ATTRIBUTE("Mass", GetMass, SetMass, float, 0.0f, AM_DEFAULT);
  70. ATOMIC_ACCESSOR_ATTRIBUTE("Inertia", GetInertia, SetInertia, float, 0.0f, AM_DEFAULT);
  71. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Mass Center", GetMassCenter, SetMassCenter, Vector2, Vector2::ZERO, AM_DEFAULT);
  72. ATOMIC_ACCESSOR_ATTRIBUTE("Use Fixture Mass", GetUseFixtureMass, SetUseFixtureMass, bool, true, AM_DEFAULT);
  73. ATOMIC_ACCESSOR_ATTRIBUTE("Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  74. ATOMIC_ACCESSOR_ATTRIBUTE("Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  75. ATOMIC_ACCESSOR_ATTRIBUTE("Allow Sleep", IsAllowSleep, SetAllowSleep, bool, true, AM_DEFAULT);
  76. ATOMIC_ACCESSOR_ATTRIBUTE("Fixed Rotation", IsFixedRotation, SetFixedRotation, bool, false, AM_DEFAULT);
  77. ATOMIC_ACCESSOR_ATTRIBUTE("Bullet", IsBullet, SetBullet, bool, false, AM_DEFAULT);
  78. ATOMIC_ACCESSOR_ATTRIBUTE("Gravity Scale", GetGravityScale, SetGravityScale, float, 1.0f, AM_DEFAULT);
  79. ATOMIC_ACCESSOR_ATTRIBUTE("Awake", IsAwake, SetAwake, bool, true, AM_DEFAULT);
  80. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector2, Vector2::ZERO, AM_DEFAULT);
  81. ATOMIC_ACCESSOR_ATTRIBUTE("Angular Velocity", GetAngularVelocity, SetAngularVelocity, float, 0.0f, AM_DEFAULT);
  82. // ATOMIC BEGIN
  83. ATOMIC_ACCESSOR_ATTRIBUTE("CastShadows", GetCastShadows, SetCastShadows, bool, true, AM_DEFAULT);
  84. // ATOMIC END
  85. }
  86. void RigidBody2D::OnSetEnabled()
  87. {
  88. bool enabled = IsEnabledEffective();
  89. bodyDef_.active = enabled;
  90. if (body_)
  91. body_->SetActive(enabled);
  92. MarkNetworkUpdate();
  93. }
  94. void RigidBody2D::SetBodyType(BodyType2D type)
  95. {
  96. b2BodyType bodyType = (b2BodyType)type;
  97. if (body_)
  98. {
  99. body_->SetType(bodyType);
  100. // Mass data was reset to keep it legal (e.g. static body should have mass 0.)
  101. // If not using fixture mass, reassign our mass data now
  102. if (!useFixtureMass_)
  103. body_->SetMassData(&massData_);
  104. }
  105. else
  106. {
  107. if (bodyDef_.type == bodyType)
  108. return;
  109. bodyDef_.type = bodyType;
  110. }
  111. MarkNetworkUpdate();
  112. }
  113. void RigidBody2D::SetMass(float mass)
  114. {
  115. mass = Max(mass, 0.0f);
  116. if (massData_.mass == mass)
  117. return;
  118. massData_.mass = mass;
  119. if (!useFixtureMass_ && body_)
  120. body_->SetMassData(&massData_);
  121. MarkNetworkUpdate();
  122. }
  123. void RigidBody2D::SetInertia(float inertia)
  124. {
  125. inertia = Max(inertia, 0.0f);
  126. if (massData_.I == inertia)
  127. return;
  128. massData_.I = inertia;
  129. if (!useFixtureMass_ && body_)
  130. body_->SetMassData(&massData_);
  131. MarkNetworkUpdate();
  132. }
  133. void RigidBody2D::SetMassCenter(const Vector2& center)
  134. {
  135. b2Vec2 b2Center = ToB2Vec2(center);
  136. if (massData_.center == b2Center)
  137. return;
  138. massData_.center = b2Center;
  139. if (!useFixtureMass_ && body_)
  140. body_->SetMassData(&massData_);
  141. MarkNetworkUpdate();
  142. }
  143. void RigidBody2D::SetUseFixtureMass(bool useFixtureMass)
  144. {
  145. if (useFixtureMass_ == useFixtureMass)
  146. return;
  147. useFixtureMass_ = useFixtureMass;
  148. if (body_)
  149. {
  150. if (useFixtureMass_)
  151. body_->ResetMassData();
  152. else
  153. body_->SetMassData(&massData_);
  154. }
  155. MarkNetworkUpdate();
  156. }
  157. void RigidBody2D::SetLinearDamping(float linearDamping)
  158. {
  159. if (body_)
  160. body_->SetLinearDamping(linearDamping);
  161. else
  162. {
  163. if (bodyDef_.linearDamping == linearDamping)
  164. return;
  165. bodyDef_.linearDamping = linearDamping;
  166. }
  167. MarkNetworkUpdate();
  168. }
  169. void RigidBody2D::SetAngularDamping(float angularDamping)
  170. {
  171. if (body_)
  172. body_->SetAngularDamping(angularDamping);
  173. else
  174. {
  175. if (bodyDef_.angularDamping == angularDamping)
  176. return;
  177. bodyDef_.angularDamping = angularDamping;
  178. }
  179. MarkNetworkUpdate();
  180. }
  181. void RigidBody2D::SetAllowSleep(bool allowSleep)
  182. {
  183. if (body_)
  184. body_->SetSleepingAllowed(allowSleep);
  185. else
  186. {
  187. if (bodyDef_.allowSleep == allowSleep)
  188. return;
  189. bodyDef_.allowSleep = allowSleep;
  190. }
  191. MarkNetworkUpdate();
  192. }
  193. void RigidBody2D::SetFixedRotation(bool fixedRotation)
  194. {
  195. if (body_)
  196. {
  197. body_->SetFixedRotation(fixedRotation);
  198. // Mass data was reset to keep it legal (e.g. non-rotating body should have inertia 0.)
  199. // If not using fixture mass, reassign our mass data now
  200. if (!useFixtureMass_)
  201. body_->SetMassData(&massData_);
  202. }
  203. else
  204. {
  205. if (bodyDef_.fixedRotation == fixedRotation)
  206. return;
  207. bodyDef_.fixedRotation = fixedRotation;
  208. }
  209. MarkNetworkUpdate();
  210. }
  211. void RigidBody2D::SetBullet(bool bullet)
  212. {
  213. if (body_)
  214. body_->SetBullet(bullet);
  215. else
  216. {
  217. if (bodyDef_.bullet == bullet)
  218. return;
  219. bodyDef_.bullet = bullet;
  220. }
  221. MarkNetworkUpdate();
  222. }
  223. void RigidBody2D::SetGravityScale(float gravityScale)
  224. {
  225. if (body_)
  226. body_->SetGravityScale(gravityScale);
  227. else
  228. {
  229. if (bodyDef_.gravityScale == gravityScale)
  230. return;
  231. bodyDef_.gravityScale = gravityScale;
  232. }
  233. MarkNetworkUpdate();
  234. }
  235. void RigidBody2D::SetAwake(bool awake)
  236. {
  237. if (body_)
  238. body_->SetAwake(awake);
  239. else
  240. {
  241. if (bodyDef_.awake == awake)
  242. return;
  243. bodyDef_.awake = awake;
  244. }
  245. MarkNetworkUpdate();
  246. }
  247. void RigidBody2D::SetLinearVelocity(const Vector2& linearVelocity)
  248. {
  249. b2Vec2 b2linearVelocity = ToB2Vec2(linearVelocity);
  250. if (body_)
  251. body_->SetLinearVelocity(b2linearVelocity);
  252. else
  253. {
  254. if (bodyDef_.linearVelocity == b2linearVelocity)
  255. return;
  256. bodyDef_.linearVelocity = b2linearVelocity;
  257. }
  258. MarkNetworkUpdate();
  259. }
  260. void RigidBody2D::SetAngularVelocity(float angularVelocity)
  261. {
  262. if (body_)
  263. body_->SetAngularVelocity(angularVelocity);
  264. else
  265. {
  266. if (bodyDef_.angularVelocity == angularVelocity)
  267. return;
  268. bodyDef_.angularVelocity = angularVelocity;
  269. }
  270. MarkNetworkUpdate();
  271. }
  272. void RigidBody2D::ApplyForce(const Vector2& force, const Vector2& point, bool wake)
  273. {
  274. if (body_ && force != Vector2::ZERO)
  275. body_->ApplyForce(ToB2Vec2(force), ToB2Vec2(point), wake);
  276. }
  277. void RigidBody2D::ApplyForceToCenter(const Vector2& force, bool wake)
  278. {
  279. if (body_ && force != Vector2::ZERO)
  280. body_->ApplyForceToCenter(ToB2Vec2(force), wake);
  281. }
  282. void RigidBody2D::ApplyTorque(float torque, bool wake)
  283. {
  284. if (body_ && torque != 0)
  285. body_->ApplyTorque(torque, wake);
  286. }
  287. void RigidBody2D::ApplyLinearImpulse(const Vector2& impulse, const Vector2& point, bool wake)
  288. {
  289. if (body_ && impulse != Vector2::ZERO)
  290. body_->ApplyLinearImpulse(ToB2Vec2(impulse), ToB2Vec2(point), wake);
  291. }
  292. void RigidBody2D::ApplyLinearImpulseToCenter(const Vector2& impulse, bool wake)
  293. {
  294. if (body_ && impulse != Vector2::ZERO)
  295. body_->ApplyLinearImpulseToCenter(ToB2Vec2(impulse), wake);
  296. }
  297. void RigidBody2D::ApplyAngularImpulse(float impulse, bool wake)
  298. {
  299. if (body_)
  300. body_->ApplyAngularImpulse(impulse, wake);
  301. }
  302. void RigidBody2D::CreateBody()
  303. {
  304. if (body_)
  305. return;
  306. if (!physicsWorld_ || !physicsWorld_->GetWorld())
  307. return;
  308. bodyDef_.position = ToB2Vec2(node_->GetWorldPosition());;
  309. bodyDef_.angle = node_->GetWorldRotation().RollAngle() * M_DEGTORAD;
  310. body_ = physicsWorld_->GetWorld()->CreateBody(&bodyDef_);
  311. body_->SetUserData(this);
  312. for (unsigned i = 0; i < collisionShapes_.Size(); ++i)
  313. {
  314. if (collisionShapes_[i])
  315. collisionShapes_[i]->CreateFixture();
  316. }
  317. if (!useFixtureMass_)
  318. body_->SetMassData(&massData_);
  319. for (unsigned i = 0; i < constraints_.Size(); ++i)
  320. {
  321. if (constraints_[i])
  322. constraints_[i]->CreateJoint();
  323. }
  324. }
  325. void RigidBody2D::ReleaseBody()
  326. {
  327. if (!body_)
  328. return;
  329. if (!physicsWorld_ || !physicsWorld_->GetWorld())
  330. return;
  331. // Make a copy for iteration
  332. Vector<WeakPtr<Constraint2D> > constraints = constraints_;
  333. for (unsigned i = 0; i < constraints.Size(); ++i)
  334. {
  335. if (constraints[i])
  336. constraints[i]->ReleaseJoint();
  337. }
  338. for (unsigned i = 0; i < collisionShapes_.Size(); ++i)
  339. {
  340. if (collisionShapes_[i])
  341. collisionShapes_[i]->ReleaseFixture();
  342. }
  343. physicsWorld_->GetWorld()->DestroyBody(body_);
  344. body_ = 0;
  345. }
  346. void RigidBody2D::ApplyWorldTransform()
  347. {
  348. if (!body_ || !node_)
  349. return;
  350. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  351. // In that case store it to PhysicsWorld2D for delayed assignment
  352. RigidBody2D* parentRigidBody = 0;
  353. Node* parent = node_->GetParent();
  354. if (parent != GetScene() && parent)
  355. parentRigidBody = parent->GetComponent<RigidBody2D>();
  356. // If body is not parented and is static or sleeping, no need to update
  357. if (!parentRigidBody && (!body_->IsActive() || body_->GetType() == b2_staticBody || !body_->IsAwake()))
  358. return;
  359. const b2Transform& transform = body_->GetTransform();
  360. Vector3 newWorldPosition = node_->GetWorldPosition();
  361. newWorldPosition.x_ = transform.p.x;
  362. newWorldPosition.y_ = transform.p.y;
  363. Quaternion newWorldRotation(transform.q.GetAngle() * M_RADTODEG, Vector3::FORWARD);
  364. if (parentRigidBody)
  365. {
  366. DelayedWorldTransform2D delayed;
  367. delayed.rigidBody_ = this;
  368. delayed.parentRigidBody_ = parentRigidBody;
  369. delayed.worldPosition_ = newWorldPosition;
  370. delayed.worldRotation_ = newWorldRotation;
  371. physicsWorld_->AddDelayedWorldTransform(delayed);
  372. }
  373. else
  374. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  375. }
  376. void RigidBody2D::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  377. {
  378. if (newWorldPosition != node_->GetWorldPosition() || newWorldRotation != node_->GetWorldRotation())
  379. {
  380. // Do not feed changed position back to simulation now
  381. physicsWorld_->SetApplyingTransforms(true);
  382. node_->SetWorldPosition(newWorldPosition);
  383. node_->SetWorldRotation(newWorldRotation);
  384. physicsWorld_->SetApplyingTransforms(false);
  385. }
  386. }
  387. void RigidBody2D::AddCollisionShape2D(CollisionShape2D* collisionShape)
  388. {
  389. if (!collisionShape)
  390. return;
  391. WeakPtr<CollisionShape2D> collisionShapePtr(collisionShape);
  392. if (collisionShapes_.Contains(collisionShapePtr))
  393. return;
  394. collisionShapes_.Push(collisionShapePtr);
  395. }
  396. void RigidBody2D::RemoveCollisionShape2D(CollisionShape2D* collisionShape)
  397. {
  398. if (!collisionShape)
  399. return;
  400. WeakPtr<CollisionShape2D> collisionShapePtr(collisionShape);
  401. collisionShapes_.Remove(collisionShapePtr);
  402. }
  403. void RigidBody2D::AddConstraint2D(Constraint2D* constraint)
  404. {
  405. if (!constraint)
  406. return;
  407. WeakPtr<Constraint2D> constraintPtr(constraint);
  408. if (constraints_.Contains(constraintPtr))
  409. return;
  410. constraints_.Push(constraintPtr);
  411. }
  412. void RigidBody2D::RemoveConstraint2D(Constraint2D* constraint)
  413. {
  414. if (!constraint)
  415. return;
  416. WeakPtr<Constraint2D> constraintPtr(constraint);
  417. constraints_.Remove(constraintPtr);
  418. }
  419. float RigidBody2D::GetMass() const
  420. {
  421. if (!useFixtureMass_)
  422. return massData_.mass;
  423. else
  424. return body_ ? body_->GetMass() : 0.0f;
  425. }
  426. float RigidBody2D::GetInertia() const
  427. {
  428. if (!useFixtureMass_)
  429. return massData_.I;
  430. else
  431. return body_ ? body_->GetInertia() : 0.0f;
  432. }
  433. Vector2 RigidBody2D::GetMassCenter() const
  434. {
  435. if (!useFixtureMass_)
  436. return ToVector2(massData_.center);
  437. else
  438. return body_ ? ToVector2(body_->GetLocalCenter()) : Vector2::ZERO;
  439. }
  440. bool RigidBody2D::IsAwake() const
  441. {
  442. return body_ ? body_->IsAwake() : bodyDef_.awake;
  443. }
  444. Vector2 RigidBody2D::GetLinearVelocity() const
  445. {
  446. return ToVector2(body_ ? body_->GetLinearVelocity() : bodyDef_.linearVelocity);
  447. }
  448. float RigidBody2D::GetAngularVelocity() const
  449. {
  450. return body_ ? body_->GetAngularVelocity() : bodyDef_.angularVelocity;
  451. }
  452. void RigidBody2D::OnNodeSet(Node* node)
  453. {
  454. if (node)
  455. {
  456. node->AddListener(this);
  457. PODVector<CollisionShape2D*> shapes;
  458. node_->GetDerivedComponents<CollisionShape2D>(shapes);
  459. for (PODVector<CollisionShape2D*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  460. {
  461. (*i)->CreateFixture();
  462. AddCollisionShape2D(*i);
  463. }
  464. }
  465. }
  466. void RigidBody2D::OnSceneSet(Scene* scene)
  467. {
  468. if (scene)
  469. {
  470. physicsWorld_ = scene->GetDerivedComponent<PhysicsWorld2D>();
  471. if (!physicsWorld_)
  472. physicsWorld_ = scene->CreateComponent<PhysicsWorld2D>();
  473. CreateBody();
  474. physicsWorld_->AddRigidBody(this);
  475. }
  476. else
  477. {
  478. if (physicsWorld_)
  479. {
  480. ReleaseBody();
  481. physicsWorld_->RemoveRigidBody(this);
  482. physicsWorld_.Reset();
  483. }
  484. }
  485. }
  486. void RigidBody2D::OnMarkedDirty(Node* node)
  487. {
  488. if (physicsWorld_ && physicsWorld_->IsApplyingTransforms())
  489. return;
  490. // Physics operations are not safe from worker threads
  491. Scene* scene = GetScene();
  492. if (scene && scene->IsThreadedUpdate())
  493. {
  494. scene->DelayedMarkedDirty(this);
  495. return;
  496. }
  497. // Check if transform has changed from the last one set in ApplyWorldTransform()
  498. b2Vec2 newPosition = ToB2Vec2(node_->GetWorldPosition());
  499. float newAngle = node_->GetWorldRotation().RollAngle() * M_DEGTORAD;
  500. if (newPosition != bodyDef_.position || newAngle != bodyDef_.angle)
  501. {
  502. if (body_)
  503. body_->SetTransform(newPosition, newAngle);
  504. else
  505. {
  506. bodyDef_.position = newPosition;
  507. bodyDef_.angle = newAngle;
  508. }
  509. }
  510. }
  511. }