@zaisma/physics 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,7 @@ export const valley = definePhysicsWorld({
45
45
  - **Body kinds with rules of their own:** `bodies: { hover: { stateFields, step(body, driverInput, stepContext) } }` on `createPhysics` and `physicsKind` steps every body of a kind by the game's rules, before the engine moves the world, the mirror of a character kind: a boat, an aircraft, a bike, a hover, a mine with a fuse. Its `stateFields` are the body's own (`body.own`), sent with it; whoever sits in seat 0 is its driver, and their input is `driverInput`. A body at rest with nobody aboard isn't stepped unless `isSteppedAtRest`. `stepContext.addForce(body, forceNewtons, atM)` and `addTorque` push it for the step, through every substep, against gravity and what it leans on; `stepContext.bodyMotion(body)` reads where it is and how it moves. Up to 8 kinds may have fields of their own.
46
46
  - **Collision layers:** named, each saying what it touches, and changed while playing (`setBody`, `setCharacter`): how a ghost passes walls, or a thing goes out of play.
47
47
  - **Queries:** `castRay`, `castBall`, `castCapsule`, `castBox`, `overlapBall`, `overlapBox` and `overlapCapsule`, and `castRayAll` (every hit along a ray, nearest first: a shot through glass and a wall) and `castRays` (many rays in one call, from a `Float32Array`: a shotgun, sensors, a car's whiskers), answering whose body or character, where, the surface's normal, which of a mesh's triangles (`triangleIndex`) and its surface (`surfaceName`); a capsule's contacts say how deep it is in each, to push a game's own movement out of walls, one a body or, with `isEachTriangle`, one for every triangle it touches. A cast writes into an object the game keeps when given one (`castRay(query, hit)`), and so do `overlapCapsule(query, contacts)` and a step's `moveAndSlide(character, movedM, moved)`, so thousands a second make nothing new.
48
- - **Surfaces:** a world names its surfaces (`surfaceNames: ["grass", "metal_grate", "glass"]`), a shape says which it is (`surfaceName`) or a mesh says triangle by triangle (`triangleSurfaceIndices`), and every hit and contact answers the name: footsteps, bullet marks, tyre grip. `castBall` and `castCapsule` with `isStoppedAtPenetration: false` move out of what they start touching (a camera pressed to a wall).
48
+ - **Surfaces:** a world names its surfaces (`surfaceNames: ["grass", "metal_grate", "glass"]`), a shape says which it is (`surfaceName`) or a mesh says triangle by triangle (`triangleSurfaceIndices`), and every hit and contact answers the name: footsteps, bullet marks, tyre grip. A collision says both (`bodyHit`'s `surfaceName` and `otherSurfaceName`), and `bodyTouch(bodyId)` answers what a moving body slides or rolls along and how fast (`slideSpeedMPerSec`, `rollSpeedMPerSec`): a crate dragged over gravel, a barrel rolling on planks (since 2.8.0). `castBall` and `castCapsule` with `isStoppedAtPenetration: false` move out of what they start touching (a camera pressed to a wall).
49
49
  - **A level's collision as it ships:** a mesh takes a `Float32Array` of points and a `Uint32Array` of indices as they are, up to 2,000,000 triangles (built in tiles past 65,536, so opening one needs little more memory than the 94 bytes a triangle it ends up holding), and `triangleGroupNumbers` puts triangles in up to 63 groups the world switches on and off (`setTriangleGroup`: a door that opens, a bridge that falls). A group may sit on a collision layer of its own (`triangleGroups: [{ groupNumber: 4, collisionLayerName: "glass" }]`: glass that stops soldiers and lets shots through). The engine holds a mesh once however many worlds are made from it: every room a game server copy runs, a menu's world and the match's.
50
50
  - **The engine itself:** `physicsEngine()` answers Rapier as the piece ships it; `rapier/rapier.d.ts` types all of it (what a game uses most closely, the rest loosely). A body a game makes straight in the engine (`stepContext.rapierWorld`) isn't the piece's: it's never sent, nor put back on a replay, so online it differs in every game. Declare it (or add it with `addBody`), or hold it to a character with a joint (`otherBodyId`), and it's shared like any other; keep the engine's own for what's only drawn.
51
51
 
@@ -154,7 +154,7 @@ Opened like every piece's ([`@zaisma/piece`](../piece)), and changed while playi
154
154
  | `walkSpeedMPerSec`, `jumpHeightM` | the walking characters' speed and jump; a kind of the game's own reads them as `tuning` |
155
155
  | `characterMassKg` | how heavy a character is beside what it pushes |
156
156
 
157
- Online, whoever runs the world decides them. Hooks: `beforePutBack` (where something that fell out of the world comes back), `bodyHit` (for a thud or dust), `zoneEntered` and `zoneLeft`, and `jointBroke`. A character kind adds its own (`characterSettings`, `characterHooks`).
157
+ Online, whoever runs the world decides them. Hooks: `beforePutBack` (where something that fell out of the world comes back), `bodyHit` (for a thud or dust: how fast, where the two met, the surface each is there and how heavy the moving one is, since 2.8.0), `zoneEntered` and `zoneLeft`, and `jointBroke`. A character kind adds its own (`characterSettings`, `characterHooks`).
158
158
 
159
159
  ## Limits
160
160
 
package/index.d.ts CHANGED
@@ -729,11 +729,27 @@ export interface PhysicsSettingValues {
729
729
  characterMassKg: number;
730
730
  }
731
731
 
732
+ /** What a moving body slides or rolls along (bodyTouch). */
733
+ export interface BodyTouch {
734
+ otherBodyId: string | null;
735
+ otherCharacterId: string | null;
736
+ positionM: Point;
737
+ /** The body's own surface at the touch, and the other's: one of the world's surfaceNames, or null. */
738
+ surfaceName: string | null;
739
+ otherSurfaceName: string | null;
740
+ slideSpeedMPerSec: number;
741
+ rollSpeedMPerSec: number;
742
+ }
743
+
732
744
  export interface PhysicsHookHandlers {
733
745
  /** Where the world is run: something fell out of the world and goes back. Answer where instead. */
734
746
  beforePutBack: (positionM: Point, fallen: { id: string; isCharacter: boolean; roomState: any }) => Point | void;
735
- /** In every game: a moving body hit something hard enough to hear. */
736
- bodyHit: (hit: { bodyId: string | null; otherBodyId: string | null; otherCharacterId: string | null; speedMPerSec: number }) => void;
747
+ /**
748
+ * In every game: a moving body hit something hard enough to hear, at speedMPerSec. positionM is where they met,
749
+ * surfaceName and otherSurfaceName the surface each is there (one of the world's surfaceNames, or null where
750
+ * nothing says), massKg how heavy the moving body is: what a sound or a puff of dust needs.
751
+ */
752
+ bodyHit: (hit: { bodyId: string | null; otherBodyId: string | null; otherCharacterId: string | null; speedMPerSec: number; positionM: Point; surfaceName: string | null; otherSurfaceName: string | null; massKg: number }) => void;
737
753
  /** In every game: a body or a character came into a zone (one of the two ids, the other null). */
738
754
  zoneEntered: (change: { zoneId: string; bodyId: string | null; characterId: string | null }) => void;
739
755
  /** In every game: a body or a character left a zone, or left the world while in it. */
@@ -874,6 +890,13 @@ export interface Physics extends PhysicsChanges {
874
890
  * touches anything. A body without wheels has none.
875
891
  */
876
892
  drawnBody(bodyId: string): { positionM: Point; rotation: Rotation; steerNumber: number; wheels: { suspensionM: number; spinRad: number; steerRad: number; isOnGround: boolean }[]; /** Its kind's own fields as drawn this frame, or null for a kind with none. */ own: Record<string, any> | null } | null;
893
+ /**
894
+ * What a moving body slides or rolls along right now, as this game's world has it: the touch it moves along
895
+ * fastest, where it is, the surface each is there, how fast its surface drags across the other's
896
+ * (slideSpeedMPerSec) and how fast it travels along it without dragging (rollSpeedMPerSec). null when it rests,
897
+ * touches nothing or isn't a moving body. For the sound and the dust of a crate dragged or a barrel rolling.
898
+ */
899
+ bodyTouch(bodyId: string): BodyTouch | null;
877
900
  /** Puts a three.js object where a body is drawn this frame. */
878
901
  applyTo(object3d: { position: { set(x: number, y: number, z: number): void }; quaternion: { set(...parts: number[]): unknown } }, bodyId: string): boolean;
879
902
  /** This player's input from now on, or with { characterId } a bot's this game moves: the character kind's input fields. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/physics",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "description": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "homepage": "https://zaisma.com",
package/piece.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "statement_version_number": 1,
3
3
  "name": "@zaisma/physics",
4
- "piece_version": "2.7.0",
4
+ "piece_version": "2.8.0",
5
5
  "kind": "foundation",
6
6
  "standard": "@zaisma/standard",
7
7
  "summary": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
@@ -136,7 +136,7 @@
136
136
  {
137
137
  "name": "body_hit",
138
138
  "hook_kind": "event",
139
- "summary": "Told when a moving body hits something hard enough to hear, with { bodyId, otherBodyId, otherCharacterId, speedMPerSec }: for a thud, dust or a rumble."
139
+ "summary": "Told when a moving body hits something hard enough to hear, with { bodyId, otherBodyId, otherCharacterId, speedMPerSec, positionM, surfaceName, otherSurfaceName, massKg }: where they met, the surface each is there and how heavy the moving one is, for a thud, dust or a rumble."
140
140
  },
141
141
  {
142
142
  "name": "zone_entered",
package/piece.json.js CHANGED
@@ -2,7 +2,7 @@
2
2
  export default {
3
3
  "statement_version_number": 1,
4
4
  "name": "@zaisma/physics",
5
- "piece_version": "2.7.0",
5
+ "piece_version": "2.8.0",
6
6
  "kind": "foundation",
7
7
  "standard": "@zaisma/standard",
8
8
  "summary": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
@@ -137,7 +137,7 @@ export default {
137
137
  {
138
138
  "name": "body_hit",
139
139
  "hook_kind": "event",
140
- "summary": "Told when a moving body hits something hard enough to hear, with { bodyId, otherBodyId, otherCharacterId, speedMPerSec }: for a thud, dust or a rumble."
140
+ "summary": "Told when a moving body hits something hard enough to hear, with { bodyId, otherBodyId, otherCharacterId, speedMPerSec, positionM, surfaceName, otherSurfaceName, massKg }: where they met, the surface each is there and how heavy the moving one is, for a thud, dust or a rumble."
141
141
  },
142
142
  {
143
143
  "name": "zone_entered",
package/simulation.js CHANGED
@@ -969,6 +969,13 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
969
969
  hit.triangleIndex = triangleIndex ?? null;
970
970
  hit.surfaceName = colliderInfo.surfaceIndices && hit.triangleIndex !== null ? (world.surfaceNames[colliderInfo.surfaceIndices[hit.triangleIndex]] ?? null) : colliderInfo.surfaceName;
971
971
  }
972
+ /** A collider's surface where a contact touches it (the contact's subshape there: a mesh's triangle), or null. */
973
+ const touchedSurface = { triangleIndex: null, surfaceName: null };
974
+ const surfaceOfCollider = (collider, subshapeNumber) => {
975
+ noteSurface(touchedSurface, colliderNumberOf(collider.handle), subshapeNumber);
976
+ return touchedSurface.surfaceName;
977
+ };
978
+ const NO_SPEED = { x: 0, y: 0, z: 0 };
972
979
  /**
973
980
  * A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
974
981
  * rays a second keeps one), else a new one.
@@ -2289,6 +2296,103 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
2289
2296
  },
2290
2297
  /** How many written bodies already were as written since the simulation was made, and how many weren't. */
2291
2298
  writeCounts: () => ({ sameWriteCount, changedWriteCount }),
2299
+ /**
2300
+ * A hit in full, written onto it: where the two met (positionM), the surface each is there (surfaceName the moving
2301
+ * body's, otherSurfaceName the other's: one of the world's surfaceNames, or null where nothing says) and how
2302
+ * heavy the moving body is (massKg). Worked out only for a hit that's told, from the contact the engine still
2303
+ * holds; a glancing touch it kept nothing of answers the body's own place and each one's first shape.
2304
+ */
2305
+ describeHit(hit) {
2306
+ const body = bodies[hit.bodyIndex];
2307
+ hit.positionM = null;
2308
+ hit.surfaceName = null;
2309
+ hit.otherSurfaceName = null;
2310
+ hit.massKg = body?.massKg ?? body?.declaration.massKg ?? 0;
2311
+ if (!body) return hit;
2312
+ for (const collider of body.colliders) {
2313
+ if (hit.positionM) break;
2314
+ rapierWorld.contactPairsWith(collider, (otherCollider) => {
2315
+ if (hit.positionM) return;
2316
+ const other = ownerByColliderHandle.get(otherCollider.handle);
2317
+ if (!other || (other.isCharacter ? other.index !== hit.otherCharacterIndex : other.index !== hit.otherBodyIndex)) return;
2318
+ rapierWorld.contactPair(collider, otherCollider, (manifold, isFlipped) => {
2319
+ if (hit.positionM || manifold.numSolverContacts() === 0) return;
2320
+ const point = manifold.solverContactPoint(0);
2321
+ if (!point) return;
2322
+ hit.positionM = { x: point.x, y: point.y, z: point.z };
2323
+ hit.surfaceName = surfaceOfCollider(collider, isFlipped ? manifold.subshape2() : manifold.subshape1());
2324
+ hit.otherSurfaceName = surfaceOfCollider(otherCollider, isFlipped ? manifold.subshape1() : manifold.subshape2());
2325
+ });
2326
+ });
2327
+ }
2328
+ if (!hit.positionM) {
2329
+ const bodyM = body.rigidBody.translation();
2330
+ hit.positionM = { x: bodyM.x, y: bodyM.y, z: bodyM.z };
2331
+ const otherCollider = hit.otherBodyIndex >= 0 ? bodies[hit.otherBodyIndex]?.colliders[0] : null;
2332
+ if (body.colliders[0]) hit.surfaceName = surfaceOfCollider(body.colliders[0], NO_TRIANGLE_INDEX);
2333
+ if (otherCollider) hit.otherSurfaceName = surfaceOfCollider(otherCollider, NO_TRIANGLE_INDEX);
2334
+ }
2335
+ return hit;
2336
+ },
2337
+ /**
2338
+ * What a moving body rests against while it moves: the touch it slides or rolls along fastest, as
2339
+ * { otherBodyIndex, otherCharacterIndex, positionM, surfaceName, otherSurfaceName, slideSpeedMPerSec,
2340
+ * rollSpeedMPerSec }, or null when it touches nothing, rests or isn't a moving body. Sliding is how fast its
2341
+ * surface drags across the other's at the touch; rolling is how fast it travels along it without dragging.
2342
+ */
2343
+ bodyTouch(index) {
2344
+ const body = bodies[index];
2345
+ if (!body || body.motionIndex !== 0 || body.rigidBody.isSleeping()) return null;
2346
+ const linear = body.rigidBody.linvel();
2347
+ const angular = body.rigidBody.angvel();
2348
+ const centerM = body.rigidBody.worldCom();
2349
+ let best = null;
2350
+ let bestSpeedMPerSec = -1;
2351
+ for (const collider of body.colliders) {
2352
+ rapierWorld.contactPairsWith(collider, (otherCollider) => {
2353
+ const other = ownerByColliderHandle.get(otherCollider.handle);
2354
+ if (!other || (!other.isCharacter && other.index === index)) return;
2355
+ rapierWorld.contactPair(collider, otherCollider, (manifold, isFlipped) => {
2356
+ if (manifold.numSolverContacts() === 0) return;
2357
+ const point = manifold.solverContactPoint(0);
2358
+ if (!point) return;
2359
+ const normal = manifold.normal();
2360
+ // The other's speed there: a fixed thing's is none; a character's or a moving body's is its own.
2361
+ const otherRigidBody = other.isCharacter ? characters[other.index]?.rigidBody : bodies[other.index]?.motionIndex === 2 ? null : bodies[other.index]?.rigidBody;
2362
+ const otherLinear = otherRigidBody ? otherRigidBody.linvel() : NO_SPEED;
2363
+ const armX = point.x - centerM.x;
2364
+ const armY = point.y - centerM.y;
2365
+ const armZ = point.z - centerM.z;
2366
+ // The body's surface at the touch moves with its centre plus its spin round it.
2367
+ const centreX = linear.x - otherLinear.x;
2368
+ const centreY = linear.y - otherLinear.y;
2369
+ const centreZ = linear.z - otherLinear.z;
2370
+ const dragX = centreX + (angular.y * armZ - angular.z * armY);
2371
+ const dragY = centreY + (angular.z * armX - angular.x * armZ);
2372
+ const dragZ = centreZ + (angular.x * armY - angular.y * armX);
2373
+ // Along the surface only: what goes into or out of it is a hit or a lift, never a slide.
2374
+ const dragIntoMPerSec = dragX * normal.x + dragY * normal.y + dragZ * normal.z;
2375
+ const centreIntoMPerSec = centreX * normal.x + centreY * normal.y + centreZ * normal.z;
2376
+ const slideSpeedMPerSec = Math.hypot(dragX - dragIntoMPerSec * normal.x, dragY - dragIntoMPerSec * normal.y, dragZ - dragIntoMPerSec * normal.z);
2377
+ const travelSpeedMPerSec = Math.hypot(centreX - centreIntoMPerSec * normal.x, centreY - centreIntoMPerSec * normal.y, centreZ - centreIntoMPerSec * normal.z);
2378
+ const rollSpeedMPerSec = Math.max(travelSpeedMPerSec - slideSpeedMPerSec, 0);
2379
+ const speedMPerSec = Math.max(slideSpeedMPerSec, rollSpeedMPerSec);
2380
+ if (speedMPerSec <= bestSpeedMPerSec) return;
2381
+ bestSpeedMPerSec = speedMPerSec;
2382
+ best = {
2383
+ otherBodyIndex: other.isCharacter ? -1 : other.index,
2384
+ otherCharacterIndex: other.isCharacter ? other.index : -1,
2385
+ positionM: { x: point.x, y: point.y, z: point.z },
2386
+ surfaceName: surfaceOfCollider(collider, isFlipped ? manifold.subshape2() : manifold.subshape1()),
2387
+ otherSurfaceName: surfaceOfCollider(otherCollider, isFlipped ? manifold.subshape1() : manifold.subshape2()),
2388
+ slideSpeedMPerSec,
2389
+ rollSpeedMPerSec,
2390
+ };
2391
+ });
2392
+ });
2393
+ }
2394
+ return best;
2395
+ },
2292
2396
  /** Hits since the last call. */
2293
2397
  takeHits() {
2294
2398
  const taken = hits;
package/sync.js CHANGED
@@ -407,7 +407,8 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
407
407
  if (!isReplay && world.zones.length) for (const change of simulation.takeZoneChanges()) tell(change.isEntered ? "zoneEntered" : "zoneLeft", { zoneId: change.zoneId, bodyId: change.bodyId, characterId: change.characterId });
408
408
  if (!isReplay) {
409
409
  for (const hit of hits) {
410
- tell("bodyHit", { bodyId: simulation.bodies[hit.bodyIndex]?.declaration.id ?? null, otherBodyId: hit.otherBodyIndex >= 0 ? (simulation.bodies[hit.otherBodyIndex]?.declaration.id ?? null) : null, otherCharacterId: hit.otherCharacterIndex >= 0 ? (simulation.characters[hit.otherCharacterIndex]?.id ?? null) : null, speedMPerSec: hit.speedMPerSec });
410
+ simulation.describeHit(hit);
411
+ tell("bodyHit", { bodyId: simulation.bodies[hit.bodyIndex]?.declaration.id ?? null, otherBodyId: hit.otherBodyIndex >= 0 ? (simulation.bodies[hit.otherBodyIndex]?.declaration.id ?? null) : null, otherCharacterId: hit.otherCharacterIndex >= 0 ? (simulation.characters[hit.otherCharacterIndex]?.id ?? null) : null, speedMPerSec: hit.speedMPerSec, positionM: hit.positionM, surfaceName: hit.surfaceName, otherSurfaceName: hit.otherSurfaceName, massKg: hit.massKg });
411
412
  }
412
413
  }
413
414
  if (!isInCharge) return;
@@ -860,6 +861,18 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
860
861
  const drawn = drawnOf(bodyId);
861
862
  return drawn ? { positionM: { x: drawn.x, y: drawn.y, z: drawn.z }, rotation: { ...drawn.rotation }, steerNumber: drawn.steerNumber ?? 0, wheels: simulationNow()?.wheelStates(bodyId) ?? [], own: ownOfBody(bodyId, drawn) } : null;
862
863
  },
864
+ /**
865
+ * What a moving body slides or rolls along right now, as this game's world has it: { otherBodyId,
866
+ * otherCharacterId, positionM, surfaceName, otherSurfaceName, slideSpeedMPerSec, rollSpeedMPerSec }, or null
867
+ * when it rests, touches nothing or isn't a moving body. For the sound and the dust of a thing dragged or rolling.
868
+ */
869
+ bodyTouch(bodyId) {
870
+ const simulation = simulationNow();
871
+ const bodyIndex = simulation?.bodyIndexById.get(bodyId);
872
+ const touch = bodyIndex === undefined ? null : simulation.bodyTouch(bodyIndex);
873
+ if (!touch) return null;
874
+ return { otherBodyId: touch.otherBodyIndex >= 0 ? (simulation.bodies[touch.otherBodyIndex]?.declaration.id ?? null) : null, otherCharacterId: touch.otherCharacterIndex >= 0 ? (simulation.characters[touch.otherCharacterIndex]?.id ?? null) : null, positionM: touch.positionM, surfaceName: touch.surfaceName, otherSurfaceName: touch.otherSurfaceName, slideSpeedMPerSec: touch.slideSpeedMPerSec, rollSpeedMPerSec: touch.rollSpeedMPerSec };
875
+ },
863
876
  /** Puts a three.js object (anything with position.set and quaternion.set) where a body is drawn this frame. */
864
877
  applyTo(object3d, bodyId) {
865
878
  const drawn = drawnOf(bodyId);