Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PhysicsModuleEntry.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
8
9#include <algorithm>
10#include <cmath>
11
12#ifndef __EMSCRIPTEN__
13namespace {
18 return pool;
19}
20} // namespace
21#endif
22
23// How closely the contact normal must align with a platform's solid normal for the
24// contact to survive (matches Box2D's own one-sided-platform sample).
25static constexpr float ONE_WAY_ALIGN_THRESHOLD = 0.95f;
26
27// Pre-solve callback: cancels contacts that approach a one-way platform from its
28// pass-through side. Box2D only invokes this for contacts whose shapes opted in via
29// b2Shape_EnablePreSolveEvents, so it costs nothing when no one-way platforms exist.
30// Must be thread-safe and side-effect free: it only reads oneWayNormals (never
31// mutated during a step) plus the passed-in contact geometry.
32static bool preSolveOneWayPlatform(b2ShapeId shapeIdA, b2ShapeId shapeIdB,
33 b2Vec2 point, b2Vec2 normal, void* context) {
34 (void)point;
35 (void)context;
36 // The manifold normal points from shape A to shape B. A one-way platform keeps a
37 // contact only while the *other* shape sits on the platform's solid side.
38 auto itA = g_ctx.oneWayNormals.find(entityFromShape(shapeIdA));
39 if (itA != g_ctx.oneWayNormals.end()) {
40 // Platform = A; direction toward the other shape (B) is +normal.
41 const b2Vec2 solid = itA->second.localSpace
42 ? b2RotateVector(b2Body_GetRotation(b2Shape_GetBody(shapeIdA)), itA->second.normal)
43 : itA->second.normal;
44 float d = normal.x * solid.x + normal.y * solid.y;
45 if (d <= ONE_WAY_ALIGN_THRESHOLD) return false;
46 }
47 auto itB = g_ctx.oneWayNormals.find(entityFromShape(shapeIdB));
48 if (itB != g_ctx.oneWayNormals.end()) {
49 // Platform = B; direction toward the other shape (A) is -normal.
50 const b2Vec2 solid = itB->second.localSpace
51 ? b2RotateVector(b2Body_GetRotation(b2Shape_GetBody(shapeIdB)), itB->second.normal)
52 : itB->second.normal;
53 float d = normal.x * solid.x + normal.y * solid.y;
54 if (d >= -ONE_WAY_ALIGN_THRESHOLD) return false;
55 }
56 return true;
57}
58
59extern "C" {
60
61// World Lifecycle
62
64void physics_init(float gx, float gy, float timestep, int substeps,
65 float contactHertz, float contactDampingRatio, float contactSpeed) {
66 if (b2World_IsValid(g_ctx.worldId)) return;
67
68 b2WorldDef worldDef = b2DefaultWorldDef();
69 worldDef.gravity = {gx, gy};
70 worldDef.contactHertz = contactHertz;
71 worldDef.contactDampingRatio = contactDampingRatio;
72 worldDef.contactSpeed = contactSpeed;
73#ifndef __EMSCRIPTEN__
74 // Solve across the cores a device has and the web build does not. The result
75 // is the same either way — Box2D is deterministic under multithreading — so
76 // this changes only how long a step takes, never what it produces.
77 taskPool().configure(worldDef);
78#endif
79 g_ctx.worldId = b2CreateWorld(&worldDef);
80 b2World_SetPreSolveCallback(g_ctx.worldId, preSolveOneWayPlatform, nullptr);
81
82 g_ctx.fixedTimestep = timestep;
83 g_ctx.subStepCount = substeps;
84 g_ctx.accumulator = 0.0f;
85}
86
87// World-level tuning (surfaced to the SDK / project settings). Hardcoded
88// b2DefaultWorldDef values otherwise. A non-positive restitutionThreshold /
89// maxLinearSpeed leaves Box2D's default in place.
91void physics_setWorldConfig(int enableSleep, int enableContinuous,
92 float restitutionThreshold, float maxLinearSpeed) {
93 if (!b2World_IsValid(g_ctx.worldId)) return;
94 b2World_EnableSleeping(g_ctx.worldId, enableSleep != 0);
95 b2World_EnableContinuous(g_ctx.worldId, enableContinuous != 0);
96 if (restitutionThreshold > 0.0f) {
97 b2World_SetRestitutionThreshold(g_ctx.worldId, restitutionThreshold);
98 }
99 if (maxLinearSpeed > 0.0f) {
100 b2World_SetMaximumLinearSpeed(g_ctx.worldId, maxLinearSpeed);
101 }
102}
103
106 g_ctx.reset();
107}
108
109// One-way (one-sided) platform: with enable != 0, contacts against this entity's
110// shapes are cancelled unless the other body approaches from the (nx, ny) solid
111// side (physics space; normalized here, falling back to +Y). enable == 0 clears it.
113void physics_setOneWayPlatform(uint32_t entityId, float nx, float ny, int enable) {
114 if (enable != 0) {
115 float len = sqrtf(nx * nx + ny * ny);
116 const b2Vec2 normal = (len > 0.0f)
117 ? b2Vec2{nx / len, ny / len}
118 : b2Vec2{0.0f, 1.0f};
119 g_ctx.oneWayNormals[entityId] = {normal, false};
120 } else {
121 g_ctx.oneWayNormals.erase(entityId);
122 }
123
124 auto it = g_ctx.entityToShapes.find(entityId);
125 if (it != g_ctx.entityToShapes.end()) {
126 for (b2ShapeId shapeId : it->second) {
127 if (b2Shape_IsValid(shapeId)) {
128 b2Shape_EnablePreSolveEvents(shapeId, enable != 0);
129 }
130 }
131 }
132}
133
135void physics_setOneWayPlatformLocal(uint32_t entityId, float nx, float ny, int enable) {
136 physics_setOneWayPlatform(entityId, nx, ny, enable);
137 if (enable != 0) g_ctx.oneWayNormals.at(entityId).localSpace = true;
138}
139
140// Body Management
141
143void physics_createBody(uint32_t entityId, int bodyType, float x, float y, float angle,
144 float gravityScale, float linearDamping, float angularDamping,
145 int fixedRotation, int bullet) {
146 if (!b2World_IsValid(g_ctx.worldId)) return;
147 if (entityId == 0xFFFFFFFF) return;
148 if (g_ctx.entityToBody.contains(entityId)) return;
149
150 b2BodyDef bodyDef = b2DefaultBodyDef();
151
152 switch (bodyType) {
153 case 0: bodyDef.type = b2_staticBody; break;
154 case 1: bodyDef.type = b2_kinematicBody; break;
155 default: bodyDef.type = b2_dynamicBody; break;
156 }
157
158 bodyDef.position = {x, y};
159 bodyDef.rotation = b2MakeRot(angle);
160 bodyDef.gravityScale = gravityScale;
161 bodyDef.linearDamping = linearDamping;
162 bodyDef.angularDamping = angularDamping;
163 bodyDef.isBullet = bullet != 0;
164 bodyDef.motionLocks.angularZ = fixedRotation != 0;
165
166 b2BodyId bodyId = b2CreateBody(g_ctx.worldId, &bodyDef);
167 b2Body_SetUserData(bodyId, reinterpret_cast<void*>(static_cast<uintptr_t>(entityId)));
168 g_ctx.entityToBody[entityId] = bodyId;
169 if (bodyDef.type == b2_dynamicBody) {
170 g_ctx.dynamicBodyEntities.push_back(entityId);
171 }
172}
173
175void physics_destroyBody(uint32_t entityId) {
176 auto it = g_ctx.entityToBody.find(entityId);
177 if (it == g_ctx.entityToBody.end()) return;
178
179 auto jit = g_ctx.entityToJoint.find(entityId);
180 if (jit != g_ctx.entityToJoint.end()) {
181 if (b2Joint_IsValid(jit->second)) {
182 b2DestroyJoint(jit->second, false);
183 }
184 g_ctx.entityToJoint.erase(jit);
185 }
186
187 if (b2Body_IsValid(it->second)) {
188 b2DestroyBody(it->second);
189 }
190 g_ctx.entityToBody.erase(it);
191 g_ctx.pausedMotion.erase(entityId);
192 g_ctx.entityToShapes.erase(entityId);
193 auto dit = std::find(g_ctx.dynamicBodyEntities.begin(), g_ctx.dynamicBodyEntities.end(), entityId);
194 if (dit != g_ctx.dynamicBodyEntities.end()) {
195 *dit = g_ctx.dynamicBodyEntities.back();
196 g_ctx.dynamicBodyEntities.pop_back();
197 }
198}
199
201int physics_hasBody(uint32_t entityId) {
202 return g_ctx.entityToBody.contains(entityId) ? 1 : 0;
203}
204
205// Enable / disable a body in place (RigidBody2D.enabled). Unlike destroy, this keeps
206// the body, its shapes, velocity, and joints — b2Body_Disable just removes it from
207// simulation/broadphase — so the reconciler can toggle without losing state.
209void physics_setBodyEnabled(uint32_t entityId, int enabled) {
210 b2BodyId body = findValidBody(entityId);
211 if (!b2Body_IsValid(body)) return;
212 if (enabled) {
213 if (b2Body_IsEnabled(body)) return;
214 b2Body_Enable(body);
215 auto it = g_ctx.pausedMotion.find(entityId);
216 if (it != g_ctx.pausedMotion.end()) {
217 b2Body_SetLinearVelocity(body, it->second.linearVelocity);
218 b2Body_SetAngularVelocity(body, it->second.angularVelocity);
219 g_ctx.pausedMotion.erase(it);
220 }
221 } else {
222 if (!b2Body_IsEnabled(body)) return;
223 g_ctx.pausedMotion[entityId] = {
224 b2Body_GetLinearVelocity(body), b2Body_GetAngularVelocity(body)
225 };
226 b2Body_Disable(body);
227 }
228}
229
230// Simulation
231
233void physics_step(float dt) {
234 if (!b2World_IsValid(g_ctx.worldId)) return;
235
236 g_ctx.collisionEnterBuffer.clear();
237 g_ctx.collisionExitBuffer.clear();
238 g_ctx.sensorEnterBuffer.clear();
239 g_ctx.sensorExitBuffer.clear();
240 g_ctx.hitEventBuffer.clear();
241
242 g_ctx.accumulator += dt;
243
244 int steps = 0;
245 while (g_ctx.accumulator >= g_ctx.fixedTimestep && steps < MAX_PHYSICS_STEPS_PER_FRAME) {
246 b2World_Step(g_ctx.worldId, g_ctx.fixedTimestep, g_ctx.subStepCount);
247 g_ctx.accumulator -= g_ctx.fixedTimestep;
248 ++steps;
249 }
250
251 if (g_ctx.accumulator > g_ctx.fixedTimestep) {
252 g_ctx.accumulator = g_ctx.fixedTimestep;
253 }
254}
255
256// Transform Sync
257
259void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle) {
260 auto it = g_ctx.entityToBody.find(entityId);
261 if (it == g_ctx.entityToBody.end()) return;
262 if (!b2Body_IsValid(it->second)) return;
263
264 b2Body_SetTransform(it->second, {x, y}, b2MakeRot(angle));
265}
266
268int physics_setBodyTransforms(uintptr_t bufferPtr, int count, float ppu) {
269 using namespace esengine;
270 if (count <= 0 || bufferPtr % alignof(EntityPose2D) || !std::isfinite(ppu) || ppu <= 0) return 0;
271 const auto* rows = boundarySpan<EntityPose2D>(bufferPtr, static_cast<u64>(count), "physics_setBodyTransforms");
272 if (!rows) return 0;
273 const double invPpu = 1.0 / static_cast<double>(ppu);
274 int changed = 0;
275 for (int i = 0; i < count; ++i) {
276 const auto& pose = rows[i];
277 if (!std::isfinite(pose.x) || !std::isfinite(pose.y) || !std::isfinite(pose.angle)) continue;
278 const auto it = g_ctx.entityToBody.find(pose.entity);
279 if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) continue;
280 const b2Vec2 next = {static_cast<float>(pose.x * invPpu), static_cast<float>(pose.y * invPpu)};
281 if (!b2IsValidVec2(next)) continue;
282 const b2Rot rotation = b2MakeRot(pose.angle);
283 const b2Vec2 position = b2Body_GetPosition(it->second);
284 const b2Rot current = b2Body_GetRotation(it->second);
285 if (position.x == next.x && position.y == next.y && current.c == rotation.c && current.s == rotation.s) continue;
286 b2Body_SetTransform(it->second, next, rotation);
287 ++changed;
288 }
289 return changed;
290}
291
292// Drive a kinematic body toward a target pose over `dt`, deriving its
293// linear+angular velocity from the delta (unlike setBodyTransform, which
294// teleports with zero velocity). The velocity is what the contact solver uses
295// to carry/push resting dynamic bodies — a moving platform is dead without it.
297void physics_setBodyTargetTransform(uint32_t entityId, float x, float y, float angle, float dt) {
298 auto it = g_ctx.entityToBody.find(entityId);
299 if (it == g_ctx.entityToBody.end()) return;
300 if (!b2Body_IsValid(it->second)) return;
301
302 b2Transform target = { {x, y}, b2MakeRot(angle) };
303 b2Body_SetTargetTransform(it->second, target, dt, true);
304}
305
308 return static_cast<int>(g_ctx.dynamicBodyEntities.size());
309}
310
311// For the resource census. The dynamic count was the only one reachable, and it
312// is the subset that cannot show the leak worth finding: a static body outliving
313// its entity still collides, and never appears in a dynamic-body readback.
316 return static_cast<int>(g_ctx.entityToBody.size());
317}
318
321 size_t total = 0;
322 for (const auto& [entityId, shapes] : g_ctx.entityToShapes) total += shapes.size();
323 return static_cast<int>(total);
324}
325
328 return static_cast<int>(g_ctx.entityToJoint.size());
329}
330
335 return static_cast<int>(g_ctx.entityToShapes.size() + g_ctx.oneWayNormals.size()
336 + g_ctx.posePrevIndex.size() + g_ctx.dynamicBodyEntities.size()
337 + g_ctx.pausedMotion.size());
338}
339
342 g_ctx.dynamicTransformBuffer.clear();
343
344 for (uint32_t entityId : g_ctx.dynamicBodyEntities) {
345 auto it = g_ctx.entityToBody.find(entityId);
346 if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) continue;
347 // A disabled body is frozen; skip it so the readback doesn't stamp its
348 // stale pose back over a Transform the game is hand-animating while
349 // physics is off (RigidBody2D.enabled = false).
350 if (!b2Body_IsEnabled(it->second)) continue;
351
352 b2Vec2 pos = b2Body_GetPosition(it->second);
353 float angle = b2Rot_GetAngle(b2Body_GetRotation(it->second));
354
355 pushEntityBits(g_ctx.dynamicTransformBuffer, entityId);
356 g_ctx.dynamicTransformBuffer.push_back(pos.x);
357 g_ctx.dynamicTransformBuffer.push_back(pos.y);
358 g_ctx.dynamicTransformBuffer.push_back(angle);
359 }
360
361 return reinterpret_cast<uintptr_t>(g_ctx.dynamicTransformBuffer.data());
362}
363
364// Render interpolation
365//
366// The snapshot pair and the lerp live here, not in the SDK: interpolation touches
367// every dynamic body every frame, and that is exactly the hot loop the no-JIT
368// budget keeps off the JS path (docs/REARCH_NATIVE.md §3.2). The SDK asks for the
369// finished buffer and hands it straight to the engine's batched Transform sync.
370
372static uint32_t poseEntityAt(const std::vector<float>& buf, size_t offset) {
373 uint32_t entityId;
374 std::memcpy(&entityId, &buf[offset], sizeof(uint32_t));
375 return entityId;
376}
377
379static float lerpAngleShortest(float a, float b, float t) {
380 constexpr float kPi = 3.14159265358979323846f;
381 constexpr float kTwoPi = 2.0f * kPi;
382 float d = std::fmod(b - a, kTwoPi);
383 if (d > kPi) d -= kTwoPi;
384 else if (d < -kPi) d += kTwoPi;
385 return a + d * t;
386}
387
394 g_ctx.posePrev.swap(g_ctx.poseCur);
395 g_ctx.poseCur.clear();
396 g_ctx.posePrevIndex.clear();
397
398 for (uint32_t entityId : g_ctx.dynamicBodyEntities) {
399 auto it = g_ctx.entityToBody.find(entityId);
400 if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) continue;
401 // Same exclusion the readback makes: a disabled body is frozen, and its
402 // stale pose must not be stamped back over a hand-animated Transform.
403 if (!b2Body_IsEnabled(it->second)) continue;
404
405 b2Vec2 pos = b2Body_GetPosition(it->second);
406 float angle = b2Rot_GetAngle(b2Body_GetRotation(it->second));
407
408 pushEntityBits(g_ctx.poseCur, entityId);
409 g_ctx.poseCur.push_back(pos.x);
410 g_ctx.poseCur.push_back(pos.y);
411 g_ctx.poseCur.push_back(angle);
412 }
413}
414
417 return static_cast<int>(g_ctx.poseCur.size() / 4);
418}
419
426uintptr_t physics_getInterpolatedTransforms(float alpha) {
427 const size_t count = g_ctx.poseCur.size();
428 g_ctx.poseInterpolated.resize(count);
429 if (count == 0) return reinterpret_cast<uintptr_t>(g_ctx.poseInterpolated.data());
430
431 // Steady state (no body created or destroyed since the last step) keeps both
432 // snapshots in the same order, so a body's previous pose sits at its own index
433 // and the whole pass is a linear walk. Only a changed body set pays for a map.
434 const bool sameLayout = g_ctx.posePrev.size() == count;
435 bool indexBuilt = false;
436
437 for (size_t o = 0; o < count; o += 4) {
438 const uint32_t entityId = poseEntityAt(g_ctx.poseCur, o);
439 const float cx = g_ctx.poseCur[o + 1];
440 const float cy = g_ctx.poseCur[o + 2];
441 const float ca = g_ctx.poseCur[o + 3];
442
443 const float* prev = nullptr;
444 if (sameLayout && poseEntityAt(g_ctx.posePrev, o) == entityId) {
445 prev = &g_ctx.posePrev[o];
446 } else if (!g_ctx.posePrev.empty()) {
447 if (!indexBuilt) {
448 for (size_t p = 0; p < g_ctx.posePrev.size(); p += 4) {
449 g_ctx.posePrevIndex[poseEntityAt(g_ctx.posePrev, p)] = static_cast<uint32_t>(p);
450 }
451 indexBuilt = true;
452 }
453 auto it = g_ctx.posePrevIndex.find(entityId);
454 if (it != g_ctx.posePrevIndex.end()) prev = &g_ctx.posePrev[it->second];
455 }
456
457 // A body seen for the first time seeds prev = cur, so it doesn't smear in
458 // from wherever it was spawned.
459 const float px = prev ? prev[1] : cx;
460 const float py = prev ? prev[2] : cy;
461 const float pa = prev ? prev[3] : ca;
462
463 std::memcpy(&g_ctx.poseInterpolated[o], &entityId, sizeof(uint32_t));
464 g_ctx.poseInterpolated[o + 1] = px + (cx - px) * alpha;
465 g_ctx.poseInterpolated[o + 2] = py + (cy - py) * alpha;
466 g_ctx.poseInterpolated[o + 3] = lerpAngleShortest(pa, ca, alpha);
467 }
468
469 return reinterpret_cast<uintptr_t>(g_ctx.poseInterpolated.data());
470}
471
472// Collision Events
473
476 if (!b2World_IsValid(g_ctx.worldId)) return;
477
478 b2ContactEvents contactEvents = b2World_GetContactEvents(g_ctx.worldId);
479
480 for (int i = 0; i < contactEvents.beginCount; ++i) {
481 auto& evt = contactEvents.beginEvents[i];
482 uint32_t entityA = entityFromShape(evt.shapeIdA);
483 uint32_t entityB = entityFromShape(evt.shapeIdB);
484 if (entityA == 0xFFFFFFFF || entityB == 0xFFFFFFFF) continue;
485
486 pushEntityBits(g_ctx.collisionEnterBuffer, entityA);
487 pushEntityBits(g_ctx.collisionEnterBuffer, entityB);
488
489 float nx = 0, ny = 0, cx = 0, cy = 0;
490 if (b2Contact_IsValid(evt.contactId)) {
491 b2ContactData cd = b2Contact_GetData(evt.contactId);
492 nx = cd.manifold.normal.x;
493 ny = cd.manifold.normal.y;
494 if (cd.manifold.pointCount > 0) {
495 cx = cd.manifold.points[0].point.x;
496 cy = cd.manifold.points[0].point.y;
497 }
498 }
499 g_ctx.collisionEnterBuffer.push_back(nx);
500 g_ctx.collisionEnterBuffer.push_back(ny);
501 g_ctx.collisionEnterBuffer.push_back(cx);
502 g_ctx.collisionEnterBuffer.push_back(cy);
503 }
504
505 for (int i = 0; i < contactEvents.endCount; ++i) {
506 auto& evt = contactEvents.endEvents[i];
507 if (!b2Shape_IsValid(evt.shapeIdA) || !b2Shape_IsValid(evt.shapeIdB)) continue;
508
509 uint32_t entityA = entityFromShape(evt.shapeIdA);
510 uint32_t entityB = entityFromShape(evt.shapeIdB);
511 if (entityA == 0xFFFFFFFF || entityB == 0xFFFFFFFF) continue;
512
513 pushEntityBits(g_ctx.collisionExitBuffer, entityA);
514 pushEntityBits(g_ctx.collisionExitBuffer, entityB);
515 }
516
517 // High-speed impacts (approach speed past the world's hitEventThreshold) —
518 // per hit: [entityA, entityB, pointX, pointY, normalX, normalY, approachSpeed].
519 for (int i = 0; i < contactEvents.hitCount; ++i) {
520 auto& evt = contactEvents.hitEvents[i];
521 uint32_t entityA = entityFromShape(evt.shapeIdA);
522 uint32_t entityB = entityFromShape(evt.shapeIdB);
523 if (entityA == 0xFFFFFFFF || entityB == 0xFFFFFFFF) continue;
524 pushEntityBits(g_ctx.hitEventBuffer, entityA);
525 pushEntityBits(g_ctx.hitEventBuffer, entityB);
526 g_ctx.hitEventBuffer.push_back(evt.point.x);
527 g_ctx.hitEventBuffer.push_back(evt.point.y);
528 g_ctx.hitEventBuffer.push_back(evt.normal.x);
529 g_ctx.hitEventBuffer.push_back(evt.normal.y);
530 g_ctx.hitEventBuffer.push_back(evt.approachSpeed);
531 }
532
533 b2SensorEvents sensorEvents = b2World_GetSensorEvents(g_ctx.worldId);
534
535 for (int i = 0; i < sensorEvents.beginCount; ++i) {
536 auto& evt = sensorEvents.beginEvents[i];
537 uint32_t sensor = entityFromShape(evt.sensorShapeId);
538 uint32_t visitor = entityFromShape(evt.visitorShapeId);
539 if (sensor == 0xFFFFFFFF || visitor == 0xFFFFFFFF) continue;
540
541 pushEntityBits(g_ctx.sensorEnterBuffer, sensor);
542 pushEntityBits(g_ctx.sensorEnterBuffer, visitor);
543 }
544
545 for (int i = 0; i < sensorEvents.endCount; ++i) {
546 auto& evt = sensorEvents.endEvents[i];
547 if (!b2Shape_IsValid(evt.sensorShapeId) || !b2Shape_IsValid(evt.visitorShapeId)) continue;
548
549 uint32_t sensor = entityFromShape(evt.sensorShapeId);
550 uint32_t visitor = entityFromShape(evt.visitorShapeId);
551 if (sensor == 0xFFFFFFFF || visitor == 0xFFFFFFFF) continue;
552
553 pushEntityBits(g_ctx.sensorExitBuffer, sensor);
554 pushEntityBits(g_ctx.sensorExitBuffer, visitor);
555 }
556}
557
560 return static_cast<int>(g_ctx.collisionEnterBuffer.size() / 6);
561}
562
565 return reinterpret_cast<uintptr_t>(g_ctx.collisionEnterBuffer.data());
566}
567
570 return static_cast<int>(g_ctx.hitEventBuffer.size() / 7);
571}
572
575 return reinterpret_cast<uintptr_t>(g_ctx.hitEventBuffer.data());
576}
577
580 return static_cast<int>(g_ctx.collisionExitBuffer.size() / 2);
581}
582
585 return reinterpret_cast<uintptr_t>(g_ctx.collisionExitBuffer.data());
586}
587
590 return static_cast<int>(g_ctx.sensorEnterBuffer.size() / 2);
591}
592
595 return reinterpret_cast<uintptr_t>(g_ctx.sensorEnterBuffer.data());
596}
597
600 return static_cast<int>(g_ctx.sensorExitBuffer.size() / 2);
601}
602
605 return reinterpret_cast<uintptr_t>(g_ctx.sensorExitBuffer.data());
606}
607
608// Force / Impulse / Velocity
609
611void physics_applyForce(uint32_t entityId, float forceX, float forceY) {
612 auto it = g_ctx.entityToBody.find(entityId);
613 if (it == g_ctx.entityToBody.end()) return;
614 if (!b2Body_IsValid(it->second)) return;
615
616 b2Vec2 center = b2Body_GetPosition(it->second);
617 b2Body_ApplyForce(it->second, {forceX, forceY}, center, true);
618}
619
621void physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY) {
622 auto it = g_ctx.entityToBody.find(entityId);
623 if (it == g_ctx.entityToBody.end()) return;
624 if (!b2Body_IsValid(it->second)) return;
625
626 b2Vec2 center = b2Body_GetPosition(it->second);
627 b2Body_ApplyLinearImpulse(it->second, {impulseX, impulseY}, center, true);
628}
629
631void physics_setLinearVelocity(uint32_t entityId, float vx, float vy) {
632 auto paused = g_ctx.pausedMotion.find(entityId);
633 if (paused != g_ctx.pausedMotion.end()) {
634 paused->second.linearVelocity = {vx, vy};
635 return;
636 }
637 auto it = g_ctx.entityToBody.find(entityId);
638 if (it == g_ctx.entityToBody.end()) return;
639 if (!b2Body_IsValid(it->second)) return;
640
641 b2Body_SetLinearVelocity(it->second, {vx, vy});
642}
643
645uintptr_t physics_getLinearVelocity(uint32_t entityId) {
646 auto it = g_ctx.entityToBody.find(entityId);
647 if (it == g_ctx.entityToBody.end()) {
648 g_ctx.velocityBuffer[0] = 0;
649 g_ctx.velocityBuffer[1] = 0;
650 return reinterpret_cast<uintptr_t>(g_ctx.velocityBuffer);
651 }
652 if (!b2Body_IsValid(it->second)) {
653 g_ctx.velocityBuffer[0] = 0;
654 g_ctx.velocityBuffer[1] = 0;
655 return reinterpret_cast<uintptr_t>(g_ctx.velocityBuffer);
656 }
657
658 auto paused = g_ctx.pausedMotion.find(entityId);
659 b2Vec2 v = paused != g_ctx.pausedMotion.end()
660 ? paused->second.linearVelocity : b2Body_GetLinearVelocity(it->second);
661 g_ctx.velocityBuffer[0] = v.x;
662 g_ctx.velocityBuffer[1] = v.y;
663 return reinterpret_cast<uintptr_t>(g_ctx.velocityBuffer);
664}
665
666// Gravity
667
669void physics_setGravity(float gx, float gy) {
670 if (!b2World_IsValid(g_ctx.worldId)) return;
671 b2World_SetGravity(g_ctx.worldId, {gx, gy});
672}
673
676 if (!b2World_IsValid(g_ctx.worldId)) {
677 g_ctx.gravityBuffer[0] = 0;
678 g_ctx.gravityBuffer[1] = 0;
679 return reinterpret_cast<uintptr_t>(g_ctx.gravityBuffer);
680 }
681 b2Vec2 g = b2World_GetGravity(g_ctx.worldId);
682 g_ctx.gravityBuffer[0] = g.x;
683 g_ctx.gravityBuffer[1] = g.y;
684 return reinterpret_cast<uintptr_t>(g_ctx.gravityBuffer);
685}
686
687// Angular Velocity / Torque
688
690void physics_setAngularVelocity(uint32_t entityId, float omega) {
691 auto paused = g_ctx.pausedMotion.find(entityId);
692 if (paused != g_ctx.pausedMotion.end()) {
693 paused->second.angularVelocity = omega;
694 return;
695 }
696 auto it = g_ctx.entityToBody.find(entityId);
697 if (it == g_ctx.entityToBody.end()) return;
698 if (!b2Body_IsValid(it->second)) return;
699 b2Body_SetAngularVelocity(it->second, omega);
700}
701
703float physics_getAngularVelocity(uint32_t entityId) {
704 auto paused = g_ctx.pausedMotion.find(entityId);
705 if (paused != g_ctx.pausedMotion.end()) return paused->second.angularVelocity;
706 auto it = g_ctx.entityToBody.find(entityId);
707 if (it == g_ctx.entityToBody.end()) return 0;
708 if (!b2Body_IsValid(it->second)) return 0;
709 return b2Body_GetAngularVelocity(it->second);
710}
711
713void physics_applyTorque(uint32_t entityId, float torque) {
714 auto it = g_ctx.entityToBody.find(entityId);
715 if (it == g_ctx.entityToBody.end()) return;
716 if (!b2Body_IsValid(it->second)) return;
717 b2Body_ApplyTorque(it->second, torque, true);
718}
719
721void physics_applyAngularImpulse(uint32_t entityId, float impulse) {
722 auto it = g_ctx.entityToBody.find(entityId);
723 if (it == g_ctx.entityToBody.end()) return;
724 if (!b2Body_IsValid(it->second)) return;
725 b2Body_ApplyAngularImpulse(it->second, impulse, true);
726}
727
728// Runtime Body Property Update
729
731void physics_updateBodyProperties(uint32_t entityId, int bodyType,
732 float gravityScale, float linearDamping, float angularDamping,
733 int fixedRotation, int bullet) {
734 auto it = g_ctx.entityToBody.find(entityId);
735 if (it == g_ctx.entityToBody.end()) return;
736 if (!b2Body_IsValid(it->second)) return;
737
738 b2BodyType type;
739 switch (bodyType) {
740 case 0: type = b2_staticBody; break;
741 case 1: type = b2_kinematicBody; break;
742 default: type = b2_dynamicBody; break;
743 }
744 b2BodyType oldType = b2Body_GetType(it->second);
745 b2Body_SetType(it->second, type);
746 if (oldType != type) {
747 auto dit = std::find(g_ctx.dynamicBodyEntities.begin(), g_ctx.dynamicBodyEntities.end(), entityId);
748 if (type == b2_dynamicBody && dit == g_ctx.dynamicBodyEntities.end()) {
749 g_ctx.dynamicBodyEntities.push_back(entityId);
750 } else if (type != b2_dynamicBody && dit != g_ctx.dynamicBodyEntities.end()) {
751 *dit = g_ctx.dynamicBodyEntities.back();
752 g_ctx.dynamicBodyEntities.pop_back();
753 }
754 }
755 b2Body_SetGravityScale(it->second, gravityScale);
756 b2Body_SetLinearDamping(it->second, linearDamping);
757 b2Body_SetAngularDamping(it->second, angularDamping);
758 b2Body_SetBullet(it->second, bullet != 0);
759
760 b2MotionLocks locks = b2Body_GetMotionLocks(it->second);
761 locks.angularZ = fixedRotation != 0;
762 b2Body_SetMotionLocks(it->second, locks);
763}
764
765// Sleep / Wake
766
768void physics_setAwake(uint32_t entityId, int awake) {
769 auto it = g_ctx.entityToBody.find(entityId);
770 if (it == g_ctx.entityToBody.end()) return;
771 if (!b2Body_IsValid(it->second)) return;
772 b2Body_SetAwake(it->second, awake != 0);
773}
774
776int physics_isAwake(uint32_t entityId) {
777 auto it = g_ctx.entityToBody.find(entityId);
778 if (it == g_ctx.entityToBody.end()) return 0;
779 if (!b2Body_IsValid(it->second)) return 0;
780 return b2Body_IsAwake(it->second) ? 1 : 0;
781}
782
783// Body Mass Queries
784
786float physics_getBodyMass(uint32_t entityId) {
787 auto body = findValidBody(entityId);
788 if (B2_IS_NULL(body)) return 0;
789 return b2Body_GetMass(body);
790}
791
793float physics_getBodyInertia(uint32_t entityId) {
794 auto body = findValidBody(entityId);
795 if (B2_IS_NULL(body)) return 0;
796 return b2Body_GetRotationalInertia(body);
797}
798
800uintptr_t physics_getBodyCenterOfMass(uint32_t entityId) {
801 g_massDataBuffer[0] = 0;
802 g_massDataBuffer[1] = 0;
803 auto body = findValidBody(entityId);
804 if (!B2_IS_NULL(body)) {
805 b2Vec2 com = b2Body_GetLocalCenterOfMass(body);
806 g_massDataBuffer[0] = com.x;
807 g_massDataBuffer[1] = com.y;
808 }
809 return reinterpret_cast<uintptr_t>(g_massDataBuffer);
810}
811
812} // extern "C"
Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.
#define EMSCRIPTEN_KEEPALIVE
The Box2D module's entry points, declared once for both platforms.
float g_massDataBuffer[2]
PhysicsContext g_ctx
uint32_t entityFromShape(b2ShapeId shapeId)
void pushEntityBits(std::vector< float > &buf, uint32_t entityId)
b2BodyId findValidBody(uint32_t entityId)
static constexpr int MAX_PHYSICS_STEPS_PER_FRAME
int physics_isAwake(uint32_t entityId)
void physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY)
int physics_getDynamicBodyCount()
int physics_getSensorExitCount()
void physics_setBodyEnabled(uint32_t entityId, int enabled)
void physics_init(float gx, float gy, float timestep, int substeps, float contactHertz, float contactDampingRatio, float contactSpeed)
uintptr_t physics_getSensorExitBuffer()
int physics_setBodyTransforms(uintptr_t bufferPtr, int count, float ppu)
uintptr_t physics_getBodyCenterOfMass(uint32_t entityId)
void physics_collectEvents()
int physics_getJointCount()
void physics_setGravity(float gx, float gy)
void physics_setAngularVelocity(uint32_t entityId, float omega)
float physics_getBodyInertia(uint32_t entityId)
void physics_setWorldConfig(int enableSleep, int enableContinuous, float restitutionThreshold, float maxLinearSpeed)
void physics_applyForce(uint32_t entityId, float forceX, float forceY)
static constexpr float ONE_WAY_ALIGN_THRESHOLD
int physics_getBodyCount()
void physics_setBodyTargetTransform(uint32_t entityId, float x, float y, float angle, float dt)
int physics_getInterpolatedCount()
void physics_setLinearVelocity(uint32_t entityId, float vx, float vy)
int physics_getSensorEnterCount()
int physics_getCollisionEnterCount()
void physics_shutdown()
uintptr_t physics_getCollisionEnterBuffer()
void physics_updateBodyProperties(uint32_t entityId, int bodyType, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, int bullet)
uintptr_t physics_getInterpolatedTransforms(float alpha)
uintptr_t physics_getGravity()
void physics_createBody(uint32_t entityId, int bodyType, float x, float y, float angle, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, int bullet)
int physics_hasBody(uint32_t entityId)
int physics_getShapeCount()
void physics_setOneWayPlatform(uint32_t entityId, float nx, float ny, int enable)
static bool preSolveOneWayPlatform(b2ShapeId shapeIdA, b2ShapeId shapeIdB, b2Vec2 point, b2Vec2 normal, void *context)
float physics_getAngularVelocity(uint32_t entityId)
static uint32_t poseEntityAt(const std::vector< float > &buf, size_t offset)
uintptr_t physics_getDynamicBodyTransforms()
uintptr_t physics_getHitEventBuffer()
void physics_applyAngularImpulse(uint32_t entityId, float impulse)
static float lerpAngleShortest(float a, float b, float t)
void physics_applyTorque(uint32_t entityId, float torque)
void physics_setAwake(uint32_t entityId, int awake)
void physics_step(float dt)
int physics_getTrackingRows()
uintptr_t physics_getLinearVelocity(uint32_t entityId)
void physics_capturePoses()
int physics_getHitEventCount()
int physics_getCollisionExitCount()
void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle)
float physics_getBodyMass(uint32_t entityId)
void physics_setOneWayPlatformLocal(uint32_t entityId, float nx, float ny, int enable)
uintptr_t physics_getCollisionExitBuffer()
void physics_destroyBody(uint32_t entityId)
uintptr_t physics_getSensorEnterBuffer()
The worker pool Box2D solves across on a device.
const T * boundarySpan(uintptr_t ptr, u64 count, const char *what)
Validates a JS-supplied pointer to count elements of T and returns it typed.
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47