| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- // Copyright (c) 2008-2023 the Urho3D project
- // License: MIT
- #pragma once
- #include "../Scene/Component.h"
- #include "../IO/VectorBuffer.h"
- #include <box2d/box2d.h>
- #include <memory>
- namespace Urho3D
- {
- class Camera;
- class CollisionShape2D;
- class RigidBody2D;
- /// 2D Physics raycast hit.
- struct URHO3D_API PhysicsRaycastResult2D
- {
- /// Test for inequality, added to prevent GCC from complaining.
- bool operator !=(const PhysicsRaycastResult2D& rhs) const
- {
- return position_ != rhs.position_ || normal_ != rhs.normal_ || distance_ != rhs.distance_ || body_ != rhs.body_;
- }
- /// Hit worldspace position.
- Vector2 position_;
- /// Hit worldspace normal.
- Vector2 normal_;
- /// Hit distance from ray origin.
- float distance_{};
- /// Rigid body that was hit.
- RigidBody2D* body_{};
- };
- /// Delayed world transform assignment for parented 2D rigidbodies.
- struct DelayedWorldTransform2D
- {
- /// Rigid body.
- RigidBody2D* rigidBody_;
- /// Parent rigid body.
- RigidBody2D* parentRigidBody_;
- /// New world position.
- Vector3 worldPosition_;
- /// New world rotation.
- Quaternion worldRotation_;
- };
- /// 2D physics simulation world component. Should be added only to the root scene node.
- class URHO3D_API PhysicsWorld2D : public Component, public b2ContactListener, public b2Draw
- {
- URHO3D_OBJECT(PhysicsWorld2D, Component);
- public:
- /// Construct.
- explicit PhysicsWorld2D(Context* context);
- /// Destruct.
- ~PhysicsWorld2D() override;
- /// Register object factory.
- /// @nobind
- static void RegisterObject(Context* context);
- /// Visualize the component as debug geometry.
- void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
- // Implement b2ContactListener
- /// Called when two fixtures begin to touch.
- void BeginContact(b2Contact* contact) override;
- /// Called when two fixtures cease to touch.
- void EndContact(b2Contact* contact) override;
- /// Called when contact is updated.
- void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override;
- // Implement b2Draw
- /// Draw a closed polygon provided in CCW order.
- void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
- /// Draw a solid closed polygon provided in CCW order.
- void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
- /// Draw a circle.
- void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) override;
- /// Draw a solid circle.
- void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) override;
- /// Draw a line segment.
- void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override;
- /// Draw a transform. Choose your own length scale.
- void DrawTransform(const b2Transform& xf) override;
- /// Draw a point.
- void DrawPoint(const b2Vec2& p, float size, const b2Color& color) override;
- /// Step the simulation forward.
- void Update(float timeStep);
- /// Add debug geometry to the debug renderer.
- void DrawDebugGeometry();
- /// Enable or disable automatic physics simulation during scene update. Enabled by default.
- /// @property
- void SetUpdateEnabled(bool enable);
- /// Set draw shape.
- /// @property
- void SetDrawShape(bool drawShape);
- /// Set draw joint.
- /// @property
- void SetDrawJoint(bool drawJoint);
- /// Set draw aabb.
- /// @property
- void SetDrawAabb(bool drawAabb);
- /// Set draw pair.
- /// @property
- void SetDrawPair(bool drawPair);
- /// Set draw center of mass.
- /// @property
- void SetDrawCenterOfMass(bool drawCenterOfMass);
- /// Set allow sleeping.
- /// @property
- void SetAllowSleeping(bool enable);
- /// Set warm starting.
- /// @property
- void SetWarmStarting(bool enable);
- /// Set continuous physics.
- /// @property
- void SetContinuousPhysics(bool enable);
- /// Set sub stepping.
- /// @property
- void SetSubStepping(bool enable);
- /// Set gravity.
- /// @property
- void SetGravity(const Vector2& gravity);
- /// Set auto clear forces.
- /// @property
- void SetAutoClearForces(bool enable);
- /// Set velocity iterations.
- /// @property
- void SetVelocityIterations(int velocityIterations);
- /// Set position iterations.
- /// @property
- void SetPositionIterations(int positionIterations);
- /// Add rigid body.
- void AddRigidBody(RigidBody2D* rigidBody);
- /// Remove rigid body.
- void RemoveRigidBody(RigidBody2D* rigidBody);
- /// Add a delayed world transform assignment. Called by RigidBody2D.
- void AddDelayedWorldTransform(const DelayedWorldTransform2D& transform);
- /// Perform a physics world raycast and return all hits.
- void Raycast(Vector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint,
- u16 collisionMask = M_U16_MASK_ALL_BITS);
- /// Perform a physics world raycast and return the closest hit.
- void RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint,
- u16 collisionMask = M_U16_MASK_ALL_BITS);
- /// Return rigid body at point.
- RigidBody2D* GetRigidBody(const Vector2& point, u16 collisionMask = M_U16_MASK_ALL_BITS);
- /// Return rigid body at screen point.
- RigidBody2D* GetRigidBody(int screenX, int screenY, u16 collisionMask = M_U16_MASK_ALL_BITS);
- /// Return rigid bodies by a box query.
- void GetRigidBodies(Vector<RigidBody2D*>& results, const Rect& aabb, u16 collisionMask = M_U16_MASK_ALL_BITS);
- /// Return whether physics world will automatically simulate during scene update.
- /// @property
- bool IsUpdateEnabled() const { return updateEnabled_; }
- /// Return draw shape.
- /// @property
- bool GetDrawShape() const { return (m_drawFlags & e_shapeBit) != 0; }
- /// Return draw joint.
- /// @property
- bool GetDrawJoint() const { return (m_drawFlags & e_jointBit) != 0; }
- /// Return draw aabb.
- /// @property
- bool GetDrawAabb() const { return (m_drawFlags & e_aabbBit) != 0; }
- /// Return draw pair.
- /// @property
- bool GetDrawPair() const { return (m_drawFlags & e_pairBit) != 0; }
- /// Return draw center of mass.
- /// @property
- bool GetDrawCenterOfMass() const { return (m_drawFlags & e_centerOfMassBit) != 0; }
- /// Return allow sleeping.
- /// @property
- bool GetAllowSleeping() const;
- /// Return warm starting.
- /// @property
- bool GetWarmStarting() const;
- /// Return continuous physics.
- /// @property
- bool GetContinuousPhysics() const;
- /// Return sub stepping.
- /// @property
- bool GetSubStepping() const;
- /// Return auto clear forces.
- /// @property
- bool GetAutoClearForces() const;
- /// Return gravity.
- /// @property
- const Vector2& GetGravity() const { return gravity_; }
- /// Return velocity iterations.
- /// @property
- int GetVelocityIterations() const { return velocityIterations_; }
- /// Return position iterations.
- /// @property
- int GetPositionIterations() const { return positionIterations_; }
- /// Return the Box2D physics world.
- b2World* GetWorld() { return world_.get(); }
- /// Set node dirtying to be disregarded.
- void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
- /// Return whether node dirtying should be disregarded.
- bool IsApplyingTransforms() const { return applyingTransforms_; }
- protected:
- /// Handle scene being assigned.
- void OnSceneSet(Scene* scene) override;
- /// Handle the scene subsystem update event, step simulation here.
- void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
- /// Send begin contact events.
- void SendBeginContactEvents();
- /// Send end contact events.
- void SendEndContactEvents();
- /// Box2D physics world.
- std::unique_ptr<b2World> world_;
- /// Gravity.
- Vector2 gravity_;
- /// Velocity iterations.
- int velocityIterations_{};
- /// Position iterations.
- int positionIterations_{};
- /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
- WeakPtr<Scene> scene_;
- /// Debug renderer.
- DebugRenderer* debugRenderer_{};
- /// Debug draw depth test mode.
- bool debugDepthTest_{};
- /// Automatic simulation update enabled flag.
- bool updateEnabled_{true};
- /// Whether is currently stepping the world. Used internally.
- bool physicsStepping_{};
- /// Applying transforms.
- bool applyingTransforms_{};
- /// Rigid bodies.
- Vector<WeakPtr<RigidBody2D>> rigidBodies_;
- /// Delayed (parented) world transform assignments.
- HashMap<RigidBody2D*, DelayedWorldTransform2D> delayedWorldTransforms_;
- /// Contact info.
- struct ContactInfo
- {
- /// Construct.
- ContactInfo();
- /// Construct.
- explicit ContactInfo(b2Contact* contact);
- /// Write contact info to buffer.
- const Vector<byte>& Serialize(VectorBuffer& buffer) const;
- /// Rigid body A.
- SharedPtr<RigidBody2D> bodyA_;
- /// Rigid body B.
- SharedPtr<RigidBody2D> bodyB_;
- /// Node A.
- SharedPtr<Node> nodeA_;
- /// Node B.
- SharedPtr<Node> nodeB_;
- /// Shape A.
- SharedPtr<CollisionShape2D> shapeA_;
- /// Shape B.
- SharedPtr<CollisionShape2D> shapeB_;
- /// Number of contact points.
- int numPoints_{};
- /// Contact normal in world space.
- Vector2 worldNormal_;
- /// Contact positions in world space.
- Vector2 worldPositions_[b2_maxManifoldPoints];
- /// Contact overlap values.
- float separations_[b2_maxManifoldPoints]{};
- };
- /// Begin contact infos.
- Vector<ContactInfo> beginContactInfos_;
- /// End contact infos.
- Vector<ContactInfo> endContactInfos_;
- /// Temporary buffer with contact data.
- VectorBuffer contacts_;
- };
- }
|