载入中...
搜索中...
未找到
World.h
浏览该文件的文档.
1#pragma once
2#include "common/Export.h"
3
4
6#include "common/Result.h"
7#include "common/Snapshot.h"
8#include "physics/Joint2D.h"
11
12#include <cstdint>
13#include <memory>
14#include <string>
15#include <unordered_map>
16#include <unordered_set>
17#include <vector>
18
19class b2World;
20class b2Body;
21class b2Fixture;
22class b2Joint;
23class b2Contact;
24struct b2Manifold;
25struct b2ContactImpulse;
26
27namespace eve::graphics {
28class Graphics;
29}
30
31namespace eve::physics {
32struct ForceStepState;
33
34class Body;
35class Joint2D;
36class Fixture;
37class ContactRelay;
38class Mechanism2D;
39
45public:
47 struct ContactEvent {
48 int bodyAId = 0;
49 int bodyBId = 0;
50 std::string fixtureATag;
51 std::string fixtureBTag;
52 };
53
59 struct TriggerEvent {
60 int sensorBodyId = 0;
61 int visitorBodyId = 0;
62 std::string sensorFixtureTag;
63 std::string visitorFixtureTag;
64 };
65
67 float pointX = 0.f;
68 float pointY = 0.f;
69 float normalX = 0.f;
70 float normalY = 0.f;
71 float relativeNormalSpeed = 0.f;
72 float normalImpulse = 0.f;
73 float tangentImpulse = 0.f;
74 };
75
80 struct ClothContact {
81 bool hit = false;
82 float nx = 0.f;
83 float ny = 0.f;
84 float depth = 0.f; // radius - distance (pixels); > 0 when inside
85 Body *body = nullptr;
86 };
87
95 World(float gravityX, float gravityY, bool sleep, float meter,
97 ~World();
98
99 World(const World &) = delete;
100 World &operator=(const World &) = delete;
101
103 void update(float dt);
105 void updateFull(float dt, int velocityIterations, int positionIterations);
106
116 [[nodiscard("check the physics step outcome or explicitly ignore it")]]
118
120 [[nodiscard]] SimulationObservation simulationObservation() const noexcept;
122 [[nodiscard]] SimulationBackendKind backendKind() const noexcept;
124 [[nodiscard]] SimulationDeterminism backendDeterminism() const noexcept;
126 [[nodiscard]] eve::SimulationTick simulationTick() const noexcept { return simulationTick_; }
128 [[nodiscard]] PhysicsWorldHandle runtimeHandle() const noexcept { return runtimeHandle_; }
137 [[nodiscard]] std::weak_ptr<const void> lifetimeToken() const noexcept { return lifetime_; }
139 [[nodiscard]] eve::PersistentId persistentId() const noexcept { return instanceId_; }
141 [[nodiscard]] bool usedBackendFallback() const noexcept { return backendFallback_; }
146 [[nodiscard("inspect backend selection diagnostics")]]
147 eve::Status backendSelectionStatus() const;
148
157 [[nodiscard("check or persist the physics snapshot")]]
159
173 [[nodiscard("check the physics snapshot restore outcome")]]
174 eve::Result<void> restore(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider);
175
177 void setGravity(float gx, float gy);
178 float getGravityX() const;
179 float getGravityY() const;
180
182 void setMeter(float pixelsPerMeter);
183 float getMeter() const { return meter_; }
184
193 Body *newBody(const std::string &bodyType, float x, float y);
195 [[nodiscard]] Body *findBody(PhysicsBodyHandle handle) const;
197 [[nodiscard]] Body *findBodyById(int bodyId) const;
199 [[nodiscard]] Joint2D *findJoint(PhysicsJointHandle handle) const;
200
211 Joint2D *newDistanceJoint(Body *bodyA, Body *bodyB, float anchorAX, float anchorAY, float anchorBX, float anchorBY,
212 float lengthPixels, bool collideConnected = false);
223 Joint2D *newRevoluteJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, bool collideConnected = false);
234 Joint2D *newPrismaticJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, float axisX, float axisY,
235 bool collideConnected = false);
246 Joint2D *newWeldJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, bool collideConnected = false);
257 Joint2D *newWheelJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, float axisX, float axisY,
258 bool collideConnected = false);
269 Joint2D *newMotorJoint(Body *bodyA, Body *bodyB, bool collideConnected = false);
281 Joint2D *newGearJoint(Joint2D *joint1, Joint2D *joint2, float ratio);
282
291 Mechanism2D *newShaft(Body *support, Body *rotor, float anchorX, float anchorY, bool collideConnected = false);
302 Mechanism2D *newRatchet(Body *frame, Body *wheel, float anchorX, float anchorY, int direction,
303 float engagementTorque, bool collideConnected = false);
313 Mechanism2D *newCrankSlider(Body *frame, Body *crank, Body *rod, Body *slider, float crankAnchorX,
314 float crankAnchorY, float crankPinX, float crankPinY, float sliderPinX,
315 float sliderPinY, float slideAxisX, float slideAxisY, bool collideConnected = false);
316
325 [[nodiscard]] ResultRef<Joint2D> resolveJoint2D(int id) const;
327 void destroyBody(Body *body);
329 void destroy();
330
332 bool isValid() const { return !destroyed_ && world_ != nullptr; }
333
338 bool pointProbe(float x, float y, float radius, ClothContact *out) const;
339
341 void drawDebug(graphics::Graphics *gfx);
342
347 int rayCast(float x1, float y1, float x2, float y2);
348 bool hasRayHit() const { return rayHitBodyId_ >= 0; }
349 int getRayHitBodyId() const { return rayHitBodyId_; }
350 float getRayHitX() const { return rayHitX_; }
351 float getRayHitY() const { return rayHitY_; }
352 float getRayHitNormalX() const { return rayHitNormalX_; }
353 float getRayHitNormalY() const { return rayHitNormalY_; }
355 float getRayHitFraction() const { return rayHitFraction_; }
356
361 int queryAABB(float x, float y, float w, float h);
362 int getQueryCount() const { return static_cast<int>(queryBodyIds_.size()); }
363 int getQueryBodyId(int index) const;
364
365 int getBeginContactCount() const { return int(beginContacts_.size()); }
366 int getBeginContactBodyAId(int index) const;
367 int getBeginContactBodyBId(int index) const;
368 std::string getBeginContactFixtureATag(int index) const;
369 std::string getBeginContactFixtureBTag(int index) const;
370 int getEndContactCount() const { return int(endContacts_.size()); }
371 int getEndContactBodyAId(int index) const;
372 int getEndContactBodyBId(int index) const;
373 std::string getEndContactFixtureATag(int index) const;
374 std::string getEndContactFixtureBTag(int index) const;
375
377 int getBeginTriggerCount() const { return int(beginTriggers_.size()); }
378 int getBeginTriggerSensorBodyId(int index) const;
379 int getBeginTriggerVisitorBodyId(int index) const;
380 std::string getBeginTriggerSensorFixtureTag(int index) const;
381 std::string getBeginTriggerVisitorFixtureTag(int index) const;
383 int getEndTriggerCount() const { return int(endTriggers_.size()); }
384 int getEndTriggerSensorBodyId(int index) const;
385 int getEndTriggerVisitorBodyId(int index) const;
386 std::string getEndTriggerSensorFixtureTag(int index) const;
387 std::string getEndTriggerVisitorFixtureTag(int index) const;
388
389 int getImpactCount() const { return int(impacts_.size()); }
390 int getImpactBodyAId(int index) const;
391 int getImpactBodyBId(int index) const;
392 std::string getImpactFixtureATag(int index) const;
393 std::string getImpactFixtureBTag(int index) const;
394 float getImpactPointX(int index) const;
395 float getImpactPointY(int index) const;
396 float getImpactNormalX(int index) const;
397 float getImpactNormalY(int index) const;
398 float getImpactRelativeNormalSpeed(int index) const;
399 float getImpactNormalImpulse(int index) const;
400 float getImpactTangentImpulse(int index) const;
402 void clearContactEvents();
403
405 float toMeters(float pixels) const;
407 float toPixels(float meters) const;
408
417 b2World *raw() { return world_; }
426 const b2World *raw() const { return world_; }
427
428 void onBeginContact(b2Contact *contact);
429 void onEndContact(b2Contact *contact);
430 void onPreSolve(b2Contact *contact, const b2Manifold *oldManifold);
431 void onPostSolve(b2Contact *contact, const b2ContactImpulse *impulse);
432
433 void forgetBody(Body *body);
434 void forgetFixture(Fixture *fixture);
436 void forgetJoint(Joint2D *joint);
438 void forgetMechanism(Mechanism2D *mechanism);
439
440 int nextBodyId();
441 PhysicsBodyHandle nextBodyRuntimeHandle();
443 PhysicsJointHandle nextJointRuntimeHandle();
445 int nextJointId();
447 int nextMechanismId();
448
449private:
450 std::shared_ptr<ForceStepState> pendingForceStep_;
451 bool simulationStepActive_ = false;
452 [[nodiscard]] Result<void> validateForceStep(const SimulationStep &step) const;
453 void finishForceStep() noexcept;
454 void cancelForceStep() noexcept;
455 friend struct WorldSnapshotAccess;
457 friend class Body;
458 friend class ForceBatch;
459 friend class Joint2D;
460 friend struct PhysicsJointLink;
461 friend class Fixture;
462 friend class Joint2D;
463 friend class Mechanism2D;
464
472 void releaseBodyJoints2D(Body &body);
473 void invalidateJoints2D() noexcept;
474 std::vector<std::unique_ptr<Joint2D>> restoredJoints2D_;
475 std::vector<std::unique_ptr<Body>> restoredBodies_;
476 std::vector<std::unique_ptr<Fixture>> restoredFixtures_;
477
478 b2World *world_ = nullptr;
479 ContactRelay *relay_ = nullptr;
480 std::unique_ptr<ISimulationBackend> simulation_;
481 PhysicsWorldHandle runtimeHandle_ = PhysicsWorldHandle::invalid();
482 std::shared_ptr<const void> lifetime_ = std::make_shared<int>(0);
483 eve::PersistentId instanceId_ = eve::PersistentId::nil();
484 float meter_ = 30.f;
485 int nextId_ = 1;
486 int nextJointId_ = 1;
487 int nextMechanismId_ = 1;
488 std::uint32_t nextBodyHandleIndex_ = 1u;
489 std::uint32_t nextJointHandleIndex_ = 1u;
490 bool destroyed_ = false;
491 eve::SimulationTick simulationTick_ = eve::SimulationTick::zero();
492 eve::Status backendSelectionStatus_ = eve::Status::success();
493 bool backendFallback_ = false;
494
495 std::unordered_set<Body *> bodies_;
496 std::unordered_set<Fixture *> fixtures_;
497 std::unordered_set<Joint2D *> joints_;
498 std::unordered_set<Mechanism2D *> mechanisms_;
499 std::unordered_map<PhysicsJointHandle, Joint2D *> jointHandles_;
500
501 int rayHitBodyId_ = -1;
502 float rayHitX_ = 0.f;
503 float rayHitY_ = 0.f;
504 float rayHitNormalX_ = 0.f;
505 float rayHitNormalY_ = 0.f;
506 float rayHitFraction_ = 0.f;
507
508 std::vector<int> queryBodyIds_;
509
510 struct PreSolveData {
511 float pointX = 0.f;
512 float pointY = 0.f;
513 float normalX = 0.f;
514 float normalY = 0.f;
515 float relativeNormalSpeed = 0.f;
516 };
517 std::unordered_map<b2Contact *, PreSolveData> preSolve_;
518 std::vector<ContactEvent> beginContacts_;
519 std::vector<ContactEvent> endContacts_;
520 std::vector<TriggerEvent> beginTriggers_;
521 std::vector<TriggerEvent> endTriggers_;
522 std::vector<ImpactEvent> impacts_;
523
524 const TriggerEvent &triggerEventAt(const std::vector<TriggerEvent> &events, int index, const char *operation) const;
525
526 [[nodiscard]] eve::Result<void> prepareRuntimeHandleRefresh(std::size_t incomingBodyCount) const;
527 void refreshRuntimeHandlesAfterRestore();
528 void adoptPreparedTopology(World &prepared);
529};
530
531} // namespace eve::physics
double y
double x
ActionParameterOperation operation
float w
Definition AnimClip.cpp:738
Vocabulary aliases for nullable and checked borrowed references.
int instanceId
#define EVENGINE_API_WORLD
Definition Export.h:109
float u
Definition Grass.cpp:233
int h
void(* destroy)(void *)
float ratio
bool collideConnected
Snapshot snapshot
double radius
Definition MeleeHit.cpp:42
OceanWakeSettings settings
ssq::Object frame
double dt
std::vector< particles::ParticleRecordEvent > events
float f
Process-local, generation-qualified handles owned by the physics domain.
bool hit
PrimitiveHandle handle
std::string body
uint8_t * pixels
Move-only, checked operation results for the common layer.
RoadLaneDirection direction
float axisY
Definition RockMesh.cpp:22
float axisX
Definition RockMesh.cpp:22
ScriptStructure out
Backend-neutral, observable fixed-step contract for physics domains.
Versioned, integrity-checked persistence envelopes.
float step
Definition TreeMesh.cpp:451
std::uint32_t depth
uint32_t index
Contact contact
std::array< double, 3 > impulse
Move-only operation result carrying either a value or Status.
Definition Result.h:176
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
Id128 public API.
Definition Identity.h:111
static constexpr Id128 nil() noexcept
Returns the all-zero nil value.
Definition Identity.h:141
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Definition Body.h:21
2D fixture: a shape attached to a Body with material + filter settings. Also carries a string tag use...
Definition Fixture.h:18
Move-only, single-use collection of validated force requests. @ownership Owns values and handles only...
Definition ForceBatch.h:26
Minimal observable contract for physics simulation providers.
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
Definition Joint2D.h:58
Composed 2D mechanical assembly owned by a World.
Definition Mechanism2D.h:25
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
float getRayHitX() const
Definition World.h:350
int getRayHitBodyId() const
Definition World.h:349
int getEndTriggerCount() const
Sensor/visitor end overlaps collected during the last step.
Definition World.h:383
int getBeginTriggerCount() const
Sensor/visitor begin overlaps collected during the last step (2D parity with World3D).
Definition World.h:377
std::weak_ptr< const void > lifetimeToken() const noexcept
Weak lifetime token for guarded cross-domain world observers.
Definition World.h:137
float getRayHitY() const
Definition World.h:351
World(const World &)=delete
int getQueryCount() const
Definition World.h:362
eve::PersistentId persistentId() const noexcept
Stable non-nil identity written to snapshot envelopes.
Definition World.h:139
int getImpactCount() const
Definition World.h:389
float getRayHitFraction() const
Fraction along the segment [0,1] of the closest hit.
Definition World.h:355
float getRayHitNormalY() const
Definition World.h:353
bool hasRayHit() const
Definition World.h:348
b2World * raw()
Exposes the underlying Box2D world for tightly-scoped backend integration.
Definition World.h:417
bool usedBackendFallback() const noexcept
Whether optional accelerator selection fell back to CPU.
Definition World.h:141
int getBeginContactCount() const
Definition World.h:365
PhysicsWorldHandle runtimeHandle() const noexcept
Process-local identity used by PhysicsLink; invalid after destruction.
Definition World.h:128
World & operator=(const World &)=delete
float getRayHitNormalX() const
Definition World.h:352
int getEndContactCount() const
Definition World.h:370
const b2World * raw() const
Exposes the underlying Box2D world for read-only backend integration.
Definition World.h:426
bool isValid() const
True while the underlying Box2D world is alive.
Definition World.h:332
float getMeter() const
Definition World.h:183
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
SimulationBackendKind
Kind of implementation that owns a simulation step.
SimulationDeterminism
Determinism guarantee made by a simulation backend.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Observable backend progress shared by CPU and accelerator providers.
Validated solver policy for one simulation step.
Result of a point probe: deepest non-sensor fixture within radius. Normal points from the shape towar...
Definition World.h:80
ContactEvent public API.
Definition World.h:47
Begin/end sensor overlap with an explicit sensor and visitor side. Populated when exactly one fixture...
Definition World.h:59