A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(physics): the 3D world says what touched what
esengine171ff1be9c54
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eec0ffb71..34022d0d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,16 @@ published separately; it ships inside the editor.### Added+- **The 3D world says what touched what.** Contacts and sensor overlaps reach+ the ECS through a `Physics3DEvents` resource, drained per fixed step: an enter+ carries both entities, the normal and the point; a sensor names itself first,+ so a listener never has to work out which of the two it subscribed to.++ An ended contact carries only the pair. At that moment the solver holds both+ bodies locked and one may already have been destroyed, so there is nothing left+ to report — and a contact ends when a body falls ASLEEP as well as when it moves+ away, which is what the gate had to be rewritten to see.+- **A 3D character stands, walks and climbs a step.** `CharacterController3D`is swept against the world rather than solved in it, which is what lets itclimb a 20cm step and stay glued to a slope without inheriting the momentum ofdiff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex 74048c501..809dc3437 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -75,6 +75,40 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;leaving every caller to rediscover it.</Aside>+## Collision events++Each step publishes what touched what into the `Physics3DEvents` resource. It is+drained per fixed step, so a system reading it must run inside one — a read from+`Update` sees whatever the last step happened to leave.++```typescript+const events = app.getResource(Physics3DEvents);+for (const hit of events.contactEnters) {+ // both entities, and where they met+ spawnSparks(hit.pointX, hit.pointY, hit.pointZ);+}+for (const { sensorEntity, visitorEntity } of events.sensorEnters) {+ if (sensorEntity === goalZone) score(visitorEntity);+}+```++| Channel | What it carries |+|---|---|+| `contactEnters` | Both entities, the contact normal and the point. |+| `contactExits` | Only the pair — see below. |+| `sensorEnters` / `sensorExits` | The **sensor first**, then the visitor. |++<Aside>+ An ended contact carries no geometry: at that moment the solver has both bodies+ locked and one of them may already have been destroyed, so there is nothing left+ to report but who the pair was. A contact also ends when a body falls asleep,+ not only when it moves away — treat an exit as "this pair is no longer touching",+ not as "something moved".+</Aside>++A collider with `isSensor` reports overlaps and stops nothing: the visitor passes+straight through and shows up in `sensorEnters` instead of `contactEnters`.+## Which world a scene is inNothing stops an entity carrying both sets, but nothing merges them either: the twodiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdxindex 67e26e1b2..78194dbaa 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx@@ -69,6 +69,37 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;而不是让每个调用者各自重新发现这件事。</Aside>+## 碰撞事件++每一步都会把「谁碰到了谁」发布到 `Physics3DEvents` 资源里。它按固定步长排空,+所以读它的系统必须跑在固定步里——从 `Update` 里读只会看到上一步碰巧留下的东西。++```typescript+const events = app.getResource(Physics3DEvents);+for (const hit of events.contactEnters) {+ // 两个实体,以及它们相遇的位置+ spawnSparks(hit.pointX, hit.pointY, hit.pointZ);+}+for (const { sensorEntity, visitorEntity } of events.sensorEnters) {+ if (sensorEntity === goalZone) score(visitorEntity);+}+```++| 通道 | 带着什么 |+|---|---|+| `contactEnters` | 两个实体、接触法线和接触点。 |+| `contactExits` | 只有这一对——原因见下。 |+| `sensorEnters` / `sensorExits` | **传感器在前**,然后是访客。 |++<Aside>+ 结束的接触不带几何:在那一刻求解器锁着两个刚体,其中一个甚至可能已经被销毁,+ 所以除了「这一对是谁」之外什么都报不出来。另外,接触也会在刚体**睡着**时结束,+ 而不只是在它移开时——请把 exit 理解成「这一对不再接触了」,而不是「有东西动了」。+</Aside>++带 `isSensor` 的碰撞体报告重叠但不拦任何东西:访客直接穿过去,并且出现在+`sensorEnters` 而不是 `contactEnters` 里。+## 一个场景在哪个世界里没有东西阻止一个实体同时带两套组件,但也没有东西会把它们合并:两个世界互相看不见,diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex c65548918..0d8525d4c 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -5,6 +5,9 @@* @brief The 3D physics wasm module's surface, and how it is loaded.*/+import { defineResource } from '../ecs/resource';+import type { Entity } from '../types';+/** What the module exports. Kept in step with Physics3DModuleEntry.cpp by* {@link assertPhysics3DContract} — a TypeScript interface is gone at run time,* and a module built before the JS that drives it installs happily and then@@ -52,6 +55,15 @@ export interface Physics3DWasmModule {_physics3d_raycast(ox: number, oy: number, oz: number,dx: number, dy: number, dz: number): number;+ _physics3d_contactEnters(): number;+ _physics3d_contactEntersBytes(): number;+ _physics3d_contactExits(): number;+ _physics3d_contactExitsBytes(): number;+ _physics3d_sensorEnters(): number;+ _physics3d_sensorEntersBytes(): number;+ _physics3d_sensorExits(): number;+ _physics3d_sensorExitsBytes(): number;+_physics3d_transforms(): number;_physics3d_transformsBytes(): number;_physics3d_queryResult(): number;@@ -73,6 +85,8 @@ const REQUIRED_EXPORTS = ['_physics3d_removeBody', '_physics3d_setTransform', '_physics3d_raycast','_physics3d_transforms', '_physics3d_transformsBytes','_physics3d_addCharacter', '_physics3d_moveCharacter', '_physics3d_removeCharacter',+ '_physics3d_contactEnters', '_physics3d_contactEntersBytes',+ '_physics3d_sensorEnters', '_physics3d_sensorEntersBytes',] as const;/** Throws naming what is missing, rather than letting the first frame do it. */@@ -95,3 +109,78 @@ export async function loadPhysics3DModule(assertPhysics3DContract(module);return module;}++// =============================================================================+// Events+// =============================================================================++/** Two bodies met, and where. */+export interface Contact3DEvent {+ entityA: Entity;+ entityB: Entity;+ normalX: number;+ normalY: number;+ normalZ: number;+ pointX: number;+ pointY: number;+ pointZ: number;+}++/** A sensor was entered or left. The SENSOR is always named first. */+export interface Sensor3DEvent {+ sensorEntity: Entity;+ visitorEntity: Entity;+}++export interface Physics3DEventsData {+ contactEnters: Contact3DEvent[];+ /** Ends carry only the pair: at that moment the bodies are locked and one may+ * already be gone, so there is no geometry left to report. */+ contactExits: Array<{ entityA: Entity; entityB: Entity }>;+ sensorEnters: Sensor3DEvent[];+ sensorExits: Sensor3DEvent[];+}++/**+ * This step's 3D collision and trigger events. Drained per fixed step, so a+ * system reading it must run inside one — a read from `Update` sees whatever the+ * last step left.+ *+ * @beta+ */+export const Physics3DEvents = defineResource<Physics3DEventsData>({+ contactEnters: [],+ contactExits: [],+ sensorEnters: [],+ sensorExits: [],+}, 'Physics3DEvents');++/** Refill `events` from the module's four buffers. */+export function drainPhysics3DEvents(module: Physics3DWasmModule,+ events: Physics3DEventsData): void {+ const f32 = module.HEAPF32;+ const read = <T>(ptr: number, bytes: number, stride: number,+ make: (base: number) => T): T[] => {+ const out: T[] = [];+ const base = ptr >> 2;+ for (let i = 0; i < bytes / 4; i += stride) out.push(make(base + i));+ return out;+ };++ events.contactEnters = read(+ module._physics3d_contactEnters(), module._physics3d_contactEntersBytes(), 8,+ (o) => ({+ entityA: f32[o] as Entity, entityB: f32[o + 1] as Entity,+ normalX: f32[o + 2]!, normalY: f32[o + 3]!, normalZ: f32[o + 4]!,+ pointX: f32[o + 5]!, pointY: f32[o + 6]!, pointZ: f32[o + 7]!,+ }));+ events.contactExits = read(+ module._physics3d_contactExits(), module._physics3d_contactExitsBytes(), 2,+ (o) => ({ entityA: f32[o] as Entity, entityB: f32[o + 1] as Entity }));+ events.sensorEnters = read(+ module._physics3d_sensorEnters(), module._physics3d_sensorEntersBytes(), 2,+ (o) => ({ sensorEntity: f32[o] as Entity, visitorEntity: f32[o + 1] as Entity }));+ events.sensorExits = read(+ module._physics3d_sensorExits(), module._physics3d_sensorExitsBytes(), 2,+ (o) => ({ sensorEntity: f32[o] as Entity, visitorEntity: f32[o + 1] as Entity }));+}diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex d58228974..68d9c28f4 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -9,7 +9,8 @@ import { Schedule, defineSystem } from '../ecs/system';import { defineResource } from '../ecs/resource';import type { Entity } from '../types';import {- loadPhysics3DModule, type Physics3DModuleFactory, type Physics3DWasmModule,+ loadPhysics3DModule, Physics3DEvents, type Physics3DModuleFactory,+ type Physics3DWasmModule, type Physics3DEventsData,} from './Physics3DModule';import {stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,@@ -48,6 +49,10 @@ export class Physics3DPlugin implements Plugin {const runtime: Physics3DRuntime = {module: null, initPromise: null, bodies: new Map(), characters: new Map(),};+ const events: Physics3DEventsData = {+ contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],+ };+ app.insertResource(Physics3DEvents, events);app.insertResource(Physics3DRuntime, runtime);app.subsystems?.transition?.('physics3d', 'initializing');@@ -57,7 +62,8 @@ export class Physics3DPlugin implements Plugin {module._physics3d_init(gravity.x, gravity.y, gravity.z, maxBodies);runtime.module = module;app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {- stepPhysics3D(app, module, runtime.bodies, this.config_, runtime.characters);+ stepPhysics3D(app, module, runtime.bodies, this.config_,+ runtime.characters, events);}));app.setFixedTimestep?.(this.config_.fixedTimestep);app.subsystems?.transition?.('physics3d', 'ready');diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.tsindex 66689b855..36b59867c 100644--- a/sdk/src/physics3d/Physics3DSystem.ts+++ b/sdk/src/physics3d/Physics3DSystem.ts@@ -20,8 +20,8 @@ import {type CapsuleCollider3DData, type CharacterController3DData,} from './Physics3DComponents';import type { Entity } from '../types';-import type { Physics3DWasmModule } from './Physics3DModule';-import { PHYSICS3D_TRANSFORM_STRIDE } from './Physics3DModule';+import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';+import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';/** Body kinds, in the order the module reads them. */const MOTION = { Static: 0, Kinematic: 1, Dynamic: 2 } as const;@@ -155,7 +155,8 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,/** Bring the world's population in line with the ECS, then step and read back. */export function stepPhysics3D(app: App, module: Physics3DWasmModule,bodies: BodyMap, config: Physics3DConfig,- characters: BodyMap = new Map()): void {+ characters: BodyMap = new Map(),+ events?: Physics3DEventsData): void {const ppu = config.pixelsPerUnit;moveCharacters(app, module, characters, config);@@ -176,6 +177,9 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,}module._physics3d_step(config.fixedTimestep, config.collisionSteps);+ // Drained immediately after the step that produced them: the module's buffers+ // hold one step's worth and the next step clears them.+ if (events) drainPhysics3DEvents(module, events);// Only bodies the solver moved are in the buffer, so this is the frame's// moving population rather than every body in the world.diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.tsindex b731b7037..953be0752 100644--- a/sdk/tests/physics3d-ecs.test.ts+++ b/sdk/tests/physics3d-ecs.test.ts@@ -31,15 +31,17 @@ function fakeModule(): Physics3DWasmModule & {} {const calls: { name: string; args: number[] }[] = [];// One heap the module's two pointers index into, as wasm has.- const combined = new Float32Array(1088);+ const combined = new Float32Array(2176);const heap = combined.subarray(0, 1024);const record = (name: string) => (...args: number[]): number => {calls.push({ name, args });return calls.length; // a non-zero body id};const query = combined.subarray(1024);+ const eventArea = combined.subarray(2048);let published = 0;let publishedQuery = 0;+ let publishedEvents = 0;return {calls,publish(records: number[]) {@@ -50,6 +52,10 @@ function fakeModule(): Physics3DWasmModule & {query.set(records, 0);publishedQuery = records.length * 4;},+ publishContacts(records: number[]) {+ eventArea.set(records, 0);+ publishedEvents = records.length * 4;+ },HEAPF32: combined,HEAPU32: new Uint32Array(combined.buffer),_physics3d_init: record('init'),@@ -69,6 +75,14 @@ function fakeModule(): Physics3DWasmModule & {_physics3d_removeCharacter: record('removeCharacter'),_physics3d_moveCharacter: record('moveCharacter'),_physics3d_setCharacterPosition: record('setCharacterPosition'),+ _physics3d_contactEnters: () => 2048 * 4,+ _physics3d_contactEntersBytes: () => publishedEvents,+ _physics3d_contactExits: () => 0,+ _physics3d_contactExitsBytes: () => 0,+ _physics3d_sensorEnters: () => 0,+ _physics3d_sensorEntersBytes: () => 0,+ _physics3d_sensorExits: () => 0,+ _physics3d_sensorExitsBytes: () => 0,_physics3d_transforms: () => 0,_physics3d_transformsBytes: () => published,// A byte offset past the transform buffer, so the two never alias.@@ -78,6 +92,7 @@ function fakeModule(): Physics3DWasmModule & {calls: { name: string; args: number[] }[];publish(records: number[]): void;publishQuery(records: number[]): void;+ publishContacts(records: number[]): void;};}@@ -247,6 +262,24 @@ describe('the 3D world and the ECS', () => {expect((world.get(e, Transform) as TransformData).position.y).toBeCloseTo(200, 4);});+ it('hands this step\u2019s contacts to the events resource', () => {+ const e = spawn();+ world.insert(e, BoxCollider3D);+ const events = {+ contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],+ };+ // (entityA, entityB, normal, point) — two bodies met head-on at 1m up.+ module.publishContacts([7, 9, 0, 1, 0, 0, 1, 0]);+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, new Map(), events);++ expect(events.contactEnters).toHaveLength(1);+ const [hit] = events.contactEnters as Array<Record<string, number>>;+ expect(hit!.entityA).toBe(7);+ expect(hit!.entityB).toBe(9);+ expect(hit!.normalY).toBeCloseTo(1, 6);+ expect(hit!.pointY).toBeCloseTo(1, 6);+ });+it('leaves a disabled body out of the world', () => {const e = spawn();world.insert(e, BoxCollider3D);diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex a97368389..c78a954da 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -199,7 +199,85 @@ check('a removed character can no longer be moved',(m._physics3d_moveCharacter(hero, 1, 0, 0, 1 / 60, 0.4, 0.5),m._physics3d_queryResultBytes() === 0));-// ── 7) A removed body is gone from both the sweep and the getter ────────────+// ── 7) What touched what ───────────────────────────────────────────────────+// Contact events name BOTH entities and where they met. A falling sphere landing+// on a fresh floor is one enter; nothing leaves until it is moved away.+const pairs = (ptr, bytes, stride) => {+ const base = m[ptr]() >> 2;+ const out = [];+ for (let i = 0; i < m[bytes]() / 4; i += stride) {+ out.push(Array.from({ length: stride }, (_, k) => m.HEAPF32[base + i + k]));+ }+ return out;+};+const contactEnters = () => pairs('_physics3d_contactEnters', '_physics3d_contactEntersBytes', 8);+const contactExits = () => pairs('_physics3d_contactExits', '_physics3d_contactExitsBytes', 2);+const sensorEnters = () => pairs('_physics3d_sensorEnters', '_physics3d_sensorEntersBytes', 2);+const sensorExits = () => pairs('_physics3d_sensorExits', '_physics3d_sensorExitsBytes', 2);++const PAD = 20, DROP = 21;+m._physics3d_addBox(PAD, 2, 0.5, 2, 20, -0.5, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+const dropId = m._physics3d_addSphere(DROP, 0.5, 20, 2, 0, ...IDENTITY,+ ...FREE(DYNAMIC), 0.5, 0, 0);+m._physics3d_optimize();+let landing = null;+for (let i = 0; i < 180 && !landing; i++) {+ step(1);+ landing = contactEnters().find((e) => e[1] === DROP || e[0] === DROP) ?? null;+}+check('a contact names both entities', landing != null+ && (landing[0] === PAD || landing[1] === PAD), JSON.stringify(landing));+check('and where they met', landing != null && near(landing[6], 0.0, 0.15),+ `contact y=${landing?.[6]?.toFixed(4)} want the pad's top at 0`);+// A buffer holds ONE step's events, so they are collected as the steps run —+// reading after a run of steps catches only the last one's.+const collect = (read, steps) => {+ const seen = [];+ for (let i = 0; i < steps; i++) { step(1); seen.push(...read()); }+ return seen;+};+const settledEnters = [];+const seenExits = [];+for (let i = 0; i < 90; i++) {+ step(1);+ settledEnters.push(...contactEnters());+ seenExits.push(...contactExits());+}+check('a contact does not fire again while it persists', settledEnters.length === 0,+ `${settledEnters.length} re-fired`);++// The contact ends on its own once the sphere settles and sleeps; moving it away+// is the other way it ends. Either is the claim — that an ended contact is+// REPORTED — so both windows count toward it.+m._physics3d_setTransform(dropId, 40, 5, 0, ...IDENTITY);+seenExits.push(...collect(contactExits, 30));+check('an ended contact reports an exit', seenExits.some((e) => e.includes(DROP)),+ JSON.stringify(seenExits));++// A sensor reports the overlap without stopping anything, and names ITSELF first.+// The visitor is registered first on purpose: Jolt orders a contact by body id, so+// a sensor created first would lead on its own and prove nothing.+const FIELD = 22, VISITOR = 23;+const visitorId = m._physics3d_addSphere(VISITOR, 0.5, -20, 6, 0, ...IDENTITY,+ ...FREE(DYNAMIC), 0.5, 0, 0);+m._physics3d_addBox(FIELD, 2, 2, 2, -20, 0, 0, ...IDENTITY, ...FREE(STATIC), 0, 0, 1);+m._physics3d_optimize();+let entered = null;+for (let i = 0; i < 240 && !entered; i++) {+ step(1);+ entered = sensorEnters().find((e) => e[0] === FIELD) ?? null;+}+check('a sensor reports its visitor', entered != null && entered[1] === VISITOR,+ JSON.stringify(entered));+// It carries on to the floor below (top at 0, so a 0.5 sphere rests at 0.5). A+// sensor that stopped it would hold it on its own top face at 2.5 instead.+const sensorLeft = collect(sensorExits, 180).find((e) => e[0] === FIELD) ?? null;+check('and does not stop it', near(bodyState(visitorId).y, 0.5, 0.1),+ `visitor y=${bodyState(visitorId)?.y?.toFixed(4)} want 0.5 (through it, onto the floor)`);+check('and reports when it leaves', sensorLeft != null && sensorLeft[1] === VISITOR,+ JSON.stringify(sensorLeft));++// ── 8) A removed body is gone from both the sweep and the getter ────────────m._physics3d_removeBody(capId);step(1);check('a removed body leaves the readback', bodyPos(CAP) === null);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp b/src/esengine/bindings/modules/physics3d/Physics3DContext.hppindex 2f6d14e69..acbc50469 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp@@ -28,6 +28,7 @@#include <cstdint>#include <memory>#include <unordered_map>+#include <unordered_set>#include <vector>namespace JPH { class CharacterVirtual; }@@ -104,6 +105,19 @@ struct Context {/// The last query's hits, in the shape its getter documents.std::vector<float> queryBuffer;+ /// Refilled every step by the contact listener. Enter carries the geometry+ /// (entityA, entityB, nx,ny,nz, px,py,pz); exit only the pair, because at+ /// that moment Jolt has both bodies locked and one of them may already be gone.+ std::vector<float> contactEnterBuffer;+ std::vector<float> contactExitBuffer;+ std::vector<float> sensorEnterBuffer;+ std::vector<float> sensorExitBuffer;++ /// Which bodies are sensors, remembered at registration: OnContactRemoved+ /// cannot ask a body anything, so a sensor that stopped overlapping would+ /// otherwise be indistinguishable from a solid one.+ std::unordered_set<uint32_t> sensorBodies;+/// Characters are not bodies: a CharacterVirtual is swept against the world/// rather than solved in it, which is what lets it climb stairs and stay/// glued to a slope without inheriting momentum from whatever it stands on.diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex e20117317..1f7b6e129 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -23,6 +23,7 @@#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>#include <Jolt/Physics/Collision/Shape/SphereShape.h>#include <Jolt/Physics/Character/CharacterVirtual.h>+#include <Jolt/Physics/Collision/ContactListener.h>#include <Jolt/RegisterTypes.h>#include <cstddef>@@ -74,6 +75,71 @@ struct BodyMotion {int fixedRotation = 0;};+/// The entity a body speaks for, or 0 when nothing claims it.+uint32_t entityOfBody(const BodyID& id) {+ auto found = g().entityOf.find(id.GetIndexAndSequenceNumber());+ return found == g().entityOf.end() ? 0u : found->second;+}++/**+ * Records what touched what. Jolt calls this with every body locked, so it reads+ * only its own tables and the geometry it is handed — never the world.+ */+class ContactRecorder final : public ContactListener {+public:+ void OnContactAdded(const Body& body1, const Body& body2, const ContactManifold& manifold,+ ContactSettings&) override {+ const uint32_t a = body1.GetID().GetIndexAndSequenceNumber();+ const uint32_t b = body2.GetID().GetIndexAndSequenceNumber();+ const uint32_t entityA = entityOfBody(body1.GetID());+ const uint32_t entityB = entityOfBody(body2.GetID());+ if (entityA == 0 && entityB == 0) return;++ const bool aIsSensor = g().sensorBodies.count(a) != 0;+ const bool bIsSensor = g().sensorBodies.count(b) != 0;+ if (aIsSensor || bIsSensor) {+ // The sensor is named first, so a listener never has to work out+ // which of the two it subscribed to.+ g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityA : entityB));+ g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityB : entityA));+ return;+ }+ const RVec3 point = manifold.GetWorldSpaceContactPointOn1(0);+ const Vec3 normal = manifold.mWorldSpaceNormal;+ g().contactEnterBuffer.insert(g().contactEnterBuffer.end(), {+ static_cast<float>(entityA), static_cast<float>(entityB),+ normal.GetX(), normal.GetY(), normal.GetZ(),+ static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),+ static_cast<float>(point.GetZ()),+ });+ }++ void OnContactRemoved(const SubShapeIDPair& pair) override {+ const uint32_t a = pair.GetBody1ID().GetIndexAndSequenceNumber();+ const uint32_t b = pair.GetBody2ID().GetIndexAndSequenceNumber();+ const uint32_t entityA = entityOfBody(pair.GetBody1ID());+ const uint32_t entityB = entityOfBody(pair.GetBody2ID());+ if (entityA == 0 && entityB == 0) return;++ const bool aIsSensor = g().sensorBodies.count(a) != 0;+ const bool bIsSensor = g().sensorBodies.count(b) != 0;+ std::vector<float>& out = (aIsSensor || bIsSensor) ? g().sensorExitBuffer+ : g().contactExitBuffer;+ if (aIsSensor || bIsSensor) {+ out.push_back(static_cast<float>(aIsSensor ? entityA : entityB));+ out.push_back(static_cast<float>(aIsSensor ? entityB : entityA));+ } else {+ out.push_back(static_cast<float>(entityA));+ out.push_back(static_cast<float>(entityB));+ }+ }+};++ContactRecorder& recorder() {+ static ContactRecorder instance;+ return instance;+}+/// Register a shape as a body, and remember which entity it speaks for.uint32_t addBody(uint32_t entity, Shape* shape, float px, float py, float pz,float qx, float qy, float qz, float qw, const BodyMotion& how,@@ -99,6 +165,7 @@ uint32_t addBody(uint32_t entity, Shape* shape, float px, float py, float pz,: EActivation::Activate);if (id.IsInvalid()) return 0;g().entityOf[id.GetIndexAndSequenceNumber()] = entity;+ if (isSensor != 0) g().sensorBodies.insert(id.GetIndexAndSequenceNumber());return id.GetIndexAndSequenceNumber();}@@ -126,6 +193,7 @@ void physics3d_init(float gx, float gy, float gz, uint32_t maxBodies) {g().system->Init(bodies, 0, bodies * 2, bodies * 2, g().broadPhaseLayers,g().objectVsBroadPhase, g().objectPairs);g().system->SetGravity(Vec3(gx, gy, gz));+ g().system->SetContactListener(&recorder());}EMSCRIPTEN_KEEPALIVE@@ -138,6 +206,11 @@ void physics3d_shutdown() {g().jobs = nullptr;g().temp = nullptr;g().characters.clear();+ g().sensorBodies.clear();+ g().contactEnterBuffer.clear();+ g().contactExitBuffer.clear();+ g().sensorEnterBuffer.clear();+ g().sensorExitBuffer.clear();g().entityOf.clear();g().transformBuffer.clear();g().queryBuffer.clear();@@ -152,6 +225,12 @@ int physics3d_isReady() { return g().isValid() ? 1 : 0; }EMSCRIPTEN_KEEPALIVEvoid physics3d_step(float dt, int collisionSteps) {if (!g().isValid() || dt <= 0.0f) return;+ // Cleared before the step, not after: the listener fires DURING Update, and a+ // buffer emptied afterwards would publish nothing.+ g().contactEnterBuffer.clear();+ g().contactExitBuffer.clear();+ g().sensorEnterBuffer.clear();+ g().sensorExitBuffer.clear();g().system->Update(dt, collisionSteps > 0 ? collisionSteps : 1, g().temp, g().jobs);BodyIDVector active;@@ -232,6 +311,7 @@ void physics3d_removeBody(uint32_t bodyId) {bodies.RemoveBody(id);bodies.DestroyBody(id);g().entityOf.erase(bodyId);+ g().sensorBodies.erase(bodyId);}EMSCRIPTEN_KEEPALIVE@@ -393,6 +473,38 @@ size_t physics3d_transformsBytes() {return g().transformBuffer.size() * sizeof(float);}+EMSCRIPTEN_KEEPALIVE+const float* physics3d_contactEnters() { return g().contactEnterBuffer.data(); }++EMSCRIPTEN_KEEPALIVE+size_t physics3d_contactEntersBytes() {+ return g().contactEnterBuffer.size() * sizeof(float);+}++EMSCRIPTEN_KEEPALIVE+const float* physics3d_contactExits() { return g().contactExitBuffer.data(); }++EMSCRIPTEN_KEEPALIVE+size_t physics3d_contactExitsBytes() {+ return g().contactExitBuffer.size() * sizeof(float);+}++EMSCRIPTEN_KEEPALIVE+const float* physics3d_sensorEnters() { return g().sensorEnterBuffer.data(); }++EMSCRIPTEN_KEEPALIVE+size_t physics3d_sensorEntersBytes() {+ return g().sensorEnterBuffer.size() * sizeof(float);+}++EMSCRIPTEN_KEEPALIVE+const float* physics3d_sensorExits() { return g().sensorExitBuffer.data(); }++EMSCRIPTEN_KEEPALIVE+size_t physics3d_sensorExitsBytes() {+ return g().sensorExitBuffer.size() * sizeof(float);+}+EMSCRIPTEN_KEEPALIVEconst float* physics3d_queryResult() { return g().queryBuffer.data(); }