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(physics3d): a script can push a 3D body about - Physics3D applies forces, impulses and torques at a point or the centre of mass, reads and sets linear and angular velocity, reads mass, wakes and sleeps bodies and changes gravity, from Jolt and PhysX alike; explode strikes everything in reach and every Breakable it reaches; Broke is sent when a thing breaks
yhheb147c22d980
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 56777c823..a209780d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,9 @@ published separately; it ships inside the editor.- **Things that break.** A model can end with a `fracture` step, `{ op: "fracture", pieces: 12, at, focus }`, which cuts it beforehand into pieces that fit together with no gap, each a closed solid whose cut faces are tagged apart from its skin, smaller round `at` where it will be struck. It is still drawn whole; the editor also writes a mesh for each piece and a prefab of them, each with a dynamic body and a convex hull, and the reply hands over a `Breakable` to put beside the MeshRenderer. Raising `Breakable.broken` hides the whole (its renderer, body and colliders are switched off, not removed), puts the pieces where it stood and throws them out from `origin` at `burst` world units a second; `lifetime` takes them away later, and lowering the flag makes it whole again. Its pieces are loaded while it stands whole, so they appear on the frame it breaks. In the editor a clay pot written by `model_write` and placed on a floor broke into the 12 pieces asked for, then the 5 asked for after an edit, each of which moved, spread apart and came to rest on the floor, and was whole again when the flag was lowered. Nothing breaks it of itself yet: a script, a graph or a collision handler raises the flag. `Physics3D.setLinearVelocity(entity, velocity)` is what throws the pieces and is there for anything else that sends a body off. `Prefabs.prepare(path)` loads a prefab and everything its entities use and holds it, so a later `instantiate` does not wait on files.- **A thing breaks when it is hit hard enough.** `Breakable.breakImpulse` breaks it on a contact at least that hard, the speed at which the two came together times the mass they met with, and the pieces leave from where it was hit. It needs a collider of its own, which the editor's reply to a fractured model now hands over as `hull` (a `ConvexCollider3D` of its shape); with a dynamic body as well it can be knocked over and break where it lands. Every `Physics3DEvents.contactEnters` entry now carries `speed` (how fast the first body was closing on the second along the normal, read before the solver answered), `mass` (the kilograms they met with, 1 / (1/a + 1/b), a body that does not move counting as none) and `impulse`, their product, from both the Jolt and PhysX worlds. A sphere of 0.5 m dropped 1.5 m onto a pad reported 5.56 m/s from Jolt and 5.40 from PhysX against the 5.42 the fall gives, and met it with 523.60 kg, its own mass, from both. In the editor a 2 kg stone dropped six metres onto a pot broke it from its rim and took its collider away, and a 50 g pebble dropped from as high onto another left it whole. Native builds carry the new buffers but were only compiled on Windows, not run.- **A 3D body has a mass of its own.** `RigidBody3D.mass` sets a moving body's mass in kilograms, its inertia scaled with it; 0, the default, keeps the mass its shape gives at the density of water, so scenes made before it weigh what they did. It reaches a body already in play when it changes. Both worlds were given 2 kg and answered 2, and refused a mass that is not a positive number.+- **A script can push a 3D body about.** `Physics3D` answered where things were and could set a velocity, and nothing more: there was no force, no impulse, no torque, and a script could not ask how fast a body was going, while the 2D world had all of it. It now has `applyImpulse(entity, impulse, at?)` and `applyForce(entity, force, at?)`, at a world point or the centre of mass, `applyTorque`, `applyAngularImpulse`, `getLinearVelocity`, `setAngularVelocity` and `getAngularVelocity`, `getMass`, `setAwake` and `isAwake`, and `setGravity` and `getGravity`, all in world units, from both the Jolt and PhysX worlds. In each, 4 N s at the centre of a 2 kg sphere gave it 2.000 m/s and no spin; 1 N s half a metre off its centre gave it 2.500 rad/s, which r x J over its inertia says; a force lasted one step; and with gravity set to 2 m/s squared a body fell at 1.000 m/s after half a second.+- **A blast.** `Physics3D.explode(centre, radius, impulse, { upward })` strikes every moving body within reach away from the centre, less the further it is and none at the edge, and strikes every `Breakable` it reaches as hard, standing or not, so a grenade breaks the pots round it. In the editor a blast beside a pot broke it and threw the 50 g pebble at its foot away and up.+- **A thing that breaks says so.** `Broke` is sent once a `Breakable`'s pieces stand in its place, with where it was struck in the world and how hard, for the sound, the dust and the score; a thing whose pieces could not be loaded did not break and sends nothing.## [0.104.1] - 2026-11-13diff --git a/desktop b/desktopindex cce5604f4..8e727c571 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit cce5604f45c20c849d7111856dc61cfe696dbe3c+Subproject commit 8e727c5718a435c181539e0e40e249a16ce58e2cdiff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex 8d1cbe906..c87d03724 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -513,6 +513,39 @@ that asks in the first frames should check for it.units long.</Aside>+## Pushing bodies++The same `Physics3D` resource pushes bodies about: throwing, kicking, knocking+back, a blast. Lengths and speeds are world units, as `Transform`'s; masses+kilograms; angles radians. An impulse is kilograms by world units a second, so a+2 kg body given an impulse of 200 gains 100 world units a second; a force is the+same per second.++```typescript+const physics = app.getResource(Physics3D);+// Kick a ball where the foot meets it: it flies and spins.+physics.applyImpulse(ball, { x: 0, y: 150, z: -600 }, footPoint);+// A blast: every moving body within 400 thrown away and a little up,+// and every Breakable it reaches hard enough broken.+physics.explode(grenadeAt, 400, 3000, { upward: 0.4 });+```++| Call | Does |+|---|---|+| `applyImpulse(entity, impulse, at?)` | Strikes it all at once: its velocity changes by impulse / mass. At `at`, a world point, it also turns it; without, at its centre of mass. Wakes it. |+| `applyForce(entity, force, at?)` | Pushes it over the next fixed step only: a steady push is given again each step, from a system in `Schedule.FixedUpdate`. |+| `applyTorque(entity, torque)` / `applyAngularImpulse(entity, impulse)` | Twists it, over the next step or all at once, about each world axis. Kilograms by world units squared a second squared, and a second. |+| `setLinearVelocity(entity, v)` / `getLinearVelocity(entity)` | Its speed, in world units a second. |+| `setAngularVelocity(entity, w)` / `getAngularVelocity(entity)` | Its spin, in radians a second. |+| `getMass(entity)` | Kilograms; `null` for a body that does not move. Set with `RigidBody3D.mass`. |+| `setAwake(entity, awake)` / `isAwake(entity)` | Wake a sleeping body, or put one to sleep until something touches it. |+| `setGravity(g)` / `getGravity()` | The world's gravity, in metres a second squared as the project's physics settings give it. A sleeping body stays put until woken. |+| `explode(centre, radius, impulse, { upward?, layers? })` | Strikes every moving body within `radius` away from `centre` with `impulse`, less the further it is and none at the edge; `upward` (0..1) tips the push toward the sky. A `Breakable` it reaches is struck as hard, standing or not. Answers how many bodies it moved. |++A body that does not move takes none of it, and each call answers `false` (or+`null`) for an entity the world has no body for yet, which is true for the+frame an entity is spawned in.+## Collision layersEvery body is in one of sixteen layers, and a project says which layers hear from@@ -677,3 +710,14 @@ they should have with `RigidBody3D.mass`.there for anything else that needs to send a body off: a blast, a kick. Itanswers false for an entity that has no body yet, which is true for the frame anentity is spawned in.++When it breaks, `Broke` is sent, once the pieces stand in its place, for the+sound, the dust and the score: `{ entity, x, y, z, impulse }`, where it was+struck in the world and how hard (0 when its flag was raised by hand).++```typescript+app.addSystemToSchedule(Schedule.Update, defineSystem([EventReader(Broke), Res(Audio)], (broke, audio) => {+ // Louder the harder it was struck; a pot broken by hand makes its quietest sound.+ for (const b of broke) audio.playSFX('assets/shatter.wav', { volume: Math.min(1, 0.3 + b.impulse / 3000) });+}));+```diff --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 fedd18781..ed415c99d 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@@ -449,6 +449,36 @@ const occupants = q.overlapSphere(spawnPoint, 50);乘上 `pixelsPerUnit` 只会得到一个长度 100 的单位向量。</Aside>+## 推动刚体++同一个 `Physics3D` 资源也用来推动刚体:投掷、踢、击退、爆炸。长度和速度用世界单位,与+`Transform` 一致;质量用千克;角度用弧度。冲量是千克·世界单位每秒,所以给 2 kg 的刚体+200 的冲量,它的速度增加 100 世界单位每秒;力则是同样的量每秒。++```typescript+const physics = app.getResource(Physics3D);+// 在脚碰到球的位置踢它:球会飞出并旋转。+physics.applyImpulse(ball, { x: 0, y: 150, z: -600 }, footPoint);+// 爆炸:400 范围内的运动刚体被向外并略向上抛出,+// 被波及得够重的 Breakable 会碎。+physics.explode(grenadeAt, 400, 3000, { upward: 0.4 });+```++| 调用 | 作用 |+|---|---|+| `applyImpulse(entity, impulse, at?)` | 一次性撞击:速度变化为冲量除以质量。给了世界坐标 `at` 时还会让它转动;不给时作用在质心。会唤醒刚体。 |+| `applyForce(entity, force, at?)` | 只在下一个固定步里施力:持续的推力要在 `Schedule.FixedUpdate` 的系统里每步施加一次。 |+| `applyTorque(entity, torque)` / `applyAngularImpulse(entity, impulse)` | 绕各世界轴扭转,分别作用于下一步或一次性作用。单位是千克·世界单位²每秒²,以及每秒。 |+| `setLinearVelocity(entity, v)` / `getLinearVelocity(entity)` | 线速度,世界单位每秒。 |+| `setAngularVelocity(entity, w)` / `getAngularVelocity(entity)` | 角速度,弧度每秒。 |+| `getMass(entity)` | 千克;不动的刚体返回 `null`。用 `RigidBody3D.mass` 设定。 |+| `setAwake(entity, awake)` / `isAwake(entity)` | 唤醒休眠的刚体,或让它休眠直到被碰到。 |+| `setGravity(g)` / `getGravity()` | 世界重力,单位与项目物理设置一致,米每秒²。休眠的刚体在被唤醒前不会动。 |+| `explode(centre, radius, impulse, { upward?, layers? })` | 把 `radius` 内的每个运动刚体从 `centre` 向外撞开,力度为 `impulse`,越远越小,到边缘为零;`upward`(0..1)让推力偏向上方。被波及的 `Breakable` 以同样力度计算,不论它是否静止。返回推动了多少个刚体。 |++不动的刚体不受这些影响;世界里还没有对应刚体的实体,每个调用都返回 `false`(或 `null`),+实体刚生成的那一帧就是这样。+## 碰撞层每个刚体属于十六层中的一层,由项目声明哪些层之间能互相听见。**两边都得同意**——@@ -579,3 +609,13 @@ world.update(pot, Breakable, (b) => { b.origin = hitPointInItsOwnSpace; b.broken把碎块抛出去用的是 `Physics3D.setLinearVelocity(entity, velocity)`,其他需要把刚体送出去的场合(爆炸、踢击)也可以用它。实体还没有刚体时它返回 false,实体刚生成的那一帧就是这样。++碎的时候会在碎块放好之后发送 `Broke` 事件,用来播放声音、扬尘和计分:+`{ entity, x, y, z, impulse }`,即在世界中被击中的位置和力度(手动置标志时为 0)。++```typescript+app.addSystemToSchedule(Schedule.Update, defineSystem([EventReader(Broke), Res(Audio)], (broke, audio) => {+ // Louder the harder it was struck; a pot broken by hand makes its quietest sound.+ for (const b of broke) audio.playSFX('assets/shatter.wav', { volume: Math.min(1, 0.3 + b.impulse / 3000) });+}));+```diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex e95204a1d..198ee4c2d 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 178,- "experimental": 3099,+ "experimental": 3101,"deprecated": 3},- "total": 3392,+ "total": 3394,"subsystems": [{"id": "mobile-controls",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 5c19096cb..6967e337f 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2188 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2190 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1958,6 +1958,20 @@ static new (): BreakablePluginstatic prototype: BreakablePlugin```+## Broke — const @experimental+```+EventDef<BrokePayload>+```++## BrokePayload — interface @experimental+```+entity: number+impulse: number+x: number+y: number+z: number+```+## BuildProfile — interface @experimental```remoteRoot: string | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 067dc818e..e3c512126 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 171 beta · 2208 experimental · 3 deprecated+Symbols: 115 public · 171 beta · 2210 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1958,6 +1958,20 @@ static new (): BreakablePluginstatic prototype: BreakablePlugin```+## Broke — const @experimental+```+EventDef<BrokePayload>+```++## BrokePayload — interface @experimental+```+entity: number+impulse: number+x: number+y: number+z: number+```+## BuildProfile — interface @experimental```remoteRoot: string | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cedf10d44..403f5ca78 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 168 beta · 2187 experimental · 3 deprecated+Symbols: 115 public · 168 beta · 2189 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1953,6 +1953,20 @@ static new (): BreakablePluginstatic prototype: BreakablePlugin```+## Broke — const @experimental+```+EventDef<BrokePayload>+```++## BrokePayload — interface @experimental+```+entity: number+impulse: number+x: number+y: number+z: number+```+## BuildProfile — interface @experimental```remoteRoot: string | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex a7baa306a..efa75f2a8 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2209 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2211 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1953,6 +1953,20 @@ static new (): BreakablePluginstatic prototype: BreakablePlugin```+## Broke — const @experimental+```+EventDef<BrokePayload>+```++## BrokePayload — interface @experimental+```+entity: number+impulse: number+x: number+y: number+z: number+```+## BuildProfile — interface @experimental```remoteRoot: string | undefineddiff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.mdindex 9eafaea7d..d1d5ed9cd 100644--- a/sdk/etc/physics3d.api.md+++ b/sdk/etc/physics3d.api.md@@ -318,14 +318,27 @@ static prototype: Physics3DPlugin## Physics3DQueries — class @experimental```+applyAngularImpulse: (entity: Entity, impulse: { x: number; y: number; z: number; }) => boolean+applyForce: (entity: Entity, force: { x: number; y: number; z: number; }, at?: { x: number; y: number; z: number; }) => boolean+applyImpulse: (entity: Entity, impulse: { x: number; y: number; z: number; }, at?: { x: number; y: number; z: number; }) => boolean+applyTorque: (entity: Entity, torque: { x: number; y: number; z: number; }) => boolean+explode: (centre: { x: number; y: number; z: number; }, radius: number, impulse: number, options?: { upward?: number; layers?: number; }) => number+getAngularVelocity: (entity: Entity) => { x: number; y: number; z: number; } | null+getGravity: () => { x: number; y: number; z: number; }+getLinearVelocity: (entity: Entity) => { x: number; y: number; z: number; } | null+getMass: (entity: Entity) => number | nullhasBody: (entity: Entity) => boolean+isAwake: (entity: Entity) => booleanoverlapBox: (centre: { x: number; y: number; z: number; }, halfExtents: { x: number; y: number; z: number; }, layerMask?: number) => Overlap3DHit[]overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => Overlap3DHit[]raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, layerMask?: number, options?: { characters?: boolean; }) => Cast3DHit | null+setAngularVelocity: (entity: Entity, velocity: { x: number; y: number; z: number; }) => boolean+setAwake: (entity: Entity, awake: boolean) => boolean+setGravity: (gravity: { x: number; y: number; z: number; }) => booleansetLinearVelocity: (entity: Entity, velocity: { x: number; y: number; z: number; }) => booleansphereCast: (origin: { x: number; y: number; z: number; }, radius: number, direction: { x: number; y: number; z: number; }, layerMask?: number) => Cast3DHit | nullteleportCharacter: (entity: Entity, position: { x: number; y: number; z: number; }) => boolean-static new (module_: Physics3DWasmModule, ppu_: number, characters_?: ReadonlyMap<Entity, number>, bodies_?: ReadonlyMap<Entity, number>): Physics3DQueries+static new (module_: Physics3DWasmModule, ppu_: number, characters_?: ReadonlyMap<Entity, number>, bodies_?: ReadonlyMap<Entity, number>, world_?: { gravity: { x: number; y: number; z: number; }; }): Physics3DQueriesstatic prototype: Physics3DQueries```@@ -346,6 +359,7 @@ HEAPF32: Float32Array<ArrayBufferLike>HEAPU32: Uint32Array<ArrayBufferLike>_free: (ptr: number) => void_malloc: (bytes: number) => number+_physics3d_addAngularImpulse: ((bodyId: number, ix: number, iy: number, iz: number) => void) | undefined_physics3d_addBox: (entity: number, hx: number, hy: number, hz: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number, cx: number, cy: number, cz: number) => number_physics3d_addCapsule: (entity: number, radius: number, halfHeight: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number, cx: number, cy: number, cz: number) => number_physics3d_addCharacter: (entity: number, radius: number, halfHeight: number, px: number, py: number, pz: number, maxSlope: number, mass: number, layer: number, pushForce: number) => number@@ -355,6 +369,7 @@ _physics3d_addDistanceJoint: (entity: number, bodyA: number, bodyB: number, ax:_physics3d_addFixedJoint: (entity: number, bodyA: number, bodyB: number, collideConnected: number) => number_physics3d_addForce: ((bodyId: number, fx: number, fy: number, fz: number, px: number, py: number, pz: number) => void) | undefined_physics3d_addHingeJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, enableLimit: number, lower: number, upper: number, enableMotor: number, motorSpeed: number, maxTorque: number, collideConnected: number) => number+_physics3d_addImpulse: ((bodyId: number, ix: number, iy: number, iz: number, px: number, py: number, pz: number) => void) | undefined_physics3d_addMeshBody: (entity: number, vertexPtr: number, vertexCount: number, indexPtr: number, indexCount: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, layer: number, friction: number, restitution: number) => number_physics3d_addPointJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, collideConnected: number) => number_physics3d_addSixDOFJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, nx: number, ny: number, nz: number, translationMotion: number, rotationMotion: number, lx: number, ly: number, lz: number, hx: number, hy: number, hz: number, rx: number, ry: number, rz: number, sx: number, sy: number, sz: number, collideConnected: number) => number@@ -373,6 +388,7 @@ _physics3d_contactExitsBytes: () => number_physics3d_getBodyDynamics: ((bodyId: number) => number) | undefined_physics3d_getBodyState: (bodyId: number) => number_physics3d_init: (gx: number, gy: number, gz: number, maxBodies: number) => void+_physics3d_isAwake: ((bodyId: number) => number) | undefined_physics3d_isReady: () => number_physics3d_jointValue: (entity: number) => number_physics3d_moveCharacter: (characterId: number, vx: number, vy: number, vz: number, dt: number, stepUp: number, stepDown: number) => void@@ -391,7 +407,10 @@ _physics3d_sensorEntersBytes: () => number_physics3d_sensorExits: () => number_physics3d_sensorExitsBytes: () => number_physics3d_setAdvancedJointMotor: (entity: number, enable: number, vx: number, vy: number, vz: number, wx: number, wy: number, wz: number, maxForce: number, maxTorque: number) => void+_physics3d_setAngularVelocity: ((bodyId: number, wx: number, wy: number, wz: number) => void) | undefined+_physics3d_setAwake: ((bodyId: number, awake: number) => void) | undefined_physics3d_setCharacterPosition: (characterId: number, px: number, py: number, pz: number) => void+_physics3d_setGravity: ((gx: number, gy: number, gz: number) => void) | undefined_physics3d_setJointMotor: (entity: number, enable: number, speed: number) => void_physics3d_setLayerMask: (layer: number, mask: number) => void_physics3d_setLinearVelocity: (bodyId: number, vx: number, vy: number, vz: number) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex ccdaf3bcf..1e5e4ef49 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2200 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2202 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1953,6 +1953,20 @@ static new (): BreakablePluginstatic prototype: BreakablePlugin```+## Broke — const @experimental+```+EventDef<BrokePayload>+```++## BrokePayload — interface @experimental+```+entity: number+impulse: number+x: number+y: number+z: number+```+## BuildProfile — interface @experimental```remoteRoot: string | undefineddiff --git a/sdk/src/breakable/breakable.ts b/sdk/src/breakable/breakable.tsindex 9aa7f37e3..f242cc5d6 100644--- a/sdk/src/breakable/breakable.ts+++ b/sdk/src/breakable/breakable.ts@@ -23,6 +23,22 @@ import { isEditor, isPlayMode } from '../ecs/env';import { Prefabs, type PrefabServer } from '../prefab/prefabServer';import { q } from '../math/quat';import { log } from '../util/logger';+import { defineEvent, EventWriter, type EventDef, type EventWriterInstance } from '../ecs/event';++/** Something broke: which, where it was struck in the world, and how hard (0 when its flag was raised by hand). */+export interface BrokePayload {+ entity: Entity;+ x: number;+ y: number;+ z: number;+ impulse: number;+}++/**+ * Sent the frame a Breakable breaks, for the sound, the dust and the score: read it with `EventReader(Broke)` in a+ * system of your own. Not sent when it is made whole again.+ */+export const Broke: EventDef<BrokePayload> = defineEvent<BrokePayload>('Broke', { entity: 0 as Entity, x: 0, y: 0, z: 0, impulse: 0 });export interface BreakableData {/** The prefab of its pieces, as a model's `fracture` step writes it. */@@ -175,7 +191,15 @@ export class BreakablePlugin implements Plugin {});void offDespawn;- const shatter = (entity: Entity, data: BreakableData, prefabs: PrefabServer): void => {+ // The blow that broke a thing, kept until it breaks, for what the event says.+ const struck = new Map<Entity, { impulse: number; point: Vec3 }>();+ const shatter = (entity: Entity, data: BreakableData, prefabs: PrefabServer, broke: EventWriterInstance<BrokePayload>): void => {+ const blow = struck.get(entity);+ struck.delete(entity);+ const t = world.get(entity, Transform) as TransformData & { worldPosition?: Vec3; worldRotation?: { x: number; y: number; z: number; w: number }; worldScale?: Vec3 };+ const [position, rotation, scale] = [t.worldPosition ?? t.position, t.worldRotation ?? t.rotation, t.worldScale ?? t.scale];+ const from = q.rotate(rotation, { x: data.origin.x * scale.x, y: data.origin.y * scale.y, z: data.origin.z * scale.z });+ const point = blow?.point ?? { x: position.x + from.x, y: position.y + from.y, z: position.z + from.z };const b: Broken = { loading: true, root: null, age: 0, throws: [] };state.set(entity, b);prefabs.instantiate(data.pieces).then((made) => {@@ -187,6 +211,8 @@ export class BreakablePlugin implements Plugin {world.update(made.root, Transform, (d: TransformData) => { d.position = { ...position }; d.rotation = { ...rotation }; d.scale = { ...scale }; });show(entity, false);b.loading = false;+ // Said once the pieces stand in its place: a thing whose pieces could not be loaded did not break.+ broke.send({ entity, x: point.x, y: point.y, z: point.z, impulse: blow?.impulse ?? 0 });b.root = made.root;if (data.burst > 0) {const from = q.rotate(rotation, { x: data.origin.x * scale.x, y: data.origin.y * scale.y, z: data.origin.z * scale.z });@@ -209,7 +235,7 @@ export class BreakablePlugin implements Plugin {});};- app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time)], (time: TimeData) => {+ app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time), EventWriter(Broke)], (time: TimeData, broke: EventWriterInstance<BrokePayload>) => {if (isEditor() && !isPlayMode()) {// Out of play nothing is broken: what a scene saves is the whole.for (const entity of [...state.keys()]) mend(entity);@@ -231,6 +257,7 @@ export class BreakablePlugin implements Plugin {d.origin = { x: local.x / (scale.x || 1), y: local.y / (scale.y || 1), z: local.z / (scale.z || 1) };d.broken = true;});+ struck.set(entity, h);}}const live = new Set<Entity>();@@ -240,7 +267,7 @@ export class BreakablePlugin implements Plugin {if (prefabs && data.enabled) keepWarm(entity, data.pieces, prefabs); else cool(entity);const b = state.get(entity);if (!data.enabled || !data.broken) { if (b) mend(entity); continue; }- if (!b) { if (data.pieces && prefabs) shatter(entity, data, prefabs); continue; }+ if (!b) { if (data.pieces && prefabs) shatter(entity, data, prefabs, broke); continue; }if (b.loading) continue;// The world makes a piece's body on its next step; until then there is nothing to throw.if (b.throws.length) {diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 5ff82cdbb..9e5928f08 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -433,7 +433,7 @@ export {} from './prefab/index';export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin, type SpawnOverride } from './prefab/prefabServer';-export { Breakable, BreakablePlugin, breakablePlugin, burstVelocity, setBodyPusher, type BreakableData, type BodyPusher } from './breakable/breakable';+export { Breakable, BreakablePlugin, breakablePlugin, Broke, burstVelocity, setBodyPusher, type BreakableData, type BodyPusher, type BrokePayload } from './breakable/breakable';// =============================================================================// Runtime Loaderdiff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex dbe1b5cde..9165b7ac0 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -149,6 +149,13 @@ export interface Physics3DWasmModule {_physics3d_contactEnterMassesBytes?(): number;/** Optional for older binaries: a moving body's mass in kilograms. */_physics3d_setMass?(bodyId: number, mass: number): void;+ /** Optional for older binaries: a blow in newton seconds at a world point, or the centre of mass for NaN. */+ _physics3d_addImpulse?(bodyId: number, ix: number, iy: number, iz: number, px: number, py: number, pz: number): void;+ _physics3d_addAngularImpulse?(bodyId: number, ix: number, iy: number, iz: number): void;+ _physics3d_setAngularVelocity?(bodyId: number, wx: number, wy: number, wz: number): void;+ _physics3d_setGravity?(gx: number, gy: number, gz: number): void;+ _physics3d_setAwake?(bodyId: number, awake: number): void;+ _physics3d_isAwake?(bodyId: number): number;_physics3d_contactExits(): number;_physics3d_contactExitsBytes(): number;_physics3d_sensorEnters(): number;diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex dd56f93b5..5c00edfec 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -75,7 +75,7 @@ export class Physics3DPlugin implements Plugin {runtime.module = module;// The character map, not a copy of it: characters are created lazily// by the step, so a snapshot taken here would never hold one.- const queries = new Physics3DQueries(module, this.config_.pixelsPerUnit, runtime.characters, runtime.bodies);+ const queries = new Physics3DQueries(module, this.config_.pixelsPerUnit, runtime.characters, runtime.bodies, this.config_);// Whatever throws things about without knowing there is a solver asks through this.setBodyPusher((entity, velocity) => queries.setLinearVelocity(entity, velocity));app.insertResource(Physics3D, queries);diff --git a/sdk/src/physics3d/Physics3DQueries.ts b/sdk/src/physics3d/Physics3DQueries.tsindex 64bd1074b..c9b876d2b 100644--- a/sdk/src/physics3d/Physics3DQueries.ts+++ b/sdk/src/physics3d/Physics3DQueries.ts@@ -7,6 +7,7 @@* same contract the step follows — a query answering in the solver's* units would be a second set of numbers for a caller to remember.*/+import { reportContact } from '../breakable/breakable';import type { Entity } from '../types';import type { Physics3DWasmModule } from './Physics3DModule';@@ -42,7 +43,158 @@ export class Physics3DQueries {constructor(private readonly module_: Physics3DWasmModule,private readonly ppu_: number,private readonly characters_: ReadonlyMap<Entity, number> = new Map(),- private readonly bodies_: ReadonlyMap<Entity, number> = new Map()) {}+ private readonly bodies_: ReadonlyMap<Entity, number> = new Map(),+ private readonly world_: { gravity: { x: number; y: number; z: number } } = { gravity: { x: 0, y: -9.81, z: 0 } }) {}++ // ── Pushing bodies ────────────────────────────────────────────────────────+ // Lengths and speeds are world units, as Transform's; masses kilograms; angles radians. A force is kilograms by+ // world units a second squared, an impulse kilograms by world units a second, so a 2 kg body given an impulse of+ // 200 gains 100 world units a second. A body that does not move takes none of it. Each answers false for an+ // entity the world has no body for yet - which is also true for the frame an entity is spawned in.++ /**+ * Push a body over the next step. At `at`, a world point, it also turns it; without one it pushes at its centre of+ * mass. A force lasts one step: a steady push is given again each fixed step (a system in Schedule.FixedUpdate).+ */+ applyForce(entity: Entity, force: { x: number; y: number; z: number }, at?: { x: number; y: number; z: number }): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_addForce) return false;+ const p = this.ppu_;+ this.module_._physics3d_addForce(id, force.x / p, force.y / p, force.z / p, ...this.pointOf_(at));+ return true;+ }++ /** Strike a body, all at once: its velocity changes by impulse / mass. At `at` it also turns it. Wakes it. */+ applyImpulse(entity: Entity, impulse: { x: number; y: number; z: number }, at?: { x: number; y: number; z: number }): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_addImpulse) return false;+ const p = this.ppu_;+ this.module_._physics3d_addImpulse(id, impulse.x / p, impulse.y / p, impulse.z / p, ...this.pointOf_(at));+ return true;+ }++ /** Twist a body over the next step, about each world axis: kilograms by world units squared a second squared. */+ applyTorque(entity: Entity, torque: { x: number; y: number; z: number }): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_addTorque) return false;+ const p2 = this.ppu_ * this.ppu_;+ this.module_._physics3d_addTorque(id, torque.x / p2, torque.y / p2, torque.z / p2);+ return true;+ }++ /** Twist a body all at once: kilograms by world units squared a second. */+ applyAngularImpulse(entity: Entity, impulse: { x: number; y: number; z: number }): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_addAngularImpulse) return false;+ const p2 = this.ppu_ * this.ppu_;+ this.module_._physics3d_addAngularImpulse(id, impulse.x / p2, impulse.y / p2, impulse.z / p2);+ return true;+ }++ /** How fast it is going, in world units a second; null for an entity with no body. */+ getLinearVelocity(entity: Entity): { x: number; y: number; z: number } | null {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_getBodyState(id)) return null;+ const f32 = this.module_.HEAPF32, o = this.module_._physics3d_queryResult() >> 2, p = this.ppu_;+ return { x: f32[o + 7]! * p, y: f32[o + 8]! * p, z: f32[o + 9]! * p };+ }++ /** How fast it turns, in radians a second about each world axis; null for a body that does not move. */+ getAngularVelocity(entity: Entity): { x: number; y: number; z: number } | null {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_getBodyDynamics?.(id)) return null;+ const f32 = this.module_.HEAPF32, o = this.module_._physics3d_queryResult() >> 2;+ return { x: f32[o + 1]!, y: f32[o + 2]!, z: f32[o + 3]! };+ }++ /** Set how fast it turns, in radians a second about each world axis. Wakes it. */+ setAngularVelocity(entity: Entity, velocity: { x: number; y: number; z: number }): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_setAngularVelocity) return false;+ this.module_._physics3d_setAngularVelocity(id, velocity.x, velocity.y, velocity.z);+ return true;+ }++ /** Its mass in kilograms; null for a body that does not move, which has none. */+ getMass(entity: Entity): number | null {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_getBodyDynamics?.(id)) return null;+ return this.module_.HEAPF32[this.module_._physics3d_queryResult() >> 2]!;+ }++ /** Wake a sleeping body, or put one to sleep until something touches it. */+ setAwake(entity: Entity, awake: boolean): boolean {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_setAwake) return false;+ this.module_._physics3d_setAwake(id, awake ? 1 : 0);+ return true;+ }++ /** Whether it is awake: false for one asleep, one that does not move, or an entity with no body. */+ isAwake(entity: Entity): boolean {+ const id = this.bodies_.get(entity);+ return id !== undefined && (this.module_._physics3d_isAwake?.(id) ?? 0) === 1;+ }++ /**+ * The world's gravity, in metres a second squared as the project's physics settings give it (y -9.81 is Earth's).+ * A body asleep when it changes stays where it is until something wakes it.+ */+ setGravity(gravity: { x: number; y: number; z: number }): boolean {+ if (!this.module_._physics3d_setGravity) return false;+ this.module_._physics3d_setGravity(gravity.x, gravity.y, gravity.z);+ this.world_.gravity = { ...gravity };+ return true;+ }++ getGravity(): { x: number; y: number; z: number } {+ return { ...this.world_.gravity };+ }++ /**+ * A blast at `centre`: every moving body within `radius` is struck away from it with `impulse` at the centre,+ * less the further it is, to none at the edge; `upward` (0..1) tips the push toward the sky, as a blast on the+ * ground throws things up. Whatever can break and is caught in it is struck as hard, so a Breakable with a+ * breakImpulse that the blast reaches at least that hard breaks, standing or not. Answers how many bodies it moved.+ */+ explode(centre: { x: number; y: number; z: number }, radius: number, impulse: number,+ options: { upward?: number; layers?: number } = {}): number {+ if (!(radius > 0) || !(impulse > 0)) return 0;+ const upward = Math.max(0, Math.min(1, options.upward ?? 0));+ const seen = new Set<Entity>();+ let moved = 0;+ for (const hit of this.overlapSphere(centre, radius, options.layers ?? 0)) {+ if (seen.has(hit.entity)) continue;+ seen.add(hit.entity);+ const at = this.bodyPosition_(hit.entity) ?? { x: hit.x, y: hit.y, z: hit.z };+ let [x, y, z] = [at.x - centre.x, at.y - centre.y, at.z - centre.z];+ const far = Math.hypot(x, y, z);+ const share = Math.max(0, 1 - far / radius);+ if (share <= 0) continue;+ [x, y, z] = far > 1e-6 ? [x / far, y / far, z / far] : [0, 1, 0];+ y += upward;+ const long = Math.hypot(x, y, z) || 1;+ const blow = impulse * share;+ reportContact(hit.entity, hit.entity, blow, at);+ if (this.getMass(hit.entity) !== null+ && this.applyImpulse(hit.entity, { x: (x / long) * blow, y: (y / long) * blow, z: (z / long) * blow })) moved++;+ }+ return moved;+ }++ private bodyPosition_(entity: Entity): { x: number; y: number; z: number } | null {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_getBodyState(id)) return null;+ const f32 = this.module_.HEAPF32, o = this.module_._physics3d_queryResult() >> 2, p = this.ppu_;+ return { x: f32[o]! * p, y: f32[o + 1]! * p, z: f32[o + 2]! * p };+ }++ /** A world point in metres, or not-a-number for the centre of mass. */+ private pointOf_(at?: { x: number; y: number; z: number }): [number, number, number] {+ if (!at) return [NaN, NaN, NaN];+ const p = this.ppu_;+ return [at.x / p, at.y / p, at.z / p];+ }/*** Send a body off at a velocity, in world units a second: a blast, a kick, a piece of something that broke. Whatdiff --git a/sdk/tests/breakable.test.ts b/sdk/tests/breakable.test.tsindex 2e3d9fb1d..22975dee6 100644--- a/sdk/tests/breakable.test.ts+++ b/sdk/tests/breakable.test.ts@@ -27,7 +27,18 @@ vi.mock('../src/ecs/component', async (importOriginal) => {const { App } = await import('../src/app/app');const { Transform, getComponent } = await import('../src/ecs/component');-const { Breakable, BreakablePlugin, burstVelocity, reportContact, setBodyPusher } = await import('../src/breakable/breakable');+const { Breakable, BreakablePlugin, Broke, burstVelocity, reportContact, setBodyPusher } = await import('../src/breakable/breakable');+const { defineSystem, Schedule } = await import('../src/ecs/system');+const { EventReader } = await import('../src/ecs/event');++/** Everything said about breaking, as a game's own system would read it. */+function listen(app: InstanceType<typeof App>) {+ const heard: { entity: Entity; x: number; y: number; z: number; impulse: number }[] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([EventReader(Broke)], (broke: Iterable<(typeof heard)[number]>) => {+ for (const e of broke) heard.push({ ...e });+ }, { name: 'ListenForBreaks' }));+ return heard;+}const { Prefabs } = await import('../src/prefab/prefabServer');const MeshRenderer = getComponent('MeshRenderer')!;const Body = getComponent('RigidBody3D')!;@@ -210,6 +221,36 @@ describe('a thing that breaks', () => {expect(prefabs.instantiate).not.toHaveBeenCalled();});+ it('says it broke once the pieces stand, with the blow and where it landed', async () => {+ const { app, whole, tick } = setup();+ const heard = listen(app);+ app.world.update(whole, Breakable, (d) => { d.breakImpulse = 400; });+ reportContact(app.world.spawn('Stone'), whole, 650, { x: 100, y: 70, z: 10 });+ await tick(4);+ expect(heard).toEqual([{ entity: whole, x: 100, y: 70, z: 10, impulse: 650 }]);+ // Once: lying broken, it says nothing more.+ await tick(3);+ expect(heard).toHaveLength(1);+ });++ it('says it broke when its flag is raised, at its origin and with no blow', async () => {+ const { app, whole, breakIt, tick } = setup();+ const heard = listen(app);+ app.world.update(whole, Breakable, (d) => { d.origin = { x: 0, y: 20, z: 0 }; });+ breakIt(true);+ await tick(4);+ expect(heard).toEqual([{ entity: whole, x: 100, y: 70, z: 0, impulse: 0 }]);+ });++ it('says nothing when its pieces cannot be loaded, since it did not break', async () => {+ const { app, breakIt, tick, failNext } = setup();+ const heard = listen(app);+ failNext();+ breakIt(true);+ await tick(4);+ expect(heard).toEqual([]);+ });+it('stops hearing hits when its app ends', async () => {const { app, whole } = setup();const ball = app.world.spawn('Ball');diff --git a/sdk/tests/physics3d-body-control.test.ts b/sdk/tests/physics3d-body-control.test.tsnew file mode 100644index 000000000..8e927931d--- /dev/null+++ b/sdk/tests/physics3d-body-control.test.ts@@ -0,0 +1,169 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file physics3d-body-control.test.ts+ * @brief What a script hands Physics3D to push a body reaches the solver in its units, and a blast falls off.+ *+ * Held here: world units become metres on the way in and back on the way out (a length once, an impulse once,+ * a torque twice), a push with no point goes to the centre of mass, a blast strikes what it reaches less the+ * further it is and every breakable in it as hard, and a world without the newer calls says so rather than+ * throwing. What the solver does with a push is the real-solver smoke's (physics3d-smoke.mjs).+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import type { Entity } from '../src/types';+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';+import { Physics3DQueries } from '../src/physics3d/Physics3DQueries';+import { reportContact } from '../src/breakable/breakable';++// What a blast tells whatever breaks: caught here rather than through a world of breakables.+vi.mock('../src/breakable/breakable', async (original) => ({ ...(await original<object>()), reportContact: vi.fn() }));++interface Call { name: string; args: number[] }++/** Bodies 1 and 2 move (2 kg); body 3 stands still. Body states are (x, y, z) metres in a table. */+function fakeWorld(at: Record<number, [number, number, number]>, overlaps: number[] = []) {+ const calls: Call[] = [];+ const heap = new Float32Array(256);+ const moving = new Set([1, 2]);+ const record = (name: string) => (...args: number[]): void => { calls.push({ name, args }); };+ const module = {+ HEAPF32: heap,+ _physics3d_queryResult: () => 0,+ _physics3d_addForce: record('addForce'),+ _physics3d_addTorque: record('addTorque'),+ _physics3d_addImpulse: record('addImpulse'),+ _physics3d_addAngularImpulse: record('addAngularImpulse'),+ _physics3d_setAngularVelocity: record('setAngularVelocity'),+ _physics3d_setGravity: record('setGravity'),+ _physics3d_setAwake: record('setAwake'),+ _physics3d_isAwake: (id: number) => (moving.has(id) ? 1 : 0),+ _physics3d_getBodyState: (id: number) => {+ const p = at[id];+ if (!p) return 0;+ heap.set([p[0], p[1], p[2], 0, 0, 0, 1, 0.5, -1, 0], 0);+ return 1;+ },+ _physics3d_getBodyDynamics: (id: number) => {+ if (!moving.has(id)) return 0;+ heap.set([2, 0.1, 0.2, 0.3], 0);+ return 1;+ },+ _physics3d_overlapSphere: () => {+ // Read out before anything else uses the buffer, as the real one is.+ // Entities, as the real one names them: body n is entity 10 n here.+ overlaps.forEach((id, i) => heap.set([id * 10, ...(at[id] ?? [0, 0, 0])], i * 4));+ return overlaps.length;+ },+ };+ return { module: module as unknown as Physics3DWasmModule, calls };+}++const bodies = new Map<Entity, number>([[10 as Entity, 1], [20 as Entity, 2], [30 as Entity, 3]]);++describe('pushing a 3D body from a script', () => {+ let world: ReturnType<typeof fakeWorld>;+ let physics: Physics3DQueries;+ const gravity = { gravity: { x: 0, y: -9.81, z: 0 } };+ beforeEach(() => {+ world = fakeWorld({ 1: [1, 0, 0], 2: [0, 0, 3], 3: [0, 0, 0] });+ physics = new Physics3DQueries(world.module, 100, new Map(), bodies, gravity);+ });+ const last = (name: string) => world.calls.filter((c) => c.name === name).at(-1)?.args;++ it('hands the solver an impulse in newton seconds, at a point in metres or at the centre of mass', () => {+ expect(physics.applyImpulse(10 as Entity, { x: 200, y: 0, z: -100 })).toBe(true);+ const [id, ix, iy, iz, ...point] = last('addImpulse')!;+ expect([id, ix, iy, iz]).toEqual([1, 2, 0, -1]);+ expect(point.every(Number.isNaN)).toBe(true);+ physics.applyImpulse(10 as Entity, { x: 0, y: 100, z: 0 }, { x: 150, y: 50, z: 0 });+ expect(last('addImpulse')).toEqual([1, 0, 1, 0, 1.5, 0.5, 0]);+ });++ it('scales a force once and a torque twice, a length being in both', () => {+ physics.applyForce(10 as Entity, { x: 981, y: 0, z: 0 });+ expect(last('addForce')!.slice(0, 4)).toEqual([1, 9.81, 0, 0]);+ physics.applyTorque(10 as Entity, { x: 0, y: 10000, z: 0 });+ expect(last('addTorque')).toEqual([1, 0, 1, 0]);+ physics.applyAngularImpulse(10 as Entity, { x: 20000, y: 0, z: 0 });+ expect(last('addAngularImpulse')).toEqual([1, 2, 0, 0]);+ });++ it('reads velocity back in world units, spin in radians, and mass in kilograms', () => {+ expect(physics.getLinearVelocity(10 as Entity)).toEqual({ x: 50, y: -100, z: 0 });+ const spin = physics.getAngularVelocity(10 as Entity)!;+ expect([spin.x, spin.y, spin.z].map((v) => +v.toFixed(5))).toEqual([0.1, 0.2, 0.3]);+ expect(physics.getMass(10 as Entity)).toBe(2);+ // A body that does not move has neither spin nor mass to tell.+ expect(physics.getMass(30 as Entity)).toBeNull();+ expect(physics.getAngularVelocity(30 as Entity)).toBeNull();+ });++ it('answers false and null for an entity the world has no body for', () => {+ expect(physics.applyImpulse(99 as Entity, { x: 1, y: 0, z: 0 })).toBe(false);+ expect(physics.applyForce(99 as Entity, { x: 1, y: 0, z: 0 })).toBe(false);+ expect(physics.getLinearVelocity(99 as Entity)).toBeNull();+ expect(physics.isAwake(99 as Entity)).toBe(false);+ expect(world.calls).toEqual([]);+ });++ it('wakes, sleeps, and keeps the gravity it was given in metres a second squared', () => {+ physics.setAwake(10 as Entity, false);+ expect(last('setAwake')).toEqual([1, 0]);+ expect(physics.isAwake(10 as Entity)).toBe(true);+ expect(physics.isAwake(30 as Entity)).toBe(false);+ physics.setGravity({ x: 0, y: -1.62, z: 0 });+ expect(last('setGravity')).toEqual([0, -1.62, 0]);+ expect(physics.getGravity()).toEqual({ x: 0, y: -1.62, z: 0 });+ physics.setGravity({ x: 0, y: -9.81, z: 0 });+ });++ it('says so, rather than throwing, in a world built before these calls', () => {+ const old = { ...world.module } as Record<string, unknown>;+ for (const name of ['_physics3d_addImpulse', '_physics3d_addAngularImpulse', '_physics3d_setAngularVelocity', '_physics3d_setGravity', '_physics3d_setAwake', '_physics3d_isAwake']) delete old[name];+ const before = new Physics3DQueries(old as unknown as Physics3DWasmModule, 100, new Map(), bodies);+ expect(before.applyImpulse(10 as Entity, { x: 1, y: 0, z: 0 })).toBe(false);+ expect(before.setGravity({ x: 0, y: -1, z: 0 })).toBe(false);+ expect(before.isAwake(10 as Entity)).toBe(false);+ });+});++describe('a blast', () => {+ it('strikes each moving body it reaches away from its centre, less the further it is, and none past its edge', () => {+ // Body 1 is 100 units from the blast, body 2 300, body 3 does not move; the blast reaches 400.+ const world = fakeWorld({ 1: [1, 0, 0], 2: [0, 0, 3], 3: [0, 0, 0.5] }, [1, 1, 2, 3]);+ const physics = new Physics3DQueries(world.module, 100, new Map(), bodies);+ const moved = physics.explode({ x: 0, y: 0, z: 0 }, 400, 1000);+ expect(moved).toBe(2);+ const blows = world.calls.filter((c) => c.name === 'addImpulse').map((c) => c.args);+ // Each once, though the overlap named body 1 twice: 1000 at 3/4 of the way in, 1000 at 1/4.+ expect(blows).toHaveLength(2);+ const [near, far] = blows;+ expect(near![0]).toBe(1);+ expect(near![1]).toBeCloseTo(7.5, 4);+ expect(far![0]).toBe(2);+ expect(far![3]).toBeCloseTo(2.5, 4);+ // And everything it caught is told how hard, the body that does not move too: that is how a blast breaks a pot.+ const told = vi.mocked(reportContact).mock.calls.map(([a, b, blow]) => [a, b, +blow.toFixed(3)]);+ expect(told).toEqual([[10, 10, 750], [20, 20, 250], [30, 30, 875]]);+ });++ beforeEach(() => vi.mocked(reportContact).mockClear());++ it('tips its push toward the sky by upward', () => {+ const world = fakeWorld({ 1: [1, 0, 0] }, [1]);+ const physics = new Physics3DQueries(world.module, 100, new Map(), bodies);+ physics.explode({ x: 0, y: 0, z: 0 }, 200, 1000, { upward: 1 });+ const [, ix, iy] = world.calls.find((c) => c.name === 'addImpulse')!.args;+ // Out and up alike, at half the blow: 500 along (1, 1)/sqrt 2, in newton seconds.+ expect(ix).toBeCloseTo(iy!, 5);+ expect(Math.hypot(ix!, iy!)).toBeCloseTo(5, 4);+ });++ it('does nothing with no reach or no strength', () => {+ const world = fakeWorld({ 1: [1, 0, 0] }, [1]);+ const physics = new Physics3DQueries(world.module, 100, new Map(), bodies);+ expect(physics.explode({ x: 0, y: 0, z: 0 }, 0, 1000)).toBe(0);+ expect(physics.explode({ x: 0, y: 0, z: 0 }, 100, -5)).toBe(0);+ expect(world.calls).toEqual([]);+ });+});diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex 957f87609..1000c403a 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -852,6 +852,72 @@ const live = peakAfterImpact(9302, 9002);check('with the backend\'s own threshold the same impact bounces', live > 1.0, `peak=${live}`);m._physics3d_removeBody(solverFloor);+// ── Pushing bodies by hand ─────────────────────────────────────────────────+// Spheres of 2 kg, 0.5 m across the middle out, weightless and undamped, far from everything else: what a blow does+// is then exactly what it should. A solid sphere's inertia is 2/5 m r^2 = 0.2 kg m^2.+{+const FLOATING = [DYNAMIC, 0, 0, 0, 0, 0, 0];+let nextBall = 9400;+const floatingBall = () => {+ const id = m._physics3d_addSphere(nextBall, 0.5, 5000 + (nextBall - 9400) * 10, 50, 0, ...IDENTITY, ...FLOATING, 0.5, 0, 0);+ nextBall++;+ m._physics3d_setMass(id, 2);+ return id;+};+const velocityOf = (id) => { m._physics3d_getBodyState(id); const o = m._physics3d_queryResult() >> 2; return [m.HEAPF32[o + 7], m.HEAPF32[o + 8], m.HEAPF32[o + 9]]; };+const spinOf = (id) => { m._physics3d_getBodyDynamics(id); const o = m._physics3d_queryResult() >> 2; return [m.HEAPF32[o + 1], m.HEAPF32[o + 2], m.HEAPF32[o + 3]]; };+const centreOf = (id) => { m._physics3d_getBodyState(id); const o = m._physics3d_queryResult() >> 2; return [m.HEAPF32[o], m.HEAPF32[o + 1], m.HEAPF32[o + 2]]; };+const fmt = (v) => v.map((x) => x.toFixed(3)).join(',');++const struck = floatingBall();+m._physics3d_addImpulse(struck, 4, 0, 0, NaN, NaN, NaN);+step(1);+check('an impulse at the centre changes the speed by impulse / mass', near(velocityOf(struck)[0], 2, 1e-3), fmt(velocityOf(struck)));+check('and turns nothing', spinOf(struck).every((w) => near(w, 0, 1e-4)), fmt(spinOf(struck)));++const clipped = floatingBall();+const [cx, cy, cz] = centreOf(clipped);+m._physics3d_addImpulse(clipped, 0, 0, 1, cx, cy + 0.5, cz);+step(1);+// r x J = (0, 0.5, 0) x (0, 0, 1) = (0.5, 0, 0); over 0.2 kg m^2 that is 2.5 rad/s about x.+check('an impulse off the centre turns it as r x J / inertia says', near(spinOf(clipped)[0], 2.5, 0.01) && near(velocityOf(clipped)[2], 0.5, 1e-3),+ `spin ${fmt(spinOf(clipped))} velocity ${fmt(velocityOf(clipped))}`);++const twisted = floatingBall();+m._physics3d_addAngularImpulse(twisted, 0, 0.2, 0);+step(1);+check('an angular impulse turns it by impulse / inertia', near(spinOf(twisted)[1], 1, 0.01), fmt(spinOf(twisted)));++const spun = floatingBall();+m._physics3d_setAngularVelocity(spun, 0, 0, 3);+step(1);+check('a spin can be set', near(spinOf(spun)[2], 3, 0.01), fmt(spinOf(spun)));++const pushed = floatingBall();+m._physics3d_addForce(pushed, 120, 0, 0, NaN, NaN, NaN);+step(1);+// 120 N on 2 kg for a sixtieth of a second: 1 m/s, and only the one step.+check('a force at the centre lasts one step', near(velocityOf(pushed)[0], 1, 1e-3) && spinOf(pushed).every((w) => near(w, 0, 1e-4)), fmt(velocityOf(pushed)));+step(1);+check('and is gone the step after', near(velocityOf(pushed)[0], 1, 1e-3), fmt(velocityOf(pushed)));++const sleeper = floatingBall();+m._physics3d_setAwake(sleeper, 0);+check('a body can be put to sleep', m._physics3d_isAwake(sleeper) === 0);+m._physics3d_setAwake(sleeper, 1);+check('and woken', m._physics3d_isAwake(sleeper) === 1);+const ledge = m._physics3d_addBox(9498, 1, 0.5, 1, 7000, 0, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+check('a body that does not move is never awake', m._physics3d_isAwake(ledge) === 0);++const faller = m._physics3d_addSphere(9499, 0.5, 6000, 50, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);+m._physics3d_setGravity(0, -2, 0);+step(30);+const fall = velocityOf(faller)[1];+m._physics3d_setGravity(0, -9.81, 0);+check('the world\'s gravity can be changed', near(fall, -1, 0.02), `vy=${fall.toFixed(4)} after half a second at 2 m/s^2`);++}+m._physics3d_shutdown();check('the world reports itself gone', m._physics3d_isReady() === 0);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hppindex 8f30fba12..ac58cbe3b 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp@@ -90,6 +90,19 @@ void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz);// A moving body's mass, in kilograms, its inertia scaled with it so it turns as its shape says; nothing for a body// that does not move, or a mass that is not a positive number.void physics3d_setMass(uint32_t bodyId, float mass);+// A blow of (ix, iy, iz) newton seconds at the world point (px, py, pz) - at its centre of mass where the point is not a+// number - all at once: its speed changes by impulse /+// mass, and it turns by as much as the point is off its centre of mass. Wakes it. Nothing for a body that does not move.+void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz);+// A twist of (ix, iy, iz) newton metre seconds, all at once. Wakes it.+void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz);+// Its spin, in radians a second about each world axis. Wakes it.+void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz);+// The world's gravity, in metres a second squared. A sleeping body stays asleep until something wakes it.+void physics3d_setGravity(float gx, float gy, float gz);+// Wake a body (awake != 0) or put it to sleep; and whether it is awake: 1 awake, 0 asleep or not a moving body.+void physics3d_setAwake(uint32_t bodyId, int awake);+int physics3d_isAwake(uint32_t bodyId);int physics3d_getBodyState(uint32_t bodyId);// What a force needs to know of a body: its mass and how it is turning.int physics3d_getBodyDynamics(uint32_t bodyId);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex 67b0c9371..004dac888 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -576,7 +576,55 @@ int physics3d_getBodyDynamics(uint32_t bodyId) {EMSCRIPTEN_KEEPALIVEvoid physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {if (!g().isValid() || bodyId == 0) return;- g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz), RVec3(px, py, pz));+ // A point that is not a number is its centre of mass: pushed there, it turns nothing.+ if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz), RVec3(px, py, pz));+ else g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz) {+ if (!g().isValid() || bodyId == 0) return;+ BodyInterface& bodies = g().system->GetBodyInterface();+ if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;+ if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz), RVec3(px, py, pz));+ else bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz) {+ if (!g().isValid() || bodyId == 0) return;+ BodyInterface& bodies = g().system->GetBodyInterface();+ if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;+ bodies.AddAngularImpulse(BodyID(bodyId), Vec3(ix, iy, iz));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz) {+ if (!g().isValid() || bodyId == 0) return;+ BodyInterface& bodies = g().system->GetBodyInterface();+ if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;+ bodies.SetAngularVelocity(BodyID(bodyId), Vec3(wx, wy, wz));+ bodies.ActivateBody(BodyID(bodyId));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setGravity(float gx, float gy, float gz) {+ if (!g().isValid()) return;+ g().system->SetGravity(Vec3(gx, gy, gz));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setAwake(uint32_t bodyId, int awake) {+ if (!g().isValid() || bodyId == 0) return;+ BodyInterface& bodies = g().system->GetBodyInterface();+ if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;+ if (awake) bodies.ActivateBody(BodyID(bodyId)); else bodies.DeactivateBody(BodyID(bodyId));+}++EMSCRIPTEN_KEEPALIVE+int physics3d_isAwake(uint32_t bodyId) {+ if (!g().isValid() || bodyId == 0) return 0;+ return g().system->GetBodyInterface().IsActive(BodyID(bodyId)) ? 1 : 0;}/// A torque of (tx, ty, tz) newton metres, over the next step.diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cppindex 99f83a039..f67afcf89 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp@@ -691,7 +691,53 @@ EMSCRIPTEN_KEEPALIVEvoid physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {PxRigidDynamic* dynamic = dynamicOf(bodyId);if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;- PxRigidBodyExt::addForceAtPos(*dynamic, PxVec3(fx, fy, fz), PxVec3(px, py, pz), PxForceMode::eFORCE, true);+ // A point that is not a number is its centre of mass: pushed there, it turns nothing.+ if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) PxRigidBodyExt::addForceAtPos(*dynamic, PxVec3(fx, fy, fz), PxVec3(px, py, pz), PxForceMode::eFORCE, true);+ else dynamic->addForce(PxVec3(fx, fy, fz), PxForceMode::eFORCE, true);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz) {+ PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;+ const PxVec3 impulse(ix, iy, iz);+ if (!impulse.isFinite()) return;+ if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) PxRigidBodyExt::addForceAtPos(*dynamic, impulse, PxVec3(px, py, pz), PxForceMode::eIMPULSE, true);+ else dynamic->addForce(impulse, PxForceMode::eIMPULSE, true);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz) {+ PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;+ dynamic->addTorque(PxVec3(ix, iy, iz), PxForceMode::eIMPULSE, true);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz) {+ PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;+ dynamic->setAngularVelocity(PxVec3(wx, wy, wz), true);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setGravity(float gx, float gy, float gz) {+ if (!g().isValid()) return;+ g().scene->setGravity(PxVec3(gx, gy, gz));+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setAwake(uint32_t bodyId, int awake) {+ PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return;+ if (awake) dynamic->wakeUp(); else dynamic->putToSleep();+}++EMSCRIPTEN_KEEPALIVE+int physics3d_isAwake(uint32_t bodyId) {+ const PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return 0;+ return dynamic->isSleeping() ? 0 : 1;}EMSCRIPTEN_KEEPALIVEdiff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 90de2bd3d..b41d54f5c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4740,4 +4740,8 @@ export const NOTED = {{"note": "A thing breaks when it is hit hard enough."},"feat(editor): the breakable check drops a 2 kg stone and a 50 g pebble from the same height, and the tool text says how hard a hit is":{"note": "A thing breaks when it is hit hard enough."},+ "feat(physics3d): a script can push a 3D body about - Physics3D applies forces, impulses and torques at a point or the centre of mass, reads and sets linear and angular velocity, reads mass, wakes and sleeps bodies and changes gravity, from Jolt and PhysX alike; explode strikes everything in reach and every Breakable it reaches; Broke is sent when a thing breaks":+ {"note": "A script can push a 3D body about."},+ "feat(editor): the breakable check sets off a blast beside the last pot, which breaks it and throws the pebble at its foot":+ {"note": "A blast."},};