PhysicsWorld2D.cpp 27 KB

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