PhysicsWorld2D.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 "../Graphics/DebugRenderer.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/Renderer.h"
  28. #include "../IO/Log.h"
  29. #include "../Scene/Scene.h"
  30. #include "../Scene/SceneEvents.h"
  31. #include "../Atomic2D/PhysicsEvents2D.h"
  32. #include "../Atomic2D/PhysicsUtils2D.h"
  33. #include "../Atomic2D/PhysicsWorld2D.h"
  34. #include "../Atomic2D/RigidBody2D.h"
  35. #include "../DebugNew.h"
  36. namespace Atomic
  37. {
  38. extern const char* SUBSYSTEM_CATEGORY;
  39. static const Vector2 DEFAULT_GRAVITY(0.0f, -9.81f);
  40. static const int DEFAULT_VELOCITY_ITERATIONS = 8;
  41. static const int DEFAULT_POSITION_ITERATIONS = 3;
  42. PhysicsWorld2D::PhysicsWorld2D(Context* context) :
  43. Component(context),
  44. world_(0),
  45. gravity_(DEFAULT_GRAVITY),
  46. velocityIterations_(DEFAULT_VELOCITY_ITERATIONS),
  47. positionIterations_(DEFAULT_POSITION_ITERATIONS),
  48. debugRenderer_(0),
  49. physicsStepping_(false),
  50. applyingTransforms_(false),
  51. updateEnabled_(true)
  52. {
  53. // Set default debug draw flags
  54. m_drawFlags = e_shapeBit;
  55. // Create Box2D world
  56. world_ = new b2World(ToB2Vec2(gravity_));
  57. // Set contact listener
  58. world_->SetContactListener(this);
  59. // Set debug draw
  60. world_->SetDebugDraw(this);
  61. // BEGIN ATOMIC
  62. // These should be false, as per the attribute defaults
  63. world_->SetContinuousPhysics(false);
  64. world_->SetSubStepping(false);
  65. // END ATOMIC
  66. }
  67. PhysicsWorld2D::~PhysicsWorld2D()
  68. {
  69. for (unsigned i = 0; i < rigidBodies_.Size(); ++i)
  70. if (rigidBodies_[i])
  71. rigidBodies_[i]->ReleaseBody();
  72. delete world_;
  73. world_ = 0;
  74. }
  75. void PhysicsWorld2D::RegisterObject(Context* context)
  76. {
  77. context->RegisterFactory<PhysicsWorld2D>(SUBSYSTEM_CATEGORY);
  78. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Shape", GetDrawShape, SetDrawShape, bool, false, AM_DEFAULT);
  79. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Joint", GetDrawJoint, SetDrawJoint, bool, false, AM_DEFAULT);
  80. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Aabb", GetDrawAabb, SetDrawAabb, bool, false, AM_DEFAULT);
  81. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Pair", GetDrawPair, SetDrawPair, bool, false, AM_DEFAULT);
  82. ATOMIC_ACCESSOR_ATTRIBUTE("Draw CenterOfMass", GetDrawCenterOfMass, SetDrawCenterOfMass, bool, false, AM_DEFAULT);
  83. ATOMIC_ACCESSOR_ATTRIBUTE("Allow Sleeping", GetAllowSleeping, SetAllowSleeping, bool, false, AM_DEFAULT);
  84. ATOMIC_ACCESSOR_ATTRIBUTE("Warm Starting", GetWarmStarting, SetWarmStarting, bool, false, AM_DEFAULT);
  85. // ATOMIC BEGIN
  86. // default false
  87. ATOMIC_ACCESSOR_ATTRIBUTE("Continuous Physics", GetContinuousPhysics, SetContinuousPhysics, bool, false, AM_DEFAULT);
  88. // ATOMIC END
  89. ATOMIC_ACCESSOR_ATTRIBUTE("Sub Stepping", GetSubStepping, SetSubStepping, bool, false, AM_DEFAULT);
  90. ATOMIC_ACCESSOR_ATTRIBUTE("Gravity", GetGravity, SetGravity, Vector2, DEFAULT_GRAVITY, AM_DEFAULT);
  91. ATOMIC_ACCESSOR_ATTRIBUTE("Auto Clear Forces", GetAutoClearForces, SetAutoClearForces, bool, false, AM_DEFAULT);
  92. ATOMIC_ACCESSOR_ATTRIBUTE("Velocity Iterations", GetVelocityIterations, SetVelocityIterations, int, DEFAULT_VELOCITY_ITERATIONS,
  93. AM_DEFAULT);
  94. ATOMIC_ACCESSOR_ATTRIBUTE("Position Iterations", GetPositionIterations, SetPositionIterations, int, DEFAULT_POSITION_ITERATIONS,
  95. AM_DEFAULT);
  96. }
  97. void PhysicsWorld2D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  98. {
  99. if (debug)
  100. {
  101. ATOMIC_PROFILE(Physics2DDrawDebug);
  102. debugRenderer_ = debug;
  103. debugDepthTest_ = depthTest;
  104. world_->DrawDebugData();
  105. debugRenderer_ = 0;
  106. }
  107. }
  108. void PhysicsWorld2D::BeginContact(b2Contact* contact)
  109. {
  110. // Only handle contact event while stepping the physics simulation
  111. if (!physicsStepping_)
  112. return;
  113. b2Fixture* fixtureA = contact->GetFixtureA();
  114. b2Fixture* fixtureB = contact->GetFixtureB();
  115. if (!fixtureA || !fixtureB)
  116. return;
  117. beginContactInfos_.Push(ContactInfo(contact));
  118. }
  119. void PhysicsWorld2D::EndContact(b2Contact* contact)
  120. {
  121. if (!physicsStepping_)
  122. return;
  123. b2Fixture* fixtureA = contact->GetFixtureA();
  124. b2Fixture* fixtureB = contact->GetFixtureB();
  125. if (!fixtureA || !fixtureB)
  126. return;
  127. endContactInfos_.Push(ContactInfo(contact));
  128. }
  129. void PhysicsWorld2D::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
  130. {
  131. if (!debugRenderer_)
  132. return;
  133. Color c = ToColor(color);
  134. for (int i = 0; i < vertexCount - 1; ++i)
  135. debugRenderer_->AddLine(ToVector3(vertices[i]), ToVector3(vertices[i + 1]), c, debugDepthTest_);
  136. debugRenderer_->AddLine(ToVector3(vertices[vertexCount - 1]), ToVector3(vertices[0]), c, debugDepthTest_);
  137. }
  138. void PhysicsWorld2D::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
  139. {
  140. if (!debugRenderer_)
  141. return;
  142. Vector3 v = ToVector3(vertices[0]);
  143. Color c(color.r, color.g, color.b, 0.5f);
  144. for (int i = 1; i < vertexCount - 1; ++i)
  145. debugRenderer_->AddTriangle(v, ToVector3(vertices[i]), ToVector3(vertices[i + 1]), c, debugDepthTest_);
  146. }
  147. void PhysicsWorld2D::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
  148. {
  149. if (!debugRenderer_)
  150. return;
  151. Vector3 p = ToVector3(center);
  152. Color c = ToColor(color);
  153. for (unsigned i = 0; i < 360; i += 30)
  154. {
  155. unsigned j = i + 30;
  156. float x1 = radius * Cos((float)i);
  157. float y1 = radius * Sin((float)i);
  158. float x2 = radius * Cos((float)j);
  159. float y2 = radius * Sin((float)j);
  160. debugRenderer_->AddLine(p + Vector3(x1, y1, 0.0f), p + Vector3(x2, y2, 0.0f), c, debugDepthTest_);
  161. }
  162. }
  163. void PhysicsWorld2D::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
  164. {
  165. if (!debugRenderer_)
  166. return;
  167. Vector3 p = ToVector3(center);
  168. Color c(color.r, color.g, color.b, 0.5f);
  169. for (unsigned i = 0; i < 360; i += 30)
  170. {
  171. unsigned j = i + 30;
  172. float x1 = radius * Cos((float)i);
  173. float y1 = radius * Sin((float)i);
  174. float x2 = radius * Cos((float)j);
  175. float y2 = radius * Sin((float)j);
  176. debugRenderer_->AddTriangle(p, p + Vector3(x1, y1, 0.0f), p + Vector3(x2, y2, 0.0f), c, debugDepthTest_);
  177. }
  178. }
  179. void PhysicsWorld2D::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color)
  180. {
  181. if (debugRenderer_)
  182. debugRenderer_->AddLine(ToVector3(p1), ToVector3(p2), ToColor(color), debugDepthTest_);
  183. }
  184. void PhysicsWorld2D::DrawTransform(const b2Transform& xf)
  185. {
  186. if (!debugRenderer_)
  187. return;
  188. const float32 axisScale = 0.4f;
  189. b2Vec2 p1 = xf.p, p2;
  190. p2 = p1 + axisScale * xf.q.GetXAxis();
  191. debugRenderer_->AddLine(Vector3(p1.x, p1.y, 0.0f), Vector3(p2.x, p2.y, 0.0f), Color::RED, debugDepthTest_);
  192. p2 = p1 + axisScale * xf.q.GetYAxis();
  193. debugRenderer_->AddLine(Vector3(p1.x, p1.y, 0.0f), Vector3(p2.x, p2.y, 0.0f), Color::GREEN, debugDepthTest_);
  194. }
  195. void PhysicsWorld2D::Update(float timeStep)
  196. {
  197. ATOMIC_PROFILE(UpdatePhysics2D);
  198. using namespace PhysicsPreStep;
  199. VariantMap& eventData = GetEventDataMap();
  200. eventData[P_WORLD] = this;
  201. eventData[P_TIMESTEP] = timeStep;
  202. SendEvent(E_PHYSICSPRESTEP, eventData);
  203. physicsStepping_ = true;
  204. world_->Step(timeStep, velocityIterations_, positionIterations_);
  205. physicsStepping_ = false;
  206. // Apply world transforms. Unparented transforms first
  207. for (unsigned i = 0; i < rigidBodies_.Size();)
  208. {
  209. if (rigidBodies_[i])
  210. {
  211. rigidBodies_[i]->ApplyWorldTransform();
  212. ++i;
  213. }
  214. else
  215. {
  216. // Erase possible stale weak pointer
  217. rigidBodies_.Erase(i);
  218. }
  219. }
  220. // Apply delayed (parented) world transforms now, if any
  221. while (!delayedWorldTransforms_.Empty())
  222. {
  223. for (HashMap<RigidBody2D*, DelayedWorldTransform2D>::Iterator i = delayedWorldTransforms_.Begin();
  224. i != delayedWorldTransforms_.End();)
  225. {
  226. const DelayedWorldTransform2D& transform = i->second_;
  227. // If parent's transform has already been assigned, can proceed
  228. if (!delayedWorldTransforms_.Contains(transform.parentRigidBody_))
  229. {
  230. transform.rigidBody_->ApplyWorldTransform(transform.worldPosition_, transform.worldRotation_);
  231. i = delayedWorldTransforms_.Erase(i);
  232. }
  233. else
  234. ++i;
  235. }
  236. }
  237. SendBeginContactEvents();
  238. SendEndContactEvents();
  239. using namespace PhysicsPostStep;
  240. SendEvent(E_PHYSICSPOSTSTEP, eventData);
  241. }
  242. void PhysicsWorld2D::DrawDebugGeometry()
  243. {
  244. DebugRenderer* debug = GetComponent<DebugRenderer>();
  245. if (debug)
  246. DrawDebugGeometry(debug, false);
  247. }
  248. void PhysicsWorld2D::SetUpdateEnabled(bool enable)
  249. {
  250. updateEnabled_ = enable;
  251. }
  252. void PhysicsWorld2D::SetDrawShape(bool drawShape)
  253. {
  254. if (drawShape)
  255. m_drawFlags |= e_shapeBit;
  256. else
  257. m_drawFlags &= ~e_shapeBit;
  258. }
  259. void PhysicsWorld2D::SetDrawJoint(bool drawJoint)
  260. {
  261. if (drawJoint)
  262. m_drawFlags |= e_jointBit;
  263. else
  264. m_drawFlags &= ~e_jointBit;
  265. }
  266. void PhysicsWorld2D::SetDrawAabb(bool drawAabb)
  267. {
  268. if (drawAabb)
  269. m_drawFlags |= e_aabbBit;
  270. else
  271. m_drawFlags &= ~e_aabbBit;
  272. }
  273. void PhysicsWorld2D::SetDrawPair(bool drawPair)
  274. {
  275. if (drawPair)
  276. m_drawFlags |= e_pairBit;
  277. else
  278. m_drawFlags &= ~e_pairBit;
  279. }
  280. void PhysicsWorld2D::SetDrawCenterOfMass(bool drawCenterOfMass)
  281. {
  282. if (drawCenterOfMass)
  283. m_drawFlags |= e_centerOfMassBit;
  284. else
  285. m_drawFlags &= ~e_centerOfMassBit;
  286. }
  287. void PhysicsWorld2D::SetAllowSleeping(bool enable)
  288. {
  289. world_->SetAllowSleeping(enable);
  290. }
  291. void PhysicsWorld2D::SetWarmStarting(bool enable)
  292. {
  293. world_->SetWarmStarting(enable);
  294. }
  295. void PhysicsWorld2D::SetContinuousPhysics(bool enable)
  296. {
  297. world_->SetContinuousPhysics(enable);
  298. }
  299. void PhysicsWorld2D::SetSubStepping(bool enable)
  300. {
  301. world_->SetSubStepping(enable);
  302. }
  303. void PhysicsWorld2D::SetGravity(const Vector2& gravity)
  304. {
  305. gravity_ = gravity;
  306. world_->SetGravity(ToB2Vec2(gravity_));
  307. }
  308. void PhysicsWorld2D::SetAutoClearForces(bool enable)
  309. {
  310. world_->SetAutoClearForces(enable);
  311. }
  312. void PhysicsWorld2D::SetVelocityIterations(int velocityIterations)
  313. {
  314. velocityIterations_ = velocityIterations;
  315. }
  316. void PhysicsWorld2D::SetPositionIterations(int positionIterations)
  317. {
  318. positionIterations_ = positionIterations;
  319. }
  320. void PhysicsWorld2D::AddRigidBody(RigidBody2D* rigidBody)
  321. {
  322. if (!rigidBody)
  323. return;
  324. WeakPtr<RigidBody2D> rigidBodyPtr(rigidBody);
  325. if (rigidBodies_.Contains(rigidBodyPtr))
  326. return;
  327. rigidBodies_.Push(rigidBodyPtr);
  328. }
  329. void PhysicsWorld2D::RemoveRigidBody(RigidBody2D* rigidBody)
  330. {
  331. if (!rigidBody)
  332. return;
  333. WeakPtr<RigidBody2D> rigidBodyPtr(rigidBody);
  334. rigidBodies_.Remove(rigidBodyPtr);
  335. }
  336. void PhysicsWorld2D::AddDelayedWorldTransform(const DelayedWorldTransform2D& transform)
  337. {
  338. delayedWorldTransforms_[transform.rigidBody_] = transform;
  339. }
  340. // Ray cast call back class.
  341. class RayCastCallback : public b2RayCastCallback
  342. {
  343. public:
  344. // Construct.
  345. RayCastCallback(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, unsigned collisionMask) :
  346. results_(results),
  347. startPoint_(startPoint),
  348. collisionMask_(collisionMask)
  349. {
  350. }
  351. // Called for each fixture found in the query.
  352. virtual float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction)
  353. {
  354. // Ignore sensor
  355. if (fixture->IsSensor())
  356. return true;
  357. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  358. return true;
  359. PhysicsRaycastResult2D result;
  360. result.position_ = ToVector2(point);
  361. result.normal_ = ToVector2(normal);
  362. result.distance_ = (result.position_ - startPoint_).Length();
  363. result.body_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  364. results_.Push(result);
  365. return true;
  366. }
  367. protected:
  368. // Physics raycast results.
  369. PODVector<PhysicsRaycastResult2D>& results_;
  370. // Start point.
  371. Vector2 startPoint_;
  372. // Collision mask.
  373. unsigned collisionMask_;
  374. };
  375. void PhysicsWorld2D::Raycast(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint,
  376. unsigned collisionMask)
  377. {
  378. results.Clear();
  379. RayCastCallback callback(results, startPoint, collisionMask);
  380. world_->RayCast(&callback, ToB2Vec2(startPoint), ToB2Vec2(endPoint));
  381. }
  382. // Single ray cast call back class.
  383. class SingleRayCastCallback : public b2RayCastCallback
  384. {
  385. public:
  386. // Construct.
  387. SingleRayCastCallback(PhysicsRaycastResult2D& result, const Vector2& startPoint, unsigned collisionMask) :
  388. result_(result),
  389. startPoint_(startPoint),
  390. collisionMask_(collisionMask),
  391. minDistance_(M_INFINITY)
  392. {
  393. }
  394. // Called for each fixture found in the query.
  395. virtual float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction)
  396. {
  397. // Ignore sensor
  398. if (fixture->IsSensor())
  399. return true;
  400. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  401. return true;
  402. float distance = (ToVector2(point) - startPoint_).Length();
  403. if (distance < minDistance_)
  404. {
  405. minDistance_ = distance;
  406. result_.position_ = ToVector2(point);
  407. result_.normal_ = ToVector2(normal);
  408. result_.distance_ = distance;
  409. result_.body_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  410. }
  411. return true;
  412. }
  413. private:
  414. // Physics raycast result.
  415. PhysicsRaycastResult2D& result_;
  416. // Start point.
  417. Vector2 startPoint_;
  418. // Collision mask.
  419. unsigned collisionMask_;
  420. // Minimum distance.
  421. float minDistance_;
  422. };
  423. void PhysicsWorld2D::RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint,
  424. unsigned collisionMask)
  425. {
  426. result.body_ = 0;
  427. SingleRayCastCallback callback(result, startPoint, collisionMask);
  428. world_->RayCast(&callback, ToB2Vec2(startPoint), ToB2Vec2(endPoint));
  429. }
  430. // Point query callback class.
  431. class PointQueryCallback : public b2QueryCallback
  432. {
  433. public:
  434. // Construct.
  435. PointQueryCallback(const b2Vec2& point, unsigned collisionMask) :
  436. point_(point),
  437. collisionMask_(collisionMask),
  438. rigidBody_(0)
  439. {
  440. }
  441. // Called for each fixture found in the query AABB.
  442. virtual bool ReportFixture(b2Fixture* fixture)
  443. {
  444. // Ignore sensor
  445. if (fixture->IsSensor())
  446. return true;
  447. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  448. return true;
  449. if (fixture->TestPoint(point_))
  450. {
  451. rigidBody_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  452. return false;
  453. }
  454. return true;
  455. }
  456. // Return rigid body.
  457. RigidBody2D* GetRigidBody() const { return rigidBody_; }
  458. private:
  459. // Point.
  460. b2Vec2 point_;
  461. // Collision mask.
  462. unsigned collisionMask_;
  463. // Rigid body.
  464. RigidBody2D* rigidBody_;
  465. };
  466. RigidBody2D* PhysicsWorld2D::GetRigidBody(const Vector2& point, unsigned collisionMask)
  467. {
  468. PointQueryCallback callback(ToB2Vec2(point), collisionMask);
  469. b2AABB b2Aabb;
  470. Vector2 delta(M_EPSILON, M_EPSILON);
  471. b2Aabb.lowerBound = ToB2Vec2(point - delta);
  472. b2Aabb.upperBound = ToB2Vec2(point + delta);
  473. world_->QueryAABB(&callback, b2Aabb);
  474. return callback.GetRigidBody();
  475. }
  476. RigidBody2D* PhysicsWorld2D::GetRigidBody(int screenX, int screenY, unsigned collisionMask)
  477. {
  478. Renderer* renderer = GetSubsystem<Renderer>();
  479. for (unsigned i = 0; i < renderer->GetNumViewports(); ++i)
  480. {
  481. Viewport* viewport = renderer->GetViewport(i);
  482. // Find a viewport with same scene
  483. if (viewport && viewport->GetScene() == GetScene())
  484. {
  485. Vector3 worldPoint = viewport->ScreenToWorldPoint(screenX, screenY, 0.0f);
  486. return GetRigidBody(Vector2(worldPoint.x_, worldPoint.y_), collisionMask);
  487. }
  488. }
  489. return 0;
  490. }
  491. // Aabb query callback class.
  492. class AabbQueryCallback : public b2QueryCallback
  493. {
  494. public:
  495. // Construct.
  496. AabbQueryCallback(PODVector<RigidBody2D*>& results, unsigned collisionMask) :
  497. results_(results),
  498. collisionMask_(collisionMask)
  499. {
  500. }
  501. // Called for each fixture found in the query AABB.
  502. virtual bool ReportFixture(b2Fixture* fixture)
  503. {
  504. // Ignore sensor
  505. if (fixture->IsSensor())
  506. return true;
  507. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  508. return true;
  509. results_.Push((RigidBody2D*)(fixture->GetBody()->GetUserData()));
  510. return true;
  511. }
  512. private:
  513. // Results.
  514. PODVector<RigidBody2D*>& results_;
  515. // Collision mask.
  516. unsigned collisionMask_;
  517. };
  518. void PhysicsWorld2D::GetRigidBodies(PODVector<RigidBody2D*>& results, const Rect& aabb, unsigned collisionMask)
  519. {
  520. AabbQueryCallback callback(results, collisionMask);
  521. b2AABB b2Aabb;
  522. Vector2 delta(M_EPSILON, M_EPSILON);
  523. b2Aabb.lowerBound = ToB2Vec2(aabb.min_ - delta);
  524. b2Aabb.upperBound = ToB2Vec2(aabb.max_ + delta);
  525. world_->QueryAABB(&callback, b2Aabb);
  526. }
  527. bool PhysicsWorld2D::GetAllowSleeping() const
  528. {
  529. return world_->GetAllowSleeping();
  530. }
  531. bool PhysicsWorld2D::GetWarmStarting() const
  532. {
  533. return world_->GetWarmStarting();
  534. }
  535. bool PhysicsWorld2D::GetContinuousPhysics() const
  536. {
  537. return world_->GetContinuousPhysics();
  538. }
  539. bool PhysicsWorld2D::GetSubStepping() const
  540. {
  541. return world_->GetSubStepping();
  542. }
  543. bool PhysicsWorld2D::GetAutoClearForces() const
  544. {
  545. return world_->GetAutoClearForces();
  546. }
  547. void PhysicsWorld2D::OnSceneSet(Scene* scene)
  548. {
  549. // Subscribe to the scene subsystem update, which will trigger the physics simulation step
  550. if (scene)
  551. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, ATOMIC_HANDLER(PhysicsWorld2D, HandleSceneSubsystemUpdate));
  552. else
  553. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  554. }
  555. void PhysicsWorld2D::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  556. {
  557. if (!updateEnabled_)
  558. return;
  559. using namespace SceneSubsystemUpdate;
  560. Update(eventData[P_TIMESTEP].GetFloat());
  561. }
  562. void PhysicsWorld2D::SendBeginContactEvents()
  563. {
  564. if (beginContactInfos_.Empty())
  565. return;
  566. using namespace PhysicsBeginContact2D;
  567. VariantMap& eventData = GetEventDataMap();
  568. VariantMap nodeEventData;
  569. eventData[P_WORLD] = this;
  570. for (unsigned i = 0; i < beginContactInfos_.Size(); ++i)
  571. {
  572. ContactInfo& contactInfo = beginContactInfos_[i];
  573. eventData[P_BODYA] = contactInfo.bodyA_.Get();
  574. eventData[P_BODYB] = contactInfo.bodyB_.Get();
  575. eventData[P_NODEA] = contactInfo.nodeA_.Get();
  576. eventData[P_NODEB] = contactInfo.nodeB_.Get();
  577. eventData[P_CONTACT] = (void*)contactInfo.contact_;
  578. SendEvent(E_PHYSICSBEGINCONTACT2D, eventData);
  579. nodeEventData[NodeBeginContact2D::P_CONTACT] = (void*)contactInfo.contact_;
  580. if (contactInfo.nodeA_)
  581. {
  582. nodeEventData[NodeBeginContact2D::P_BODY] = contactInfo.bodyA_.Get();
  583. nodeEventData[NodeBeginContact2D::P_OTHERNODE] = contactInfo.nodeB_.Get();
  584. nodeEventData[NodeBeginContact2D::P_OTHERBODY] = contactInfo.bodyB_.Get();
  585. contactInfo.nodeA_->SendEvent(E_NODEBEGINCONTACT2D, nodeEventData);
  586. }
  587. if (contactInfo.nodeB_)
  588. {
  589. nodeEventData[NodeBeginContact2D::P_BODY] = contactInfo.bodyB_.Get();
  590. nodeEventData[NodeBeginContact2D::P_OTHERNODE] = contactInfo.nodeA_.Get();
  591. nodeEventData[NodeBeginContact2D::P_OTHERBODY] = contactInfo.bodyA_.Get();
  592. contactInfo.nodeB_->SendEvent(E_NODEBEGINCONTACT2D, nodeEventData);
  593. }
  594. }
  595. beginContactInfos_.Clear();
  596. }
  597. void PhysicsWorld2D::SendEndContactEvents()
  598. {
  599. if (endContactInfos_.Empty())
  600. return;
  601. using namespace PhysicsEndContact2D;
  602. VariantMap& eventData = GetEventDataMap();
  603. VariantMap nodeEventData;
  604. eventData[P_WORLD] = this;
  605. for (unsigned i = 0; i < endContactInfos_.Size(); ++i)
  606. {
  607. ContactInfo& contactInfo = endContactInfos_[i];
  608. eventData[P_BODYA] = contactInfo.bodyA_.Get();
  609. eventData[P_BODYB] = contactInfo.bodyB_.Get();
  610. eventData[P_NODEA] = contactInfo.nodeA_.Get();
  611. eventData[P_NODEB] = contactInfo.nodeB_.Get();
  612. eventData[P_CONTACT] = (void*)contactInfo.contact_;
  613. SendEvent(E_PHYSICSENDCONTACT2D, eventData);
  614. nodeEventData[NodeEndContact2D::P_CONTACT] = (void*)contactInfo.contact_;
  615. if (contactInfo.nodeA_)
  616. {
  617. nodeEventData[NodeEndContact2D::P_BODY] = contactInfo.bodyA_.Get();
  618. nodeEventData[NodeEndContact2D::P_OTHERNODE] = contactInfo.nodeB_.Get();
  619. nodeEventData[NodeEndContact2D::P_OTHERBODY] = contactInfo.bodyB_.Get();
  620. contactInfo.nodeA_->SendEvent(E_NODEENDCONTACT2D, nodeEventData);
  621. }
  622. if (contactInfo.nodeB_)
  623. {
  624. nodeEventData[NodeEndContact2D::P_BODY] = contactInfo.bodyB_.Get();
  625. nodeEventData[NodeEndContact2D::P_OTHERNODE] = contactInfo.nodeA_.Get();
  626. nodeEventData[NodeEndContact2D::P_OTHERBODY] = contactInfo.bodyA_.Get();
  627. contactInfo.nodeB_->SendEvent(E_NODEENDCONTACT2D, nodeEventData);
  628. }
  629. }
  630. endContactInfos_.Clear();
  631. }
  632. PhysicsWorld2D::ContactInfo::ContactInfo()
  633. {
  634. }
  635. PhysicsWorld2D::ContactInfo::ContactInfo(b2Contact* contact)
  636. {
  637. b2Fixture* fixtureA = contact->GetFixtureA();
  638. b2Fixture* fixtureB = contact->GetFixtureB();
  639. bodyA_ = (RigidBody2D*)(fixtureA->GetBody()->GetUserData());
  640. bodyB_ = (RigidBody2D*)(fixtureB->GetBody()->GetUserData());
  641. nodeA_ = bodyA_->GetNode();
  642. nodeB_ = bodyB_->GetNode();
  643. contact_ = contact;
  644. }
  645. PhysicsWorld2D::ContactInfo::ContactInfo(const ContactInfo& other) :
  646. bodyA_(other.bodyA_),
  647. bodyB_(other.bodyB_),
  648. nodeA_(other.nodeA_),
  649. nodeB_(other.nodeB_),
  650. contact_(other.contact_)
  651. {
  652. }
  653. }