@zaisma/physics 2.4.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/declare.js CHANGED
@@ -16,10 +16,14 @@ export const JOINT_KINDS = ["fixed", "ball", "hinge", "slider", "spring", "rope"
16
16
  export const PLAYER_CHARACTER_MODES = ["on_join", "by_game"];
17
17
  const ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
18
18
 
19
- /** Bodies one world holds at most, declared and added while playing together. */
20
- export const MAXIMUM_BODY_COUNT = 1000;
19
+ /** Bodies that move or may (moving and kinematic ones, and every body added while playing) one world holds at most. */
20
+ export const MAXIMUM_BODY_COUNT = 2000;
21
+ /** Bodies declared fixed one world holds at most: a level's pieces, which never move and are never sent. */
22
+ export const MAXIMUM_FIXED_BODY_COUNT = 20_000;
21
23
  /** Characters one world holds at most: players' and bots'. */
22
- export const MAXIMUM_CHARACTER_COUNT = 64;
24
+ export const MAXIMUM_CHARACTER_COUNT = 250;
25
+ /** Sizes of character a world names at most, beside its own character's. */
26
+ export const MAXIMUM_CHARACTER_SIZE_COUNT = 31;
23
27
  const MAXIMUM_SHAPE_COUNT = 16;
24
28
  const MAXIMUM_HULL_POINT_COUNT = 255;
25
29
  const MAXIMUM_MESH_TRIANGLE_COUNT = 50_000;
@@ -31,6 +35,8 @@ const MAXIMUM_HEIGHTFIELD_SIDE_COUNT = 4096;
31
35
  export const MAXIMUM_COLLISION_LAYER_COUNT = 16;
32
36
  /** Joints one world holds at most, declared and added while playing together. */
33
37
  export const MAXIMUM_JOINT_COUNT = 1000;
38
+ /** Bodies that aren't fixed and joints a world declares together at most: what the online core takes from the start. More come while playing, with addBody and addJoint. */
39
+ export const MAXIMUM_DECLARED_THING_COUNT = 2048;
34
40
  const MAXIMUM_WHEEL_COUNT = 8;
35
41
  const MAXIMUM_SEAT_COUNT = 8;
36
42
  /** The layer a character riding in a seat is on: it touches nothing, not its seat nor the body under it. */
@@ -42,22 +48,52 @@ export const WORLD_REACH_M = 10_000;
42
48
  /** How heavy a cubic metre of a body is when it doesn't say its mass: furniture is mostly air. */
43
49
  export const DEFAULT_DENSITY_KG_PER_M3_NUMBER = 250;
44
50
 
45
- const WORLD_KEYS = ["bodies", "bodyKinds", "character", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "joints", "substepCount", "groundReachM"];
46
- const BODY_KEYS = ["id", "bodyKindName", "motionKind", "positionM", "rotationDeg", "massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
51
+ const WORLD_KEYS = ["bodies", "bodyKinds", "character", "characterSizes", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "surfaceNames", "joints", "substepCount", "groundReachM"];
52
+ const BODY_KEYS = ["id", "bodyKindName", "motionKind", "positionM", "rotationDeg", "massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats", "timetable"];
47
53
  const BODY_KIND_KEYS = ["massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
48
54
  const WHEEL_KEYS = ["positionM", "radiusM", "suspensionRestM", "suspensionTravelM", "isSteered", "isDriven"];
49
55
  const VEHICLE_KEYS = ["maximumEngineForceNewtons", "maximumBrakeForceNewtons", "maximumSteerDeg", "suspensionStiffnessNumber", "suspensionDampingNumber", "frictionSlipNumber", "sideFrictionNumber", "maximumSuspensionForceNewtons", "wheelCollisionLayerNames"];
50
56
  const SEAT_KEYS = ["positionM", "facingYawDeg"];
57
+ const TIMETABLE_KEYS = ["stops", "repeatMode", "easeKind"];
58
+ const TIMETABLE_STOP_KEYS = ["positionM", "rotationDeg", "travelDurationSec", "waitDurationSec"];
59
+ /** What a timetable does after its last stop: goes on to its first again, runs back the way it came, or stays. */
60
+ export const TIMETABLE_REPEAT_MODES = ["loop", "back_and_forth", "once"];
61
+ /** How a body goes from a stop to the next: at one speed, or easing out of one and into the other. */
62
+ export const TIMETABLE_EASE_KINDS = ["linear", "smooth"];
63
+ /** Stops one timetable has at most. */
64
+ export const MAXIMUM_TIMETABLE_STOP_COUNT = 32;
65
+ /**
66
+ * The grain of a timetable's places: the wire's own for a place (a millimetre). A character carried by a body moves
67
+ * by whole steps of it, so being put on the wire's steps every step never leaves it behind.
68
+ */
69
+ const TIMETABLE_STEPS_PER_M = 1000;
70
+ /** The longest a trip between two stops, or a wait at one, lasts, in seconds. */
71
+ export const MAXIMUM_TIMETABLE_DURATION_SEC = 3600;
51
72
  const JOINT_KEYS = ["id", "jointKind", "bodyId", "otherBodyId", "anchorM", "otherAnchorM", "axis", "minimumNumber", "maximumNumber", "restLengthM", "stiffnessNumber", "dampingNumber"];
52
73
  const COLLISION_LAYER_KEYS = ["touches"];
53
74
  const DATA_PATH_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_./-]{0,199}$/;
54
75
  const BODY_KIND_NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
55
76
  /** Kinds of body one world declares at most. */
56
77
  export const MAXIMUM_BODY_KIND_COUNT = 250;
57
- const SHAPE_KEYS = ["shapeKind", "sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", "triangleGroupNumbers", "positionM", "rotationDeg", "dataPath", "heightsM", "rowCount", "columnCount", "cellSizeM"];
78
+ const SHAPE_KEYS = ["shapeKind", "sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", "triangleGroupNumbers", "triangleGroups", "triangleSurfaceIndices", "surfaceName", "positionM", "rotationDeg", "dataPath", "heightsM", "rowCount", "columnCount", "cellSizeM"];
79
+ const TRIANGLE_GROUP_KEYS = ["groupNumber", "collisionLayerName"];
58
80
  /** A mesh's triangle groups a world switches on and off while playing (doors, bridges): numbered 1 to this; 0 is always there. */
59
- export const MAXIMUM_TRIANGLE_GROUP_NUMBER = 31;
81
+ export const MAXIMUM_TRIANGLE_GROUP_NUMBER = 63;
82
+ /**
83
+ * Which groups are off travels as whole numbers with a bit for each group, and a whole number on the wire holds 31
84
+ * bits: so three of them, 21 groups each. Group 1 is the first's lowest bit.
85
+ */
86
+ export const TRIANGLE_GROUP_MASK_COUNT = 3;
87
+ const TRIANGLE_GROUP_MASK_BIT_COUNT = 21;
88
+ export const MAXIMUM_TRIANGLE_GROUP_MASK_NUMBER = 2 ** TRIANGLE_GROUP_MASK_BIT_COUNT - 1;
89
+ /** Which of the masks a group's bit is in, from 0. */
90
+ export const triangleGroupMaskIndexOf = (groupNumber) => Math.floor((groupNumber - 1) / TRIANGLE_GROUP_MASK_BIT_COUNT);
91
+ /** A group's bit in its mask. */
92
+ export const triangleGroupBitNumberOf = (groupNumber) => 1 << ((groupNumber - 1) % TRIANGLE_GROUP_MASK_BIT_COUNT);
93
+ /** Surfaces one world names at most (what a hit says it met: concrete, metal, water). */
94
+ export const MAXIMUM_SURFACE_COUNT = 255;
60
95
  const CHARACTER_KEYS = ["heightM", "radiusM", "stepHeightM", "maximumSlopeDeg"];
96
+ const CHARACTER_SIZE_KEYS = ["name", ...CHARACTER_KEYS];
61
97
 
62
98
  const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
63
99
  const isFiniteNumber = (given) => typeof given === "number" && Number.isFinite(given);
@@ -109,13 +145,115 @@ function lengthOf(given, code, what, { minimumM = 0.01, maximumM = WORLD_REACH_M
109
145
  return given;
110
146
  }
111
147
 
148
+ function timetableDurationOf(given, minimumSec, what, fix) {
149
+ if (!isFiniteNumber(given) || given < minimumSec || given > MAXIMUM_TIMETABLE_DURATION_SEC) refuse("bad_body", `${what} is ${JSON.stringify(given)}.`, what, fix);
150
+ return given;
151
+ }
152
+
153
+ /**
154
+ * A kinematic body's timetable, checked: the stops it goes between and how long each trip and wait lasts, so where
155
+ * it is at any step is the same in every game and on the game server, and nothing of it is sent. Answers
156
+ * { repeatMode, easeKind, stops, legs, durationSec }: each stop's place and rotation, and one round's legs (a trip
157
+ * from a stop to another, or a wait at one) with when each starts.
158
+ */
159
+ function timetableOf(given, positionM, rotation, motionKind, what) {
160
+ if (given === undefined || given === null) return null;
161
+ if (motionKind !== "kinematic") refuse("bad_body", `${what} is on a body that's ${motionKind}.`, what, 'Give the body motionKind "kinematic": a timetable moves it, whatever it meets.');
162
+ if (!isPlainObject(given)) refuse("bad_body", `${what} isn't a timetable.`, what, "Give { stops: [{ positionM }, { positionM, travelDurationSec: 4 }] }.");
163
+ refuseUnknownKeys(given, TIMETABLE_KEYS, "bad_body", what);
164
+ const { repeatMode = "loop", easeKind = "linear" } = given;
165
+ if (!TIMETABLE_REPEAT_MODES.includes(repeatMode)) refuse("bad_body", `${what}.repeatMode is ${JSON.stringify(repeatMode)}.`, `${what}.repeatMode`, `Use: ${TIMETABLE_REPEAT_MODES.join(", ")}.`);
166
+ if (!TIMETABLE_EASE_KINDS.includes(easeKind)) refuse("bad_body", `${what}.easeKind is ${JSON.stringify(easeKind)}.`, `${what}.easeKind`, `Use: ${TIMETABLE_EASE_KINDS.join(", ")}.`);
167
+ if (!Array.isArray(given.stops) || given.stops.length < 2 || given.stops.length > MAXIMUM_TIMETABLE_STOP_COUNT) refuse("bad_body", `${what}.stops isn't a list of 2 to ${MAXIMUM_TIMETABLE_STOP_COUNT} stops.`, `${what}.stops`, "Give each place it stops at, in the order it visits them.");
168
+ const isLoop = repeatMode === "loop";
169
+ const stops = given.stops.map((stop, stopIndex) => {
170
+ const stopWhat = `${what}.stops[${stopIndex}]`;
171
+ if (!isPlainObject(stop)) refuse("bad_body", `${stopWhat} isn't a stop.`, stopWhat, "Give { positionM, rotationDeg, travelDurationSec, waitDurationSec }: any left out is the body's own place or turn, and no wait.");
172
+ refuseUnknownKeys(stop, TIMETABLE_STOP_KEYS, "bad_body", stopWhat);
173
+ // The first stop's trip is the one back to it from the last, which only a loop makes.
174
+ const hasTrip = stopIndex > 0 || isLoop;
175
+ if (!hasTrip && stop.travelDurationSec !== undefined) refuse("bad_body", `${stopWhat} is the first stop and has a travelDurationSec.`, `${stopWhat}.travelDurationSec`, 'Leave it out: only a timetable with repeatMode "loop" travels to its first stop, from its last.');
176
+ const place = pointOf(stop.positionM, positionM, "bad_body", `${stopWhat}.positionM`);
177
+ const turn = stop.rotationDeg === undefined ? rotation : rotationOf(stop.rotationDeg, "bad_body", `${stopWhat}.rotationDeg`);
178
+ return {
179
+ x: place.x,
180
+ y: place.y,
181
+ z: place.z,
182
+ // On the engine's own grain, so every side starts from the same numbers.
183
+ rotation: { x: Math.fround(turn.x), y: Math.fround(turn.y), z: Math.fround(turn.z), w: Math.fround(turn.w) },
184
+ travelDurationSec: hasTrip ? timetableDurationOf(stop.travelDurationSec, 0.01, `${stopWhat}.travelDurationSec`, `Give how long the trip to this stop takes in seconds, from 0.01 to ${MAXIMUM_TIMETABLE_DURATION_SEC}.`) : 0,
185
+ waitDurationSec: stop.waitDurationSec === undefined ? 0 : timetableDurationOf(stop.waitDurationSec, 0, `${stopWhat}.waitDurationSec`, `Give how long it waits at this stop in seconds, from 0 to ${MAXIMUM_TIMETABLE_DURATION_SEC}, or leave it out for no wait.`),
186
+ };
187
+ });
188
+ const legs = [];
189
+ let durationSec = 0;
190
+ const addLeg = (fromStopIndex, toStopIndex, legDurationSec) => {
191
+ if (legDurationSec <= 0) return;
192
+ legs.push({ fromStopIndex, toStopIndex, startSec: durationSec, durationSec: legDurationSec });
193
+ durationSec += legDurationSec;
194
+ };
195
+ const lastStopIndex = stops.length - 1;
196
+ for (let stopIndex = 0; stopIndex <= lastStopIndex; stopIndex += 1) {
197
+ if (stopIndex > 0) addLeg(stopIndex - 1, stopIndex, stops[stopIndex].travelDurationSec);
198
+ addLeg(stopIndex, stopIndex, stops[stopIndex].waitDurationSec);
199
+ }
200
+ if (isLoop) addLeg(lastStopIndex, 0, stops[0].travelDurationSec);
201
+ // Back the way it came, each trip as long as it was, waiting again at each stop between.
202
+ if (repeatMode === "back_and_forth") {
203
+ for (let stopIndex = lastStopIndex; stopIndex > 0; stopIndex -= 1) {
204
+ addLeg(stopIndex, stopIndex - 1, stops[stopIndex].travelDurationSec);
205
+ if (stopIndex > 1) addLeg(stopIndex - 1, stopIndex - 1, stops[stopIndex - 1].waitDurationSec);
206
+ }
207
+ }
208
+ return { repeatMode, easeKind, stops, legs, durationSec };
209
+ }
210
+
211
+ /**
212
+ * Where a timetable has its body, clockSec after it started (a room's step index times a step's length): written
213
+ * into { x, y, z, rotationX, rotationY, rotationZ, rotationW } and answered, its place on the wire's millimetres.
214
+ * Only adding, multiplying, rounding and a square root, so every browser and the game server get the same numbers.
215
+ */
216
+ export function timetablePlaceInto(timetable, clockSec, into) {
217
+ const { legs, stops, durationSec } = timetable;
218
+ let roundSec = 0;
219
+ if (clockSec > 0) roundSec = timetable.repeatMode === "once" ? Math.min(clockSec, durationSec) : clockSec - Math.floor(clockSec / durationSec) * durationSec;
220
+ let leg = legs[legs.length - 1];
221
+ for (let legIndex = 0; legIndex < legs.length; legIndex += 1) {
222
+ if (roundSec < legs[legIndex].startSec + legs[legIndex].durationSec) {
223
+ leg = legs[legIndex];
224
+ break;
225
+ }
226
+ }
227
+ let shareNumber = Math.min(Math.max((roundSec - leg.startSec) / leg.durationSec, 0), 1);
228
+ if (timetable.easeKind === "smooth") shareNumber = shareNumber * shareNumber * (3 - 2 * shareNumber);
229
+ const from = stops[leg.fromStopIndex];
230
+ const to = stops[leg.toStopIndex];
231
+ into.x = Math.round((from.x + (to.x - from.x) * shareNumber) * TIMETABLE_STEPS_PER_M) / TIMETABLE_STEPS_PER_M;
232
+ into.y = Math.round((from.y + (to.y - from.y) * shareNumber) * TIMETABLE_STEPS_PER_M) / TIMETABLE_STEPS_PER_M;
233
+ into.z = Math.round((from.z + (to.z - from.z) * shareNumber) * TIMETABLE_STEPS_PER_M) / TIMETABLE_STEPS_PER_M;
234
+ // The shorter way round, straight between the two rotations and brought back to length: even for a quarter turn or less.
235
+ const fromRotation = from.rotation;
236
+ const toRotation = to.rotation;
237
+ const signNumber = fromRotation.x * toRotation.x + fromRotation.y * toRotation.y + fromRotation.z * toRotation.z + fromRotation.w * toRotation.w < 0 ? -1 : 1;
238
+ const rotationX = fromRotation.x + (toRotation.x * signNumber - fromRotation.x) * shareNumber;
239
+ const rotationY = fromRotation.y + (toRotation.y * signNumber - fromRotation.y) * shareNumber;
240
+ const rotationZ = fromRotation.z + (toRotation.z * signNumber - fromRotation.z) * shareNumber;
241
+ const rotationRealNumber = fromRotation.w + (toRotation.w * signNumber - fromRotation.w) * shareNumber;
242
+ const lengthNumber = Math.sqrt(rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ + rotationRealNumber * rotationRealNumber) || 1;
243
+ into.rotationX = rotationX / lengthNumber;
244
+ into.rotationY = rotationY / lengthNumber;
245
+ into.rotationZ = rotationZ / lengthNumber;
246
+ into.rotationW = rotationRealNumber / lengthNumber;
247
+ return into;
248
+ }
249
+
112
250
  /** One shape of a body, checked. Answers it with how much room it takes, for a body's mass when it gives none. */
113
251
  function shapeOf(given, isFixed, what) {
114
252
  refuseUnknownKeys(given, SHAPE_KEYS, "bad_body", what);
115
253
  const { shapeKind } = given;
116
254
  if (!SHAPE_KINDS.includes(shapeKind)) refuse("bad_body", `${what}.shapeKind is ${JSON.stringify(shapeKind)}.`, `${what}.shapeKind`, `Use: ${SHAPE_KINDS.join(", ")}.`);
117
255
  if (shapeKind === "heightfield" || (shapeKind === "mesh" && given.dataPath !== undefined)) return groundShapeOf(given, isFixed, what);
118
- if (shapeKind !== "mesh" && given.triangleGroupNumbers !== undefined) refuse("bad_body", `${what} is a ${shapeKind}, which has no triangleGroupNumbers.`, `${what}.triangleGroupNumbers`, "Only a mesh's triangles come in groups.");
256
+ for (const key of ["triangleGroupNumbers", "triangleGroups", "triangleSurfaceIndices"]) if (shapeKind !== "mesh" && given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, key === "triangleSurfaceIndices" ? "Only a mesh says its surface triangle by triangle: give this shape a surfaceName." : "Only a mesh's triangles come in groups.");
119
257
  for (const key of ["dataPath", "heightsM", "rowCount", "columnCount", "cellSizeM"]) if (given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, key === "dataPath" ? "Only a mesh or a heightfield is read from a data file." : "rowCount, columnCount, cellSizeM and heightsM are a heightfield's.");
120
258
  const takes = { box: ["sizeM"], ball: ["radiusM"], capsule: ["radiusM", "heightM"], cylinder: ["radiusM", "heightM"], hull: ["pointsM"], mesh: ["pointsM", "triangleIndices"] }[shapeKind];
121
259
  for (const key of ["sizeM", "radiusM", "heightM", "pointsM", "triangleIndices"]) {
@@ -123,7 +261,7 @@ function shapeOf(given, isFixed, what) {
123
261
  refuse("bad_body", takes.includes(key) ? `${what} is a ${shapeKind} with no ${key}.` : `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, `A ${shapeKind} takes: ${takes.join(", ")}.`);
124
262
  }
125
263
  }
126
- const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
264
+ const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, triangleGroups: null, triangleSurfaceIndices: null, surfaceName: surfaceNameOf(given.surfaceName, what), dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
127
265
  let volumeNumber = 0;
128
266
  if (shapeKind === "box") {
129
267
  if (!isPlainObject(given.sizeM)) refuse("bad_body", `${what}.sizeM isn't a size.`, `${what}.sizeM`, "Give { x, y, z }: how wide, tall and deep the box is, in metres.");
@@ -170,12 +308,65 @@ function shapeOf(given, isFixed, what) {
170
308
  }
171
309
  shape.triangleIndices = isTypedIndices ? indices : indices.slice();
172
310
  shape.triangleGroupNumbers = triangleGroupsOf(given.triangleGroupNumbers, indices.length / 3, what);
311
+ shape.triangleGroups = groupLayersOf(given.triangleGroups, shape.triangleGroupNumbers, what);
312
+ shape.triangleSurfaceIndices = triangleSurfacesOf(given.triangleSurfaceIndices, indices.length / 3, given.surfaceName, what);
173
313
  }
174
314
  }
175
315
  return { shape, volumeNumber };
176
316
  }
177
317
 
178
- /** A mesh's triangle groups, checked: one number a triangle, 0 (always there) or a group from 1 to 31 the world switches. */
318
+ /** A shape's surfaceName, checked: one of the world's surfaceNames (which the world checks), or left out. */
319
+ function surfaceNameOf(given, what) {
320
+ if (given === undefined || given === null) return null;
321
+ if (typeof given !== "string" || !BODY_KIND_NAME_PATTERN.test(given)) refuse("bad_body", `${what}.surfaceName is ${JSON.stringify(given)}.`, `${what}.surfaceName`, 'Give one of the world\'s surfaceNames, like "metal", or leave it out.');
322
+ return given;
323
+ }
324
+
325
+ /** A mesh's surface triangle by triangle, checked: for each triangle, which of the world's surfaceNames it is, from 0. */
326
+ function triangleSurfacesOf(given, triangleCount, surfaceName, what) {
327
+ if (given === undefined) return null;
328
+ if (surfaceName !== undefined && surfaceName !== null) refuse("bad_body", `${what} has a surfaceName and triangleSurfaceIndices.`, `${what}.triangleSurfaceIndices`, "Give one: surfaceName for a mesh that's one surface all over, or triangleSurfaceIndices for one that isn't.");
329
+ const isList = Array.isArray(given) || given instanceof Uint8Array;
330
+ if (!isList || given.length !== triangleCount || Array.prototype.some.call(given, (surfaceIndex) => !Number.isInteger(surfaceIndex) || surfaceIndex < 0 || surfaceIndex >= MAXIMUM_SURFACE_COUNT)) {
331
+ refuse("bad_body", `${what}.triangleSurfaceIndices isn't a surface for each of its ${triangleCount} triangles.`, `${what}.triangleSurfaceIndices`, "Give one number a triangle (a list or a Uint8Array): which of the world's surfaceNames the triangle is, from 0.");
332
+ }
333
+ return given instanceof Uint8Array ? given : Uint8Array.from(given);
334
+ }
335
+
336
+ /** A mesh's triangleGroups, checked: the groups that are on a collision layer of their own, [{ groupNumber, collisionLayerName }]. */
337
+ function groupLayersOf(given, groupNumbers, what) {
338
+ if (given === undefined) return null;
339
+ const fix = `Give the groups that aren't on the body's own collision layer, like [{ groupNumber: 4, collisionLayerName: "glass" }]: groupNumber from 0 (the triangles always there) to ${MAXIMUM_TRIANGLE_GROUP_NUMBER}, each once.`;
340
+ if (!groupNumbers) refuse("bad_body", `${what} has triangleGroups and no triangleGroupNumbers.`, `${what}.triangleGroups`, "Give triangleGroupNumbers too: the group each triangle is in.");
341
+ if (!Array.isArray(given) || given.length > MAXIMUM_TRIANGLE_GROUP_NUMBER + 1) refuse("bad_body", `${what}.triangleGroups isn't a list of groups.`, `${what}.triangleGroups`, fix);
342
+ const seenNumbers = new Set();
343
+ return given.map((group, groupIndex) => {
344
+ refuseUnknownKeys(group, TRIANGLE_GROUP_KEYS, "bad_body", `${what}.triangleGroups[${groupIndex}]`);
345
+ const { groupNumber, collisionLayerName } = group;
346
+ if (!Number.isInteger(groupNumber) || groupNumber < 0 || groupNumber > MAXIMUM_TRIANGLE_GROUP_NUMBER || seenNumbers.has(groupNumber)) refuse("bad_body", `${what}.triangleGroups[${groupIndex}].groupNumber is ${JSON.stringify(groupNumber)}.`, `${what}.triangleGroups[${groupIndex}].groupNumber`, fix);
347
+ if (typeof collisionLayerName !== "string" || !BODY_KIND_NAME_PATTERN.test(collisionLayerName)) refuse("bad_body", `${what}.triangleGroups[${groupIndex}].collisionLayerName is ${JSON.stringify(collisionLayerName)}.`, `${what}.triangleGroups[${groupIndex}].collisionLayerName`, "Give the name of one of the world's collisionLayers.");
348
+ seenNumbers.add(groupNumber);
349
+ return { groupNumber, collisionLayerName };
350
+ });
351
+ }
352
+
353
+ /**
354
+ * A body's names, checked against its world's: the collision layers its mesh's groups are on, and its shapes'
355
+ * surfaces. For a declared body as the world is defined, and for one added while playing.
356
+ */
357
+ export function checkBodyNames(body, what, world) {
358
+ const layerNames = world.collisionLayers.map((layer) => layer.name);
359
+ for (const [shapeIndex, shape] of body.shapes.entries()) {
360
+ const shapeWhat = `${what}.shapes[${shapeIndex}]`;
361
+ if (shape.surfaceName !== null && shape.surfaceName !== undefined && !world.surfaceNames.includes(shape.surfaceName)) refuse("bad_body", `${shapeWhat}.surfaceName is "${shape.surfaceName}".`, `${shapeWhat}.surfaceName`, world.surfaceNames.length ? `Use one of the world's surfaceNames: ${world.surfaceNames.join(", ")}.` : 'Name the world\'s surfaces first, like surfaceNames: ["concrete", "metal"].');
362
+ if (shape.triangleSurfaceIndices && Array.prototype.some.call(shape.triangleSurfaceIndices, (surfaceIndex) => surfaceIndex >= world.surfaceNames.length)) refuse("bad_body", `${shapeWhat}.triangleSurfaceIndices names a surface the world doesn't have.`, `${shapeWhat}.triangleSurfaceIndices`, `Give numbers from 0 to ${world.surfaceNames.length - 1}: the world has ${world.surfaceNames.length} surfaceNames.`);
363
+ for (const [groupIndex, group] of (shape.triangleGroups ?? []).entries()) {
364
+ if (!layerNames.includes(group.collisionLayerName) || group.collisionLayerName === RIDING_LAYER_NAME) refuse("bad_body", `${shapeWhat}.triangleGroups[${groupIndex}].collisionLayerName is "${group.collisionLayerName}".`, `${shapeWhat}.triangleGroups[${groupIndex}].collisionLayerName`, `Use one of the world's collisionLayers: ${layerNames.filter((name) => name !== RIDING_LAYER_NAME).join(", ")}.`);
365
+ }
366
+ }
367
+ }
368
+
369
+ /** A mesh's triangle groups, checked: one number a triangle, 0 (always there) or a group from 1 to 63 the world switches. */
179
370
  function triangleGroupsOf(given, triangleCount, what) {
180
371
  if (given === undefined) return null;
181
372
  const isList = Array.isArray(given) || given instanceof Uint8Array;
@@ -195,8 +386,8 @@ function triangleGroupsOf(given, triangleCount, what) {
195
386
  function groundShapeOf(given, isFixed, what) {
196
387
  const { shapeKind } = given;
197
388
  if (!isFixed) refuse("bad_body", `${what} is a ${shapeKind} on a body that moves.`, `${what}.shapeKind`, "A heightfield or a mesh read from a file is the fixed world's ground: give its body motionKind \"fixed\".");
198
- const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
199
- for (const key of ["sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", ...(shapeKind === "heightfield" ? ["triangleGroupNumbers"] : [])]) if (given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind} ${shapeKind === "mesh" ? "read from a file" : ""}, which has no ${key}.`, `${what}.${key}`, shapeKind === "mesh" ? "A mesh gives either pointsM and triangleIndices, or dataPath." : "A heightfield takes rowCount, columnCount, cellSizeM, and heightsM or dataPath.");
389
+ const shape = { shapeKind, sizeM: null, radiusM: null, heightM: null, pointsM: null, triangleIndices: null, triangleGroupNumbers: null, triangleGroups: null, triangleSurfaceIndices: null, surfaceName: surfaceNameOf(given.surfaceName, what), dataPath: null, heightsM: null, rowCount: null, columnCount: null, cellSizeM: null, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`) };
390
+ for (const key of ["sizeM", "radiusM", "heightM", "pointsM", "triangleIndices", ...(shapeKind === "heightfield" ? ["triangleGroupNumbers", "triangleGroups", "triangleSurfaceIndices"] : [])]) if (given[key] !== undefined) refuse("bad_body", `${what} is a ${shapeKind} ${shapeKind === "mesh" ? "read from a file" : ""}, which has no ${key}.`, `${what}.${key}`, shapeKind === "mesh" ? "A mesh gives either pointsM and triangleIndices, or dataPath." : "A heightfield takes rowCount, columnCount, cellSizeM, and heightsM or dataPath.");
200
391
  if (given.dataPath !== undefined) {
201
392
  if (typeof given.dataPath !== "string" || !DATA_PATH_PATTERN.test(given.dataPath) || given.dataPath.includes("..")) refuse("bad_body", `${what}.dataPath is ${JSON.stringify(given.dataPath)}.`, `${what}.dataPath`, 'Give the data file\'s path from the game\'s folder (and the same from zaisma-server/), like "levels/valley-heights.bin".');
202
393
  shape.dataPath = given.dataPath;
@@ -204,6 +395,8 @@ function groundShapeOf(given, isFixed, what) {
204
395
  if (shapeKind === "mesh") {
205
396
  // A mesh read from a file may still say its triangles' groups; how many it has is known once the file is read.
206
397
  if (given.triangleGroupNumbers !== undefined) shape.triangleGroupNumbers = triangleGroupsOf(given.triangleGroupNumbers, given.triangleGroupNumbers?.length, what);
398
+ shape.triangleGroups = groupLayersOf(given.triangleGroups, shape.triangleGroupNumbers, what);
399
+ shape.triangleSurfaceIndices = triangleSurfacesOf(given.triangleSurfaceIndices, given.triangleSurfaceIndices?.length, given.surfaceName, what);
207
400
  return { shape, volumeNumber: 0 };
208
401
  }
209
402
  for (const key of ["rowCount", "columnCount"]) {
@@ -246,7 +439,7 @@ export function checkBody(declared, what = "body", bodyKinds = []) {
246
439
  bodyKindNumber = bodyKinds.findIndex((bodyKind) => bodyKind.name === declared.bodyKindName) + 1;
247
440
  if (bodyKindNumber === 0) refuse("bad_body", `${what}.bodyKindName is ${JSON.stringify(declared.bodyKindName)}.`, `${what}.bodyKindName`, bodyKinds.length ? `Use one of the world's bodyKinds: ${bodyKinds.map((bodyKind) => bodyKind.name).join(", ")}.` : "Declare the kind in the world's bodyKinds first, or give the body shapes of its own.");
248
441
  for (const key of [...BODY_KIND_KEYS, "motionKind"]) if (declared[key] !== undefined) refuse("bad_body", `${what} has a bodyKindName and its own ${key}.`, `${what}.${key}`, `Leave ${key} out: a body of a kind is what the kind says. Give it shapes of its own instead of a bodyKindName to make it different.`);
249
- given = { ...bodyKinds[bodyKindNumber - 1].declared, id: declared.id, positionM: declared.positionM, rotationDeg: declared.rotationDeg };
442
+ given = { ...bodyKinds[bodyKindNumber - 1].declared, id: declared.id, positionM: declared.positionM, rotationDeg: declared.rotationDeg, timetable: declared.timetable };
250
443
  for (const key of Object.keys(given)) if (given[key] === undefined) delete given[key];
251
444
  }
252
445
  const { id, motionKind = "moving" } = given;
@@ -267,13 +460,17 @@ export function checkBody(declared, what = "body", bodyKinds = []) {
267
460
  const seats = checkSeats(given.seats, isFixed, what);
268
461
  if (given.canBeGrabbed !== undefined && typeof given.canBeGrabbed !== "boolean") refuse("bad_body", `${what}.canBeGrabbed isn't true or false.`, `${what}.canBeGrabbed`, "Give true or false, or leave it out: a moving body can be grabbed, the fixed world can't.");
269
462
  if (given.canBeGrabbed === true && isFixed) refuse("bad_body", `${what} is fixed and canBeGrabbed.`, `${what}.canBeGrabbed`, "Only a moving body can be grabbed and carried.");
463
+ const positionM = pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`);
464
+ const rotation = rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`);
270
465
  return {
271
466
  id,
272
467
  // 0 for a body with shapes of its own; else the place of its kind among the world's bodyKinds, from 1.
273
468
  bodyKindNumber,
274
469
  motionKind,
275
- positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_body", `${what}.positionM`),
276
- rotation: rotationOf(given.rotationDeg, "bad_body", `${what}.rotationDeg`),
470
+ positionM,
471
+ rotation,
472
+ // null, or where a kinematic body is at every step: its stops, and one round's trips and waits.
473
+ timetable: timetableOf(given.timetable, positionM, rotation, motionKind, `${what}.timetable`),
277
474
  massKg,
278
475
  bouncePct: percentOf(given.bouncePct, 100, `${what}.bouncePct`),
279
476
  gripPct: percentOf(given.gripPct, 300, `${what}.gripPct`),
@@ -420,6 +617,17 @@ function checkBodyKinds(given) {
420
617
  });
421
618
  }
422
619
 
620
+ /** A character's size, checked: what it leaves out is the size it starts from (the piece's own for world.character, world.character for a named size). */
621
+ function checkCharacterSize(given, what, from, keys) {
622
+ refuseUnknownKeys(given, keys, "bad_world", what);
623
+ const radiusM = given.radiusM === undefined ? from.radiusM : lengthOf(given.radiusM, "bad_world", `${what}.radiusM`, { minimumM: 0.05, maximumM: 5 });
624
+ const heightM = given.heightM === undefined ? from.heightM : lengthOf(given.heightM, "bad_world", `${what}.heightM`, { minimumM: 0.2, maximumM: 20 });
625
+ if (heightM < radiusM * 2) refuse("bad_world", `${what} is shorter than it is wide.`, `${what}.heightM`, "Give a heightM of at least twice the radiusM: a character is a capsule standing up.");
626
+ const stepHeightM = given.stepHeightM === undefined ? from.stepHeightM : lengthOf(given.stepHeightM, "bad_world", `${what}.stepHeightM`, { minimumM: 0, maximumM: 5 });
627
+ if (given.maximumSlopeDeg !== undefined && (!isFiniteNumber(given.maximumSlopeDeg) || given.maximumSlopeDeg < 0 || given.maximumSlopeDeg > 89)) refuse("bad_world", `${what}.maximumSlopeDeg is ${JSON.stringify(given.maximumSlopeDeg)}.`, `${what}.maximumSlopeDeg`, "Give the steepest ground a character walks up, in degrees from 0 to 89.");
628
+ return { heightM, radiusM, stepHeightM, maximumSlopeDeg: given.maximumSlopeDeg ?? from.maximumSlopeDeg };
629
+ }
630
+
423
631
  /**
424
632
  * A physics world, checked: what createPhysics and physicsKind take. Write it in a file of its own that the game's
425
633
  * page and, with a game server, the game server both import, so both build the same world. Throws PieceError
@@ -430,7 +638,7 @@ export function definePhysicsWorld(given = {}) {
430
638
  const { bodies = [], character = {}, playerCharacterMode = "on_join", startPositionsM = [{ x: 0, y: 0, z: 0 }], fallOutHeightM = -30, joints = [], substepCount = 2, groundReachM = 24 } = given;
431
639
  const collisionLayers = checkCollisionLayers(given.collisionLayers);
432
640
  const bodyKinds = checkBodyKinds(given.bodyKinds);
433
- if (!Array.isArray(bodies) || bodies.length > MAXIMUM_BODY_COUNT) refuse("bad_world", `world.bodies isn't a list of up to ${MAXIMUM_BODY_COUNT} bodies.`, "world.bodies", 'Give the world\'s bodies, like [{ id: "floor", motionKind: "fixed", shapes: [...] }].');
641
+ if (!Array.isArray(bodies) || bodies.length > MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT) refuse("bad_world", "world.bodies isn't a list of bodies.", "world.bodies", 'Give the world\'s bodies, like [{ id: "floor", motionKind: "fixed", shapes: [...] }].');
434
642
  const ids = new Set();
435
643
  const checkedBodies = bodies.map((body, bodyIndex) => {
436
644
  const checked = checkBody(body, `world.bodies[${bodyIndex}]`, bodyKinds);
@@ -438,6 +646,14 @@ export function definePhysicsWorld(given = {}) {
438
646
  ids.add(checked.id);
439
647
  return checked;
440
648
  });
649
+ const fixedBodyCount = checkedBodies.reduce((count, body) => count + (body.motionKind === "fixed" ? 1 : 0), 0);
650
+ if (fixedBodyCount > MAXIMUM_FIXED_BODY_COUNT) refuse("bad_world", `world.bodies has ${fixedBodyCount} fixed bodies, and a world holds ${MAXIMUM_FIXED_BODY_COUNT}.`, "world.bodies", "Make pieces that sit together one body of several shapes, or one mesh.");
651
+ if (checkedBodies.length - fixedBodyCount > MAXIMUM_BODY_COUNT) refuse("bad_world", `world.bodies has ${checkedBodies.length - fixedBodyCount} bodies that aren't fixed, and a world holds ${MAXIMUM_BODY_COUNT}.`, "world.bodies", 'Declare what never moves with motionKind: "fixed": those aren\'t counted here.');
652
+ const { surfaceNames = [] } = given;
653
+ if (!Array.isArray(surfaceNames) || surfaceNames.length > MAXIMUM_SURFACE_COUNT || surfaceNames.some((name) => typeof name !== "string" || !BODY_KIND_NAME_PATTERN.test(name)) || new Set(surfaceNames).size !== surfaceNames.length) refuse("bad_world", "world.surfaceNames isn't a list of surfaces, each named once.", "world.surfaceNames", `Give up to ${MAXIMUM_SURFACE_COUNT} names in lowercase words joined by underscores, like ["concrete", "metal", "wet_grass"]: what a shape's surfaceName and a mesh's triangleSurfaceIndices pick from, and what a hit says it met.`);
654
+ const named = { collisionLayers, surfaceNames };
655
+ for (const [bodyIndex, body] of checkedBodies.entries()) checkBodyNames(body, `world.bodies[${bodyIndex}]`, named);
656
+ for (const bodyKind of bodyKinds) checkBodyNames(checkBody({ ...bodyKind.declared, id: "kind" }, `world.bodyKinds.${bodyKind.name}`), `world.bodyKinds.${bodyKind.name}`, named);
441
657
  const layerNames = collisionLayers.map((layer) => layer.name);
442
658
  for (const [bodyIndex, body] of checkedBodies.entries()) if (!layerNames.includes(body.collisionLayerName)) refuse("bad_world", `world.bodies[${bodyIndex}].collisionLayerName is "${body.collisionLayerName}".`, `world.bodies[${bodyIndex}].collisionLayerName`, `Use one of the world's collisionLayers: ${layerNames.join(", ")}.`);
443
659
  for (const bodyKind of bodyKinds) {
@@ -449,6 +665,8 @@ export function definePhysicsWorld(given = {}) {
449
665
  for (const name of wheelLayerNames ?? []) if (!layerNames.includes(name)) refuse("bad_world", `${what}.vehicle.wheelCollisionLayerNames names "${name}".`, `${what}.vehicle.wheelCollisionLayerNames`, `Use the world's collisionLayers: ${layerNames.join(", ")}.`);
450
666
  }
451
667
  if (!Array.isArray(joints) || joints.length > MAXIMUM_JOINT_COUNT) refuse("bad_world", `world.joints isn't a list of up to ${MAXIMUM_JOINT_COUNT} joints.`, "world.joints", 'Give joints like [{ id: "door:hinge", jointKind: "hinge", bodyId: "door", anchorM: { x: -0.45, y: 0, z: 0 } }].');
668
+ const declaredThingCount = checkedBodies.length - fixedBodyCount + joints.length;
669
+ if (declaredThingCount > MAXIMUM_DECLARED_THING_COUNT) refuse("bad_world", `world declares ${checkedBodies.length - fixedBodyCount} bodies that aren't fixed and ${joints.length} joints, and a world starts with ${MAXIMUM_DECLARED_THING_COUNT} of them together.`, "world.joints", "Declare fewer, and add the rest while playing with addBody and addJoint.");
452
670
  const jointIds = new Set();
453
671
  const checkedJoints = joints.map((joint, jointIndex) => {
454
672
  const checked = checkJoint(joint, `world.joints[${jointIndex}]`, (bodyId) => ids.has(bodyId));
@@ -458,21 +676,27 @@ export function definePhysicsWorld(given = {}) {
458
676
  });
459
677
  if (!Number.isInteger(substepCount) || substepCount < 1 || substepCount > 8) refuse("bad_world", `world.substepCount is ${JSON.stringify(substepCount)}.`, "world.substepCount", "Give how many times the engine steps in each of the room's fixed steps, from 1 to 8: 2 (the default) steps a 30-a-second room 60 times a second, which cars and quick things want.");
460
678
  const groundReach = lengthOf(groundReachM, "bad_world", "world.groundReachM", { minimumM: 2, maximumM: 1000 });
461
- refuseUnknownKeys(character, CHARACTER_KEYS, "bad_world", "world.character");
462
- const radiusM = character.radiusM === undefined ? 0.28 : lengthOf(character.radiusM, "bad_world", "world.character.radiusM", { minimumM: 0.05, maximumM: 5 });
463
- const heightM = character.heightM === undefined ? 1.5 : lengthOf(character.heightM, "bad_world", "world.character.heightM", { minimumM: 0.2, maximumM: 20 });
464
- if (heightM < radiusM * 2) refuse("bad_world", "world.character is shorter than it is wide.", "world.character.heightM", "Give a heightM of at least twice the radiusM: a character is a capsule standing up.");
465
- const stepHeightM = character.stepHeightM === undefined ? 0.35 : lengthOf(character.stepHeightM, "bad_world", "world.character.stepHeightM", { minimumM: 0, maximumM: 5 });
466
- if (character.maximumSlopeDeg !== undefined && (!isFiniteNumber(character.maximumSlopeDeg) || character.maximumSlopeDeg < 0 || character.maximumSlopeDeg > 89)) refuse("bad_world", `world.character.maximumSlopeDeg is ${JSON.stringify(character.maximumSlopeDeg)}.`, "world.character.maximumSlopeDeg", "Give the steepest ground a character walks up, in degrees from 0 to 89.");
467
- const maximumSlopeDeg = character.maximumSlopeDeg ?? 50;
679
+ const ownCharacter = checkCharacterSize(character, "world.character", { heightM: 1.5, radiusM: 0.28, stepHeightM: 0.35, maximumSlopeDeg: 50 }, CHARACTER_KEYS);
680
+ const { characterSizes = [] } = given;
681
+ if (!Array.isArray(characterSizes) || characterSizes.length > MAXIMUM_CHARACTER_SIZE_COUNT) refuse("bad_world", `world.characterSizes isn't a list of up to ${MAXIMUM_CHARACTER_SIZE_COUNT} sizes.`, "world.characterSizes", 'Give the other sizes a character takes, like [{ name: "crouched", heightM: 1 }]: what a size leaves out is world.character\'s.');
682
+ const checkedCharacterSizes = characterSizes.map((size, sizeIndex) => {
683
+ const what = `world.characterSizes[${sizeIndex}]`;
684
+ if (!isPlainObject(size) || typeof size.name !== "string" || !BODY_KIND_NAME_PATTERN.test(size.name)) refuse("bad_world", `${what} has no name.`, `${what}.name`, 'Give each size a name in lowercase words joined by underscores, like "crouched".');
685
+ if (characterSizes.findIndex((other) => other?.name === size.name) !== sizeIndex) refuse("bad_world", `world.characterSizes names "${size.name}" twice.`, `${what}.name`, "Give each size its own name.");
686
+ return { name: size.name, ...checkCharacterSize(size, what, ownCharacter, CHARACTER_SIZE_KEYS) };
687
+ });
468
688
  if (!PLAYER_CHARACTER_MODES.includes(playerCharacterMode)) refuse("bad_world", `world.playerCharacterMode is ${JSON.stringify(playerCharacterMode)}.`, "world.playerCharacterMode", `Use: ${PLAYER_CHARACTER_MODES.join(", ")}.`);
469
689
  if (!Array.isArray(startPositionsM) || !startPositionsM.length || startPositionsM.length > MAXIMUM_CHARACTER_COUNT) refuse("bad_world", "world.startPositionsM isn't a list of places.", "world.startPositionsM", "Give where characters start, their feet on the ground, like [{ x: 0, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }]: each new character takes the next.");
470
690
  if (!isFiniteNumber(fallOutHeightM) || Math.abs(fallOutHeightM) > WORLD_REACH_M) refuse("bad_world", `world.fallOutHeightM is ${JSON.stringify(fallOutHeightM)}.`, "world.fallOutHeightM", "Give the height in metres below which anything that falls is put back where it started, like -30.");
471
691
  return {
472
692
  bodies: checkedBodies,
693
+ bodyById: new Map(checkedBodies.map((body) => [body.id, body])),
694
+ fixedBodyIds: checkedBodies.filter((body) => body.motionKind === "fixed").map((body) => body.id),
473
695
  bodyKinds,
474
- character: { heightM, radiusM, stepHeightM, maximumSlopeDeg },
696
+ character: ownCharacter,
697
+ characterSizes: checkedCharacterSizes,
475
698
  collisionLayers,
699
+ surfaceNames: [...surfaceNames],
476
700
  joints: checkedJoints,
477
701
  substepCount,
478
702
  groundReachM: groundReach,