@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/sync.js CHANGED
@@ -9,10 +9,11 @@
9
9
  // calls (physicsCalls), the same alone and online.
10
10
  import statement from "./piece.json.js";
11
11
  import { camelName, openPiece, openSettings } from "../piece/index.js";
12
- import { checkBody, checkId, checkJoint, refuse, rotationFromDeg, triangleGroupBitNumberOf, triangleGroupMaskIndexOf, worldOf, MAXIMUM_BODY_COUNT, MAXIMUM_CHARACTER_COUNT, MAXIMUM_JOINT_COUNT, MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER, MAXIMUM_TRIANGLE_GROUP_NUMBER, MOTION_KINDS, WORLD_REACH_M } from "./declare.js";
12
+ import { checkBody, checkId, checkJoint, refuse, rotationFromDeg, triangleGroupBitNumberOf, triangleGroupMaskIndexOf, worldOf, MAXIMUM_BODY_COUNT, MAXIMUM_CHARACTER_COUNT, MAXIMUM_CHARACTER_SIZE_COUNT, MAXIMUM_FIXED_BODY_COUNT, MAXIMUM_JOINT_COUNT, MAXIMUM_MOTOR_TARGET_NUMBER, MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER, MAXIMUM_TRIANGLE_GROUP_NUMBER, MOTION_KINDS, WORLD_REACH_M } from "./declare.js";
13
13
  import { physicsEngine } from "./engine.js";
14
14
  import { defineCharacterKind, walkingCharacters } from "./characters.js";
15
15
  import { createSimulation, turned } from "./simulation.js";
16
+ import { defineBodyBehaviors } from "./bodies.js";
16
17
 
17
18
  /** The one thing in every world that holds its rules: the settings every side must step by. */
18
19
  const RULES_ID = "physics:rules";
@@ -22,12 +23,27 @@ const TRIANGLE_GROUPS_ID = "physics:triangle_groups";
22
23
  const TRIANGLE_GROUP_MASK_NAMES = ["offMaskNumber", "offSecondMaskNumber", "offThirdMaskNumber"];
23
24
  const TRIANGLE_GROUP_FIELDS = TRIANGLE_GROUP_MASK_NAMES.map((name) => ({ name, valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER }));
24
25
  const NO_TRIANGLE_GROUPS_OFF = Object.freeze(Object.fromEntries(TRIANGLE_GROUP_MASK_NAMES.map((name) => [name, 0])));
26
+ /** Which zones are switched off, as one thing of whole numbers with a bit a zone: only in a world that has zones. */
27
+ const ZONE_SWITCHES_ID = "physics:zone_switches";
28
+ const ZONE_MASK_BIT_COUNT = 24;
29
+ const zoneMaskNameOf = (maskIndex) => `off${maskIndex}MaskNumber`;
30
+ const zoneMaskFieldsOf = (world) => Array.from({ length: Math.ceil(world.zones.length / ZONE_MASK_BIT_COUNT) }, (unused, maskIndex) => ({ name: zoneMaskNameOf(maskIndex), valueKind: "integer", minimumNumber: 0, maximumNumber: 2 ** ZONE_MASK_BIT_COUNT - 1 }));
31
+ /** The switches' fields from whether each zone is on. */
32
+ const zoneSwitchesOf = (world, isEnabledOf) => {
33
+ const state = Object.fromEntries(zoneMaskFieldsOf(world).map((field) => [field.name, 0]));
34
+ for (const [zoneIndex, zone] of world.zones.entries()) if (!isEnabledOf(zone)) state[zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT))] |= 1 << (zoneIndex % ZONE_MASK_BIT_COUNT);
35
+ return state;
36
+ };
37
+ const isZoneOffIn = (state, zoneIndex) => Boolean((state?.[zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT))] ?? 0) & (1 << (zoneIndex % ZONE_MASK_BIT_COUNT)));
25
38
  const hasTriangleGroups = (world) => world.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
26
39
  /** The piece's settings every side steps by, in the order they're sent. */
27
40
  const BASE_SYNCED_SETTING_NAMES = ["gravityMPerSecPerSec", "bouncePct", "gripPct", "walkSpeedMPerSec", "jumpHeightM", "characterMassKg"];
28
41
  const LISTENED_EVENT_NAMES = ["bodyAdded", "bodyRemoved", "characterAdded", "characterRemoved"];
29
- const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg"];
30
- const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "own"];
42
+ const SET_BODY_KEYS = ["positionM", "rotationDeg", "velocityMPerSec", "spinRadPerSec", "motionKind", "collisionLayerName", "massKg", "own"];
43
+ /** Whether a kind of thing on the wire is a body: the piece's own, or one of a body kind with fields of its own (bodies.js). */
44
+ const isBodyEntityKind = (entityKindName) => entityKindName === "body" || (typeof entityKindName === "string" && entityKindName.startsWith("body_kind_"));
45
+ const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "characterSizeName", "own"];
46
+ const ADD_CHARACTER_KEYS = ["positionM", "characterSizeName"];
31
47
  // How far a game may be off the room's word, field by field, before it goes back and runs again: two copies of the
32
48
  // engine drift a hair apart after going back, and nobody sees three centimetres. Whole numbers and yes-or-no fields
33
49
  // are never off at all.
@@ -44,7 +60,7 @@ const BODY_FIELDS = [
44
60
  speed("velocityZ"),
45
61
  ...["spinX", "spinY", "spinZ"].map((name) => ({ name, valueKind: "number", minimumNumber: -120, maximumNumber: 120, stepSizeNumber: 0.05, toleranceNumber: 1.5 })),
46
62
  // Which body it is in every side's simulation, so a joint and a seat can name it; and which of the world's kinds it's made as (0: declared with shapes of its own).
47
- { name: "bodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT },
63
+ { name: "bodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT },
48
64
  { name: "bodyKindNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 255 },
49
65
  // Which of the world's collision layers it's on, and how it moves now (moving, kinematic or fixed): a parked cart made fixed.
50
66
  { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 1 },
@@ -65,11 +81,20 @@ const CHARACTER_BASE_FIELDS = [
65
81
  { name: "isGrounded", valueKind: "boolean" },
66
82
  { name: "airTickCount", valueKind: "integer", minimumNumber: 0, maximumNumber: 250 },
67
83
  // The body it rides in (its number and one more, 0 for none), and which of its seats.
68
- { name: "rideBodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + 1 },
84
+ { name: "rideBodyNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT + 1 },
69
85
  { name: "seatIndex", valueKind: "integer", minimumNumber: 0, maximumNumber: 7 },
70
86
  { name: "layerNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: 15, defaultValue: 2 },
87
+ // Which size it is: 0 for the world's own character's, then the world's characterSizes in order.
88
+ { name: "sizeNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_CHARACTER_SIZE_COUNT },
89
+ ];
90
+ // Whether it holds, whether it let go by breaking, and what its motor holds or goes to (0 for a joint without one).
91
+ const JOINT_FIELDS = [
92
+ { name: "isEnabled", valueKind: "boolean", defaultValue: true },
93
+ { name: "isBroken", valueKind: "boolean" },
94
+ { name: "motorTargetNumber", valueKind: "number", minimumNumber: -MAXIMUM_MOTOR_TARGET_NUMBER, maximumNumber: MAXIMUM_MOTOR_TARGET_NUMBER, stepSizeNumber: 0.001 },
71
95
  ];
72
- const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
96
+ /** A joint's fields as it starts: holding, whole, its motor at its declared target. */
97
+ const startJointFields = (declaration) => ({ isEnabled: true, isBroken: false, motorTargetNumber: declaration.motor?.targetNumber ?? 0 });
73
98
  // The same grain as the engine takes it, so a step leaves every awake body on the wire's steps (and reading it back
74
99
  // from the wire changes nothing): each number field's range, step and count of steps, counted as the core's shape
75
100
  // counts them, and how many steps each part of the rotation has.
@@ -108,7 +133,7 @@ function pointOrRefuse(given, what, fix) {
108
133
  * Everything one world needs that's the same wherever it's opened: the world, its character kind, the fields each
109
134
  * thing shares, and which settings every side steps by.
110
135
  */
111
- function worldPlan(world, kind) {
136
+ function worldPlan(world, kind, bodyBehaviors = null) {
112
137
  const kindSyncedNames = kind.syncedSettingNames ?? [];
113
138
  const baseStated = new Map(openSettings(statement).list().map((stated) => [stated.name, stated]));
114
139
  const kindStated = kind.settingsStatement ? new Map(openSettings(kind.settingsStatement).list().map((stated) => [stated.name, stated])) : new Map();
@@ -116,7 +141,23 @@ function worldPlan(world, kind) {
116
141
  const defaultRules = Object.fromEntries(rulesFields.map((field) => [field.name, field.defaultValue]));
117
142
  // A field the kind keeps locally (isShared: false) is worked out by each step and never goes on the wire.
118
143
  const characterFields = characterFieldsOf(kind);
119
- return { world, kind, kindSyncedNames, rulesFields, ruleNames: rulesFields.map((field) => field.name), defaultRules, characterFields };
144
+ // The body kinds with fields of their own are each a kind of thing of their own on the wire.
145
+ const ownFieldBehaviors = (bodyBehaviors ?? []).filter((behavior) => behavior?.stateFields.length);
146
+ return {
147
+ world,
148
+ kind,
149
+ kindSyncedNames,
150
+ rulesFields,
151
+ ruleNames: rulesFields.map((field) => field.name),
152
+ defaultRules,
153
+ characterFields,
154
+ bodyBehaviors,
155
+ ownFieldBehaviors,
156
+ bodyEntityKindNames: ["body", ...ownFieldBehaviors.map((behavior) => behavior.entityKindName)],
157
+ /** Which kind of thing a body of one of the world's body kinds is on the wire, and its kind's own fields as they start. */
158
+ bodyEntityKindNameOf: (bodyKindNumber) => bodyBehaviors?.[bodyKindNumber]?.entityKindName ?? "body",
159
+ startOwnOf: (bodyKindNumber) => bodyBehaviors?.[bodyKindNumber]?.startOwn() ?? {},
160
+ };
120
161
  }
121
162
 
122
163
  /**
@@ -142,7 +183,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
142
183
  isStateOnSteps: true,
143
184
  };
144
185
  const ownRules = () => Object.fromEntries(ruleNames.map((name) => [name, BASE_SYNCED_SETTING_NAMES.includes(name) ? settings.get(name) : kindSettings.get(name)]));
145
- const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches, bodyGrain: BODY_GRAIN });
186
+ const simulation = createSimulation(physicsEngine(), world, { tickDurationSec, characterKind: kind, tuning: tuningOf({ ...defaultRules, ...ownRules() }), readDataFile, tracksTouches, bodyGrain: BODY_GRAIN, bodyBehaviors: plan.bodyBehaviors });
146
187
  /** Where each character started, to put it back when it falls out of the world. */
147
188
  const startOf = new Map();
148
189
  /** The kind of thing each id is: "body", "character", "joint" or "rules". */
@@ -196,8 +237,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
196
237
  },
197
238
  /** The next body number nothing has. */
198
239
  freeBodyNumber() {
199
- const freeIndex = simulation.bodies.findIndex((held) => held === null);
200
- return freeIndex === -1 ? simulation.bodies.length : freeIndex;
240
+ return simulation.freeBodyIndex();
201
241
  },
202
242
  add(entity, state) {
203
243
  kindOf.set(entity.id, entity.entityKindName);
@@ -219,9 +259,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
219
259
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
220
260
  return;
221
261
  }
262
+ if (entity.entityKindName === "zone_switches") {
263
+ switchZones(state);
264
+ return;
265
+ }
222
266
  if (entity.entityKindName === "joint") {
223
267
  const declaration = world.joints.find((joint) => joint.id === entity.id) ?? (entity.entityData ? checkJoint({ ...entity.entityData, id: entity.id }, "joint") : null);
224
- if (declaration) pendingJoints.set(entity.id, { declaration, isEnabled: state.isEnabled });
268
+ if (declaration) pendingJoints.set(entity.id, { declaration, fields: { isEnabled: state.isEnabled, isBroken: Boolean(state.isBroken), motorTargetNumber: state.motorTargetNumber ?? declaration.motor?.targetNumber ?? 0 } });
225
269
  retryJoints();
226
270
  return;
227
271
  }
@@ -242,11 +286,12 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
242
286
  const characterIndex = simulation.characterIndexById.get(entityId);
243
287
  if (characterIndex !== undefined) simulation.removeCharacter(characterIndex);
244
288
  startOf.delete(entityId);
245
- } else if (entityKindName === "body") {
289
+ } else if (isBodyEntityKind(entityKindName)) {
246
290
  const bodyIndex = simulation.bodyIndexById.get(entityId);
247
291
  if (bodyIndex !== undefined) simulation.removeBody(bodyIndex);
248
292
  } else if (entityKindName === "joint") {
249
293
  pendingJoints.delete(entityId);
294
+ readJointFields.delete(entityId);
250
295
  simulation.removeJoint(entityId);
251
296
  }
252
297
  },
@@ -262,10 +307,18 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
262
307
  return characterIndex === undefined ? null : simulation.readSteppedCharacter(characterIndex);
263
308
  }
264
309
  if (entityKindName === "triangle_groups") return { offMaskNumber: simulation.offTriangleGroupMaskNumber(0), offSecondMaskNumber: simulation.offTriangleGroupMaskNumber(1), offThirdMaskNumber: simulation.offTriangleGroupMaskNumber(2) };
310
+ if (entityKindName === "zone_switches") return zoneSwitchesOf(world, (zone) => simulation.isZoneEnabled(zone.id));
265
311
  if (entityKindName === "joint") {
266
- const isEnabled = simulation.joints.has(entityId) ? simulation.isJointEnabled(entityId) : pendingJoints.has(entityId) ? pendingJoints.get(entityId).isEnabled : null;
267
- if (isEnabled !== null) readJointEnabled.set(entityId, isEnabled);
268
- return isEnabled === null ? null : { isEnabled };
312
+ // The joint's own object, filled again: the core reads it at once and keeps nothing.
313
+ let fields = readJointFields.get(entityId);
314
+ if (!fields) readJointFields.set(entityId, (fields = { isEnabled: true, isBroken: false, motorTargetNumber: 0 }));
315
+ if (simulation.readJoint(entityId, fields)) return fields;
316
+ const pending = pendingJoints.get(entityId);
317
+ if (!pending) {
318
+ readJointFields.delete(entityId);
319
+ return null;
320
+ }
321
+ return Object.assign(fields, pending.fields);
269
322
  }
270
323
  const bodyIndex = simulation.bodyIndexById.get(entityId);
271
324
  if (bodyIndex === undefined) return null;
@@ -277,6 +330,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
277
330
  const bodyIndex = kindOf.get(entityId) === "body" ? simulation.bodyIndexById.get(entityId) : undefined;
278
331
  return bodyIndex !== undefined && simulation.isBodyOnSteps(bodyIndex);
279
332
  },
333
+ /** isOnSteps for a body's motion alone: its kind's own fields may still want rounding. */
334
+ isMotionOnSteps(entityId) {
335
+ const bodyIndex = isBodyEntityKind(kindOf.get(entityId)) ? simulation.bodyIndexById.get(entityId) : undefined;
336
+ return bodyIndex !== undefined && simulation.isBodyMotionOnSteps(bodyIndex);
337
+ },
280
338
  write(entityId, state, writeInfo) {
281
339
  const entityKindName = kindOf.get(entityId);
282
340
  if (entityKindName === "rules") {
@@ -286,9 +344,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
286
344
  if (characterIndex !== undefined) simulation.writeCharacter(characterIndex, state, writeInfo.isResting);
287
345
  } else if (entityKindName === "triangle_groups") {
288
346
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
347
+ } else if (entityKindName === "zone_switches") {
348
+ switchZones(state);
289
349
  } else if (entityKindName === "joint") {
290
- if (simulation.joints.has(entityId)) simulation.setJointEnabled(entityId, state.isEnabled);
291
- else if (pendingJoints.has(entityId)) pendingJoints.get(entityId).isEnabled = state.isEnabled;
350
+ if (simulation.joints.has(entityId)) simulation.writeJoint(entityId, state);
351
+ else if (pendingJoints.has(entityId)) Object.assign(pendingJoints.get(entityId).fields, { isEnabled: state.isEnabled, isBroken: Boolean(state.isBroken), motorTargetNumber: state.motorTargetNumber ?? 0 });
292
352
  } else {
293
353
  const bodyIndex = simulation.bodyIndexById.get(entityId);
294
354
  if (bodyIndex !== undefined) simulation.writeBody(bodyIndex, state, writeInfo.isResting);
@@ -300,7 +360,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
300
360
  * stays with that character, run ahead.
301
361
  */
302
362
  drawnWith(entityId) {
303
- if (kindOf.get(entityId) !== "body") return null;
363
+ if (!isBodyEntityKind(kindOf.get(entityId))) return null;
304
364
  const bodyIndex = simulation.bodyIndexById.get(entityId);
305
365
  if (bodyIndex === undefined) return null;
306
366
  const kindAnswer = kind.drawnWith?.(bodyIndex, opened.ownCharacterId, simulation.stepTools);
@@ -323,9 +383,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
323
383
  // The rules are read every step: a change of them is the word's to say at once.
324
384
  if (entityKindName === "rules") return false;
325
385
  // Groups change only when the game switches one, which the core already knows.
326
- if (entityKindName === "triangle_groups") return true;
327
- // A joint rests until a step ties or lets it go (setJoint from a character kind's step).
328
- if (entityKindName === "joint") return !simulation.joints.has(entityId) || readJointEnabled.get(entityId) === simulation.isJointEnabled(entityId);
386
+ if (entityKindName === "triangle_groups" || entityKindName === "zone_switches") return true;
387
+ // A joint rests until a step ties it, lets it go, breaks it or gives its motor another target.
388
+ if (entityKindName === "joint") {
389
+ const read = readJointFields.get(entityId);
390
+ const now = simulation.readJoint(entityId, jointNow);
391
+ return !now || (read !== undefined && read.isEnabled === now.isEnabled && read.isBroken === now.isBroken && read.motorTargetNumber === now.motorTargetNumber);
392
+ }
329
393
  if (entityKindName === "character") {
330
394
  const characterIndex = simulation.characterIndexById.get(entityId);
331
395
  return characterIndex !== undefined && simulation.isCharacterResting(characterIndex);
@@ -339,6 +403,8 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
339
403
  simulation.step({ tickIndex, timetableTickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
340
404
  const hits = simulation.takeHits();
341
405
  // A step run again already happened: no sound, no hook, twice.
406
+ if (!isReplay && simulation.jointBreakChangeCount() !== seenJointBreakChangeCount) tellBrokenJoints();
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 });
342
408
  if (!isReplay) {
343
409
  for (const hit of hits) {
344
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 });
@@ -365,16 +431,35 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
365
431
  simulation.dispose();
366
432
  },
367
433
  });
434
+ /** Switches every zone as the switches' fields say. */
435
+ function switchZones(state) {
436
+ for (const [zoneIndex, zone] of world.zones.entries()) simulation.setZoneEnabled(zone.id, !isZoneOffIn(state, zoneIndex));
437
+ }
368
438
  /** Joints whose ends aren't here yet (a character that hasn't arrived): made as soon as they are. */
369
439
  const pendingJoints = new Map();
370
- /** Whether each joint held when it was last read: one that changed since doesn't rest. */
371
- const readJointEnabled = new Map();
440
+ /** Each joint's fields as they were last read: one that changed since doesn't rest. */
441
+ const readJointFields = new Map();
442
+ const jointNow = { isEnabled: true, isBroken: false, motorTargetNumber: 0 };
372
443
  function retryJoints() {
373
444
  for (const [jointId, pending] of pendingJoints) {
374
- if (simulation.addJoint(pending.declaration, pending.isEnabled)) pendingJoints.delete(jointId);
445
+ if (!simulation.addJoint(pending.declaration, pending.fields.isEnabled)) continue;
446
+ simulation.writeJoint(jointId, pending.fields);
447
+ pendingJoints.delete(jointId);
448
+ }
449
+ }
450
+ /** The joints told to have broken: a step run again tells nothing twice, and one mended and broken again is told again. */
451
+ const toldBrokenJointIds = new Set();
452
+ let seenJointBreakChangeCount = 0;
453
+ function tellBrokenJoints() {
454
+ seenJointBreakChangeCount = simulation.jointBreakChangeCount();
455
+ for (const jointId of toldBrokenJointIds) if (!simulation.joints.get(jointId)?.isBroken) toldBrokenJointIds.delete(jointId);
456
+ for (const [jointId, joint] of simulation.joints) {
457
+ if (!joint.isBroken || toldBrokenJointIds.has(jointId)) continue;
458
+ toldBrokenJointIds.add(jointId);
459
+ tell("jointBroke", { jointId, bodyId: joint.declaration.bodyId, otherBodyId: joint.declaration.otherBodyId });
375
460
  }
376
461
  }
377
- for (const body of world.bodies) if (body.motionKind !== "fixed") kindOf.set(body.id, "body");
462
+ for (const body of world.bodies) if (body.motionKind !== "fixed") kindOf.set(body.id, plan.bodyEntityKindNameOf(body.bodyKindNumber));
378
463
  return opened;
379
464
  }
380
465
 
@@ -386,18 +471,21 @@ function worldFields(plan) {
386
471
  // A character first: a thing added with no kind named is one.
387
472
  character: { stateFields: plan.characterFields, hasInput: true },
388
473
  body: { stateFields: BODY_FIELDS },
474
+ ...Object.fromEntries(plan.ownFieldBehaviors.map((behavior) => [behavior.entityKindName, { stateFields: [...BODY_FIELDS, ...behavior.stateFields] }])),
389
475
  joint: { stateFields: JOINT_FIELDS },
390
476
  rules: { stateFields: plan.rulesFields },
391
477
  ...(hasTriangleGroups(world) ? { triangle_groups: { stateFields: TRIANGLE_GROUP_FIELDS } } : {}),
478
+ ...(world.zones.length ? { zone_switches: { stateFields: zoneMaskFieldsOf(world) } } : {}),
392
479
  },
393
480
  inputFields: plan.kind.inputFields,
394
481
  // The bodies that move, the joints, and the rules as the pieces have them: the same in every game, so nothing of
395
482
  // them is sent until it changes.
396
483
  entities: [
397
484
  { id: RULES_ID, entityKindName: "rules", state: { ...plan.defaultRules } },
398
- ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: "body", state: declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world) }] : [])),
399
- ...world.joints.map((joint) => ({ id: joint.id, entityKindName: "joint", state: { isEnabled: true } })),
485
+ ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: plan.bodyEntityKindNameOf(body.bodyKindNumber), state: { ...declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world), ...plan.startOwnOf(body.bodyKindNumber) } }] : [])),
486
+ ...world.joints.map((joint) => ({ id: joint.id, entityKindName: "joint", state: startJointFields(joint) })),
400
487
  ...(hasTriangleGroups(world) ? [{ id: TRIANGLE_GROUPS_ID, entityKindName: "triangle_groups", state: { ...NO_TRIANGLE_GROUPS_OFF } }] : []),
488
+ ...(world.zones.length ? [{ id: ZONE_SWITCHES_ID, entityKindName: "zone_switches", state: zoneSwitchesOf(world, (zone) => zone.isEnabled) }] : []),
401
489
  ],
402
490
  };
403
491
  }
@@ -446,6 +534,12 @@ function checkAddedBody(world, declaration) {
446
534
  return { ...checkBody(rest, "body", world.bodyKinds), startMotionKind: motionKind ?? "moving" };
447
535
  }
448
536
 
537
+ /** A size's number on the wire: 0 for the world's own character's (null), then the world's characterSizes in order. */
538
+ const sizeNumberOf = (world, characterSizeName) => {
539
+ const sizeNumber = characterSizeName === null ? 0 : world.characterSizes.findIndex((characterSize) => characterSize.name === characterSizeName) + 1;
540
+ if (sizeNumber === 0 && characterSizeName !== null) refuse("bad_argument", `characterSizeName is ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((characterSize) => characterSize.name).join(", ") || "it names none"}), or null for the world's own character.`);
541
+ return sizeNumber;
542
+ };
449
543
  const layerNumberOf = (world, layerName, what) => {
450
544
  const layerNumber = world.collisionLayers.findIndex((layer) => layer.name === layerName);
451
545
  if (layerNumber < 0 || layerName === "riding") refuse("bad_argument", `${what} is ${JSON.stringify(layerName)}.`, what, `Use one of the world's collisionLayers: ${world.collisionLayers.filter((layer) => layer.name !== "riding").map((layer) => layer.name).join(", ")}.`);
@@ -453,7 +547,7 @@ const layerNumberOf = (world, layerName, what) => {
453
547
  };
454
548
 
455
549
  /** What setBody was given, as the body's fields. */
456
- function bodyChanges(world, changes) {
550
+ function bodyChanges(world, changes, behavior = null) {
457
551
  for (const key of Object.keys(changes ?? {})) if (!SET_BODY_KEYS.includes(key)) refuse("unknown_argument", `setBody has no "${key}".`, key, `It takes: ${SET_BODY_KEYS.join(", ")}.`);
458
552
  const fields = {};
459
553
  const { positionM, rotationDeg, velocityMPerSec, spinRadPerSec, motionKind, collisionLayerName } = changes ?? {};
@@ -471,6 +565,14 @@ function bodyChanges(world, changes) {
471
565
  // On the wire's grain, so every side weighs it the same.
472
566
  fields.massKg = Math.round(changes.massKg * 100) / 100;
473
567
  }
568
+ if (changes?.own !== undefined) {
569
+ const names = behavior?.fieldNames ?? [];
570
+ if (changes.own === null || typeof changes.own !== "object") refuse("bad_argument", "own isn't an object of the body kind's fields.", "own", `Give some of: ${names.join(", ") || "(this body's kind has none)"}.`);
571
+ for (const [name, ownValue] of Object.entries(changes.own)) {
572
+ if (!names.includes(name)) refuse("bad_argument", `The body's kind has no field "${name}".`, `own.${name}`, `Its fields: ${names.join(", ") || "none"}.`);
573
+ fields[name] = ownValue;
574
+ }
575
+ }
474
576
  return fields;
475
577
  }
476
578
 
@@ -489,11 +591,13 @@ function bodyStateOf(simulation, bodyId) {
489
591
  collisionLayerName: simulation.world.collisionLayers[body.layerIndex].name,
490
592
  massKg: body.massKg ?? null,
491
593
  isResting: simulation.isBodyResting(bodyIndex),
594
+ bodyKindName: body.bodyKindName,
595
+ own: body.own ? { ...body.own } : null,
492
596
  riderCharacterIds: simulation.characters.filter((character) => character?.rideBodyIndex === bodyIndex).map((character) => character.id),
493
597
  };
494
598
  }
495
599
 
496
- const isFixedBody = (world, bodyId) => world.bodies.some((body) => body.id === bodyId && body.motionKind === "fixed");
600
+ const isFixedBody = (world, bodyId) => world.bodyById.get(bodyId)?.motionKind === "fixed";
497
601
  const unknownBody = (bodyId) => refuse("unknown_body", `There's no body ${JSON.stringify(bodyId)} in this world.`, "bodyId", "Give the id of a body in bodyIds(): one the world declares, or one added with addBody.");
498
602
  const unknownCharacter = (characterId) => refuse("unknown_character", `There's no character ${JSON.stringify(characterId)} here.`, "characterId", "Give the id of a character in characterIds(): a player's has the player's id.");
499
603
 
@@ -518,6 +622,7 @@ function characterView(world, simulation, fields, characterId) {
518
622
  rideBodyId: rideIndex >= 0 ? (simulation?.bodies[rideIndex]?.declaration.id ?? null) : null,
519
623
  seatIndex: rideIndex >= 0 ? fields.seatIndex : null,
520
624
  collisionLayerName: world.collisionLayers[fields.layerNumber]?.name ?? "character",
625
+ characterSizeName: world.characterSizes[(fields.sizeNumber ?? 0) - 1]?.name ?? null,
521
626
  };
522
627
  }
523
628
 
@@ -545,26 +650,48 @@ const ownOf = (plan, fields, simulation = null, characterId = null) => {
545
650
  /** What each query takes, beside collisionLayerNames and excludedId (and, for a shape, isStoppedAtPenetration, rotation and marginM). */
546
651
  const QUERY_KEYS = {
547
652
  castRay: ["fromM", "directionM", "maximumDistanceM"],
653
+ castRayAll: ["fromM", "directionM", "maximumDistanceM"],
548
654
  castBall: ["fromM", "radiusM", "directionM", "maximumDistanceM"],
549
655
  castCapsule: ["fromM", "radiusM", "heightM", "directionM", "maximumDistanceM"],
656
+ castBox: ["fromM", "sizeM", "directionM", "maximumDistanceM"],
550
657
  overlapCapsule: ["centerM", "radiusM", "heightM"],
551
658
  overlapBall: ["centerM", "radiusM"],
659
+ overlapBox: ["centerM", "sizeM"],
552
660
  };
553
661
  const SHAPE_QUERY_KEYS = ["isStoppedAtPenetration", "rotation", "marginM"];
554
662
  const OVERLAP_QUERY_KEYS = [...SHAPE_QUERY_KEYS, "isEachTriangle", "isOneSided"];
663
+ /** What each query may take beside what it needs, collisionLayerNames and excludedId. */
664
+ const QUERY_OPTION_KEYS = {
665
+ castRay: [],
666
+ castRayAll: ["maximumHitCount"],
667
+ castBall: SHAPE_QUERY_KEYS,
668
+ castCapsule: SHAPE_QUERY_KEYS,
669
+ castBox: ["isStoppedAtPenetration", "rotation"],
670
+ overlapCapsule: OVERLAP_QUERY_KEYS,
671
+ overlapBall: [],
672
+ overlapBox: ["rotation"],
673
+ };
674
+ /** The most hits castRayAll answers, and the most rays castRays takes in one call. */
675
+ const MAXIMUM_RAY_HIT_COUNT = 256;
676
+ const MAXIMUM_RAY_COUNT = 65536;
677
+ const ZONES_AT_KEYS = ["centerM", "radiusM", "heightM", "rotation"];
678
+ const RAYS_KEYS = ["rays", "rayCount", "maximumDistanceM", "collisionLayerNames", "excludedId"];
555
679
 
556
680
  /**
557
681
  * A query's request, checked: the points and lengths a ray, a ball's sweep or an overlap takes. The request itself
558
682
  * goes on to the search, and checking it makes nothing: a game asks thousands a second.
559
683
  */
560
- function checkQuery(given, what, isShape = false) {
684
+ function checkQuery(given, what) {
561
685
  const keys = QUERY_KEYS[what];
686
+ const optionKeys = QUERY_OPTION_KEYS[what];
562
687
  if (given === null || typeof given !== "object") refuse("bad_argument", `${what} takes an object.`, what, `Give { ${keys.join(", ")} }.`);
563
- for (const key in given) if (!keys.includes(key) && key !== "collisionLayerNames" && key !== "excludedId" && !(isShape && (what === "overlapCapsule" ? OVERLAP_QUERY_KEYS : SHAPE_QUERY_KEYS).includes(key))) refuse("unknown_argument", `${what} has no "${key}".`, key, `It takes: ${keys.join(", ")}, collisionLayerNames, excludedId.`);
688
+ for (const key in given) if (!keys.includes(key) && key !== "collisionLayerNames" && key !== "excludedId" && !optionKeys.includes(key)) refuse("unknown_argument", `${what} has no "${key}".`, key, `It takes: ${[...keys, ...optionKeys].join(", ")}, collisionLayerNames, excludedId.`);
564
689
  for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
565
690
  const key = keys[keyIndex];
566
691
  const givenValue = given[key];
567
- if (typeof givenValue === "object" && key.endsWith("M")) pointOrRefuse(givenValue, key, "Give three numbers: x, y and z, in metres.");
692
+ if (key === "sizeM") {
693
+ if (!givenValue || !(givenValue.x > 0) || !(givenValue.y > 0) || !(givenValue.z > 0) || !Number.isFinite(givenValue.x + givenValue.y + givenValue.z)) refuse("bad_argument", `sizeM is ${JSON.stringify(givenValue)}.`, "sizeM", "Give how wide (x), tall (y) and deep (z) the box is, each above 0, in metres.");
694
+ } else if (typeof givenValue === "object" && key.endsWith("M")) pointOrRefuse(givenValue, key, "Give three numbers: x, y and z, in metres.");
568
695
  else if (!Number.isFinite(givenValue) || givenValue < 0) refuse("bad_argument", `${key} is ${JSON.stringify(givenValue)}.`, key, "Give a length in metres from 0.");
569
696
  }
570
697
  return given;
@@ -572,7 +699,7 @@ function checkQuery(given, what, isShape = false) {
572
699
 
573
700
  /** A shape's query, checked: its points and lengths, and the isStoppedAtPenetration, rotation and marginM a shape's cast and overlap take beside them. */
574
701
  function shapeQueryOf(request, what) {
575
- const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what, true);
702
+ const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what);
576
703
  if (isStoppedAtPenetration !== undefined && typeof isStoppedAtPenetration !== "boolean") refuse("bad_argument", "isStoppedAtPenetration isn't true or false.", "isStoppedAtPenetration", "Give false to pass out of what the shape starts touching (a camera pressed to a wall), or leave it out.");
577
704
  if (rotation !== undefined && !(rotation && Number.isFinite(rotation.x) && Number.isFinite(rotation.y) && Number.isFinite(rotation.z) && Number.isFinite(rotation.w))) refuse("bad_argument", "rotation isn't { x, y, z, w }.", "rotation", "Give the turn as the engine and three.js hold it (a quaternion), or leave it out for standing up.");
578
705
  if (marginM !== undefined && !(Number.isFinite(marginM) && marginM >= 0 && marginM <= 1)) refuse("bad_argument", `marginM is ${JSON.stringify(marginM)}.`, "marginM", "Give how near counts as touching, 0 to 1 m, or leave it out.");
@@ -604,6 +731,46 @@ function queryCalls(simulationNow) {
604
731
  },
605
732
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
606
733
  overlapBall: (request) => simulationNow()?.overlapBall(checkQuery(request, "overlapBall")) ?? [],
734
+ /** The ids of the zones a place touches now: a point (centerM alone), a ball (with radiusM) or a capsule (with radiusM and heightM). */
735
+ zonesAt(request) {
736
+ if (request === null || typeof request !== "object") refuse("bad_argument", "zonesAt takes an object.", "zonesAt", "Give { centerM }, with radiusM for a ball and heightM too for a capsule.");
737
+ for (const key in request) if (!ZONES_AT_KEYS.includes(key)) refuse("unknown_argument", `zonesAt has no "${key}".`, key, `It takes: ${ZONES_AT_KEYS.join(", ")}.`);
738
+ pointOrRefuse(request.centerM, "centerM", "Give three numbers: x, y and z, in metres.");
739
+ for (const key of ["radiusM", "heightM"]) if (request[key] !== undefined && !(Number.isFinite(request[key]) && request[key] >= 0)) refuse("bad_argument", `${key} is ${JSON.stringify(request[key])}.`, key, "Give a length in metres from 0, or leave it out.");
740
+ if (request.heightM !== undefined && request.radiusM === undefined) refuse("bad_argument", "zonesAt was given heightM with no radiusM.", "radiusM", "A capsule takes both its radiusM and its heightM (its whole height, round ends included).");
741
+ if (request.rotation !== undefined && !(request.rotation && Number.isFinite(request.rotation.x + request.rotation.y + request.rotation.z + request.rotation.w))) refuse("bad_argument", "rotation isn't { x, y, z, w }.", "rotation", "Give the capsule's turn as a quaternion, or leave it out for standing up.");
742
+ return simulationNow()?.zonesAt(request) ?? [];
743
+ },
744
+ /** Everything a box (turned by rotation) overlaps: [{ bodyId, characterId }]. */
745
+ overlapBox: (request) => simulationNow()?.overlapBox(shapeQueryOf(request, "overlapBox")) ?? [],
746
+ /** The first thing a box (turned by rotation) meets moving along a direction, or null. */
747
+ castBox: (request, into) => simulationNow()?.castBox(shapeQueryOf(request, "castBox"), checkInto(into)) ?? null,
748
+ /** Everything a ray passes through, nearest first, one hit a shape: a list of hits as castRay's, up to maximumHitCount (default 16). */
749
+ castRayAll(request, into) {
750
+ if (into !== undefined && into !== null && !Array.isArray(into)) refuse("bad_argument", "into isn't a list.", "into", "Give a list of your own to write the hits into (kept and given again), or leave it out for a new one.");
751
+ const { maximumHitCount } = checkQuery(request, "castRayAll");
752
+ if (maximumHitCount !== undefined && !(Number.isInteger(maximumHitCount) && maximumHitCount >= 1 && maximumHitCount <= MAXIMUM_RAY_HIT_COUNT)) refuse("bad_argument", `maximumHitCount is ${JSON.stringify(maximumHitCount)}.`, "maximumHitCount", `Give how many hits to answer at most, 1 to ${MAXIMUM_RAY_HIT_COUNT}, or leave it out for 16.`);
753
+ const simulation = simulationNow();
754
+ if (simulation) return simulation.castRayAll(request, into ?? null);
755
+ if (into) into.length = 0;
756
+ return into ?? [];
757
+ },
758
+ /** Many rays in one call: { rays (six numbers a ray: its start, then its direction), maximumDistanceM }. Answers { rayCount, hitCount, distancesM, normals, hitAt(rayIndex, into) }; with into, written there. */
759
+ castRays(request, into) {
760
+ if (request === null || typeof request !== "object") refuse("bad_argument", "castRays takes an object.", "castRays", "Give { rays, maximumDistanceM }.");
761
+ for (const key in request) if (!RAYS_KEYS.includes(key)) refuse("unknown_argument", `castRays has no "${key}".`, key, `It takes: ${RAYS_KEYS.join(", ")}.`);
762
+ const { rays, rayCount = rays instanceof Float32Array ? Math.floor(rays.length / 6) : 0, maximumDistanceM } = request;
763
+ if (!(rays instanceof Float32Array)) refuse("bad_argument", "rays isn't a Float32Array.", "rays", "Give a Float32Array with six numbers a ray: where it starts (x, y, z), then its direction (x, y, z).");
764
+ if (!Number.isInteger(rayCount) || rayCount < 0 || rayCount > MAXIMUM_RAY_COUNT || rayCount * 6 > rays.length) refuse("bad_argument", `rayCount is ${JSON.stringify(rayCount)}.`, "rayCount", `Give how many of rays' rays to cast, up to ${MAXIMUM_RAY_COUNT} and what rays holds, or leave it out for all of them.`);
765
+ if (!Number.isFinite(maximumDistanceM) || maximumDistanceM < 0) refuse("bad_argument", `maximumDistanceM is ${JSON.stringify(maximumDistanceM)}.`, "maximumDistanceM", "Give how far every ray goes at most, in metres from 0.");
766
+ if (into !== undefined && into !== null && (typeof into !== "object" || Array.isArray(into))) refuse("bad_argument", "into isn't an answer of castRays.", "into", "Give what an earlier castRays answered (kept and given again), or leave it out for a new one.");
767
+ const simulation = simulationNow();
768
+ if (simulation) return simulation.castRays(request, into ?? null);
769
+ const answer = into ?? { rayCount: 0, hitCount: 0, distancesM: new Float32Array(0), normals: new Float32Array(0), hitAt: () => null };
770
+ answer.rayCount = 0;
771
+ answer.hitCount = 0;
772
+ return answer;
773
+ },
607
774
  };
608
775
  }
609
776
 
@@ -612,6 +779,10 @@ function queryCalls(simulationNow) {
612
779
  * online core's World gives it (ids, has, entityKindName, state, drawn, add, remove, set, setInput, on, simulation),
613
780
  * and the rest says who this game is in it.
614
781
  */
782
+ function unknownZone(world, zoneId) {
783
+ refuse("unknown_zone", `There's no zone ${JSON.stringify(zoneId)} in this world.`, "zoneId", world.zones.length ? `Give one of the world's zones: ${world.zones.slice(0, 20).map((zone) => zone.id).join(", ")}.` : "Give the world zones in its declaration first, in the game and on its game server.");
784
+ }
785
+
615
786
  function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer, tickNumber }) {
616
787
  const { world, kind } = plan;
617
788
  const listeners = Object.fromEntries(LISTENED_EVENT_NAMES.map((eventName) => [eventName, new Set()]));
@@ -623,17 +794,17 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
623
794
  things.on("added", (id) => {
624
795
  const entityKindName = things.entityKindName(id);
625
796
  kindById.set(id, entityKindName);
626
- if (entityKindName === "body") telling("bodyAdded", id);
797
+ if (isBodyEntityKind(entityKindName)) telling("bodyAdded", id);
627
798
  else if (entityKindName === "character") telling("characterAdded", id);
628
799
  });
629
800
  things.on("removed", (id) => {
630
801
  const entityKindName = kindById.get(id);
631
802
  kindById.delete(id);
632
- if (entityKindName === "body") telling("bodyRemoved", id);
803
+ if (isBodyEntityKind(entityKindName)) telling("bodyRemoved", id);
633
804
  else if (entityKindName === "character") telling("characterRemoved", id);
634
805
  });
635
806
  const simulationNow = () => things.simulation?.simulation ?? null;
636
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
807
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
637
808
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
638
809
  /** The world's calls where this game runs it; a refusal with a game server, and null where another player's game does. */
639
810
  const inCharge = (what) => {
@@ -649,9 +820,14 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
649
820
  const simulation = drawn ? simulationNow() : null;
650
821
  if (simulation?.timetablePlace(simulation.bodyIndexById.get(bodyId), tickNumber(), timetabledPlace)) return { ...drawn, x: timetabledPlace.x, y: timetabledPlace.y, z: timetabledPlace.z, rotation: { x: timetabledPlace.rotationX, y: timetabledPlace.rotationY, z: timetabledPlace.rotationZ, w: timetabledPlace.rotationW } };
651
822
  if (drawn) return drawn;
652
- const declaration = world.bodies.find((body) => body.id === bodyId && body.motionKind === "fixed");
823
+ const declaration = isFixedBody(world, bodyId) ? world.bodyById.get(bodyId) : null;
653
824
  return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
654
825
  };
826
+ /** A body's kind's own fields as drawn this frame, or null for a kind with none. */
827
+ const ownOfBody = (bodyId, drawn) => {
828
+ const behavior = plan.bodyBehaviors?.[world.bodyById.get(bodyId)?.bodyKindNumber ?? simulationNow()?.bodies[simulationNow().bodyIndexById.get(bodyId)]?.declaration.bodyKindNumber];
829
+ return behavior ? Object.fromEntries(behavior.fieldNames.map((name) => [name, drawn[name] ?? null])) : null;
830
+ };
655
831
  const shared = sharedCalls({ plan, things, simulationNow, inChargeOf: inCharge });
656
832
 
657
833
  const calls = {
@@ -677,12 +853,12 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
677
853
  bodyDeclaration(bodyId) {
678
854
  const simulation = simulationNow();
679
855
  if (simulation) return simulation.bodies[simulation.bodyIndexById.get(bodyId)]?.declaration ?? null;
680
- return world.bodies.find((body) => body.id === bodyId) ?? null;
856
+ return world.bodyById.get(bodyId) ?? null;
681
857
  },
682
858
  /** Where to draw a body this frame: { positionM, rotation, steerNumber }. null for a body that isn't here. */
683
859
  drawnBody(bodyId) {
684
860
  const drawn = drawnOf(bodyId);
685
- return drawn ? { positionM: { x: drawn.x, y: drawn.y, z: drawn.z }, rotation: { ...drawn.rotation }, steerNumber: drawn.steerNumber ?? 0, wheels: simulationNow()?.wheelStates(bodyId) ?? [] } : null;
861
+ 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;
686
862
  },
687
863
  /** Puts a three.js object (anything with position.set and quaternion.set) where a body is drawn this frame. */
688
864
  applyTo(object3d, bodyId) {
@@ -728,13 +904,14 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
728
904
  */
729
905
  function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
730
906
  const { world, kind } = plan;
731
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
907
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
732
908
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
733
909
  const isJoint = (jointId) => things.entityKindName(jointId) === "joint";
734
910
  // Every thing in play, declared ones included: an id freed by a removal may be used again, even in the same step.
735
911
  const ids = () => new Set(things.ids());
912
+ const movingBodyIds = () => (plan.bodyEntityKindNames.length === 1 ? things.ids("body") : plan.bodyEntityKindNames.flatMap((entityKindName) => things.ids(entityKindName)));
736
913
  return {
737
- bodyIds: () => [...world.bodies.filter((body) => body.motionKind === "fixed").map((body) => body.id), ...things.ids("body")],
914
+ bodyIds: () => [...world.fixedBodyIds, ...movingBodyIds()],
738
915
  hasBody: (bodyId) => isBody(bodyId) || isFixedBody(world, bodyId),
739
916
  /** A body as this world has it now. */
740
917
  bodyState: (bodyId) => bodyStateOf(simulationNow(), bodyId),
@@ -743,17 +920,18 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
743
920
  const running = inChargeOf("bodies are added");
744
921
  const checked = checkAddedBody(world, declaration);
745
922
  if (!running || ids().has(checked.id)) return false;
746
- if (things.ids("body").length >= MAXIMUM_BODY_COUNT) refuse("too_many_bodies", `A world holds at most ${MAXIMUM_BODY_COUNT} bodies.`, "body", "Remove bodies nobody needs.");
747
- return Boolean(running.add(checked.id, { entityKindName: "body", state: { ...declaredBodyFields(checked, things.simulation.freeBodyNumber(), checked.bodyKindNumber, world), motionNumber: MOTION_KINDS.indexOf(checked.startMotionKind) } }));
923
+ if (movingBodyIds().length >= MAXIMUM_BODY_COUNT) refuse("too_many_bodies", `A world holds at most ${MAXIMUM_BODY_COUNT} bodies.`, "body", "Remove bodies nobody needs.");
924
+ return Boolean(running.add(checked.id, { entityKindName: plan.bodyEntityKindNameOf(checked.bodyKindNumber), state: { ...declaredBodyFields(checked, things.simulation.freeBodyNumber(), checked.bodyKindNumber, world), ...plan.startOwnOf(checked.bodyKindNumber), motionNumber: MOTION_KINDS.indexOf(checked.startMotionKind) } }));
748
925
  },
749
926
  removeBody: (bodyId) => Boolean(inChargeOf("bodies are removed") && isBody(bodyId) && things.remove(bodyId)),
750
927
  /** Sets a body's place, rotation, speed or spin at once (a teleport), how it moves (motionKind), or its collision layer. */
751
928
  setBody(bodyId, changes) {
752
929
  const running = inChargeOf("bodies are set");
753
- const fields = bodyChanges(world, changes);
754
- if (!isBody(bodyId)) return world.bodies.some((body) => body.id === bodyId) ? false : unknownBody(bodyId);
930
+ const behavior = plan.bodyBehaviors?.[simulationNow()?.bodies[simulationNow().bodyIndexById.get(bodyId)]?.declaration.bodyKindNumber] ?? null;
931
+ const fields = bodyChanges(world, changes, behavior);
932
+ if (!isBody(bodyId)) return world.bodyById.has(bodyId) ? false : unknownBody(bodyId);
755
933
  const isMoved = ["x", "y", "z", "rotation"].some((name) => name in fields);
756
- if (world.bodies.some((body) => body.id === bodyId && body.timetable) && Object.keys(fields).some((name) => name !== "layerNumber")) refuse("bad_argument", `setBody was given more than a collision layer for "${bodyId}", which is on a timetable.`, "changes", "Its timetable says where it is at every step: give collisionLayerName alone, or declare it without a timetable to move it yourself.");
934
+ if (world.bodyById.get(bodyId)?.timetable && Object.keys(fields).some((name) => name !== "layerNumber" && !behavior?.fieldNames.includes(name))) refuse("bad_argument", `setBody was given more than a collision layer for "${bodyId}", which is on a timetable.`, "changes", "Its timetable says where it is at every step: give collisionLayerName alone, or declare it without a timetable to move it yourself.");
757
935
  return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
758
936
  },
759
937
  pushBody(bodyId, pushMPerSec) {
@@ -775,8 +953,11 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
775
953
  const running = inChargeOf("characters are added");
776
954
  if (!running || things.has(characterId)) return false;
777
955
  if (things.ids("character").length >= MAXIMUM_CHARACTER_COUNT) refuse("too_many_characters", `A world holds at most ${MAXIMUM_CHARACTER_COUNT} characters.`, "characterId", "Remove characters nobody needs.");
956
+ for (const key of Object.keys(addOptions ?? {})) if (!ADD_CHARACTER_KEYS.includes(key)) refuse("unknown_argument", `addCharacter has no "${key}".`, key, `It takes: ${ADD_CHARACTER_KEYS.join(", ")}.`);
778
957
  const feetM = addOptions?.positionM === undefined ? null : pointOrRefuse(addOptions.positionM, "positionM", "Give where its feet stand, in metres.");
779
- return Boolean(running.add(characterId, { entityKindName: "character", ...(feetM ? { state: { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z } } : {}) }));
958
+ const sizeNumber = addOptions?.characterSizeName === undefined ? 0 : sizeNumberOf(world, addOptions.characterSizeName);
959
+ const state = { ...(feetM ? { x: feetM.x, y: feetM.y + world.character.heightM / 2, z: feetM.z } : {}), ...(sizeNumber ? { sizeNumber } : {}) };
960
+ return Boolean(running.add(characterId, { entityKindName: "character", ...(Object.keys(state).length ? { state } : {}) }));
780
961
  },
781
962
  removeCharacter: (characterId) => Boolean(inChargeOf("characters are removed") && isCharacter(characterId) && things.remove(characterId)),
782
963
  /** Sets a character at once: its feet's place (a teleport), its speed, facing, collision layer, or its kind's own fields. */
@@ -792,6 +973,7 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
792
973
  if (changes?.velocityMPerSec !== undefined) Object.assign(fields, { velocityX: pointOrRefuse(changes.velocityMPerSec, "velocityMPerSec", "Give three numbers: x, y and z.").x, velocityY: changes.velocityMPerSec.y, velocityZ: changes.velocityMPerSec.z });
793
974
  if (changes?.facingYawRad !== undefined) fields.facingYawRad = changes.facingYawRad;
794
975
  if (changes?.collisionLayerName !== undefined) fields.layerNumber = layerNumberOf(world, changes.collisionLayerName, "collisionLayerName");
976
+ if (changes?.characterSizeName !== undefined) fields.sizeNumber = sizeNumberOf(world, changes.characterSizeName);
795
977
  if (changes?.own !== undefined) {
796
978
  if (changes.own === null || typeof changes.own !== "object") refuse("bad_argument", "own isn't an object of the character kind's fields.", "own", `Give some of: ${kind.stateFields.map((field) => field.name).join(", ") || "(this kind has none)"}.`);
797
979
  for (const [name, ownValue] of Object.entries(changes.own)) {
@@ -823,18 +1005,30 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
823
1005
  if (!running || ids().has(checked.id)) return false;
824
1006
  if (things.ids("joint").length >= MAXIMUM_JOINT_COUNT) refuse("too_many_joints", `A world holds at most ${MAXIMUM_JOINT_COUNT} joints.`, "joint", "Remove joints nobody needs.");
825
1007
  const { id, ...entityData } = declaration;
826
- return Boolean(running.add(checked.id, { entityKindName: "joint", state: { isEnabled: true }, entityData }));
1008
+ return Boolean(running.add(checked.id, { entityKindName: "joint", state: startJointFields(checked), entityData }));
827
1009
  },
828
1010
  removeJoint: (jointId) => Boolean(inChargeOf("joints are removed") && isJoint(jointId) && things.remove(jointId)),
829
- /** Lets a joint go, or holds again (a cart's handles let go and taken). */
1011
+ /** Lets a joint go or holds again (a cart's handles let go and taken; a broken one mended), or gives its motor another target (a door told to close, a winch to turn). */
830
1012
  setJoint(jointId, changes) {
831
1013
  const running = inChargeOf("joints are set");
832
- for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled.");
833
- if (typeof changes?.isEnabled !== "boolean") refuse("bad_argument", "setJoint takes { isEnabled }.", "isEnabled", "Give true to hold, false to let go.");
1014
+ for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled" && key !== "motorTargetNumber") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled, motorTargetNumber.");
1015
+ const { isEnabled, motorTargetNumber } = changes ?? {};
1016
+ if (isEnabled === undefined && motorTargetNumber === undefined) refuse("bad_argument", "setJoint takes { isEnabled, motorTargetNumber }, either or both.", "changes", "Give isEnabled true to hold or false to let go, or motorTargetNumber for its motor.");
1017
+ if (isEnabled !== undefined && typeof isEnabled !== "boolean") refuse("bad_argument", `isEnabled is ${JSON.stringify(isEnabled)}.`, "isEnabled", "Give true to hold, false to let go.");
834
1018
  if (!isJoint(jointId)) refuse("unknown_joint", `There's no joint ${JSON.stringify(jointId)} here.`, "jointId", "Give the id of a joint in jointIds().");
835
- return Boolean(running && running.set(jointId, { isEnabled: changes.isEnabled }, { isTeleport: false }));
1019
+ if (motorTargetNumber !== undefined) {
1020
+ if (!Number.isFinite(motorTargetNumber) || Math.abs(motorTargetNumber) > MAXIMUM_MOTOR_TARGET_NUMBER) refuse("bad_argument", `motorTargetNumber is ${JSON.stringify(motorTargetNumber)}.`, "motorTargetNumber", `Give a number from -${MAXIMUM_MOTOR_TARGET_NUMBER} to ${MAXIMUM_MOTOR_TARGET_NUMBER}: radians (a second) about a hinge, metres (a second) along a slider.`);
1021
+ if (simulationNow() && !simulationNow().joints.get(jointId)?.declaration.motor) refuse("bad_argument", `The joint ${JSON.stringify(jointId)} has no motor.`, "motorTargetNumber", 'Declare the joint with motor: { motorKind: "speed" } or { motorKind: "position" } (a hinge or a slider), in the game and on its game server.');
1022
+ }
1023
+ // Held again, it's whole again.
1024
+ return Boolean(running && running.set(jointId, { ...(isEnabled === undefined ? {} : { isEnabled, ...(isEnabled ? { isBroken: false } : {}) }), ...(motorTargetNumber === undefined ? {} : { motorTargetNumber }) }, { isTeleport: false }));
836
1025
  },
837
1026
  isJointEnabled: (jointId) => (isJoint(jointId) ? Boolean(things.state(jointId)?.isEnabled) : false),
1027
+ /** A joint as the world has it now: { isEnabled, isBroken, motorTargetNumber }, or null. */
1028
+ jointState(jointId) {
1029
+ const fields = isJoint(jointId) ? things.state(jointId) : null;
1030
+ return fields ? { isEnabled: Boolean(fields.isEnabled), isBroken: Boolean(fields.isBroken), motorTargetNumber: fields.motorTargetNumber ?? 0 } : null;
1031
+ },
838
1032
  /** Switches one of the world's triangle groups on or off for everyone (a door that opens, a bridge that falls), 1 to 63. */
839
1033
  setTriangleGroup(groupNumber, isEnabled) {
840
1034
  const running = inChargeOf("triangle groups are switched");
@@ -846,6 +1040,28 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
846
1040
  const bitNumber = triangleGroupBitNumberOf(groupNumber);
847
1041
  return Boolean(running && running.set(TRIANGLE_GROUPS_ID, { [maskName]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
848
1042
  },
1043
+ zoneIds: () => world.zones.map((zone) => zone.id),
1044
+ /** Who's in a zone, as of the last step: [{ bodyId, characterId }]. */
1045
+ zoneOccupants(zoneId) {
1046
+ if (!world.zones.some((zone) => zone.id === zoneId)) unknownZone(world, zoneId);
1047
+ return simulationNow()?.zoneOccupants(zoneId) ?? [];
1048
+ },
1049
+ /** Switches a zone on or off for everyone (a fan that starts, a capture point that opens): off, nobody is in it and it does nothing. */
1050
+ setZone(zoneId, changes) {
1051
+ const running = inChargeOf("zones are switched");
1052
+ for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setZone has no "${key}".`, key, "It takes: isEnabled.");
1053
+ if (typeof changes?.isEnabled !== "boolean") refuse("bad_argument", "setZone takes { isEnabled }.", "isEnabled", "Give true to switch the zone on, false to switch it off.");
1054
+ const zoneIndex = world.zones.findIndex((zone) => zone.id === zoneId);
1055
+ if (zoneIndex < 0) unknownZone(world, zoneId);
1056
+ const maskName = zoneMaskNameOf(Math.floor(zoneIndex / ZONE_MASK_BIT_COUNT));
1057
+ const maskNumber = things.state(ZONE_SWITCHES_ID)?.[maskName] ?? 0;
1058
+ const bitNumber = 1 << (zoneIndex % ZONE_MASK_BIT_COUNT);
1059
+ return Boolean(running && running.set(ZONE_SWITCHES_ID, { [maskName]: changes.isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
1060
+ },
1061
+ isZoneEnabled(zoneId) {
1062
+ const zoneIndex = world.zones.findIndex((zone) => zone.id === zoneId);
1063
+ return zoneIndex >= 0 && !isZoneOffIn(things.state(ZONE_SWITCHES_ID), zoneIndex);
1064
+ },
849
1065
  /** Whether a triangle group is there now. */
850
1066
  isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.[TRIANGLE_GROUP_MASK_NAMES[triangleGroupMaskIndexOf(groupNumber)]] ?? 0) & triangleGroupBitNumberOf(groupNumber)),
851
1067
  };
@@ -860,10 +1076,10 @@ const kindOf = (characters) => (characters === undefined ? walkingCharacters() :
860
1076
  * createNet(room).use and defineNetServer's kinds.
861
1077
  */
862
1078
  export const physicsKindFrom = (worldKind) => (givenWorld, given = {}) => {
863
- if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "characters"].includes(key))) refuse("unknown_argument", "physicsKind takes a world, then { settings, hooks, characters }.", "given", "Give the world first, then an object with settings, hooks and characters (a character kind), each optional.");
1079
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => !["settings", "hooks", "characters", "bodies"].includes(key))) refuse("unknown_argument", "physicsKind takes a world, then { settings, hooks, characters, bodies }.", "given", "Give the world first, then an object with settings, hooks, characters (a character kind) and bodies (rules for the world's body kinds), each optional.");
864
1080
  const world = worldOf(givenWorld);
865
1081
  const kind = kindOf(given.characters);
866
- const plan = worldPlan(world, kind);
1082
+ const plan = worldPlan(world, kind, defineBodyBehaviors(given.bodies, world));
867
1083
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: given.settings, hooks: given.hooks });
868
1084
  const nextStart = startStates(world);
869
1085
  const physicsWorldKind = worldKind({
@@ -972,10 +1188,10 @@ function copyMotion(into, read, rest) {
972
1188
  * A world played alone: the same calls over the same simulation, stepped here with no room. update(nowMs) runs the
973
1189
  * fixed steps that are due on the clock it's given.
974
1190
  */
975
- export function alonePhysics(givenWorld, { settings: givenSettings, hooks: givenHooks, ticksPerSec, playerId, characters, defineShape }) {
1191
+ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: givenHooks, ticksPerSec, playerId, characters, bodies, defineShape }) {
976
1192
  const world = worldOf(givenWorld);
977
1193
  const kind = kindOf(characters);
978
- const plan = worldPlan(world, kind);
1194
+ const plan = worldPlan(world, kind, defineBodyBehaviors(bodies, world));
979
1195
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: givenSettings, hooks: givenHooks });
980
1196
  const tickDurationSec = 1 / ticksPerSec;
981
1197
  const opened = openWorld({ plan, settings, kindSettings: kind.settings ?? null, ask, tell, tickDurationSec, isInChargeAtFirst: true });
@@ -994,6 +1210,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
994
1210
  let ranTickCount = 0;
995
1211
  /** Puts a thing's fields on their steps, as online: the same numbers alone as in a room. */
996
1212
  const onSteps = (entityKindName, state) => shapes[entityKindName].onSteps(state);
1213
+ /** Each body kind's own fields as a shape of their own, to put them on their steps without the whole body's. */
1214
+ const ownShapes = Object.fromEntries(plan.ownFieldBehaviors.map((behavior) => [behavior.entityKindName, { shape: defineShape(behavior.stateFields, { what: behavior.entityKindName, isPressAllowed: false }), fieldNames: behavior.fieldNames }]));
997
1215
 
998
1216
  const things = {
999
1217
  simulation: opened,
@@ -1064,7 +1282,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1064
1282
  const read = opened.read(id);
1065
1283
  if (!read) return;
1066
1284
  let onStepsRead;
1067
- if (entity.entityKindName === "body" && entity.onStepsRest && opened.isOnSteps(id) && read.layerNumber === entity.readLayerNumber && read.motionNumber === entity.readMotionNumber && read.steerNumber === entity.readSteerNumber && read.massKg === entity.readMassKg) {
1285
+ const ownShape = ownShapes[entity.entityKindName];
1286
+ if ((entity.entityKindName === "body" || ownShape) && entity.onStepsRest && opened.isMotionOnSteps(id) && read.layerNumber === entity.readLayerNumber && read.motionNumber === entity.readMotionNumber && read.steerNumber === entity.readSteerNumber && read.massKg === entity.readMassKg) {
1068
1287
  // The step left it on the wire's steps already: nothing to round and nothing to write back, so a
1069
1288
  // thousand bodies falling leave nothing for the garbage collector. Its fields go into one of two
1070
1289
  // objects of its own, turn about (nothing outside keeps them).
@@ -1074,12 +1293,34 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1074
1293
  }
1075
1294
  onStepsRead = entity.later === entity.ownFirst ? entity.ownSecond : entity.ownFirst;
1076
1295
  copyMotion(onStepsRead, read, entity.onStepsRest);
1296
+ if (ownShape) {
1297
+ // Its kind's own fields go on their steps by their own shape, and back into the body only where that moved one.
1298
+ entity.ownSlots ??= new Int32Array(ownShape.shape.slotCount);
1299
+ ownShape.shape.fromSlots(ownShape.shape.toSlots(read, entity.ownSlots), 0, onStepsRead);
1300
+ for (const name of ownShape.fieldNames) {
1301
+ if (onStepsRead[name] === read[name]) continue;
1302
+ steppedWriteInfo.isResting = isResting;
1303
+ opened.write(id, onStepsRead, steppedWriteInfo);
1304
+ break;
1305
+ }
1306
+ }
1077
1307
  } else {
1078
- onStepsRead = onSteps(entity.entityKindName, read);
1308
+ if (isBodyEntityKind(entity.entityKindName)) {
1309
+ // A body the step left off the wire's steps (one with fields of its own, a vehicle turning) is put on them
1310
+ // through slots of its own, into one of two objects of its own, turn about: nothing for the garbage collector.
1311
+ const shape = shapes[entity.entityKindName];
1312
+ entity.slots ??= new Int32Array(shape.slotCount);
1313
+ shape.toSlots(read, entity.slots);
1314
+ if (!entity.roundFirst) {
1315
+ entity.roundFirst = shape.fromSlots(entity.slots);
1316
+ entity.roundSecond = shape.fromSlots(entity.slots);
1317
+ }
1318
+ onStepsRead = shape.fromSlots(entity.slots, 0, entity.later === entity.roundFirst ? entity.roundSecond : entity.roundFirst);
1319
+ } else onStepsRead = onSteps(entity.entityKindName, read);
1079
1320
  // As online, every place steps on the wire's numbers.
1080
1321
  steppedWriteInfo.isResting = isResting;
1081
1322
  opened.write(id, onStepsRead, steppedWriteInfo);
1082
- if (entity.entityKindName === "body") {
1323
+ if (isBodyEntityKind(entity.entityKindName)) {
1083
1324
  entity.readLayerNumber = read.layerNumber;
1084
1325
  entity.readMotionNumber = read.motionNumber;
1085
1326
  entity.readSteerNumber = read.steerNumber;