@zaisma/physics 2.5.0 → 2.7.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/index.d.ts CHANGED
@@ -250,6 +250,10 @@ export interface AddedBody {
250
250
  * one; "ball" at a point, turning any way; "hinge" turning about axis (a door; minimumNumber and maximumNumber limit
251
251
  * it, in radians); "slider" sliding along axis (limits in metres); "spring" pulling toward restLengthM apart
252
252
  * (stiffnessNumber, dampingNumber); "rope" never further than restLengthM apart.
253
+ *
254
+ * A hinge's angle and a slider's distance are measured as the other end (or the world) seen from the body: a body
255
+ * on a slider to the world with limits 0 to 2 moves 2 m against the axis. Point the axis the other way to turn the
256
+ * measure round. A motor's target is measured the same way.
253
257
  */
254
258
  export interface JointDeclaration {
255
259
  id: string;
@@ -266,15 +270,65 @@ export interface JointDeclaration {
266
270
  restLengthM?: number;
267
271
  stiffnessNumber?: number;
268
272
  dampingNumber?: number;
273
+ /** What turns a hinge or slides a slider by itself: a door that closes, a winch, a lift, a crane's arm. Its target changes while playing with setJoint's motorTargetNumber. */
274
+ motor?: JointMotorDeclaration;
275
+ /** How hard it pulls or pushes its ends, in newtons, before it breaks: it lets go, every game is told (the jointBroke hook), and setJoint's isEnabled true mends it. A 10 kg weight hangs with 98 N. Left out, it never breaks. */
276
+ breakForceNewtons?: number;
277
+ }
278
+
279
+ /** A joint's motor. "speed" holds a speed (radians a second about a hinge, metres a second along a slider); "position" goes to a place (radians, metres) and holds it like a spring. */
280
+ export interface JointMotorDeclaration {
281
+ motorKind: "speed" | "position";
282
+ /** The speed it holds or the place it goes to, -10000 to 10000; default 0. */
283
+ targetNumber?: number;
284
+ /** The most it pushes: newtons along a slider, newton metres about a hinge. Left out, as hard as it takes. */
285
+ maximumForceNumber?: number;
286
+ /** How hard a "position" motor pulls toward its place, for each unit it's off, whatever the body weighs; default 2000. */
287
+ stiffnessNumber?: number;
288
+ /** How hard it resists moving off its target's speed; default 10000 for "speed" (it holds its speed firmly), 200 for "position". */
289
+ dampingNumber?: number;
290
+ }
291
+
292
+ /**
293
+ * A zone: a place in the world, with no walls, that knows who's in it and may pull, push and slow them. A capture
294
+ * point, a checkpoint, a kill plane, water, wind, a lift shaft with no gravity. Bodies that never move aren't
295
+ * counted. Who's in it is worked out before each step from where everything is; the zoneEntered and zoneLeft hooks
296
+ * tell every game, zoneOccupants(zoneId) answers now, and a character kind's step asks stepContext.zoneIdsOf(character).
297
+ */
298
+ export interface ZoneDeclaration {
299
+ id: string;
300
+ /** What it's made of, 1 to 8 shapes, each placed in the zone's own space. */
301
+ shapes: { shapeKind: "box" | "ball" | "capsule" | "cylinder"; sizeM?: Point; radiusM?: number; heightM?: number; positionM?: Point; rotationDeg?: TurnDeg }[];
302
+ positionM?: Point;
303
+ rotationDeg?: TurnDeg;
304
+ /** A body it rides: positionM and rotationDeg are then in that body's own space (the deck of a ferry, the bed of a truck, a lift's floor). */
305
+ bodyId?: string;
306
+ /** Whose layers it counts; left out, everything that moves. */
307
+ collisionLayerNames?: string[];
308
+ /** How much of the world's gravity pulls inside it, -1000 to 1000; default 100. 0 floats, 20 is the moon, -20 lifts a balloon. */
309
+ gravityPct?: number;
310
+ /** A push on everything inside, in metres a second each second, whatever it weighs: wind, a current, a fan. */
311
+ pushMPerSecPerSec?: Point;
312
+ /** How much it slows what moves inside it, 0 to 100; default 0. Water is about 2, thick mud 8: a body's speed falls by this share each second, and the piece's walkers wade at 1 / (1 + dampingNumber / 4) of their speed (two thirds in water, a third in mud). */
313
+ dampingNumber?: number;
314
+ /** Whether it's on from the start; default true. setZone switches it while playing: off, nobody is in it and it does nothing. */
315
+ isEnabled?: boolean;
269
316
  }
270
317
 
271
318
  export interface WorldDeclaration {
272
- /** The world's bodies, up to 1000. A body added while playing (addBody) counts too. */
319
+ /**
320
+ * The world's bodies. Up to 2,000 that move or may: moving and kinematic ones, and every body added while playing
321
+ * (addBody). And up to 20,000 declared "fixed": a level's pieces, which never move, are never sent and aren't
322
+ * counted with the others (about 3 KB each, and nothing a step once the world rests). The bodies that aren't
323
+ * fixed and the joints a world declares come to 2,048 together at most; more are added while playing.
324
+ */
273
325
  bodies?: readonly BodyDeclaration[];
274
326
  /** Kinds of body by name, up to 250: bodies that are alike, and what can be added while playing. */
275
327
  bodyKinds?: Record<string, BodyKindDeclaration>;
276
328
  /** Joints there from the start, up to 1000 with those added while playing. */
277
329
  joints?: JointDeclaration[];
330
+ /** Zones, up to 250: places that know who's in them and may pull, push and slow them. */
331
+ zones?: ZoneDeclaration[];
278
332
  /**
279
333
  * Layers by name, up to 15, with the layers each touches (both ways: a layer touches another when either says so).
280
334
  * "world" (fixed bodies'), "body" (moving bodies') and "character" (characters') are where things are unless they
@@ -289,9 +343,15 @@ export interface WorldDeclaration {
289
343
  * (stepHeightM, default 0.35) and the steepest slope it climbs (maximumSlopeDeg, default 50).
290
344
  */
291
345
  character?: { heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number };
346
+ /**
347
+ * The other sizes a character takes, each named: a crouch, a giant, a small creature. What a size leaves out is
348
+ * `character`'s. A character starts as `character` and is given another with addCharacter's or setCharacter's
349
+ * characterSizeName, or from its kind's step with stepContext.setSize; its feet stay where they are.
350
+ */
351
+ characterSizes?: { name: string; heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number }[];
292
352
  /** "on_join" (the default): every player gets a character with their id as they join. "by_game": the game adds them (addCharacter). */
293
353
  playerCharacterMode?: "on_join" | "by_game";
294
- /** Where characters start, their feet on the ground: each new character takes the next, round again. */
354
+ /** Where characters start, their feet on the ground: each new character takes the next, round again. A world holds up to 250 characters, players' and the game's own. */
295
355
  startPositionsM?: Point[];
296
356
  /** The height below which anything that falls is put back where it started; default -30. */
297
357
  fallOutHeightM?: number;
@@ -307,8 +367,10 @@ export interface PhysicsWorld {
307
367
  readonly bodies: readonly CheckedBody[];
308
368
  readonly bodyKinds: readonly { name: string; declared: BodyKindDeclaration }[];
309
369
  readonly joints: readonly JointDeclaration[];
370
+ readonly zones: readonly { id: string; bodyId: string | null; isEnabled: boolean; gravityPct: number; pushMPerSecPerSec: Point; dampingNumber: number }[];
310
371
  readonly collisionLayers: readonly { name: string; touchedNames: string[] }[];
311
372
  readonly character: { heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number };
373
+ readonly characterSizes: readonly { name: string; heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number }[];
312
374
  readonly playerCharacterMode: "on_join" | "by_game";
313
375
  readonly startPositionsM: readonly Point[];
314
376
  readonly fallOutHeightM: number;
@@ -348,6 +410,8 @@ export interface SteppedCharacter {
348
410
  facingYawRad: number;
349
411
  isGrounded: boolean;
350
412
  airTickCount: number;
413
+ /** Which of the world's characterSizes it is now, or null for the world's own character's. Changed with stepContext.setSize. */
414
+ readonly characterSizeName: string | null;
351
415
  /** The kind's own fields, by name. */
352
416
  own: Record<string, any>;
353
417
  readonly rigidBody: Engine.RigidBody;
@@ -423,6 +487,70 @@ export interface BallOverlapQuery {
423
487
  collisionLayerNames?: string[];
424
488
  excludedId?: string;
425
489
  }
490
+ export interface BoxCastQuery extends RayQuery {
491
+ /** Its width, height and depth. */
492
+ sizeM: Point;
493
+ rotation?: Rotation;
494
+ isStoppedAtPenetration?: boolean;
495
+ }
496
+ export interface BoxOverlapQuery {
497
+ centerM: Point;
498
+ sizeM: Point;
499
+ rotation?: Rotation;
500
+ collisionLayerNames?: string[];
501
+ excludedId?: string;
502
+ }
503
+ /** Many rays at once: rays holds six numbers a ray, where it starts (x, y, z) and its direction (x, y, z, of any length). Up to 65,536 rays a call. */
504
+ export interface RaysQuery {
505
+ rays: Float32Array;
506
+ /** How many of rays to cast; left out, all it holds. */
507
+ rayCount?: number;
508
+ maximumDistanceM: number;
509
+ collisionLayerNames?: string[];
510
+ excludedId?: string;
511
+ }
512
+ /** castRays' answer: how far each ray went (-1 for one that met nothing), the normal where it stopped (three numbers a ray), and any one ray's hit whole. */
513
+ export interface RaysAnswer {
514
+ rayCount: number;
515
+ hitCount: number;
516
+ distancesM: Float32Array;
517
+ normals: Float32Array;
518
+ /** One ray's hit as castRay answers it, or null for a ray that met nothing. With into, written there. */
519
+ hitAt(rayIndex: number, into?: QueryHit): QueryHit | null;
520
+ }
521
+ /** A place asked which zones it's in: a point (centerM alone), a ball (with radiusM) or a capsule (with radiusM and heightM, standing up or turned by rotation). */
522
+ export interface ZonesAtQuery {
523
+ centerM: Point;
524
+ radiusM?: number;
525
+ heightM?: number;
526
+ rotation?: Rotation;
527
+ }
528
+
529
+ /** What asks the world as it stands now: the same in a game, on a game server, in a kind's step and over a level. */
530
+ export interface PhysicsQueries {
531
+ /** The first thing a ray meets, or null. With into (an object the game keeps), written there instead of a new one: for a game casting thousands a second. */
532
+ castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
533
+ /** Everything a ray passes through, nearest first, one hit a shape, up to maximumHitCount (default 16, at most 256): a bullet that goes through thin walls. With into (a list the game keeps), written there. */
534
+ castRayAll(query: RayQuery & { maximumHitCount?: number }, into?: QueryHit[]): QueryHit[];
535
+ /** Many rays in one call, several times cheaper a ray than castRay: a shotgun's pellets, a lidar, a crowd's feet. With into (an answer the game keeps), written there. */
536
+ castRays(query: RaysQuery, into?: RaysAnswer): RaysAnswer;
537
+ castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
538
+ /** The first thing a capsule (standing up, or turned) meets moving along a direction, or null. */
539
+ castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
540
+ /** The first thing a box (turned by rotation) meets moving along a direction, or null: a crate's width, a vehicle's body, a melee swing. */
541
+ castBox(query: BoxCastQuery, into?: QueryHit): QueryHit | null;
542
+ overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
543
+ /** Everything a box overlaps: a room, a blast, a trigger of the game's own. */
544
+ overlapBox(query: BoxOverlapQuery): { bodyId: string | null; characterId: string | null }[];
545
+ /**
546
+ * Where a capsule touches the world, with each contact's normal and depth: what a game's own movement pushes out
547
+ * of walls by. With into (a list of the caller's own, kept and given again), written there: nothing is left for
548
+ * the garbage collector.
549
+ */
550
+ overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
551
+ /** The ids of the zones that are on and that a place touches now. */
552
+ zonesAt(query: ZonesAtQuery): string[];
553
+ }
426
554
 
427
555
  /** The world's numbers a step moves by: the piece's settings, turned by a character kind's own. */
428
556
  export interface PhysicsTuning {
@@ -438,7 +566,7 @@ export interface PhysicsTuning {
438
566
  }
439
567
 
440
568
  /** What a character kind's step reaches: the world's queries, the move, and whose step it is. */
441
- export interface CharacterStepContext {
569
+ export interface CharacterStepContext extends PhysicsQueries {
442
570
  tickIndex: number;
443
571
  tickDurationSec: number;
444
572
  isReplay: boolean;
@@ -453,20 +581,47 @@ export interface CharacterStepContext {
453
581
  * whether it stands.
454
582
  */
455
583
  moveAndSlide(character: SteppedCharacter, movedM: Point, into?: { movedM: Point; isGrounded: boolean }): { movedM: Point; isGrounded: boolean };
456
- castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
457
- castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
458
- castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
459
- overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
460
- /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
461
- overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
584
+ /** The ids of the zones a character is in now. */
585
+ zoneIdsOf(character: SteppedCharacter): string[];
586
+ /**
587
+ * What the zones a character stands in do there, together, or null where nothing pulls, pushes or slows it: the
588
+ * piece's walk moves by it, and a game's own kinematic kind does the same in its step (the engine moves bodies and
589
+ * dynamic characters by it itself). The object is the piece's own, filled again by the next call.
590
+ */
591
+ zoneEffectsOf(character: SteppedCharacter): { gravityPct: number; pushMPerSecPerSec: Point; dampingNumber: number } | null;
592
+ /** Who was in a zone at this step's start: [{ bodyId, characterId }], one of the two null. */
593
+ zoneOccupants(zoneId: string): { bodyId: string | null; characterId: string | null }[];
594
+ /** A body's place, rotation, speed and spin now, in an object of the body's own that the next call fills again (copy what you keep). Give the body a body kind's step was given, or a body's id. Null for a body that isn't here. */
595
+ bodyMotion(body: SteppedBody | string): { positionM: Point; rotation: Rotation; velocityMPerSec: Point; spinRadPerSec: Point } | null;
596
+ /**
597
+ * Pushes a moving body with a force in newtons for this one step: at its centre of mass, or at a place in the
598
+ * world (atM), which turns it too. From a body kind's step (and a character kind that steps before the world) the
599
+ * engine works with it through the whole step, so a lift equal to the body's weight holds it still. Answers false
600
+ * for a body physics doesn't move.
601
+ */
602
+ addForce(body: SteppedBody | string, forceNewtons: Point, atM?: Point | null): boolean;
603
+ /** Turns a moving body with a torque in newton metres about the world's axes, for this one step. */
604
+ addTorque(body: SteppedBody | string, torqueNewtonMetres: Point): boolean;
462
605
  /** A body as the world has it now, read only (pulling a cart: how fast it lets him go), or null. */
463
606
  bodyState(bodyId: string): (Omit<BodyState, "riderCharacterIds"> & { massKg: number | null }) | null;
464
607
  /** Another character as the world has it now, read only, or null. */
465
- characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; own: Record<string, any> } | null;
466
- /** Ties or lets go a joint from the step (a press that takes a cart's handles), so a replay runs it exactly. Answers false for a joint that isn't here. */
467
- setJoint(jointId: string, changes: { isEnabled: boolean }): boolean;
608
+ characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; characterSizeName: string | null; own: Record<string, any> } | null;
609
+ /** Ties or lets go a joint from the step (a press that takes a cart's handles), or gives its motor another target, so a replay runs it exactly. Answers false for a joint that isn't here. */
610
+ setJoint(jointId: string, changes: { isEnabled?: boolean; motorTargetNumber?: number }): boolean;
468
611
  /** Puts the character on one of the world's collision layers from its step (through his own cart while he holds it). */
469
612
  setLayer(character: SteppedCharacter, collisionLayerName: string): void;
613
+ /**
614
+ * Gives a character another of the world's characterSizes (a crouch, standing up again), or null for the world's
615
+ * own character's: its feet stay where they are. False, and nothing changes, where the size has no room: a low
616
+ * roof over a crouched head.
617
+ */
618
+ setSize(character: SteppedCharacter, characterSizeName: string | null): boolean;
619
+ /**
620
+ * Whether the character stands on what never moves and touches nothing else. With nothing asked of it and no
621
+ * speed, a step would leave it exactly where it is, so a kind may return before its move: the piece's walk does,
622
+ * and a crowd standing about costs nothing.
623
+ */
624
+ isRestingOnLevel(character: SteppedCharacter): boolean;
470
625
  /** The engine, for what the piece doesn't do. */
471
626
  engine: typeof Engine;
472
627
  rapierWorld: Engine.World;
@@ -579,6 +734,42 @@ export interface PhysicsHookHandlers {
579
734
  beforePutBack: (positionM: Point, fallen: { id: string; isCharacter: boolean; roomState: any }) => Point | void;
580
735
  /** In every game: a moving body hit something hard enough to hear. */
581
736
  bodyHit: (hit: { bodyId: string | null; otherBodyId: string | null; otherCharacterId: string | null; speedMPerSec: number }) => void;
737
+ /** In every game: a body or a character came into a zone (one of the two ids, the other null). */
738
+ zoneEntered: (change: { zoneId: string; bodyId: string | null; characterId: string | null }) => void;
739
+ /** In every game: a body or a character left a zone, or left the world while in it. */
740
+ zoneLeft: (change: { zoneId: string; bodyId: string | null; characterId: string | null }) => void;
741
+ /** In every game: a joint with a breakForceNewtons was pulled or pushed harder than that, and let go. */
742
+ jointBroke: (broken: { jointId: string; bodyId: string; otherBodyId: string | null }) => void;
743
+ }
744
+
745
+ /** A body as its kind's step gets it. */
746
+ export interface SteppedBody {
747
+ readonly id: string;
748
+ /** Which of the world's bodyKinds it's made as. */
749
+ readonly bodyKindName: string;
750
+ /** The kind's own fields for this body: change them in place. */
751
+ own: Record<string, any>;
752
+ /** Who sits in its first seat this step, or null. */
753
+ readonly driverCharacterId: string | null;
754
+ readonly rigidBody: Engine.RigidBody;
755
+ }
756
+
757
+ /**
758
+ * Rules of a game's own for one of the world's body kinds: fields every body of the kind keeps, and a step run once
759
+ * a fixed step for each, the same in every player's game and on the game server. A boat that floats and is steered,
760
+ * an aircraft, a hover bike, a turret that tracks, a mine that counts down.
761
+ */
762
+ export interface BodyBehaviorDeclaration {
763
+ /** What the kind keeps of each body beyond the piece's own (its throttle, its fuel, its fuse): plain fields, shared on the wire. Up to 8 of a world's body kinds may have fields of their own. */
764
+ stateFields?: FieldDeclaration[];
765
+ /**
766
+ * One fixed step of one body, before the engine moves the world. driverInput is the input of whoever sits in its
767
+ * first seat (the character kind's inputFields), or null with nobody there. It pushes with stepContext.addForce
768
+ * and addTorque, reads with stepContext.bodyMotion(body) and the queries, and keeps what it must remember in body.own.
769
+ */
770
+ step(body: SteppedBody, driverInput: Record<string, any> | null, stepContext: CharacterStepContext): void;
771
+ /** true to step a body of this kind while it lies at rest with nobody in its first seat (a mine's fuse, a turret that watches). By default such a body isn't stepped, and costs nothing. */
772
+ isSteppedAtRest?: boolean;
582
773
  }
583
774
 
584
775
  // ---- What a game calls ----
@@ -594,6 +785,10 @@ export interface BodyState {
594
785
  /** How heavy it is now; null for a fixed body. */
595
786
  massKg: number | null;
596
787
  isResting: boolean;
788
+ /** Which of the world's bodyKinds it's made as, or null for a body declared with shapes of its own. */
789
+ bodyKindName: string | null;
790
+ /** Its kind's own fields (physicsKind's bodies), or null for a kind with no rules of its own. */
791
+ own: Record<string, any> | null;
597
792
  riderCharacterIds: string[];
598
793
  /** A character kind's own (with @zaisma/physics-party: holderCharacterIds on a body; heldBodyId, handPositionM, loadPct on a character). */
599
794
  [kindOwn: string]: any;
@@ -611,13 +806,15 @@ export interface CharacterView {
611
806
  rideBodyId: string | null;
612
807
  seatIndex: number | null;
613
808
  collisionLayerName: string;
809
+ /** Which of the world's characterSizes it is, or null for the world's own character's. */
810
+ characterSizeName: string | null;
614
811
  own: Record<string, any>;
615
812
  /** A character kind's own (with @zaisma/physics-party: holderCharacterIds on a body; heldBodyId, handPositionM, loadPct on a character). */
616
813
  [kindOwn: string]: any;
617
814
  }
618
815
 
619
816
  /** What changes the world, the same alone, in a player's game that runs it, and on a game server. */
620
- export interface PhysicsChanges {
817
+ export interface PhysicsChanges extends PhysicsQueries {
621
818
  bodyIds(): string[];
622
819
  hasBody(bodyId: string): boolean;
623
820
  bodyState(bodyId: string): BodyState | null;
@@ -625,34 +822,33 @@ export interface PhysicsChanges {
625
822
  addBody(body: AddedBody): boolean;
626
823
  removeBody(bodyId: string): boolean;
627
824
  /** Sets a body at once: its place and turn (a teleport), its speed or spin, how it moves (a parked cart made fixed), its layer. */
628
- setBody(bodyId: string, changes: { positionM?: Point; rotationDeg?: TurnDeg; velocityMPerSec?: Point; spinRadPerSec?: Point; motionKind?: "moving" | "kinematic" | "fixed"; collisionLayerName?: string; /** How heavy it is now, 0.01 to 100000 kg, to the hundredth: what rides in a cart's bed weighs on it. */ massKg?: number }): boolean;
825
+ setBody(bodyId: string, changes: { positionM?: Point; rotationDeg?: TurnDeg; velocityMPerSec?: Point; spinRadPerSec?: Point; motionKind?: "moving" | "kinematic" | "fixed"; collisionLayerName?: string; /** How heavy it is now, 0.01 to 100000 kg, to the hundredth: what rides in a cart's bed weighs on it. */ massKg?: number; /** Some of its kind's own fields. */ own?: Record<string, any> }): boolean;
629
826
  /** A sudden change of a body's speed, as a hit gives. */
630
827
  pushBody(bodyId: string, pushMPerSec: Point): boolean;
631
828
  characterIds(): string[];
632
829
  hasCharacter(characterId: string): boolean;
633
830
  characterState(characterId: string): CharacterView | null;
634
- addCharacter(characterId: string, addOptions?: { positionM?: Point }): boolean;
831
+ addCharacter(characterId: string, addOptions?: { positionM?: Point; characterSizeName?: string | null }): boolean;
635
832
  removeCharacter(characterId: string): boolean;
636
- /** Sets a character at once: its feet's place (a teleport), speed, facing, layer, or its kind's own fields. */
637
- setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; own?: Record<string, any> }): boolean;
833
+ /** Sets a character at once: its feet's place (a teleport), speed, facing, layer, size (whether or not it fits where it stands), or its kind's own fields. */
834
+ setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; characterSizeName?: string | null; own?: Record<string, any> }): boolean;
638
835
  /** Seats a character in a body's seat (the first drives one with wheels); with bodyId null, lets it out where it is. Answers false for a seat that's taken. */
639
836
  seatCharacter(characterId: string, bodyId: string | null, seatIndex?: number): boolean;
640
837
  jointIds(): string[];
641
838
  /** Adds a joint while playing. */
642
839
  addJoint(joint: JointDeclaration): boolean;
643
840
  removeJoint(jointId: string): boolean;
644
- /** Lets a joint go (isEnabled false), or holds again. */
645
- setJoint(jointId: string, changes: { isEnabled: boolean }): boolean;
841
+ /** Lets a joint go (isEnabled false) or holds again (true: a broken one is mended), or gives its motor another target (a door told to close, a winch to turn). */
842
+ setJoint(jointId: string, changes: { isEnabled?: boolean; motorTargetNumber?: number }): boolean;
646
843
  isJointEnabled(jointId: string): boolean;
647
- /** The first thing a ray meets, or null. With into (an object the game keeps), written there instead of a new one: for a game casting thousands a second. */
648
- castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
649
- castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
650
- /** The first thing a capsule (standing up, or turned) meets moving along a direction, or null. */
651
- castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
652
- overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
653
- /** Where a capsule touches the world, with each contact's normal and depth: what a game's own movement pushes out of walls by. */
654
- /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
655
- overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
844
+ /** A joint as the world has it now: whether it holds, whether it broke, and its motor's target (0 without one). Null for a joint that isn't here. */
845
+ jointState(jointId: string): { isEnabled: boolean; isBroken: boolean; motorTargetNumber: number } | null;
846
+ zoneIds(): string[];
847
+ /** Who's in a zone, as of the last step: [{ bodyId, characterId }], one of the two null. */
848
+ zoneOccupants(zoneId: string): { bodyId: string | null; characterId: string | null }[];
849
+ /** Switches a zone on or off for everyone (a fan that starts, a capture point that opens). */
850
+ setZone(zoneId: string, changes: { isEnabled: boolean }): boolean;
851
+ isZoneEnabled(zoneId: string): boolean;
656
852
  /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 63. */
657
853
  setTriangleGroup(groupNumber: number, isEnabled: boolean): boolean;
658
854
  isTriangleGroupEnabled(groupNumber: number): boolean;
@@ -677,7 +873,7 @@ export interface Physics extends PhysicsChanges {
677
873
  * its spring reaches (where the wheel hangs below its place), how far round it's turned, its steering, and whether it
678
874
  * touches anything. A body without wheels has none.
679
875
  */
680
- drawnBody(bodyId: string): { positionM: Point; rotation: Rotation; steerNumber: number; wheels: { suspensionM: number; spinRad: number; steerRad: number; isOnGround: boolean }[] } | null;
876
+ 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;
681
877
  /** Puts a three.js object where a body is drawn this frame. */
682
878
  applyTo(object3d: { position: { set(x: number, y: number, z: number): void }; quaternion: { set(...parts: number[]): unknown } }, bodyId: string): boolean;
683
879
  /** This player's input from now on, or with { characterId } a bot's this game moves: the character kind's input fields. */
@@ -716,6 +912,8 @@ export interface PhysicsKindOptions {
716
912
  hooks?: Partial<PhysicsHookHandlers>;
717
913
  /** How the world's characters move: the piece's walk (the default), a game's own, or a piece's (@zaisma/physics-party). */
718
914
  characters?: CharacterKind | CharacterKindDeclaration;
915
+ /** Rules of the game's own for the world's body kinds, by a bodyKinds name: fields each body keeps and a step that moves it. The same in the game and on its game server. */
916
+ bodies?: Record<string, BodyBehaviorDeclaration>;
719
917
  }
720
918
 
721
919
  export interface PhysicsKind extends Kind<Physics, ServerPhysics> {
@@ -755,7 +953,7 @@ export interface LevelCharactersOptions {
755
953
  }
756
954
 
757
955
  /** What a game calls on characters over a level: @zaisma/net's characters, and the level's queries and drawing. */
758
- export interface LevelCharacters extends import("../net/index.js").Characters {
956
+ export interface LevelCharacters extends import("../net/index.js").Characters, PhysicsQueries {
759
957
  readonly world: PhysicsWorld;
760
958
  readonly settings: Settings<PhysicsSettingValues>;
761
959
  /** Where and how to draw a character this frame: its feet, facing, speed, footing and its kind's own fields. */
@@ -767,26 +965,14 @@ export interface LevelCharacters extends import("../net/index.js").Characters {
767
965
  applyTo(object3d: { position: { set(x: number, y: number, z: number): void }; quaternion: { set(...parts: number[]): unknown } }, bodyId: string): boolean;
768
966
  /** One of the level's bodies as this game has it now, or null. */
769
967
  bodyState(bodyId: string): { positionM: Point; rotation: Rotation } | null;
770
- castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
771
- castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
772
- castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
773
- overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
774
- /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
775
- overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
776
968
  }
777
969
 
778
970
  /** The same on a game server: kind.onServer(state, room). */
779
- export interface ServerLevelCharacters extends import("../net/index.js").ServerCharacters {
971
+ export interface ServerLevelCharacters extends import("../net/index.js").ServerCharacters, PhysicsQueries {
780
972
  readonly world: PhysicsWorld;
781
973
  characterState(characterId: string): CharacterView | null;
782
974
  /** One of the level's bodies as this room has it now, or null. */
783
975
  bodyState(bodyId: string): { positionM: Point; rotation: Rotation } | null;
784
- castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
785
- castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
786
- castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
787
- overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
788
- /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
789
- overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
790
976
  /** Switches one of the level's triangle groups in this room (a door, a bridge), 1 to 63: every player's game from the next step. */
791
977
  setTriangleGroup(groupNumber: number, isEnabled: boolean): boolean;
792
978
  }
package/index.js CHANGED
@@ -19,9 +19,9 @@ export { PieceError } from "../piece/index.js";
19
19
  * every frame. Throws PieceError "engine_not_loaded" before loadPhysics() has finished.
20
20
  */
21
21
  export function createPhysics(givenWorld, given = {}) {
22
- if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "ticksPerSec", "playerId", "characters"].includes(key))) refuse("unknown_argument", "createPhysics takes a world, then { settings, hooks, ticksPerSec, playerId, characters }.", "given", "Give the world first, then an object with any of those.");
22
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "ticksPerSec", "playerId", "characters", "bodies"].includes(key))) refuse("unknown_argument", "createPhysics takes a world, then { settings, hooks, ticksPerSec, playerId, characters, bodies }.", "given", "Give the world first, then an object with any of those.");
23
23
  const { ticksPerSec = 30, playerId = "player" } = given;
24
24
  if (!(Number.isInteger(ticksPerSec) && ticksPerSec >= 1 && ticksPerSec <= 60)) refuse("bad_argument", `ticksPerSec is ${JSON.stringify(ticksPerSec)}.`, "ticksPerSec", "Give a whole number from 1 to 60: 30 suits most games.");
25
25
  checkId(playerId, "bad_character_id", "playerId");
26
- return alonePhysics(givenWorld, { settings: given.settings, hooks: given.hooks, ticksPerSec, playerId, characters: given.characters, defineShape });
26
+ return alonePhysics(givenWorld, { settings: given.settings, hooks: given.hooks, ticksPerSec, playerId, characters: given.characters, bodies: given.bodies, defineShape });
27
27
  }
@@ -32,7 +32,8 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
32
32
  const kind = given.characters === undefined ? walkingCharacters() : defineCharacterKind(given.characters);
33
33
  const { settings } = openPiece(statement, { settings: given.settings });
34
34
  // The level: what doesn't move. Bodies that move, and joints, are a world's (physicsKind), never a level's.
35
- const level = { ...world, bodies: world.bodies.filter((body) => body.motionKind !== "moving"), joints: [] };
35
+ const levelBodies = world.bodies.filter((body) => body.motionKind !== "moving");
36
+ const level = { ...world, bodies: levelBodies, bodyById: new Map(levelBodies.map((body) => [body.id, body])), joints: [] };
36
37
  const sharedFields = characterFieldsOf(kind).filter((field) => !RIDING_FIELD_NAMES.includes(field.name));
37
38
  // A level whose meshes have triangle groups (doors, bridges) switches them room by room: which are off is the room's own.
38
39
  const hasGroups = level.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/physics",
3
- "version": "2.5.0",
3
+ "version": "2.7.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",
@@ -34,6 +34,7 @@
34
34
  "LICENSE.txt",
35
35
  "README.md",
36
36
  "characters.js",
37
+ "bodies.js",
37
38
  "data.js",
38
39
  "declare.js",
39
40
  "engine.js",
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.5.0",
4
+ "piece_version": "2.7.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.",
@@ -16,6 +16,7 @@
16
16
  "declare.js",
17
17
  "engine.js",
18
18
  "characters.js",
19
+ "bodies.js",
19
20
  "data.js",
20
21
  "rapier/rapier.d.ts",
21
22
  "batch.js",
@@ -40,6 +41,7 @@
40
41
  "declare.js",
41
42
  "engine.js",
42
43
  "characters.js",
44
+ "bodies.js",
43
45
  "data.js",
44
46
  "batch.js",
45
47
  "simulation.js",
@@ -135,6 +137,21 @@
135
137
  "name": "body_hit",
136
138
  "hook_kind": "event",
137
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."
140
+ },
141
+ {
142
+ "name": "zone_entered",
143
+ "hook_kind": "event",
144
+ "summary": "Told when a body or a character comes into one of the world's zones, with { zoneId, bodyId, characterId }: a capture point taken, a checkpoint crossed, a splash."
145
+ },
146
+ {
147
+ "name": "zone_left",
148
+ "hook_kind": "event",
149
+ "summary": "Told when a body or a character leaves one of the world's zones (or leaves the world while in it), with { zoneId, bodyId, characterId }."
150
+ },
151
+ {
152
+ "name": "joint_broke",
153
+ "hook_kind": "event",
154
+ "summary": "Told when a joint with a breakForceNewtons lets go because it was pulled or pushed harder than that, with { jointId, bodyId, otherBodyId }: a rope that snaps, a bridge that gives way."
138
155
  }
139
156
  ]
140
157
  }
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.5.0",
5
+ "piece_version": "2.7.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.",
@@ -17,6 +17,7 @@ export default {
17
17
  "declare.js",
18
18
  "engine.js",
19
19
  "characters.js",
20
+ "bodies.js",
20
21
  "data.js",
21
22
  "rapier/rapier.d.ts",
22
23
  "batch.js",
@@ -41,6 +42,7 @@ export default {
41
42
  "declare.js",
42
43
  "engine.js",
43
44
  "characters.js",
45
+ "bodies.js",
44
46
  "data.js",
45
47
  "batch.js",
46
48
  "simulation.js",
@@ -136,6 +138,21 @@ export default {
136
138
  "name": "body_hit",
137
139
  "hook_kind": "event",
138
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."
141
+ },
142
+ {
143
+ "name": "zone_entered",
144
+ "hook_kind": "event",
145
+ "summary": "Told when a body or a character comes into one of the world's zones, with { zoneId, bodyId, characterId }: a capture point taken, a checkpoint crossed, a splash."
146
+ },
147
+ {
148
+ "name": "zone_left",
149
+ "hook_kind": "event",
150
+ "summary": "Told when a body or a character leaves one of the world's zones (or leaves the world while in it), with { zoneId, bodyId, characterId }."
151
+ },
152
+ {
153
+ "name": "joint_broke",
154
+ "hook_kind": "event",
155
+ "summary": "Told when a joint with a breakForceNewtons lets go because it was pulled or pushed harder than that, with { jointId, bodyId, otherBodyId }: a rope that snaps, a bridge that gives way."
139
156
  }
140
157
  ]
141
158
  };
package/rapier/CHANGES.md CHANGED
@@ -4,12 +4,16 @@
4
4
 
5
5
  ## What Zaisma changed
6
6
 
7
- Nothing of Rapier's own is removed or behaves differently: its whole JavaScript API is there as in the stock package, and `rapier.d.ts` is the stock one. Added:
7
+ Nothing of Rapier's own is removed: its whole JavaScript API is there as in the stock package, and `rapier.d.ts` is the stock one. Two things in its broad phase behave differently, both below, and neither changes what a world does. Added:
8
8
 
9
9
  - **One Rust module, `RawBatch`,** compiled into the bindings. It does in one call, with plain numbers written into two buffers read straight from the engine's memory, what the stock JavaScript API does a number at a time through an object made for each answer: one substep of the world with what was hit, every awake body's place, rotation, speed and spin after a step (put on the steps the piece sends them at), a body's read and write, rays, a ball's and a capsule's sweep, overlaps, a capsule's contacts triangle by triangle, a character's move and a vehicle's update.
10
10
  - **A count of the memory the engine holds,** kept by its allocator and read with `RawBatch.heldByteCount()`, `RawBatch.mostHeldByteCount()` and `RawBatch.restartMostHeldByteCount()`: what a level costs is measured exactly instead of guessed from how far the WebAssembly memory has grown.
11
11
  - **Shapes shared between colliders,** with `RawBatch.sharedShape(shape)`: a second collider made from the same triangle mesh holds the mesh itself, not a copy, in any world.
12
12
  - **Three fields made visible inside the crate** (`pub(crate)`), so the module can reach them: the character controller's `controller`, `result` and `events` (`src/control/character_controller.rs`), and the vehicle controller's `controller` (`src/control/ray_cast_vehicle_controller.rs`).
13
+ - **Level colliders, never paired with each other** (build 2). `RawBatch.markLevelCollider(colliders, collider)` sets the lowest bit of a collider's `user_data`; the broad phase of the `rapier3d` crate (`src/geometry/broad_phase_bvh.rs`, patched in the published 0.30.1 source, whose checksum the build checks) then never keeps a pair of two marked colliders. The stock one keeps every pair of touching fixed colliders and walks them all each step, which made a level of thousands of pieces slow and heavy; two fixed colliders never collide, so nothing else changes. A game that sets `user_data` on its own colliders keeps that bit clear.
14
+ - **A broad phase that rests** (build 2). A step in which no collider moved, came or went leaves the broad phase as it is, where the stock one rewrites its whole tree every step: a world at rest costs the same however big its level.
15
+ - **Build 3: a world's own rules.** `RawBatch` gains zones (who is inside each, found once a step; their pull, push and slowing given as real forces through the step's substeps), every hit along a ray, many rays in one call, box casts and box overlaps, forces and torques on a body for one step, the force a joint holds (read from what the solver gave it, ropes and springs included) and a motor's most force. A swept ball's or capsule's touch point is now where it is in the world (it was off for anything away from the world's middle, since 2.5.0).
16
+ - **A character's move that slides along every surface it touches** (build 3; `src/control/character_controller.rs`, patched in the crate). The stock move takes one surface at a time: touching a wall and two ground triangles together, it passes what's left from one to the next until it runs out of tries and answers no move at all. Here what's left is held off every surface touched since the move last went anywhere: along one, along the crease of two, or nowhere in a corner of three. And on ground it may stand on, the move keeps its walk and loses only the slip gravity would give it: the stock one dropped the part it took for "down the slope", which on ground a hair from level points anywhere, so whether a step moved turned on a tenth of a millimetre.
13
17
  - **The loader**: one module that starts the engine from WebAssembly the piece is given (`startEngine`, `startEngineLater`) instead of fetching its own, and that also exports `RawBatch`, `ENGINE_VERSION` and `engineMemory()`.
14
18
  - **The crate versions** are locked by Zaisma's own `Cargo.lock`: the tag's lock file was a version behind its `Cargo.toml`.
15
19