@zaisma/physics 2.4.1 → 2.6.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
@@ -117,8 +117,14 @@ export interface ShapeDeclaration {
117
117
  /** A hull's or a mesh's points, x, y, z of each in a row: a list, or for a mesh a Float32Array the game already holds (taken as it is, up to 2,000,000 triangles with a Uint32Array of indices). */
118
118
  pointsM?: number[] | Float32Array;
119
119
  triangleIndices?: number[] | Uint32Array;
120
- /** A mesh's triangles in groups the world switches on and off while playing (a door, a bridge): one number a triangle, 0 for always there, 1 to 31 for a group (setTriangleGroup). */
120
+ /** A mesh's triangles in groups the world switches on and off while playing (a door, a bridge): one number a triangle, 0 for always there, 1 to 63 for a group (setTriangleGroup). */
121
121
  triangleGroupNumbers?: number[] | Uint8Array;
122
+ /** Groups of a mesh that sit on a collision layer of their own, not their body's: glass that stops soldiers and lets shots through. Needs triangleGroupNumbers. */
123
+ triangleGroups?: { groupNumber: number; collisionLayerName: string }[];
124
+ /** One of the world's surfaceNames, for the whole shape: what a hit on it says (footsteps, bullet marks, tyre grip). */
125
+ surfaceName?: string;
126
+ /** A mesh's surface triangle by triangle: for each, its place in the world's surfaceNames, from 0. In place of surfaceName. */
127
+ triangleSurfaceIndices?: number[] | Uint8Array;
122
128
  dataPath?: string;
123
129
  heightsM?: number[] | Float32Array;
124
130
  rowCount?: number;
@@ -201,6 +207,32 @@ export interface BodyDeclaration extends Partial<BodyKindDeclaration> {
201
207
  positionM?: Point;
202
208
  /** How it starts turned; default not at all. */
203
209
  rotationDeg?: TurnDeg;
210
+ /** A kinematic body's timetable: it goes between its stops by itself (a lift, a moving platform, a turning arm). Only in the world's own bodies. */
211
+ timetable?: TimetableDeclaration;
212
+ }
213
+
214
+ /**
215
+ * Where a kinematic body is at every step: 2 to 32 stops it visits in order. Every game and the game server work out
216
+ * its place from the room's step alone, so nothing of it is sent, and a step run again finds it where it was. It
217
+ * carries the characters and bodies standing on it and pushes what's in its way; nothing stops it. In a room its
218
+ * clock starts with the room; in a world played alone, with the world.
219
+ */
220
+ export interface TimetableDeclaration {
221
+ stops: TimetableStop[];
222
+ /** After the last stop: "loop" (the default) goes on to the first again, "back_and_forth" runs back the way it came, "once" stays. */
223
+ repeatMode?: "loop" | "back_and_forth" | "once";
224
+ /** "linear" (the default): each trip at one speed. "smooth": easing out of a stop and into the next. */
225
+ easeKind?: "linear" | "smooth";
226
+ }
227
+ export interface TimetableStop {
228
+ /** Where the body's middle is at this stop; default the body's own positionM. */
229
+ positionM?: Point;
230
+ /** How it's turned at this stop; default the body's own rotationDeg. It turns the short way between two stops, evenly for a quarter turn or less. */
231
+ rotationDeg?: TurnDeg;
232
+ /** How long the trip to this stop takes, 0.01 to 3600 seconds. For the first stop, the trip back to it from the last: only with repeatMode "loop", which needs it. */
233
+ travelDurationSec?: number;
234
+ /** How long it waits here before leaving, 0 to 3600 seconds; default 0. */
235
+ waitDurationSec?: number;
204
236
  }
205
237
 
206
238
  /** A body added while playing: one of the world's bodyKinds, somewhere. */
@@ -237,7 +269,12 @@ export interface JointDeclaration {
237
269
  }
238
270
 
239
271
  export interface WorldDeclaration {
240
- /** The world's bodies, up to 1000. A body added while playing (addBody) counts too. */
272
+ /**
273
+ * The world's bodies. Up to 2,000 that move or may: moving and kinematic ones, and every body added while playing
274
+ * (addBody). And up to 20,000 declared "fixed": a level's pieces, which never move, are never sent and aren't
275
+ * counted with the others (about 3 KB each, and nothing a step once the world rests). The bodies that aren't
276
+ * fixed and the joints a world declares come to 2,048 together at most; more are added while playing.
277
+ */
241
278
  bodies?: readonly BodyDeclaration[];
242
279
  /** Kinds of body by name, up to 250: bodies that are alike, and what can be added while playing. */
243
280
  bodyKinds?: Record<string, BodyKindDeclaration>;
@@ -250,14 +287,22 @@ export interface WorldDeclaration {
250
287
  * touching nothing.
251
288
  */
252
289
  collisionLayers?: Record<string, { touches?: string[] }>;
290
+ /** What the world's surfaces are called, up to 255 names like "grass" or "metal_grate": a shape's surfaceName and a mesh's triangleSurfaceIndices pick from them, and a hit says which it met. */
291
+ surfaceNames?: string[];
253
292
  /**
254
293
  * How big every character is (heightM default 1.5, radiusM default 0.28), the highest step it walks up
255
294
  * (stepHeightM, default 0.35) and the steepest slope it climbs (maximumSlopeDeg, default 50).
256
295
  */
257
296
  character?: { heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number };
297
+ /**
298
+ * The other sizes a character takes, each named: a crouch, a giant, a small creature. What a size leaves out is
299
+ * `character`'s. A character starts as `character` and is given another with addCharacter's or setCharacter's
300
+ * characterSizeName, or from its kind's step with stepContext.setSize; its feet stay where they are.
301
+ */
302
+ characterSizes?: { name: string; heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number }[];
258
303
  /** "on_join" (the default): every player gets a character with their id as they join. "by_game": the game adds them (addCharacter). */
259
304
  playerCharacterMode?: "on_join" | "by_game";
260
- /** Where characters start, their feet on the ground: each new character takes the next, round again. */
305
+ /** 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. */
261
306
  startPositionsM?: Point[];
262
307
  /** The height below which anything that falls is put back where it started; default -30. */
263
308
  fallOutHeightM?: number;
@@ -275,6 +320,7 @@ export interface PhysicsWorld {
275
320
  readonly joints: readonly JointDeclaration[];
276
321
  readonly collisionLayers: readonly { name: string; touchedNames: string[] }[];
277
322
  readonly character: { heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number };
323
+ readonly characterSizes: readonly { name: string; heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number }[];
278
324
  readonly playerCharacterMode: "on_join" | "by_game";
279
325
  readonly startPositionsM: readonly Point[];
280
326
  readonly fallOutHeightM: number;
@@ -314,19 +360,27 @@ export interface SteppedCharacter {
314
360
  facingYawRad: number;
315
361
  isGrounded: boolean;
316
362
  airTickCount: number;
363
+ /** Which of the world's characterSizes it is now, or null for the world's own character's. Changed with stepContext.setSize. */
364
+ readonly characterSizeName: string | null;
317
365
  /** The kind's own fields, by name. */
318
366
  own: Record<string, any>;
319
367
  readonly rigidBody: Engine.RigidBody;
320
368
  readonly collider: Engine.Collider;
321
369
  }
322
370
 
323
- /** A query's hit: whose it was (a body's or a character's id, the other null), where, the surface's normal there, and how far along. */
371
+ /**
372
+ * A query's hit: whose it was (a body's or a character's id, the other null), where, the surface's normal there, how
373
+ * far along, which of a mesh's triangles it's on (its place in the mesh's triangleIndices, from 0; null off a mesh)
374
+ * and that triangle's or shape's surface (one of the world's surfaceNames, or null).
375
+ */
324
376
  export interface QueryHit {
325
377
  bodyId: string | null;
326
378
  characterId: string | null;
327
379
  pointM: Point;
328
380
  normal: Point;
329
381
  distanceM: number;
382
+ triangleIndex: number | null;
383
+ surfaceName: string | null;
330
384
  }
331
385
  export interface RayQuery {
332
386
  fromM: Point;
@@ -357,14 +411,25 @@ export interface CapsuleOverlapQuery {
357
411
  marginM?: number;
358
412
  collisionLayerNames?: string[];
359
413
  excludedId?: string;
414
+ /** true for a contact with every triangle of a mesh the capsule touches; default false, a mesh's deepest only. */
415
+ isEachTriangle?: boolean;
416
+ /** true to leave out triangles facing away from the capsule's middle; default false. */
417
+ isOneSided?: boolean;
360
418
  }
361
- /** Where a capsule touches the world: whose, the point, the surface's normal there (out of it, toward the capsule), and how deep the capsule is in it. */
419
+ /**
420
+ * Where a capsule touches the world: whose, the point, the surface's normal there (out of it, toward the capsule),
421
+ * how deep the capsule is in it, the flat normal of the triangle or face it's on, which of a mesh's triangles that is
422
+ * and its surface.
423
+ */
362
424
  export interface CapsuleContact {
363
425
  bodyId: string | null;
364
426
  characterId: string | null;
365
427
  pointM: Point;
366
428
  normal: Point;
367
429
  depthM: number;
430
+ faceNormal: Point;
431
+ triangleIndex: number | null;
432
+ surfaceName: string | null;
368
433
  }
369
434
  export interface BallOverlapQuery {
370
435
  centerM: Point;
@@ -401,20 +466,33 @@ export interface CharacterStepContext {
401
466
  * it can climb, snapped down to the ground under it, pushing what's in its way. Answers how far it went and
402
467
  * whether it stands.
403
468
  */
404
- moveAndSlide(character: SteppedCharacter, movedM: Point): { movedM: Point; isGrounded: boolean };
469
+ moveAndSlide(character: SteppedCharacter, movedM: Point, into?: { movedM: Point; isGrounded: boolean }): { movedM: Point; isGrounded: boolean };
405
470
  castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
406
471
  castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
407
472
  castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
408
473
  overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
409
- overlapCapsule(query: CapsuleOverlapQuery): CapsuleContact[];
474
+ /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
475
+ overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
410
476
  /** A body as the world has it now, read only (pulling a cart: how fast it lets him go), or null. */
411
477
  bodyState(bodyId: string): (Omit<BodyState, "riderCharacterIds"> & { massKg: number | null }) | null;
412
478
  /** Another character as the world has it now, read only, or null. */
413
- characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; own: Record<string, any> } | null;
479
+ characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; characterSizeName: string | null; own: Record<string, any> } | null;
414
480
  /** 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. */
415
481
  setJoint(jointId: string, changes: { isEnabled: boolean }): boolean;
416
482
  /** Puts the character on one of the world's collision layers from its step (through his own cart while he holds it). */
417
483
  setLayer(character: SteppedCharacter, collisionLayerName: string): void;
484
+ /**
485
+ * Gives a character another of the world's characterSizes (a crouch, standing up again), or null for the world's
486
+ * own character's: its feet stay where they are. False, and nothing changes, where the size has no room: a low
487
+ * roof over a crouched head.
488
+ */
489
+ setSize(character: SteppedCharacter, characterSizeName: string | null): boolean;
490
+ /**
491
+ * Whether the character stands on what never moves and touches nothing else. With nothing asked of it and no
492
+ * speed, a step would leave it exactly where it is, so a kind may return before its move: the piece's walk does,
493
+ * and a crowd standing about costs nothing.
494
+ */
495
+ isRestingOnLevel(character: SteppedCharacter): boolean;
418
496
  /** The engine, for what the piece doesn't do. */
419
497
  engine: typeof Engine;
420
498
  rapierWorld: Engine.World;
@@ -501,7 +579,7 @@ export declare function walkingCharacters(): CharacterKind;
501
579
  /** One step of the piece's walk, for a kind of the game's own to call for its walking part. */
502
580
  export declare function walkStep(character: SteppedCharacter, input: Record<string, any>, stepContext: CharacterStepContext): void;
503
581
  /** Where the player pushes, in the world, from a stick and where they look. */
504
- export declare function wishOf(input: { moveX?: number; moveY?: number; viewYawRad?: number }): { x: number; z: number; lengthNumber: number };
582
+ export declare function wishOf(input: { moveX?: number; moveY?: number; viewYawRad?: number }, into?: { x: number; z: number; lengthNumber: number }): { x: number; z: number; lengthNumber: number };
505
583
  /** Drives a vehicle from its driver's stick: moveY forward and back, moveX steering, isBraking. */
506
584
  export declare function stickVehicleControls(input: Record<string, any>): { engineNumber: number; steerNumber: number; brakeNumber: number };
507
585
 
@@ -559,6 +637,8 @@ export interface CharacterView {
559
637
  rideBodyId: string | null;
560
638
  seatIndex: number | null;
561
639
  collisionLayerName: string;
640
+ /** Which of the world's characterSizes it is, or null for the world's own character's. */
641
+ characterSizeName: string | null;
562
642
  own: Record<string, any>;
563
643
  /** A character kind's own (with @zaisma/physics-party: holderCharacterIds on a body; heldBodyId, handPositionM, loadPct on a character). */
564
644
  [kindOwn: string]: any;
@@ -579,10 +659,10 @@ export interface PhysicsChanges {
579
659
  characterIds(): string[];
580
660
  hasCharacter(characterId: string): boolean;
581
661
  characterState(characterId: string): CharacterView | null;
582
- addCharacter(characterId: string, addOptions?: { positionM?: Point }): boolean;
662
+ addCharacter(characterId: string, addOptions?: { positionM?: Point; characterSizeName?: string | null }): boolean;
583
663
  removeCharacter(characterId: string): boolean;
584
- /** Sets a character at once: its feet's place (a teleport), speed, facing, layer, or its kind's own fields. */
585
- setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; own?: Record<string, any> }): boolean;
664
+ /** 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. */
665
+ setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; characterSizeName?: string | null; own?: Record<string, any> }): boolean;
586
666
  /** 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. */
587
667
  seatCharacter(characterId: string, bodyId: string | null, seatIndex?: number): boolean;
588
668
  jointIds(): string[];
@@ -599,8 +679,9 @@ export interface PhysicsChanges {
599
679
  castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
600
680
  overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
601
681
  /** Where a capsule touches the world, with each contact's normal and depth: what a game's own movement pushes out of walls by. */
602
- overlapCapsule(query: CapsuleOverlapQuery): CapsuleContact[];
603
- /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 31. */
682
+ /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
683
+ overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
684
+ /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 63. */
604
685
  setTriangleGroup(groupNumber: number, isEnabled: boolean): boolean;
605
686
  isTriangleGroupEnabled(groupNumber: number): boolean;
606
687
  }
@@ -708,23 +789,33 @@ export interface LevelCharacters extends import("../net/index.js").Characters {
708
789
  /** Where and how to draw a character this frame: its feet, facing, speed, footing and its kind's own fields. */
709
790
  drawnCharacter(characterId: string): CharacterView | null;
710
791
  characterState(characterId: string): CharacterView | null;
792
+ /** Where to draw one of the level's bodies this frame: one on a timetable is where this frame's moment has it. null for a body that isn't the level's. */
793
+ drawnBody(bodyId: string): { positionM: Point; rotation: Rotation } | null;
794
+ /** Puts a three.js object (anything with position.set and quaternion.set) where one of the level's bodies is drawn this frame. */
795
+ applyTo(object3d: { position: { set(x: number, y: number, z: number): void }; quaternion: { set(...parts: number[]): unknown } }, bodyId: string): boolean;
796
+ /** One of the level's bodies as this game has it now, or null. */
797
+ bodyState(bodyId: string): { positionM: Point; rotation: Rotation } | null;
711
798
  castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
712
799
  castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
713
800
  castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
714
801
  overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
715
- overlapCapsule(query: CapsuleOverlapQuery): CapsuleContact[];
802
+ /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
803
+ overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
716
804
  }
717
805
 
718
806
  /** The same on a game server: kind.onServer(state, room). */
719
807
  export interface ServerLevelCharacters extends import("../net/index.js").ServerCharacters {
720
808
  readonly world: PhysicsWorld;
721
809
  characterState(characterId: string): CharacterView | null;
810
+ /** One of the level's bodies as this room has it now, or null. */
811
+ bodyState(bodyId: string): { positionM: Point; rotation: Rotation } | null;
722
812
  castRay(query: RayQuery, into?: QueryHit): QueryHit | null;
723
813
  castBall(query: BallCastQuery, into?: QueryHit): QueryHit | null;
724
814
  castCapsule(query: CapsuleCastQuery, into?: QueryHit): QueryHit | null;
725
815
  overlapBall(query: BallOverlapQuery): { bodyId: string | null; characterId: string | null }[];
726
- overlapCapsule(query: CapsuleOverlapQuery): CapsuleContact[];
727
- /** Switches one of the level's triangle groups in this room (a door, a bridge), 1 to 31: every player's game from the next step. */
816
+ /** With into (a list of the caller's own, kept and given again), written there: nothing is left for the garbage collector. */
817
+ overlapCapsule(query: CapsuleOverlapQuery, into?: CapsuleContact[]): CapsuleContact[];
818
+ /** 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. */
728
819
  setTriangleGroup(groupNumber: number, isEnabled: boolean): boolean;
729
820
  }
730
821
 
@@ -737,7 +828,8 @@ export interface LevelCharactersKind extends Kind<LevelCharacters, ServerLevelCh
737
828
  /**
738
829
  * Characters that each move on their own over a world's level (its fixed and kinematic bodies): a shooter's soldiers.
739
830
  * The online core shares them as characters, not a world: each player's game predicts only its own, everyone else is
740
- * drawn a moment behind, and a hit is judged by what the shooter saw (stateAt, viewTickNumber). Nothing in the level
741
- * moves, characters walk through each other, and one copy of the level serves every room a game server runs.
831
+ * drawn a moment behind, and a hit is judged by what the shooter saw (stateAt, viewTickNumber). The level moves only
832
+ * by timetable (a lift, a platform: a soldier rides it and is pushed by it; a query finds it where the room's present
833
+ * step has it), characters walk through each other, and one copy of the level serves every room a game server runs.
742
834
  */
743
835
  export declare function levelCharactersKind(world: PhysicsWorld | WorldDeclaration, options?: LevelCharactersOptions): LevelCharactersKind;
@@ -1,12 +1,13 @@
1
1
  // Characters over a level: a shooter's soldiers, a racer's runners. Each moves on its own every step by its kind's
2
2
  // rules against the world's fixed and kinematic bodies (the level), and the online core shares them as characters,
3
3
  // not as a world: each player's game predicts only its own character, everyone else is drawn a moment behind, and a
4
- // hit is judged by what the shooter saw (stateAt and viewTickNumber). Nothing in the level moves, and characters walk
4
+ // hit is judged by what the shooter saw (stateAt and viewTickNumber). The level moves only by timetable (a lift, a
5
+ // platform: where each is at a step is the same on every side, so nothing of it is sent), and characters walk
5
6
  // through each other: where another player is differs in every game, so it can't be stood against. One copy of the
6
7
  // level serves every room a game server runs.
7
8
  import { openPiece } from "../piece/index.js";
8
9
  import statement from "./piece.json.js";
9
- import { MAXIMUM_TRIANGLE_GROUP_NUMBER, refuse, worldOf } from "./declare.js";
10
+ import { MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER, MAXIMUM_TRIANGLE_GROUP_NUMBER, refuse, timetablePlaceInto, triangleGroupBitNumberOf, triangleGroupMaskIndexOf, worldOf } from "./declare.js";
10
11
  import { physicsEngine } from "./engine.js";
11
12
  import { defineCharacterKind, walkingCharacters } from "./characters.js";
12
13
  import { characterFieldsOf, characterViewOf, levelTuningOf, queriesOver } from "./sync.js";
@@ -17,8 +18,8 @@ const GIVEN_KEYS = ["name", "characters", "settings", "playerCharacterMode", "ev
17
18
  const RIDING_FIELD_NAMES = ["rideBodyNumber", "seatIndex"];
18
19
  /** How long a character nobody has stepped stays in the level's memory, in seconds: one that left, or another room's that ended. */
19
20
  const FORGOTTEN_AFTER_SEC = 3;
20
- /** The room's field that says which of the level's triangle groups are off. */
21
- const GROUPS_FIELD_NAME = "offTriangleGroupMaskNumber";
21
+ /** Which triangle groups are off, in the room's own fields: three whole numbers with a bit for each group. */
22
+ const GROUPS_FIELD_NAMES = ["offTriangleGroupMaskNumber", "offTriangleGroupSecondMaskNumber", "offTriangleGroupThirdMaskNumber"];
22
23
 
23
24
  /**
24
25
  * Answers levelCharactersKind for one side's online core (its charactersKind, from index.js in a game and server.js
@@ -31,14 +32,27 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
31
32
  const kind = given.characters === undefined ? walkingCharacters() : defineCharacterKind(given.characters);
32
33
  const { settings } = openPiece(statement, { settings: given.settings });
33
34
  // The level: what doesn't move. Bodies that move, and joints, are a world's (physicsKind), never a level's.
34
- 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: [] };
35
37
  const sharedFields = characterFieldsOf(kind).filter((field) => !RIDING_FIELD_NAMES.includes(field.name));
36
38
  // A level whose meshes have triangle groups (doors, bridges) switches them room by room: which are off is the room's own.
37
39
  const hasGroups = level.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
38
- const roomFields = [...(given.roomFields ?? []), ...(hasGroups ? [{ name: GROUPS_FIELD_NAME, valueKind: "integer", minimumNumber: 0, maximumNumber: 2 ** MAXIMUM_TRIANGLE_GROUP_NUMBER - 1 }] : [])];
40
+ const roomFields = [...(given.roomFields ?? []), ...(hasGroups ? GROUPS_FIELD_NAMES.map((name) => ({ name, valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER })) : [])];
39
41
  const sharedNames = sharedFields.map((field) => field.name);
42
+ const levelBodyById = new Map(level.bodies.map((body) => [body.id, body]));
40
43
  let startCount = 0;
41
44
  let simulation = null;
45
+ /** A step's length, known from the first step run: a timetable's clock is the step's index times it. */
46
+ let levelTickDurationSec = 0;
47
+ const timetabledPlace = { x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0, rotationW: 1 };
48
+ /** Where one of the level's bodies is at a step (a whole one, or between two): { positionM, rotation }, or null for one that isn't the level's. */
49
+ const bodyPlaceAt = (bodyId, tickNumber) => {
50
+ const body = levelBodyById.get(bodyId);
51
+ if (!body) return null;
52
+ if (!body.timetable) return { positionM: { ...body.positionM }, rotation: { ...body.rotation } };
53
+ timetablePlaceInto(body.timetable, tickNumber * levelTickDurationSec, timetabledPlace);
54
+ return { positionM: { x: timetabledPlace.x, y: timetabledPlace.y, z: timetabledPlace.z }, rotation: { x: timetabledPlace.rotationX, y: timetabledPlace.rotationY, z: timetabledPlace.rotationZ, w: timetabledPlace.rotationW } };
55
+ };
42
56
  /** Each room's number, by the core's own part of its state: one level holds every room's characters, apart. */
43
57
  const roomNumbers = new WeakMap();
44
58
  let nextRoomNumber = 1;
@@ -47,6 +61,7 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
47
61
  let lastSweptTickIndex = 0;
48
62
 
49
63
  const simulationFor = (tickDurationSec) => {
64
+ levelTickDurationSec = tickDurationSec;
50
65
  simulation ??= createSimulation(physicsEngine(), level, { tickDurationSec, characterKind: kind, tuning: levelTuningOf(kind, settings), isEachCharacterAlone: true });
51
66
  return simulation;
52
67
  };
@@ -87,7 +102,7 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
87
102
  let characterIndex = level.characterIndexById.get(key);
88
103
  if (characterIndex === undefined) characterIndex = level.addCharacter(key, { x: state.x, y: state.y - world.character.heightM / 2, z: state.z });
89
104
  steppedAtTickIndex.set(key, stepContext.tickIndex);
90
- if (hasGroups) level.setOffTriangleGroups(stepContext.room?.[GROUPS_FIELD_NAME] ?? 0);
105
+ if (hasGroups) level.setOffTriangleGroups(stepContext.room?.[GROUPS_FIELD_NAMES[0]] ?? 0, stepContext.room?.[GROUPS_FIELD_NAMES[1]] ?? 0, stepContext.room?.[GROUPS_FIELD_NAMES[2]] ?? 0);
91
106
  level.writeCharacter(characterIndex, state);
92
107
  level.stepCharacterAlone(characterIndex, input, { ...level.stepTools, ...stepContext });
93
108
  const read = level.readCharacter(characterIndex);
@@ -101,9 +116,24 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
101
116
  const clientApi = netKind.clientApi;
102
117
  netKind.clientApi = (runtime, kindContext) => {
103
118
  const characters = clientApi(runtime, kindContext);
119
+ levelTickDurationSec ||= 1 / kindContext.ticksPerSec;
120
+ /** The step after this game's last: the level as it stands where its own character is now. */
121
+ characters.levelTickIndex = () => (kindContext.tickIndex() ?? -1) + 1;
104
122
  return Object.assign(characters, {
105
123
  world,
106
124
  settings,
125
+ /** Where to draw one of the level's bodies this frame: { positionM, rotation }. One on a timetable is where this frame's moment has it; null for a body that isn't the level's. */
126
+ drawnBody: (bodyId) => bodyPlaceAt(bodyId, (kindContext.tickIndex() ?? 0) + kindContext.fractionNumber()),
127
+ /** Puts a three.js object (anything with position.set and quaternion.set) where one of the level's bodies is drawn this frame. */
128
+ applyTo(object3d, bodyId) {
129
+ const drawn = bodyPlaceAt(bodyId, (kindContext.tickIndex() ?? 0) + kindContext.fractionNumber());
130
+ if (!drawn) return false;
131
+ object3d.position.set(drawn.positionM.x, drawn.positionM.y, drawn.positionM.z);
132
+ object3d.quaternion.set(drawn.rotation.x, drawn.rotation.y, drawn.rotation.z, drawn.rotation.w);
133
+ return true;
134
+ },
135
+ /** One of the level's bodies as this game has it now: { positionM, rotation }, or null. */
136
+ bodyState: (bodyId) => bodyPlaceAt(bodyId, (kindContext.tickIndex() ?? -1) + 1),
107
137
  /** Where and how to draw a character this frame: its feet, facing, speed, footing and its kind's own fields; null for one not here. */
108
138
  drawnCharacter: (characterId) => viewOf(characters.drawn(characterId), characterId),
109
139
  /** A character as this game has it now. */
@@ -112,26 +142,31 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
112
142
  ...queriesOver(() => withRoomGroups(characters)),
113
143
  });
114
144
  };
115
- /** The level with a room's triangle groups switched as that room has them, before it's asked anything. */
145
+ /** The level as a room has it now, before it's asked anything: its triangle groups switched, its bodies on timetables where that room's step has them. */
116
146
  const withRoomGroups = (characters) => {
117
- if (simulation && hasGroups) simulation.setOffTriangleGroups(characters.room()?.[GROUPS_FIELD_NAME] ?? 0);
147
+ if (simulation && hasGroups) simulation.setOffTriangleGroups(characters.room()?.[GROUPS_FIELD_NAMES[0]] ?? 0, characters.room()?.[GROUPS_FIELD_NAMES[1]] ?? 0, characters.room()?.[GROUPS_FIELD_NAMES[2]] ?? 0);
148
+ simulation?.placeTimetables(characters.levelTickIndex());
118
149
  simulation?.refreshScene();
119
150
  return simulation;
120
151
  };
121
152
  const onServer = netKind.onServer;
122
153
  netKind.onServer = (state, room) => {
123
154
  const characters = onServer(state, room);
155
+ characters.levelTickIndex = () => (characters.tickIndex ?? -1) + 1;
124
156
  return Object.assign(characters, {
125
157
  world,
158
+ /** One of the level's bodies as this room has it now, after its last step: { positionM, rotation }, or null. */
159
+ bodyState: (bodyId) => bodyPlaceAt(bodyId, (characters.tickIndex ?? -1) + 1),
126
160
  characterState: (characterId) => viewOf(characters.has(characterId) ? characters.state(characterId) : null, characterId),
127
161
  ...queriesOver(() => withRoomGroups(characters)),
128
- /** Switches one of the level's triangle groups on or off in this room (a door, a bridge), 1 to 31, for every player from the next step. */
162
+ /** Switches one of the level's triangle groups on or off in this room (a door, a bridge), 1 to 63, for every player from the next step. */
129
163
  setTriangleGroup(groupNumber, isEnabled) {
130
164
  if (!hasGroups) refuse("no_triangle_groups", "This level's meshes have no triangleGroupNumbers.", "groupNumber", "Give a mesh triangleGroupNumbers in the world's declaration, in the game and on its game server.");
131
165
  if (!Number.isInteger(groupNumber) || groupNumber < 1 || groupNumber > MAXIMUM_TRIANGLE_GROUP_NUMBER || typeof isEnabled !== "boolean") refuse("bad_argument", `setTriangleGroup was given ${JSON.stringify(groupNumber)}, ${JSON.stringify(isEnabled)}.`, "groupNumber", `Give a group from 1 to ${MAXIMUM_TRIANGLE_GROUP_NUMBER}, then true to have it there or false to take it away.`);
132
- const maskNumber = characters.room()?.[GROUPS_FIELD_NAME] ?? 0;
133
- const bitNumber = 1 << (groupNumber - 1);
134
- return characters.setRoom({ [GROUPS_FIELD_NAME]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber });
166
+ const fieldName = GROUPS_FIELD_NAMES[triangleGroupMaskIndexOf(groupNumber)];
167
+ const maskNumber = characters.room()?.[fieldName] ?? 0;
168
+ const bitNumber = triangleGroupBitNumberOf(groupNumber);
169
+ return characters.setRoom({ [fieldName]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber });
135
170
  },
136
171
  });
137
172
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/physics",
3
- "version": "2.4.1",
3
+ "version": "2.6.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",
@@ -42,11 +42,13 @@
42
42
  "piece.json",
43
43
  "piece.json.js",
44
44
  "rapier/LICENSE.txt",
45
+ "rapier/CHANGES.md",
45
46
  "rapier/rapier.d.ts",
46
47
  "rapier/rapier.js",
47
48
  "rapier/rapier.wasm",
48
49
  "server.d.ts",
49
50
  "server.js",
51
+ "batch.js",
50
52
  "simulation.js",
51
53
  "sync.js",
52
54
  "level-characters.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.4.1",
4
+ "piece_version": "2.6.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.",
@@ -18,6 +18,7 @@
18
18
  "characters.js",
19
19
  "data.js",
20
20
  "rapier/rapier.d.ts",
21
+ "batch.js",
21
22
  "simulation.js",
22
23
  "sync.js",
23
24
  "level-characters.js",
@@ -25,6 +26,7 @@
25
26
  "rapier/rapier.js",
26
27
  "rapier/rapier.wasm",
27
28
  "rapier/LICENSE.txt",
29
+ "rapier/CHANGES.md",
28
30
  "README.md",
29
31
  "LICENSE.txt"
30
32
  ],
@@ -39,13 +41,15 @@
39
41
  "engine.js",
40
42
  "characters.js",
41
43
  "data.js",
44
+ "batch.js",
42
45
  "simulation.js",
43
46
  "sync.js",
44
47
  "level-characters.js",
45
48
  "piece.json.js",
46
49
  "rapier/rapier.js",
47
50
  "rapier/rapier.wasm",
48
- "rapier/LICENSE.txt"
51
+ "rapier/LICENSE.txt",
52
+ "rapier/CHANGES.md"
49
53
  ],
50
54
  "needs": [
51
55
  {
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.4.1",
5
+ "piece_version": "2.6.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.",
@@ -19,6 +19,7 @@ export default {
19
19
  "characters.js",
20
20
  "data.js",
21
21
  "rapier/rapier.d.ts",
22
+ "batch.js",
22
23
  "simulation.js",
23
24
  "sync.js",
24
25
  "level-characters.js",
@@ -26,6 +27,7 @@ export default {
26
27
  "rapier/rapier.js",
27
28
  "rapier/rapier.wasm",
28
29
  "rapier/LICENSE.txt",
30
+ "rapier/CHANGES.md",
29
31
  "README.md",
30
32
  "LICENSE.txt"
31
33
  ],
@@ -40,13 +42,15 @@ export default {
40
42
  "engine.js",
41
43
  "characters.js",
42
44
  "data.js",
45
+ "batch.js",
43
46
  "simulation.js",
44
47
  "sync.js",
45
48
  "level-characters.js",
46
49
  "piece.json.js",
47
50
  "rapier/rapier.js",
48
51
  "rapier/rapier.wasm",
49
- "rapier/LICENSE.txt"
52
+ "rapier/LICENSE.txt",
53
+ "rapier/CHANGES.md"
50
54
  ],
51
55
  "needs": [
52
56
  {
@@ -0,0 +1,18 @@
1
+ # The engine in this folder
2
+
3
+ `rapier.js` and `rapier.wasm` are [Rapier](https://rapier.rs), the physics engine by Dimforge, under the Apache License 2.0 (`LICENSE.txt`). They are built by Zaisma from Rapier's own JavaScript bindings, [dimforge/rapier.js](https://github.com/dimforge/rapier.js) at tag `v0.19.3` (commit `0fd32c1cbbc7018af36f09b190c16ce72fbb9301`), with these changes. `ENGINE_VERSION` says which build it is: `0.19.3-zaisma.1`.
4
+
5
+ ## What Zaisma changed
6
+
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
+
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
+ - **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
+ - **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
+ - **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
+ - **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()`.
16
+ - **The crate versions** are locked by Zaisma's own `Cargo.lock`: the tag's lock file was a version behind its `Cargo.toml`.
17
+
18
+ The build is Rapier's own `dim3`, `non-deterministic` configuration (no SIMD), then `wasm-opt -O4`, with `wasm-bindgen` 0.2.100.