@zaisma/physics 2.6.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_CHARACTER_SIZE_COUNT, MAXIMUM_FIXED_BODY_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,11 +23,25 @@ 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"];
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_"));
30
45
  const SET_CHARACTER_KEYS = ["positionM", "velocityMPerSec", "facingYawRad", "collisionLayerName", "characterSizeName", "own"];
31
46
  const ADD_CHARACTER_KEYS = ["positionM", "characterSizeName"];
32
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
@@ -72,7 +87,14 @@ const CHARACTER_BASE_FIELDS = [
72
87
  // Which size it is: 0 for the world's own character's, then the world's characterSizes in order.
73
88
  { name: "sizeNumber", valueKind: "integer", minimumNumber: 0, maximumNumber: MAXIMUM_CHARACTER_SIZE_COUNT },
74
89
  ];
75
- const JOINT_FIELDS = [{ name: "isEnabled", valueKind: "boolean", defaultValue: true }];
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 },
95
+ ];
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 });
76
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
77
99
  // from the wire changes nothing): each number field's range, step and count of steps, counted as the core's shape
78
100
  // counts them, and how many steps each part of the rotation has.
@@ -111,7 +133,7 @@ function pointOrRefuse(given, what, fix) {
111
133
  * Everything one world needs that's the same wherever it's opened: the world, its character kind, the fields each
112
134
  * thing shares, and which settings every side steps by.
113
135
  */
114
- function worldPlan(world, kind) {
136
+ function worldPlan(world, kind, bodyBehaviors = null) {
115
137
  const kindSyncedNames = kind.syncedSettingNames ?? [];
116
138
  const baseStated = new Map(openSettings(statement).list().map((stated) => [stated.name, stated]));
117
139
  const kindStated = kind.settingsStatement ? new Map(openSettings(kind.settingsStatement).list().map((stated) => [stated.name, stated])) : new Map();
@@ -119,7 +141,23 @@ function worldPlan(world, kind) {
119
141
  const defaultRules = Object.fromEntries(rulesFields.map((field) => [field.name, field.defaultValue]));
120
142
  // A field the kind keeps locally (isShared: false) is worked out by each step and never goes on the wire.
121
143
  const characterFields = characterFieldsOf(kind);
122
- 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
+ };
123
161
  }
124
162
 
125
163
  /**
@@ -145,7 +183,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
145
183
  isStateOnSteps: true,
146
184
  };
147
185
  const ownRules = () => Object.fromEntries(ruleNames.map((name) => [name, BASE_SYNCED_SETTING_NAMES.includes(name) ? settings.get(name) : kindSettings.get(name)]));
148
- 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 });
149
187
  /** Where each character started, to put it back when it falls out of the world. */
150
188
  const startOf = new Map();
151
189
  /** The kind of thing each id is: "body", "character", "joint" or "rules". */
@@ -221,9 +259,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
221
259
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
222
260
  return;
223
261
  }
262
+ if (entity.entityKindName === "zone_switches") {
263
+ switchZones(state);
264
+ return;
265
+ }
224
266
  if (entity.entityKindName === "joint") {
225
267
  const declaration = world.joints.find((joint) => joint.id === entity.id) ?? (entity.entityData ? checkJoint({ ...entity.entityData, id: entity.id }, "joint") : null);
226
- 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 } });
227
269
  retryJoints();
228
270
  return;
229
271
  }
@@ -244,11 +286,12 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
244
286
  const characterIndex = simulation.characterIndexById.get(entityId);
245
287
  if (characterIndex !== undefined) simulation.removeCharacter(characterIndex);
246
288
  startOf.delete(entityId);
247
- } else if (entityKindName === "body") {
289
+ } else if (isBodyEntityKind(entityKindName)) {
248
290
  const bodyIndex = simulation.bodyIndexById.get(entityId);
249
291
  if (bodyIndex !== undefined) simulation.removeBody(bodyIndex);
250
292
  } else if (entityKindName === "joint") {
251
293
  pendingJoints.delete(entityId);
294
+ readJointFields.delete(entityId);
252
295
  simulation.removeJoint(entityId);
253
296
  }
254
297
  },
@@ -264,10 +307,18 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
264
307
  return characterIndex === undefined ? null : simulation.readSteppedCharacter(characterIndex);
265
308
  }
266
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));
267
311
  if (entityKindName === "joint") {
268
- const isEnabled = simulation.joints.has(entityId) ? simulation.isJointEnabled(entityId) : pendingJoints.has(entityId) ? pendingJoints.get(entityId).isEnabled : null;
269
- if (isEnabled !== null) readJointEnabled.set(entityId, isEnabled);
270
- 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);
271
322
  }
272
323
  const bodyIndex = simulation.bodyIndexById.get(entityId);
273
324
  if (bodyIndex === undefined) return null;
@@ -279,6 +330,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
279
330
  const bodyIndex = kindOf.get(entityId) === "body" ? simulation.bodyIndexById.get(entityId) : undefined;
280
331
  return bodyIndex !== undefined && simulation.isBodyOnSteps(bodyIndex);
281
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
+ },
282
338
  write(entityId, state, writeInfo) {
283
339
  const entityKindName = kindOf.get(entityId);
284
340
  if (entityKindName === "rules") {
@@ -288,9 +344,11 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
288
344
  if (characterIndex !== undefined) simulation.writeCharacter(characterIndex, state, writeInfo.isResting);
289
345
  } else if (entityKindName === "triangle_groups") {
290
346
  simulation.setOffTriangleGroups(state.offMaskNumber, state.offSecondMaskNumber ?? 0, state.offThirdMaskNumber ?? 0);
347
+ } else if (entityKindName === "zone_switches") {
348
+ switchZones(state);
291
349
  } else if (entityKindName === "joint") {
292
- if (simulation.joints.has(entityId)) simulation.setJointEnabled(entityId, state.isEnabled);
293
- 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 });
294
352
  } else {
295
353
  const bodyIndex = simulation.bodyIndexById.get(entityId);
296
354
  if (bodyIndex !== undefined) simulation.writeBody(bodyIndex, state, writeInfo.isResting);
@@ -302,7 +360,7 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
302
360
  * stays with that character, run ahead.
303
361
  */
304
362
  drawnWith(entityId) {
305
- if (kindOf.get(entityId) !== "body") return null;
363
+ if (!isBodyEntityKind(kindOf.get(entityId))) return null;
306
364
  const bodyIndex = simulation.bodyIndexById.get(entityId);
307
365
  if (bodyIndex === undefined) return null;
308
366
  const kindAnswer = kind.drawnWith?.(bodyIndex, opened.ownCharacterId, simulation.stepTools);
@@ -325,9 +383,13 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
325
383
  // The rules are read every step: a change of them is the word's to say at once.
326
384
  if (entityKindName === "rules") return false;
327
385
  // Groups change only when the game switches one, which the core already knows.
328
- if (entityKindName === "triangle_groups") return true;
329
- // A joint rests until a step ties or lets it go (setJoint from a character kind's step).
330
- 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
+ }
331
393
  if (entityKindName === "character") {
332
394
  const characterIndex = simulation.characterIndexById.get(entityId);
333
395
  return characterIndex !== undefined && simulation.isCharacterResting(characterIndex);
@@ -341,6 +403,8 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
341
403
  simulation.step({ tickIndex, timetableTickIndex, isReplay, isInCharge, inputOf, emit: emit ?? (() => {}), roomState: opened.roomState, ask, tell });
342
404
  const hits = simulation.takeHits();
343
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 });
344
408
  if (!isReplay) {
345
409
  for (const hit of hits) {
346
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 });
@@ -367,16 +431,35 @@ function openWorld({ plan, settings, kindSettings, ask, tell, tickDurationSec, i
367
431
  simulation.dispose();
368
432
  },
369
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
+ }
370
438
  /** Joints whose ends aren't here yet (a character that hasn't arrived): made as soon as they are. */
371
439
  const pendingJoints = new Map();
372
- /** Whether each joint held when it was last read: one that changed since doesn't rest. */
373
- 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 };
374
443
  function retryJoints() {
375
444
  for (const [jointId, pending] of pendingJoints) {
376
- 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 });
377
460
  }
378
461
  }
379
- 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));
380
463
  return opened;
381
464
  }
382
465
 
@@ -388,18 +471,21 @@ function worldFields(plan) {
388
471
  // A character first: a thing added with no kind named is one.
389
472
  character: { stateFields: plan.characterFields, hasInput: true },
390
473
  body: { stateFields: BODY_FIELDS },
474
+ ...Object.fromEntries(plan.ownFieldBehaviors.map((behavior) => [behavior.entityKindName, { stateFields: [...BODY_FIELDS, ...behavior.stateFields] }])),
391
475
  joint: { stateFields: JOINT_FIELDS },
392
476
  rules: { stateFields: plan.rulesFields },
393
477
  ...(hasTriangleGroups(world) ? { triangle_groups: { stateFields: TRIANGLE_GROUP_FIELDS } } : {}),
478
+ ...(world.zones.length ? { zone_switches: { stateFields: zoneMaskFieldsOf(world) } } : {}),
394
479
  },
395
480
  inputFields: plan.kind.inputFields,
396
481
  // The bodies that move, the joints, and the rules as the pieces have them: the same in every game, so nothing of
397
482
  // them is sent until it changes.
398
483
  entities: [
399
484
  { id: RULES_ID, entityKindName: "rules", state: { ...plan.defaultRules } },
400
- ...world.bodies.flatMap((body, bodyIndex) => (body.motionKind !== "fixed" ? [{ id: body.id, entityKindName: "body", state: declaredBodyFields(body, bodyIndex, body.bodyKindNumber, world) }] : [])),
401
- ...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) })),
402
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) }] : []),
403
489
  ],
404
490
  };
405
491
  }
@@ -450,8 +536,8 @@ function checkAddedBody(world, declaration) {
450
536
 
451
537
  /** A size's number on the wire: 0 for the world's own character's (null), then the world's characterSizes in order. */
452
538
  const sizeNumberOf = (world, characterSizeName) => {
453
- const sizeNumber = characterSizeName === null ? 0 : world.characterSizes.findIndex((size) => size.name === characterSizeName) + 1;
454
- if (sizeNumber === 0 && characterSizeName !== null) refuse("bad_argument", `characterSizeName is ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((size) => size.name).join(", ") || "it names none"}), or null for the world's own character.`);
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.`);
455
541
  return sizeNumber;
456
542
  };
457
543
  const layerNumberOf = (world, layerName, what) => {
@@ -461,7 +547,7 @@ const layerNumberOf = (world, layerName, what) => {
461
547
  };
462
548
 
463
549
  /** What setBody was given, as the body's fields. */
464
- function bodyChanges(world, changes) {
550
+ function bodyChanges(world, changes, behavior = null) {
465
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(", ")}.`);
466
552
  const fields = {};
467
553
  const { positionM, rotationDeg, velocityMPerSec, spinRadPerSec, motionKind, collisionLayerName } = changes ?? {};
@@ -479,6 +565,14 @@ function bodyChanges(world, changes) {
479
565
  // On the wire's grain, so every side weighs it the same.
480
566
  fields.massKg = Math.round(changes.massKg * 100) / 100;
481
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
+ }
482
576
  return fields;
483
577
  }
484
578
 
@@ -497,6 +591,8 @@ function bodyStateOf(simulation, bodyId) {
497
591
  collisionLayerName: simulation.world.collisionLayers[body.layerIndex].name,
498
592
  massKg: body.massKg ?? null,
499
593
  isResting: simulation.isBodyResting(bodyIndex),
594
+ bodyKindName: body.bodyKindName,
595
+ own: body.own ? { ...body.own } : null,
500
596
  riderCharacterIds: simulation.characters.filter((character) => character?.rideBodyIndex === bodyIndex).map((character) => character.id),
501
597
  };
502
598
  }
@@ -554,26 +650,48 @@ const ownOf = (plan, fields, simulation = null, characterId = null) => {
554
650
  /** What each query takes, beside collisionLayerNames and excludedId (and, for a shape, isStoppedAtPenetration, rotation and marginM). */
555
651
  const QUERY_KEYS = {
556
652
  castRay: ["fromM", "directionM", "maximumDistanceM"],
653
+ castRayAll: ["fromM", "directionM", "maximumDistanceM"],
557
654
  castBall: ["fromM", "radiusM", "directionM", "maximumDistanceM"],
558
655
  castCapsule: ["fromM", "radiusM", "heightM", "directionM", "maximumDistanceM"],
656
+ castBox: ["fromM", "sizeM", "directionM", "maximumDistanceM"],
559
657
  overlapCapsule: ["centerM", "radiusM", "heightM"],
560
658
  overlapBall: ["centerM", "radiusM"],
659
+ overlapBox: ["centerM", "sizeM"],
561
660
  };
562
661
  const SHAPE_QUERY_KEYS = ["isStoppedAtPenetration", "rotation", "marginM"];
563
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"];
564
679
 
565
680
  /**
566
681
  * A query's request, checked: the points and lengths a ray, a ball's sweep or an overlap takes. The request itself
567
682
  * goes on to the search, and checking it makes nothing: a game asks thousands a second.
568
683
  */
569
- function checkQuery(given, what, isShape = false) {
684
+ function checkQuery(given, what) {
570
685
  const keys = QUERY_KEYS[what];
686
+ const optionKeys = QUERY_OPTION_KEYS[what];
571
687
  if (given === null || typeof given !== "object") refuse("bad_argument", `${what} takes an object.`, what, `Give { ${keys.join(", ")} }.`);
572
- 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.`);
573
689
  for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
574
690
  const key = keys[keyIndex];
575
691
  const givenValue = given[key];
576
- 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.");
577
695
  else if (!Number.isFinite(givenValue) || givenValue < 0) refuse("bad_argument", `${key} is ${JSON.stringify(givenValue)}.`, key, "Give a length in metres from 0.");
578
696
  }
579
697
  return given;
@@ -581,7 +699,7 @@ function checkQuery(given, what, isShape = false) {
581
699
 
582
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. */
583
701
  function shapeQueryOf(request, what) {
584
- const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what, true);
702
+ const { isStoppedAtPenetration, rotation, marginM } = checkQuery(request, what);
585
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.");
586
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.");
587
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.");
@@ -613,6 +731,46 @@ function queryCalls(simulationNow) {
613
731
  },
614
732
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
615
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
+ },
616
774
  };
617
775
  }
618
776
 
@@ -621,6 +779,10 @@ function queryCalls(simulationNow) {
621
779
  * online core's World gives it (ids, has, entityKindName, state, drawn, add, remove, set, setInput, on, simulation),
622
780
  * and the rest says who this game is in it.
623
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
+
624
786
  function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharge, isReady, hasGameServer, tickNumber }) {
625
787
  const { world, kind } = plan;
626
788
  const listeners = Object.fromEntries(LISTENED_EVENT_NAMES.map((eventName) => [eventName, new Set()]));
@@ -632,17 +794,17 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
632
794
  things.on("added", (id) => {
633
795
  const entityKindName = things.entityKindName(id);
634
796
  kindById.set(id, entityKindName);
635
- if (entityKindName === "body") telling("bodyAdded", id);
797
+ if (isBodyEntityKind(entityKindName)) telling("bodyAdded", id);
636
798
  else if (entityKindName === "character") telling("characterAdded", id);
637
799
  });
638
800
  things.on("removed", (id) => {
639
801
  const entityKindName = kindById.get(id);
640
802
  kindById.delete(id);
641
- if (entityKindName === "body") telling("bodyRemoved", id);
803
+ if (isBodyEntityKind(entityKindName)) telling("bodyRemoved", id);
642
804
  else if (entityKindName === "character") telling("characterRemoved", id);
643
805
  });
644
806
  const simulationNow = () => things.simulation?.simulation ?? null;
645
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
807
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
646
808
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
647
809
  /** The world's calls where this game runs it; a refusal with a game server, and null where another player's game does. */
648
810
  const inCharge = (what) => {
@@ -661,6 +823,11 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
661
823
  const declaration = isFixedBody(world, bodyId) ? world.bodyById.get(bodyId) : null;
662
824
  return declaration ? { x: declaration.positionM.x, y: declaration.positionM.y, z: declaration.positionM.z, rotation: declaration.rotation } : null;
663
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
+ };
664
831
  const shared = sharedCalls({ plan, things, simulationNow, inChargeOf: inCharge });
665
832
 
666
833
  const calls = {
@@ -691,7 +858,7 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
691
858
  /** Where to draw a body this frame: { positionM, rotation, steerNumber }. null for a body that isn't here. */
692
859
  drawnBody(bodyId) {
693
860
  const drawn = drawnOf(bodyId);
694
- 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;
695
862
  },
696
863
  /** Puts a three.js object (anything with position.set and quaternion.set) where a body is drawn this frame. */
697
864
  applyTo(object3d, bodyId) {
@@ -737,13 +904,14 @@ function physicsCalls({ plan, settings, hooks, things, ownCharacterId, isInCharg
737
904
  */
738
905
  function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
739
906
  const { world, kind } = plan;
740
- const isBody = (bodyId) => things.entityKindName(bodyId) === "body";
907
+ const isBody = (bodyId) => isBodyEntityKind(things.entityKindName(bodyId));
741
908
  const isCharacter = (characterId) => things.entityKindName(characterId) === "character";
742
909
  const isJoint = (jointId) => things.entityKindName(jointId) === "joint";
743
910
  // Every thing in play, declared ones included: an id freed by a removal may be used again, even in the same step.
744
911
  const ids = () => new Set(things.ids());
912
+ const movingBodyIds = () => (plan.bodyEntityKindNames.length === 1 ? things.ids("body") : plan.bodyEntityKindNames.flatMap((entityKindName) => things.ids(entityKindName)));
745
913
  return {
746
- bodyIds: () => [...world.fixedBodyIds, ...things.ids("body")],
914
+ bodyIds: () => [...world.fixedBodyIds, ...movingBodyIds()],
747
915
  hasBody: (bodyId) => isBody(bodyId) || isFixedBody(world, bodyId),
748
916
  /** A body as this world has it now. */
749
917
  bodyState: (bodyId) => bodyStateOf(simulationNow(), bodyId),
@@ -752,17 +920,18 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
752
920
  const running = inChargeOf("bodies are added");
753
921
  const checked = checkAddedBody(world, declaration);
754
922
  if (!running || ids().has(checked.id)) return false;
755
- 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.");
756
- 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) } }));
757
925
  },
758
926
  removeBody: (bodyId) => Boolean(inChargeOf("bodies are removed") && isBody(bodyId) && things.remove(bodyId)),
759
927
  /** Sets a body's place, rotation, speed or spin at once (a teleport), how it moves (motionKind), or its collision layer. */
760
928
  setBody(bodyId, changes) {
761
929
  const running = inChargeOf("bodies are set");
762
- const fields = bodyChanges(world, changes);
930
+ const behavior = plan.bodyBehaviors?.[simulationNow()?.bodies[simulationNow().bodyIndexById.get(bodyId)]?.declaration.bodyKindNumber] ?? null;
931
+ const fields = bodyChanges(world, changes, behavior);
763
932
  if (!isBody(bodyId)) return world.bodyById.has(bodyId) ? false : unknownBody(bodyId);
764
933
  const isMoved = ["x", "y", "z", "rotation"].some((name) => name in fields);
765
- if (world.bodyById.get(bodyId)?.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.");
766
935
  return Boolean(running && running.set(bodyId, fields, { isTeleport: isMoved }));
767
936
  },
768
937
  pushBody(bodyId, pushMPerSec) {
@@ -836,18 +1005,30 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
836
1005
  if (!running || ids().has(checked.id)) return false;
837
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.");
838
1007
  const { id, ...entityData } = declaration;
839
- 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 }));
840
1009
  },
841
1010
  removeJoint: (jointId) => Boolean(inChargeOf("joints are removed") && isJoint(jointId) && things.remove(jointId)),
842
- /** 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). */
843
1012
  setJoint(jointId, changes) {
844
1013
  const running = inChargeOf("joints are set");
845
- for (const key of Object.keys(changes ?? {})) if (key !== "isEnabled") refuse("unknown_argument", `setJoint has no "${key}".`, key, "It takes: isEnabled.");
846
- 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.");
847
1018
  if (!isJoint(jointId)) refuse("unknown_joint", `There's no joint ${JSON.stringify(jointId)} here.`, "jointId", "Give the id of a joint in jointIds().");
848
- 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 }));
849
1025
  },
850
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
+ },
851
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. */
852
1033
  setTriangleGroup(groupNumber, isEnabled) {
853
1034
  const running = inChargeOf("triangle groups are switched");
@@ -859,6 +1040,28 @@ function sharedCalls({ plan, things, simulationNow, inChargeOf }) {
859
1040
  const bitNumber = triangleGroupBitNumberOf(groupNumber);
860
1041
  return Boolean(running && running.set(TRIANGLE_GROUPS_ID, { [maskName]: isEnabled ? maskNumber & ~bitNumber : maskNumber | bitNumber }, { isTeleport: false }));
861
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
+ },
862
1065
  /** Whether a triangle group is there now. */
863
1066
  isTriangleGroupEnabled: (groupNumber) => !((things.state(TRIANGLE_GROUPS_ID)?.[TRIANGLE_GROUP_MASK_NAMES[triangleGroupMaskIndexOf(groupNumber)]] ?? 0) & triangleGroupBitNumberOf(groupNumber)),
864
1067
  };
@@ -873,10 +1076,10 @@ const kindOf = (characters) => (characters === undefined ? walkingCharacters() :
873
1076
  * createNet(room).use and defineNetServer's kinds.
874
1077
  */
875
1078
  export const physicsKindFrom = (worldKind) => (givenWorld, given = {}) => {
876
- 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.");
877
1080
  const world = worldOf(givenWorld);
878
1081
  const kind = kindOf(given.characters);
879
- const plan = worldPlan(world, kind);
1082
+ const plan = worldPlan(world, kind, defineBodyBehaviors(given.bodies, world));
880
1083
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: given.settings, hooks: given.hooks });
881
1084
  const nextStart = startStates(world);
882
1085
  const physicsWorldKind = worldKind({
@@ -985,10 +1188,10 @@ function copyMotion(into, read, rest) {
985
1188
  * A world played alone: the same calls over the same simulation, stepped here with no room. update(nowMs) runs the
986
1189
  * fixed steps that are due on the clock it's given.
987
1190
  */
988
- 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 }) {
989
1192
  const world = worldOf(givenWorld);
990
1193
  const kind = kindOf(characters);
991
- const plan = worldPlan(world, kind);
1194
+ const plan = worldPlan(world, kind, defineBodyBehaviors(bodies, world));
992
1195
  const { settings, hooks, ask, tell } = openPiece(statement, { settings: givenSettings, hooks: givenHooks });
993
1196
  const tickDurationSec = 1 / ticksPerSec;
994
1197
  const opened = openWorld({ plan, settings, kindSettings: kind.settings ?? null, ask, tell, tickDurationSec, isInChargeAtFirst: true });
@@ -1007,6 +1210,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1007
1210
  let ranTickCount = 0;
1008
1211
  /** Puts a thing's fields on their steps, as online: the same numbers alone as in a room. */
1009
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 }]));
1010
1215
 
1011
1216
  const things = {
1012
1217
  simulation: opened,
@@ -1077,7 +1282,8 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1077
1282
  const read = opened.read(id);
1078
1283
  if (!read) return;
1079
1284
  let onStepsRead;
1080
- 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) {
1081
1287
  // The step left it on the wire's steps already: nothing to round and nothing to write back, so a
1082
1288
  // thousand bodies falling leave nothing for the garbage collector. Its fields go into one of two
1083
1289
  // objects of its own, turn about (nothing outside keeps them).
@@ -1087,12 +1293,34 @@ export function alonePhysics(givenWorld, { settings: givenSettings, hooks: given
1087
1293
  }
1088
1294
  onStepsRead = entity.later === entity.ownFirst ? entity.ownSecond : entity.ownFirst;
1089
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
+ }
1090
1307
  } else {
1091
- 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);
1092
1320
  // As online, every place steps on the wire's numbers.
1093
1321
  steppedWriteInfo.isResting = isResting;
1094
1322
  opened.write(id, onStepsRead, steppedWriteInfo);
1095
- if (entity.entityKindName === "body") {
1323
+ if (isBodyEntityKind(entity.entityKindName)) {
1096
1324
  entity.readLayerNumber = read.layerNumber;
1097
1325
  entity.readMotionNumber = read.motionNumber;
1098
1326
  entity.readSteerNumber = read.steerNumber;