载入中...
搜索中...
未找到
World.cpp
浏览该文件的文档.
1#include "physics/World.h"
2#include "physics/Body.h"
4#include "physics/Fixture.h"
5#include "physics/Joint2D.h"
9
10#include "common/Exception.h"
11#include "common/Profile.h"
13
14#include <Box2D/Box2D.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstring>
19#include <limits>
20#include <optional>
21#include <utility>
22
23namespace eve::physics {
24namespace {
25b2BodyType parseBodyType(const std::string &type) {
26 if (type == "static") return b2_staticBody;
27 if (type == "kinematic") return b2_kinematicBody;
28 if (type == "dynamic") return b2_dynamicBody;
29 throw eve::Exception("World.newBody: unknown body type '%s' (use static|kinematic|dynamic)", type.c_str());
30}
31
32Body *bodyFromFixture(b2Fixture *f) {
33 if (!f) return nullptr;
34 b2Body *b = f->GetBody();
35 if (!b) return nullptr;
36 return static_cast<Body *>(b->GetUserData());
37}
38
39Fixture *fixtureFromRaw(b2Fixture *f) { return f ? static_cast<Fixture *>(f->GetUserData()) : nullptr; }
40
41// Signed distance from a world point to a shape (meters). Negative when inside.
42// `normal` points from the shape toward the point (world space, unit length).
43bool shapePointDistance(const b2Shape *shape, const b2Transform &xf, const b2Vec2 &p, float &dist, b2Vec2 &normal) {
44 dist = 0.f;
45 normal = b2Vec2(0.f, 1.f);
46 if (!shape) return false;
47
48 if (shape->GetType() == b2Shape::e_circle) {
49 const auto *circle = static_cast<const b2CircleShape *>(shape);
50 const b2Vec2 center = b2Mul(xf, circle->m_p);
51 const b2Vec2 d = p - center;
52 const float r = circle->m_radius;
53 dist = b2Distance(p, center) - r;
54 const float len = d.Length();
55 if (len > 1e-6f) {
56 normal = (1.f / len) * d;
57 } else if (r > 0.f) {
58 normal = b2Vec2(0.f, 1.f);
59 }
60 return true;
61 }
62
63 if (shape->GetType() == b2Shape::e_polygon) {
64 const auto *poly = static_cast<const b2PolygonShape *>(shape);
65 const b2Vec2 local = b2MulT(xf, p);
66 const int n = poly->m_count;
67 if (n < 3) return false;
68
69 // Signed distance to each edge: positive outside for Box2D CCW polygons
70 // (m_normals point outward). Inside when every side <= 0.
71 float minSide = std::numeric_limits<float>::max();
72 float bestEdge = std::numeric_limits<float>::max();
73 b2Vec2 bestN(0.f, 1.f);
74 b2Vec2 bestQ;
75 bool inside = true;
76 for (int i = 0; i < n; ++i) {
77 const b2Vec2 &a = poly->m_vertices[i];
78 const b2Vec2 &b = poly->m_vertices[(i + 1) % n];
79 const float side = b2Dot(local - a, poly->m_normals[i]);
80 if (side > 0.f) inside = false;
81 if (side < minSide) {
82 minSide = side;
83 bestN = poly->m_normals[i];
84 }
85 // Closest point on the edge segment.
86 const b2Vec2 ab = b - a;
87 const float len2 = b2Dot(ab, ab);
88 float t = 0.f;
89 if (len2 > 1e-12f) t = b2Clamp(b2Dot(local - a, ab) / len2, 0.f, 1.f);
90 const b2Vec2 q = a + t * ab;
91 const float d2 = b2DistanceSquared(local, q);
92 if (d2 < bestEdge) {
93 bestEdge = d2;
94 bestQ = q;
95 }
96 }
97 if (inside) {
98 dist = minSide; // negative penetration
99 normal = b2Mul(xf.q, bestN);
100 } else {
101 dist = std::sqrt(bestEdge);
102 const b2Vec2 delta = local - bestQ;
103 if (delta.LengthSquared() > 1e-8f) {
104 normal = b2Mul(xf.q, (1.f / delta.Length()) * delta);
105 } else {
106 normal = b2Mul(xf.q, bestN);
107 }
108 }
109 return true;
110 }
111
112 if (shape->GetType() == b2Shape::e_edge) {
113 const auto *edge = static_cast<const b2EdgeShape *>(shape);
114 const b2Vec2 a = b2Mul(xf, edge->m_vertex1);
115 const b2Vec2 b = b2Mul(xf, edge->m_vertex2);
116 const b2Vec2 ab = b - a;
117 const float len2 = b2Dot(ab, ab);
118 float t = 0.f;
119 if (len2 > 1e-12f) t = b2Clamp(b2Dot(p - a, ab) / len2, 0.f, 1.f);
120 const b2Vec2 q = a + t * ab;
121 const b2Vec2 delta = p - q;
122 dist = delta.Length();
123 if (dist > 1e-6f) {
124 normal = (1.f / dist) * delta;
125 } else if (len2 > 1e-12f) {
126 normal = (1.f / std::sqrt(len2)) * b2Vec2(-ab.y, ab.x);
127 }
128 return true;
129 }
130
131 if (shape->GetType() == b2Shape::e_chain) {
132 const auto *chain = static_cast<const b2ChainShape *>(shape);
133 float best = std::numeric_limits<float>::max();
134 b2Vec2 bestN(0.f, 1.f);
135 for (int i = 0; i + 1 < chain->m_count; ++i) {
136 const b2Vec2 a = b2Mul(xf, chain->m_vertices[i]);
137 const b2Vec2 b = b2Mul(xf, chain->m_vertices[i + 1]);
138 const b2Vec2 ab = b - a;
139 const float len2 = b2Dot(ab, ab);
140 float t = 0.f;
141 if (len2 > 1e-12f) t = b2Clamp(b2Dot(p - a, ab) / len2, 0.f, 1.f);
142 const b2Vec2 q = a + t * ab;
143 const b2Vec2 delta = p - q;
144 const float d = delta.Length();
145 if (d < best) {
146 best = d;
147 bestN = d > 1e-6f ? (1.f / d) * delta
148 : (len2 > 1e-12f ? (1.f / std::sqrt(len2)) * b2Vec2(-ab.y, ab.x) : b2Vec2(0.f, 1.f));
149 }
150 }
151 if (best < std::numeric_limits<float>::max()) {
152 dist = best;
153 normal = bestN;
154 return true;
155 }
156 }
157 return false;
158}
159
160World::ContactEvent contactEventFrom(b2Contact *contact) {
161 World::ContactEvent out;
162 if (!contact) return out;
163 Fixture *fa = fixtureFromRaw(contact->GetFixtureA());
164 Fixture *fb = fixtureFromRaw(contact->GetFixtureB());
165 if (fa) {
166 out.bodyAId = fa->getBodyId();
167 out.fixtureATag = fa->getTag();
168 }
169 if (fb) {
170 out.bodyBId = fb->getBodyId();
171 out.fixtureBTag = fb->getTag();
172 }
173 return out;
174}
175
176// Exactly one sensor → that side is Sensor; both sensors → FixtureA is Sensor; else nullopt.
177std::optional<World::TriggerEvent> triggerEventFrom(b2Contact *contact) {
178 if (!contact) return std::nullopt;
179 Fixture *fa = fixtureFromRaw(contact->GetFixtureA());
180 Fixture *fb = fixtureFromRaw(contact->GetFixtureB());
181 if (!fa || !fb) return std::nullopt;
182 const bool aSensor = fa->isSensor();
183 const bool bSensor = fb->isSensor();
184 if (!aSensor && !bSensor) return std::nullopt;
185 World::TriggerEvent out;
186 if (aSensor && !bSensor) {
187 out.sensorBodyId = fa->getBodyId();
188 out.sensorFixtureTag = fa->getTag();
189 out.visitorBodyId = fb->getBodyId();
190 out.visitorFixtureTag = fb->getTag();
191 } else if (!aSensor && bSensor) {
192 out.sensorBodyId = fb->getBodyId();
193 out.sensorFixtureTag = fb->getTag();
194 out.visitorBodyId = fa->getBodyId();
195 out.visitorFixtureTag = fa->getTag();
196 } else {
197 out.sensorBodyId = fa->getBodyId();
198 out.sensorFixtureTag = fa->getTag();
199 out.visitorBodyId = fb->getBodyId();
200 out.visitorFixtureTag = fb->getTag();
201 }
202 return out;
203}
204
205eve::Result<eve::SimulationStep> makeLegacyStep(float dt, eve::SimulationTick currentTick) {
206 if (!std::isfinite(dt) || dt < 0.f) {
209 "World update dt must be finite and non-negative", "physics.world.update.dt"));
210 }
211 const float normalized = std::min(dt, 0.05f);
212 const auto nextTick = currentTick.incremented();
213 if (!nextTick) {
216 "World simulation tick cannot be incremented", "physics.world.simulationTick"));
217 }
218 auto duration = eve::Duration::fromSeconds(static_cast<double>(normalized));
220 return eve::Result<eve::SimulationStep>::success({*nextTick, std::move(duration).takeValue()});
221}
222
223} // namespace
224
225class ContactRelay : public b2ContactListener {
226public:
227 explicit ContactRelay(World *world) : world_(world) {}
228 void setWorld(World *world) noexcept { world_ = world; }
229
230 void BeginContact(b2Contact *contact) override { world_->onBeginContact(contact); }
231 void EndContact(b2Contact *contact) override { world_->onEndContact(contact); }
232 void PreSolve(b2Contact *contact, const b2Manifold *oldManifold) override {
233 world_->onPreSolve(contact, oldManifold);
234 }
235 void PostSolve(b2Contact *contact, const b2ContactImpulse *impulse) override {
236 world_->onPostSolve(contact, impulse);
237 }
238
239private:
240 World *world_;
241};
242
243World::World(float gravityX, float gravityY, bool sleep, float meter, eve::PersistentId instanceId)
244 : instanceId_(instanceId), meter_(meter) {
245 if (meter_ <= 0.f) meter_ = 30.f;
246 runtimeHandle_ = detail::allocatePhysicsWorldHandle();
247 if (instanceId_.isNil()) instanceId_ = detail::makePhysicsWorldPersistentId(runtimeHandle_);
248 world_ = new b2World(b2Vec2(toMeters(gravityX), toMeters(gravityY)));
249 world_->SetAllowSleeping(sleep);
250 relay_ = new ContactRelay(this);
251 world_->SetContactListener(relay_);
252 auto selection = detail::selectSimulationBackend(SimulationBackendDomain::World2D,
253 detail::makeBox2DSimulationBackend(world_), world_, true);
254 if (!selection) {
255 const eve::Status status = selection.status();
256 throw eve::Exception("World: cannot select a simulation backend: %s", status.describe().c_str());
257 }
258 backendSelectionStatus_ = selection.status();
259 auto selected = std::move(selection).takeValue();
260 backendFallback_ = selected.usedFallback;
261 simulation_ = std::move(selected.backend);
262}
263
265
266void World::adoptPreparedTopology(World &prepared) {
267 cancelForceStep();
268 std::swap(world_, prepared.world_);
269 std::swap(relay_, prepared.relay_);
270 std::swap(simulation_, prepared.simulation_);
271 std::swap(meter_, prepared.meter_);
272 std::swap(nextId_, prepared.nextId_);
273 std::swap(bodies_, prepared.bodies_);
274 std::swap(fixtures_, prepared.fixtures_);
275 std::swap(joints_, prepared.joints_);
276 std::swap(jointHandles_, prepared.jointHandles_);
277 std::swap(mechanisms_, prepared.mechanisms_);
278 std::swap(restoredJoints2D_, prepared.restoredJoints2D_);
279 std::swap(restoredBodies_, prepared.restoredBodies_);
280 std::swap(restoredFixtures_, prepared.restoredFixtures_);
281 std::swap(nextJointId_, prepared.nextJointId_);
282 std::swap(nextJointHandleIndex_, prepared.nextJointHandleIndex_);
283 for (Joint2D *joint : joints_) joint->world_ = this;
284 for (Joint2D *joint : prepared.joints_) joint->world_ = &prepared;
285 std::swap(simulationTick_, prepared.simulationTick_);
286 for (Body *body : bodies_) body->world_ = this;
287 for (Fixture *fixture : fixtures_) fixture->world_ = this;
288 for (Body *body : prepared.bodies_) body->world_ = &prepared;
289 for (Fixture *fixture : prepared.fixtures_) fixture->world_ = &prepared;
290 relay_->setWorld(this);
291 world_->SetContactListener(relay_);
292 prepared.relay_->setWorld(&prepared);
293 prepared.world_->SetContactListener(prepared.relay_);
294}
295
297 if (destroyed_) return;
298 cancelForceStep();
299 destroyed_ = true;
300 lifetime_.reset();
301 invalidateJoints2D();
302
303 std::vector<Mechanism2D *> mechanisms(mechanisms_.begin(), mechanisms_.end());
304 for (Mechanism2D *mechanism : mechanisms) {
305 if (mechanism) mechanism->invalidate();
306 }
307 mechanisms_.clear();
308
309 std::vector<Joint2D *> joints(joints_.begin(), joints_.end());
310 for (Joint2D *joint : joints) {
311 if (joint) joint->invalidate();
312 }
313 joints_.clear();
314 jointHandles_.clear();
315
316 // Copy sets — Body/Fixture destructors erase from them.
317 std::vector<Body *> bodies(bodies_.begin(), bodies_.end());
318 for (Body *b : bodies) {
319 if (b) {
320 b->invalidate();
321 // Script may still hold Body*; leave object but null raw pointer.
322 // If World is script-owned and Body is also script-owned, Body::~Body
323 // will see null body_ and skip DestroyBody.
324 }
325 }
326 bodies_.clear();
327
328 std::vector<Fixture *> fixtures(fixtures_.begin(), fixtures_.end());
329 for (Fixture *f : fixtures) {
330 if (f) f->invalidate();
331 }
332 fixtures_.clear();
333 restoredFixtures_.clear();
334 restoredBodies_.clear();
336
337 simulation_.reset();
338
339 if (world_) {
340 world_->SetContactListener(nullptr);
341 delete world_;
342 world_ = nullptr;
343 }
344 delete relay_;
345 relay_ = nullptr;
346 runtimeHandle_ = PhysicsWorldHandle::invalid();
347}
348
349bool World::pointProbe(float x, float y, float radius, ClothContact *out) const {
350 if (out) *out = ClothContact{};
351 if (!isValid() || radius <= 0.f) return false;
352
353 const float rM = toMeters(radius);
354 const b2Vec2 centerM(toMeters(x), toMeters(y));
355
356 struct Probe : b2QueryCallback {
357 const World *world = nullptr;
358 ClothContact *best = nullptr;
359 b2Vec2 center;
360 float radiusM = 0.f;
361
362 bool ReportFixture(b2Fixture *fixture) override {
363 if (!fixture || fixture->IsSensor()) return true;
364 const b2Shape *shape = fixture->GetShape();
365 if (!shape) return true;
366 float dist;
367 b2Vec2 normal;
368 if (!shapePointDistance(shape, fixture->GetBody()->GetTransform(), center, dist, normal)) {
369 return true;
370 }
371 const float depth = radiusM - dist;
372 if (depth > 0.f && depth > best->depth) {
373 best->hit = true;
374 best->depth = world->toPixels(depth);
375 best->nx = normal.x;
376 best->ny = normal.y;
377 best->body = static_cast<Body *>(fixture->GetBody()->GetUserData());
378 }
379 return true;
380 }
381 } probe;
382 probe.world = this;
383 probe.best = out;
384 probe.center = centerM;
385 probe.radiusM = rM;
386
387 b2AABB aabb;
388 aabb.lowerBound = centerM - b2Vec2(rM, rM);
389 aabb.upperBound = centerM + b2Vec2(rM, rM);
390 world_->QueryAABB(&probe, aabb);
391 return out->hit;
392}
393
394void World::update(float dt) { updateFull(dt, 8, 3); }
395
396void World::updateFull(float dt, int velocityIterations, int positionIterations) {
397 EV_PROFILE_MODULE("physics", "World::update");
398 auto legacyStep = makeLegacyStep(dt, simulationTick_);
399 if (!legacyStep) {
400 legacyStep.ignore("legacy World::updateFull cannot return a structured error");
401 return;
402 }
403 auto result =
404 step(std::move(legacyStep).takeValue(), SimulationSettings{velocityIterations, positionIterations, 4});
405 result.ignore("legacy World::updateFull cannot return a structured result");
406}
407
409 if (!isValid() || !simulation_ || simulationStepActive_ || world_->IsLocked()) {
412 "Cannot step a destroyed or uninitialized physics world", "physics.world.step"));
413 }
414 auto forceStep = validateForceStep(stepValue);
415 if (!forceStep) return forceStep;
416 auto valid = detail::validateSimulationStep(stepValue, settings, simulation_->observation());
417 if (!valid) return valid;
418 struct StepGuard {
419 bool &active;
420 explicit StepGuard(bool &flag) : active(flag) { active = true; }
421 ~StepGuard() { active = false; }
422 } guard(simulationStepActive_);
423 for (Mechanism2D *mechanism : mechanisms_) {
424 if (mechanism) mechanism->syncBeforeStep();
425 }
426 auto result = simulation_->step(stepValue, settings);
427 if (!result) return result;
428 simulationTick_ = stepValue.tick;
429 finishForceStep();
430 return result;
431}
432
434 return simulation_ ? simulation_->observation() : SimulationObservation{};
435}
436
438 return simulation_ ? simulation_->kind() : SimulationBackendKind::Cpu;
439}
440
442 return simulation_ ? simulation_->determinism() : SimulationDeterminism::ToleranceBounded;
443}
444
445eve::Status World::backendSelectionStatus() const { return backendSelectionStatus_; }
446
447void World::setGravity(float gx, float gy) {
448 if (!world_) return;
449 world_->SetGravity(b2Vec2(toMeters(gx), toMeters(gy)));
450}
451
452float World::getGravityX() const {
453 if (!world_) return 0.f;
454 return toPixels(world_->GetGravity().x);
455}
456
457float World::getGravityY() const {
458 if (!world_) return 0.f;
459 return toPixels(world_->GetGravity().y);
460}
461
462void World::setMeter(float pixelsPerMeter) {
463 if (pixelsPerMeter <= 0.f) throw eve::Exception("World.setMeter: pixelsPerMeter must be > 0");
464 meter_ = pixelsPerMeter;
465}
466
467float World::toMeters(float pixels) const { return pixels / meter_; }
468float World::toPixels(float meters) const { return meters * meter_; }
469
470int World::nextBodyId() { return nextId_++; }
471
473 if (nextBodyHandleIndex_ == PhysicsBodyHandle::invalidIndex)
474 throw eve::Exception("World.newBody: process-local body handle space exhausted");
475 return PhysicsBodyHandle(nextBodyHandleIndex_++, 1u);
476}
477
478Body *World::newBody(const std::string &bodyType, float x, float y) {
479 if (!world_ || destroyed_) throw eve::Exception("World.newBody: world destroyed");
480
481 b2BodyDef def;
482 def.type = parseBodyType(bodyType);
483 def.position = b2Vec2(toMeters(x), toMeters(y));
484
486 b2Body *raw = world_->CreateBody(&def);
487 Body *body = new Body(this, raw, nextBodyId(), runtimeHandle);
488 raw->SetUserData(body);
489 bodies_.insert(body);
490 return body;
491}
492
494 if (!isValid() || handle.isInvalid()) return nullptr;
495 for (Body *body : bodies_) {
496 if (body && body->isValid() && body->runtimeHandle() == handle) return body;
497 }
498 return nullptr;
499}
500
501Body *World::findBodyById(int bodyId) const {
502 if (!isValid() || bodyId < 0) return nullptr;
503 for (Body *body : bodies_) {
504 if (body && body->isValid() && body->getId() == bodyId) return body;
505 }
506 return nullptr;
507}
508
510 if (!body) return;
511 body->destroy();
512}
513
515 if (!body) return;
516 const int id = body->getId();
517 bodies_.erase(body);
518 auto touches = [id](const ContactEvent &e) { return e.bodyAId == id || e.bodyBId == id; };
519 auto triggerTouches = [id](const TriggerEvent &e) { return e.sensorBodyId == id || e.visitorBodyId == id; };
520 beginContacts_.erase(std::remove_if(beginContacts_.begin(), beginContacts_.end(), touches), beginContacts_.end());
521 endContacts_.erase(std::remove_if(endContacts_.begin(), endContacts_.end(), touches), endContacts_.end());
522 beginTriggers_.erase(std::remove_if(beginTriggers_.begin(), beginTriggers_.end(), triggerTouches),
523 beginTriggers_.end());
524 endTriggers_.erase(std::remove_if(endTriggers_.begin(), endTriggers_.end(), triggerTouches), endTriggers_.end());
525 impacts_.erase(std::remove_if(impacts_.begin(), impacts_.end(), touches), impacts_.end());
526}
528 if (!fixture) return;
529 const int bodyId = fixture->getBodyId();
530 const std::string tag = fixture->getTag();
531 auto touches = [&](const ContactEvent &e) {
532 return (e.bodyAId == bodyId && e.fixtureATag == tag) || (e.bodyBId == bodyId && e.fixtureBTag == tag);
533 };
534 auto triggerTouches = [&](const TriggerEvent &e) {
535 return (e.sensorBodyId == bodyId && e.sensorFixtureTag == tag) ||
536 (e.visitorBodyId == bodyId && e.visitorFixtureTag == tag);
537 };
538 beginContacts_.erase(std::remove_if(beginContacts_.begin(), beginContacts_.end(), touches), beginContacts_.end());
539 endContacts_.erase(std::remove_if(endContacts_.begin(), endContacts_.end(), touches), endContacts_.end());
540 beginTriggers_.erase(std::remove_if(beginTriggers_.begin(), beginTriggers_.end(), triggerTouches),
541 beginTriggers_.end());
542 endTriggers_.erase(std::remove_if(endTriggers_.begin(), endTriggers_.end(), triggerTouches), endTriggers_.end());
543 impacts_.erase(std::remove_if(impacts_.begin(), impacts_.end(), touches), impacts_.end());
544 b2Fixture *raw = fixture->raw();
545 for (auto it = preSolve_.begin(); it != preSolve_.end();) {
546 b2Contact *contact = it->first;
547 if (contact && (contact->GetFixtureA() == raw || contact->GetFixtureB() == raw))
548 it = preSolve_.erase(it);
549 else
550 ++it;
551 }
552 fixtures_.erase(fixture);
553}
554
556 if (!contact || !fixtureFromRaw(contact->GetFixtureA()) || !fixtureFromRaw(contact->GetFixtureB())) return;
557 Body *a = bodyFromFixture(contact->GetFixtureA());
558 Body *b = bodyFromFixture(contact->GetFixtureB());
559 if (!a || !b) return;
560
561 beginContacts_.push_back(contactEventFrom(contact));
562 auto trigger = triggerEventFrom(contact);
563 if (trigger) beginTriggers_.push_back(*trigger);
564
565 auto *ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>("PlatformEvent");
566 if (!ev) return;
567 std::vector<eve::platform_event::Variant> args = {eve::platform_event::Variant::makeInt(a->getId()),
569 ev->push(new eve::platform_event::Message("begincontact", args));
570 if (trigger) {
571 std::vector<eve::platform_event::Variant> triggerArgs = {
572 eve::platform_event::Variant::makeInt(trigger->sensorBodyId),
573 eve::platform_event::Variant::makeInt(trigger->visitorBodyId)};
574 ev->push(new eve::platform_event::Message("begintrigger", triggerArgs));
575 }
576}
577
578void World::onEndContact(b2Contact *contact) {
579 preSolve_.erase(contact);
580 if (!contact || !fixtureFromRaw(contact->GetFixtureA()) || !fixtureFromRaw(contact->GetFixtureB())) return;
581 Body *a = bodyFromFixture(contact->GetFixtureA());
582 Body *b = bodyFromFixture(contact->GetFixtureB());
583 if (!a || !b) return;
584
585 endContacts_.push_back(contactEventFrom(contact));
586 auto trigger = triggerEventFrom(contact);
587 if (trigger) endTriggers_.push_back(*trigger);
588
589 auto *ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>("PlatformEvent");
590 if (!ev) return;
591 std::vector<eve::platform_event::Variant> args = {eve::platform_event::Variant::makeInt(a->getId()),
593 ev->push(new eve::platform_event::Message("endcontact", args));
594 if (trigger) {
595 std::vector<eve::platform_event::Variant> triggerArgs = {
596 eve::platform_event::Variant::makeInt(trigger->sensorBodyId),
597 eve::platform_event::Variant::makeInt(trigger->visitorBodyId)};
598 ev->push(new eve::platform_event::Message("endtrigger", triggerArgs));
599 }
600}
601
602void World::onPreSolve(b2Contact *contact, const b2Manifold * /*oldManifold*/) {
603 if (!contact || !world_) return;
604 b2WorldManifold manifold;
605 contact->GetWorldManifold(&manifold);
606 const b2Manifold *local = contact->GetManifold();
607 if (!local || local->pointCount <= 0) return;
608
609 b2Body *a = contact->GetFixtureA()->GetBody();
610 b2Body *b = contact->GetFixtureB()->GetBody();
611 if (!a || !b) return;
612 const b2Vec2 point = manifold.points[0];
613 const b2Vec2 va = a->GetLinearVelocityFromWorldPoint(point);
614 const b2Vec2 vb = b->GetLinearVelocityFromWorldPoint(point);
615
616 PreSolveData data;
617 data.pointX = toPixels(point.x);
618 data.pointY = toPixels(point.y);
619 data.normalX = manifold.normal.x;
620 data.normalY = manifold.normal.y;
621 data.relativeNormalSpeed = toPixels(std::max(0.f, b2Dot(va - vb, manifold.normal)));
622 preSolve_[contact] = data;
623}
624
625void World::onPostSolve(b2Contact *contact, const b2ContactImpulse *impulse) {
626 if (!contact || !impulse) return;
627 auto found = preSolve_.find(contact);
628 if (found == preSolve_.end()) return;
629
631 static_cast<ContactEvent &>(out) = contactEventFrom(contact);
632 out.pointX = found->second.pointX;
633 out.pointY = found->second.pointY;
634 out.normalX = found->second.normalX;
635 out.normalY = found->second.normalY;
636 out.relativeNormalSpeed = found->second.relativeNormalSpeed;
637 const int count = contact->GetManifold() ? contact->GetManifold()->pointCount : 0;
638 for (int i = 0; i < count; ++i) {
639 out.normalImpulse += toPixels(impulse->normalImpulses[i]);
640 out.tangentImpulse += toPixels(std::fabs(impulse->tangentImpulses[i]));
641 }
642 if (out.normalImpulse > 0.f) impacts_.push_back(std::move(out));
643}
644
645namespace {
646template <typename Event>
647const Event *eventAt(const std::vector<Event> &events, int index) {
648 return index >= 0 && index < int(events.size()) ? &events[size_t(index)] : nullptr;
649}
650} // namespace
651
653 auto *e = eventAt(beginContacts_, index);
654 return e ? e->bodyAId : 0;
655}
657 auto *e = eventAt(beginContacts_, index);
658 return e ? e->bodyBId : 0;
659}
661 auto *e = eventAt(beginContacts_, index);
662 return e ? e->fixtureATag : std::string();
663}
665 auto *e = eventAt(beginContacts_, index);
666 return e ? e->fixtureBTag : std::string();
667}
669 auto *e = eventAt(endContacts_, index);
670 return e ? e->bodyAId : 0;
671}
673 auto *e = eventAt(endContacts_, index);
674 return e ? e->bodyBId : 0;
675}
677 auto *e = eventAt(endContacts_, index);
678 return e ? e->fixtureATag : std::string();
679}
681 auto *e = eventAt(endContacts_, index);
682 return e ? e->fixtureBTag : std::string();
683}
684
685const World::TriggerEvent &World::triggerEventAt(const std::vector<TriggerEvent> &events, int index,
686 const char *operation) const {
687 if (index < 0 || index >= int(events.size())) throw eve::Exception("World.%s: index out of range", operation);
688 return events[size_t(index)];
689}
690
692 return triggerEventAt(beginTriggers_, index, "getBeginTriggerSensorBodyId").sensorBodyId;
693}
695 return triggerEventAt(beginTriggers_, index, "getBeginTriggerVisitorBodyId").visitorBodyId;
696}
698 return triggerEventAt(beginTriggers_, index, "getBeginTriggerSensorFixtureTag").sensorFixtureTag;
699}
701 return triggerEventAt(beginTriggers_, index, "getBeginTriggerVisitorFixtureTag").visitorFixtureTag;
702}
704 return triggerEventAt(endTriggers_, index, "getEndTriggerSensorBodyId").sensorBodyId;
705}
707 return triggerEventAt(endTriggers_, index, "getEndTriggerVisitorBodyId").visitorBodyId;
708}
710 return triggerEventAt(endTriggers_, index, "getEndTriggerSensorFixtureTag").sensorFixtureTag;
711}
713 return triggerEventAt(endTriggers_, index, "getEndTriggerVisitorFixtureTag").visitorFixtureTag;
714}
716 auto *e = eventAt(impacts_, index);
717 return e ? e->bodyAId : 0;
718}
720 auto *e = eventAt(impacts_, index);
721 return e ? e->bodyBId : 0;
722}
723std::string World::getImpactFixtureATag(int index) const {
724 auto *e = eventAt(impacts_, index);
725 return e ? e->fixtureATag : std::string();
726}
727std::string World::getImpactFixtureBTag(int index) const {
728 auto *e = eventAt(impacts_, index);
729 return e ? e->fixtureBTag : std::string();
730}
732 auto *e = eventAt(impacts_, index);
733 return e ? e->pointX : 0.f;
734}
736 auto *e = eventAt(impacts_, index);
737 return e ? e->pointY : 0.f;
738}
740 auto *e = eventAt(impacts_, index);
741 return e ? e->normalX : 0.f;
742}
744 auto *e = eventAt(impacts_, index);
745 return e ? e->normalY : 0.f;
746}
748 auto *e = eventAt(impacts_, index);
749 return e ? e->relativeNormalSpeed : 0.f;
750}
752 auto *e = eventAt(impacts_, index);
753 return e ? e->normalImpulse : 0.f;
754}
756 auto *e = eventAt(impacts_, index);
757 return e ? e->tangentImpulse : 0.f;
758}
759
761 beginContacts_.clear();
762 endContacts_.clear();
763 beginTriggers_.clear();
764 endTriggers_.clear();
765 impacts_.clear();
766 preSolve_.clear();
767}
768
769int World::rayCast(float x1, float y1, float x2, float y2) {
770 rayHitBodyId_ = -1;
771 rayHitX_ = 0.f;
772 rayHitY_ = 0.f;
773 rayHitNormalX_ = 0.f;
774 rayHitNormalY_ = 0.f;
775 rayHitFraction_ = 0.f;
776 if (!world_ || destroyed_) return -1;
777
778 struct Closest : public b2RayCastCallback {
779 World *world = nullptr;
780 float best = 1.f;
781 Body *hit = nullptr;
782 b2Vec2 point{};
783 b2Vec2 normal{};
784
785 float32 ReportFixture(b2Fixture *fixture, const b2Vec2 &pointIn, const b2Vec2 &normalIn,
786 float32 fraction) override {
787 Body *b = bodyFromFixture(fixture);
788 if (!b) return -1.f;
789 if (fraction < best) {
790 best = fraction;
791 hit = b;
792 point = pointIn;
793 normal = normalIn;
794 }
795 return fraction;
796 }
797 } cb;
798 cb.world = this;
799
800 b2Vec2 p1(toMeters(x1), toMeters(y1));
801 b2Vec2 p2(toMeters(x2), toMeters(y2));
802 world_->RayCast(&cb, p1, p2);
803
804 if (!cb.hit) return -1;
805 rayHitBodyId_ = cb.hit->getId();
806 rayHitX_ = toPixels(cb.point.x);
807 rayHitY_ = toPixels(cb.point.y);
808 rayHitNormalX_ = cb.normal.x;
809 rayHitNormalY_ = cb.normal.y;
810 rayHitFraction_ = cb.best;
811 return rayHitBodyId_;
812}
813
814int World::queryAABB(float x, float y, float w, float h) {
815 queryBodyIds_.clear();
816 if (!world_ || destroyed_) return 0;
817
818 struct Collector : public b2QueryCallback {
819 World *world = nullptr;
820 std::vector<int> *ids = nullptr;
821 std::unordered_set<int> seen;
822
823 bool ReportFixture(b2Fixture *fixture) override {
824 Body *b = bodyFromFixture(fixture);
825 if (!b) return true;
826 int id = b->getId();
827 if (seen.insert(id).second) ids->push_back(id);
828 return true;
829 }
830 } cb;
831 cb.world = this;
832 cb.ids = &queryBodyIds_;
833
834 b2AABB aabb;
835 float x0 = toMeters(x);
836 float y0 = toMeters(y);
837 float x1 = toMeters(x + w);
838 float y1 = toMeters(y + h);
839 aabb.lowerBound = b2Vec2(std::min(x0, x1), std::min(y0, y1));
840 aabb.upperBound = b2Vec2(std::max(x0, x1), std::max(y0, y1));
841 world_->QueryAABB(&cb, aabb);
842 return static_cast<int>(queryBodyIds_.size());
843}
844
846 if (index < 0 || index >= static_cast<int>(queryBodyIds_.size()))
847 throw eve::Exception("World.getQueryBodyId: index out of range");
848 return queryBodyIds_[static_cast<size_t>(index)];
849}
850
851} // namespace eve::physics
double y
double x
ActionParameterOperation operation
bool & active
float w
Definition AnimClip.cpp:738
float duration
std::string selected
glm::vec4 p[6]
int instanceId
ShaderImageInput shape
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
std::uint32_t ab
double r
int h
std::string local
std::string id
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
const std::string * tag
OceanWakeSettings settings
glm::dvec2 center
double dt
std::vector< particles::ParticleRecordEvent > events
float f
eve::Value fixtures
bool hit
PrimitiveHandle handle
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
std::string body
float d
float t
uint8_t * pixels
bool found
ScriptStructure out
Backend-neutral, observable fixed-step contract for physics domains.
int count
std::map< Cell, int > best
float step
Definition TreeMesh.cpp:451
std::uint32_t depth
uint32_t index
std::vector< char > inside
float fraction
Contact contact
std::array< double, 3 > impulse
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static constexpr index_type invalidIndex
Reserved index value shared by all invalid handles.
static constexpr RuntimeHandle invalid() noexcept
Returns the canonical invalid handle.
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
Id128 public API.
Definition Identity.h:111
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:175
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Definition Body.h:21
void destroy()
Destroys the body inside its world.
Definition Body.cpp:73
ContactRelay(World *world)
Definition World.cpp:227
void PreSolve(b2Contact *contact, const b2Manifold *oldManifold) override
Definition World.cpp:232
void setWorld(World *world) noexcept
Definition World.cpp:228
void BeginContact(b2Contact *contact) override
Definition World.cpp:230
void PostSolve(b2Contact *contact, const b2ContactImpulse *impulse) override
Definition World.cpp:235
void EndContact(b2Contact *contact) override
Definition World.cpp:231
2D fixture: a shape attached to a Body with material + filter settings. Also carries a string tag use...
Definition Fixture.h:18
b2Fixture * raw()
Exposes the underlying Box2D fixture for tightly-scoped backend integration.
Definition Fixture.h:93
int getBodyId() const
Id of the owning body.
Definition Fixture.cpp:103
const std::string & getTag() const
Returns the tag.
Definition Fixture.h:51
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
void setMeter(float pixelsPerMeter)
Changes the pixels-per-meter conversion.
Definition World.cpp:462
int getEndTriggerSensorBodyId(int index) const
Definition World.cpp:703
void update(float dt)
Steps the simulation by dt seconds (5 velocity / 2 position iterations).
Definition World.cpp:394
int queryAABB(float x, float y, float w, float h)
Query fixtures overlapping an axis-aligned box in pixel space (x,y,w,h). Returns match count; read id...
Definition World.cpp:814
Body * findBodyById(int bodyId) const
Resolves a live body by its world-local stable event/query id.
Definition World.cpp:501
float getImpactNormalY(int index) const
Definition World.cpp:743
SimulationObservation simulationObservation() const noexcept
Snapshot of completed backend steps and logical simulation time.
Definition World.cpp:433
void destroyBody(Body *body)
Destroys a body (null is ignored).
Definition World.cpp:509
void onBeginContact(b2Contact *contact)
Definition World.cpp:555
std::string getBeginContactFixtureATag(int index) const
Definition World.cpp:660
void forgetBody(Body *body)
Definition World.cpp:514
void onEndContact(b2Contact *contact)
Definition World.cpp:578
void forgetFixture(Fixture *fixture)
Definition World.cpp:527
std::string getEndContactFixtureATag(int index) const
Definition World.cpp:676
int getBeginTriggerSensorBodyId(int index) const
Definition World.cpp:691
float getImpactPointX(int index) const
Definition World.cpp:731
int getQueryBodyId(int index) const
Definition World.cpp:845
eve::Status backendSelectionStatus() const
Returns the selection outcome, including an absent-capability warning.
Definition World.cpp:445
int getEndContactBodyBId(int index) const
Definition World.cpp:672
int getBeginContactBodyBId(int index) const
Definition World.cpp:656
std::string getEndTriggerSensorFixtureTag(int index) const
Definition World.cpp:709
void destroy()
Destroys the underlying Box2D world and resets event buffers.
Definition World.cpp:296
int getEndTriggerVisitorBodyId(int index) const
Definition World.cpp:706
void setGravity(float gx, float gy)
Sets the world gravity vector in pixels/s^2.
Definition World.cpp:447
void onPostSolve(b2Contact *contact, const b2ContactImpulse *impulse)
Definition World.cpp:625
int getEndContactBodyAId(int index) const
Definition World.cpp:668
float getGravityX() const
Definition World.cpp:452
float toPixels(float meters) const
Converts a meter-space length to pixels.
Definition World.cpp:468
friend class Body
Definition World.h:457
std::string getBeginTriggerSensorFixtureTag(int index) const
Definition World.cpp:697
float getImpactNormalX(int index) const
Definition World.cpp:739
float getImpactRelativeNormalSpeed(int index) const
Definition World.cpp:747
b2World * raw()
Exposes the underlying Box2D world for tightly-scoped backend integration.
Definition World.h:417
bool pointProbe(float x, float y, float radius, ClothContact *out) const
Probe the deepest non-sensor fixture within radius of a pixel point. Returns false when nothing is hi...
Definition World.cpp:349
Body * newBody(const std::string &bodyType, float x, float y)
Creates a body in pixel-space units.
Definition World.cpp:478
std::string getBeginTriggerVisitorFixtureTag(int index) const
Definition World.cpp:700
int getBeginContactBodyAId(int index) const
Definition World.cpp:652
std::string getEndTriggerVisitorFixtureTag(int index) const
Definition World.cpp:712
int getImpactBodyAId(int index) const
Definition World.cpp:715
PhysicsWorldHandle runtimeHandle() const noexcept
Process-local identity used by PhysicsLink; invalid after destruction.
Definition World.h:128
int getImpactBodyBId(int index) const
Definition World.cpp:719
PhysicsBodyHandle nextBodyRuntimeHandle()
Definition World.cpp:472
int getBeginTriggerVisitorBodyId(int index) const
Definition World.cpp:694
World(float gravityX, float gravityY, bool sleep, float meter, eve::PersistentId instanceId=eve::PersistentId::nil())
Creates a physics world.
Definition World.cpp:243
float getImpactNormalImpulse(int index) const
Definition World.cpp:751
SimulationDeterminism backendDeterminism() const noexcept
Replay/numeric guarantee declared by the selected backend.
Definition World.cpp:441
std::string getEndContactFixtureBTag(int index) const
Definition World.cpp:680
int rayCast(float x1, float y1, float x2, float y2)
Closest raycast in pixel space from (x1,y1) to (x2,y2). Returns hit body id, or -1....
Definition World.cpp:769
bool isValid() const
True while the underlying Box2D world is alive.
Definition World.h:332
float getImpactTangentImpulse(int index) const
Definition World.cpp:755
float getGravityY() const
Definition World.cpp:457
std::string getBeginContactFixtureBTag(int index) const
Definition World.cpp:664
Body * findBody(PhysicsBodyHandle handle) const
Resolves a live body handle; returns null for a stale or foreign handle.
Definition World.cpp:493
eve::Result< void > step(const eve::SimulationStep &step, const SimulationSettings &settings={})
Advances the domain with an injected deterministic simulation step.
Definition World.cpp:408
void updateFull(float dt, int velocityIterations, int positionIterations)
Steps with explicit iteration counts.
Definition World.cpp:396
void clearContactEvents()
Clears collected begin/end contact and impact event buffers.
Definition World.cpp:760
void onPreSolve(b2Contact *contact, const b2Manifold *oldManifold)
Definition World.cpp:602
float toMeters(float pixels) const
Converts a pixel-space length to meters.
Definition World.cpp:467
std::string getImpactFixtureATag(int index) const
Definition World.cpp:723
std::string getImpactFixtureBTag(int index) const
Definition World.cpp:727
SimulationBackendKind backendKind() const noexcept
Selected CPU/GPU/mock backend family.
Definition World.cpp:437
float getImpactPointY(int index) const
Definition World.cpp:735
A named event carrying an ordered list of Variant payloads. Pushed messages are heap-allocated; the q...
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
PhysicsWorldHandle allocatePhysicsWorldHandle()
Allocates a process-local world handle from the physics owner.
std::unique_ptr< ISimulationBackend > makeBox2DSimulationBackend(b2World *world)
Creates the built-in Box2D CPU backend adapter.
eve::PersistentId makePhysicsWorldPersistentId(PhysicsWorldHandle runtimeHandle)
Creates a non-nil process-local generated identity for a world without an injected persistent ID.
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.
@ ToleranceBounded
Results are equivalent within a documented numeric tolerance.
eve::RuntimeHandle< PhysicsBodyHandleTag > PhysicsBodyHandle
Generation-qualified runtime identity for a physics body.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
SimulationTick tick
Tick reached after this step is applied.
Definition Time.h:160
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
static Variant makeInt(int64_t v)
Constructs an integer variant.