castle-web-cli 0.4.230 → 0.4.231

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.
Files changed (69) hide show
  1. package/dist/castle-host/host.js +81 -0
  2. package/dist/devSaveStorage.d.ts +36 -0
  3. package/dist/devSaveStorage.js +469 -0
  4. package/dist/devSessionChild.js +22 -12
  5. package/dist/devSessionServer.js +8 -2
  6. package/dist/devSessionStorage.d.ts +9 -0
  7. package/dist/devSessionStorage.js +66 -1
  8. package/dist/init.js +1 -1
  9. package/dist/serve.js +5 -1
  10. package/kits/base/castle.json +1 -1
  11. package/kits/base/sdk/README.md +148 -1
  12. package/kits/base/sdk/castle.d.ts +4 -0
  13. package/kits/base/sdk/castle.js +2 -0
  14. package/kits/base/sdk/commands.d.ts +15 -0
  15. package/kits/base/sdk/multiplayer.js +52 -4
  16. package/kits/base/sdk/save.d.ts +197 -0
  17. package/kits/base/sdk/save.js +525 -0
  18. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  19. package/kits/base/sdk/saveCoordinator.js +252 -0
  20. package/kits/base/sdk/server/storage.d.ts +3 -2
  21. package/kits/base/sdk/server/storage.js +25 -5
  22. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  23. package/kits/base/sdk/server/wrapper.js +2 -0
  24. package/kits/base/sdk/store.d.ts +3 -2
  25. package/kits/base/sdk/store.js +5 -0
  26. package/kits/hub-game/CLAUDE.md +4 -1
  27. package/kits/hub-game/code/client/chrome.js +43 -9
  28. package/kits/hub-game/code/client/grab.js +142 -7
  29. package/kits/hub-game/code/client/hookLayer.js +7 -1
  30. package/kits/hub-game/code/client/state.js +13 -1
  31. package/kits/hub-game/code/client/talk.js +10 -36
  32. package/kits/hub-game/code/client/tiers.js +480 -0
  33. package/kits/hub-game/code/client/together.js +78 -3
  34. package/kits/hub-game/code/server/grab.js +3 -2
  35. package/kits/hub-game/code/server/hub.js +99 -5
  36. package/kits/hub-game/code/server/manifest.js +34 -7
  37. package/kits/hub-game/code/server/npcs.js +21 -33
  38. package/kits/hub-game/code/server/party.js +64 -6
  39. package/kits/hub-game/code/systems/hub.js +133 -16
  40. package/kits/hub-game/docs/contract.md +84 -14
  41. package/kits/hub-game/package.json +1 -1
  42. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  43. package/kits/hub-game/scripts/test-hub-trip.mjs +208 -0
  44. package/kits/hub-game/scripts/test-manifest.mjs +47 -1
  45. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  46. package/kits/hub-game/scripts/test-party.mjs +87 -4
  47. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  48. package/kits/hub-game/scripts/test-together.mjs +33 -1
  49. package/kits/physics-2d/CLAUDE.md +2 -0
  50. package/kits/physics-2d/castle.json +2 -2
  51. package/kits/physics-2d/engine/scene.js +92 -0
  52. package/kits/physics-2d/package.json +1 -1
  53. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  54. package/kits/physics-3d/CLAUDE.md +279 -0
  55. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  56. package/kits/physics-3d/castle.json +3 -3
  57. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +1 -1
  58. package/kits/physics-3d/engine3d/actornode.js +253 -0
  59. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  60. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  61. package/kits/physics-3d/engine3d/world3d.js +465 -7
  62. package/kits/physics-3d/package.json +1 -1
  63. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  64. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  65. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  66. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  67. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  68. package/kits/physics-3d/systems/physics3d.js +182 -3
  69. package/package.json +1 -1
@@ -0,0 +1,153 @@
1
+ // The terms of `"engine": { "skipUnchangedActors": true }`:
2
+ //
3
+ // With the key absent, a scene runs the engine exactly as before. With the key
4
+ // present, each frame equals what the engine would have produced without it
5
+ // PROVIDED the scene's components are plain stored data (no accessors, Proxies,
6
+ // toJSON, custom iterators) and three.js objects under actors are changed only
7
+ // through position/rotation/quaternion/scale/visible/parenting. A scene that does
8
+ // not meet that is unsupported under the key and must not set it.
9
+ //
10
+ // "Is this component still what it was?" answered without building a string.
11
+ // Used only by scenes that set `"engine": { "skipUnchangedActors": true }`.
12
+ //
13
+ // The engine decides whether to rebuild an actor's mesh or its physics body by
14
+ // comparing a signature: `JSON.stringify` of the components that shape it.
15
+ // Building that string for every actor on every frame costs more than drawing
16
+ // a small scene. `remember(value)` keeps what the string was built from, and
17
+ // `sameAs(value, memory)` says whether `JSON.stringify(value)` would come out
18
+ // the same again, by reading the value's own fields against the memory: the
19
+ // same object with the same prototype, the same keys in the same order, the
20
+ // same primitive under each. It says no more often than the string would (a
21
+ // different object holding equal values, a NaN), and the caller then builds
22
+ // the string and compares that, as it always did.
23
+ //
24
+ // Only plain data is read this way: objects whose prototype is Object's (or
25
+ // none) and arrays whose prototype is Array's, holding stored values. Anything
26
+ // that computes what it hands out is never "the same" and takes the string
27
+ // path every frame, read exactly as often and in the order it always was:
28
+ // an object or array with an accessor property, with a `toJSON` (its own or
29
+ // inherited, enumerable or not, stored or itself a getter), of any other class
30
+ // (a Date, a Map), and a bigint, which `JSON.stringify` throws on. `remember`
31
+ // and `sameAs` find that out from property descriptors and `in`, without
32
+ // calling a getter. An array is read by index up to its length, as JSON reads
33
+ // it, whatever its iterator does.
34
+ //
35
+ // That last paragraph is protection, not part of the terms: a component that is
36
+ // not plain stored data is unsupported under the key. Other reads of such a
37
+ // component elsewhere in the skipping path (a Transform's fields, `Shape.solid`)
38
+ // are not guarded, a Proxy cannot be told from the object it stands in for, and
39
+ // a stored field redefined as an accessor in place is read once here before
40
+ // the string path reads it again.
41
+ const NEVER = { never: true };
42
+
43
+ // `'toJSON' in value`, not `value.toJSON`: asking whether there is one, on the
44
+ // value or anything it inherits from, calls no getter.
45
+ function holdsOnlyStoredValues(value) {
46
+ if ('toJSON' in value) {
47
+ return false;
48
+ }
49
+ const descriptors = Object.getOwnPropertyDescriptors(value);
50
+ for (const key of Reflect.ownKeys(descriptors)) {
51
+ if (!('value' in descriptors[key])) {
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ }
57
+
58
+ // How deep a value is read. Past this it is "never the same": the walk here
59
+ // goes down by calling itself, and a value JSON.stringify can still write may
60
+ // be deeper than a call stack allows. Components are a few levels deep.
61
+ const DEEPEST = 32;
62
+
63
+ export function remember(value, depth = 0) {
64
+ if (typeof value === 'bigint') {
65
+ return NEVER;
66
+ }
67
+ if (typeof value !== 'object' || value === null) {
68
+ return value;
69
+ }
70
+ if (depth >= DEEPEST) {
71
+ return NEVER;
72
+ }
73
+ const proto = Object.getPrototypeOf(value);
74
+ const isArray = Array.isArray(value);
75
+ const plain = isArray ? proto === Array.prototype : proto === Object.prototype || proto === null;
76
+ if (!plain || !holdsOnlyStoredValues(value)) {
77
+ return NEVER;
78
+ }
79
+ if (isArray) {
80
+ // By index up to `length`, which is how JSON reads an array; not by its
81
+ // iterator, which can be anyone's.
82
+ const values = [];
83
+ for (let i = 0; i < value.length; i++) {
84
+ values.push(remember(value[i], depth + 1));
85
+ }
86
+ return { of: value, proto, keys: null, values };
87
+ }
88
+ const keys = Object.keys(value);
89
+ return { of: value, proto, keys, values: keys.map((key) => remember(value[key], depth + 1)) };
90
+ }
91
+
92
+ export function sameAs(value, memory) {
93
+ if (typeof value !== 'object' || value === null) {
94
+ // A primitive is never `===` a memory of an object, NEVER included, and
95
+ // NaN is not `===` itself.
96
+ return value === memory;
97
+ }
98
+ if (typeof memory !== 'object' || memory === null || memory.of !== value) {
99
+ return false;
100
+ }
101
+ if (Object.getPrototypeOf(value) !== memory.proto || 'toJSON' in value) {
102
+ return false;
103
+ }
104
+ return memory.keys === null ? sameItems(value, memory.values) : sameFields(value, memory);
105
+ }
106
+
107
+ // Most fields are primitives that are simply still equal; only what is not
108
+ // `===` (an object, a NaN, a changed value) is looked at further.
109
+ function sameFields(value, { keys, values }) {
110
+ let i = 0;
111
+ for (const key in value) {
112
+ if (key !== keys[i]) {
113
+ return false;
114
+ }
115
+ const now = value[key];
116
+ if (now !== values[i] && !sameAs(now, values[i])) {
117
+ return false;
118
+ }
119
+ i += 1;
120
+ }
121
+ return i === keys.length;
122
+ }
123
+
124
+ function sameItems(value, values) {
125
+ if (value.length !== values.length) {
126
+ return false;
127
+ }
128
+ for (let i = 0; i < values.length; i++) {
129
+ const now = value[i];
130
+ if (now !== values[i] && !sameAs(now, values[i])) {
131
+ return false;
132
+ }
133
+ }
134
+ return true;
135
+ }
136
+
137
+ // An object that reads like `target` and writes down each read as `key, value`
138
+ // in `reads`, so a signature built from a lookup table (`sprites`, the deck's
139
+ // files) can be checked later by making the same reads again. A missing table
140
+ // reads as an empty one, which is what `table?.[key]` gives.
141
+ const EMPTY = Object.freeze({});
142
+
143
+ export function recordReads(target, reads) {
144
+ return new Proxy(target ?? EMPTY, {
145
+ get(table, key) {
146
+ const value = table[key];
147
+ if (typeof key === 'string') {
148
+ reads.push(key, value);
149
+ }
150
+ return value;
151
+ },
152
+ });
153
+ }
@@ -17,6 +17,11 @@ import {
17
17
  import { parseModelCached, buildModelNode, modelArtSignature, animateModelParts } from './pxmodel';
18
18
  import { animateMotion } from './motion';
19
19
  import { modelRefSignature } from './modelrefs';
20
+ import { lookIsEnabled } from './look';
21
+ import { artReady } from '@imports/castle.physics-2d/engine/art';
22
+ import { ActorNode } from './actornode.js';
23
+ import { remember, sameAs, recordReads } from './unchanged.js';
24
+ import { renderWithNearShadows, dropNearShadows } from './nearshadows.js';
20
25
  import {
21
26
  takeModel,
22
27
  releaseModel,
@@ -83,6 +88,21 @@ export function makeWorld3D(canvas) {
83
88
  scenePath: undefined,
84
89
  parked: new Map(),
85
90
  models: new Map(),
91
+ // For scenes that set `"engine": { "skipUnchangedActors": true }`
92
+ // (`syncActorsSkipping`): whether the scene now playing is one, each model
93
+ // file's signature with what it was read from, and the counts that say
94
+ // when those are due a check.
95
+ skipping: { on: false },
96
+ modelSigs: new Map(),
97
+ sigEpoch: 0,
98
+ syncCount: 0,
99
+ syncDepth: 0,
100
+ generation: 0,
101
+ snapshots: new WeakMap(),
102
+ // For scenes that set `"engine": { "shadows": { "distance": n } }`
103
+ // (nearshadows.js): the shadow the engine draws for them, which is its
104
+ // own; the sun's is never written.
105
+ nearShadows: null,
86
106
  instances: new Map(),
87
107
  instanceModels: false,
88
108
  debugLines,
@@ -258,6 +278,11 @@ const DEG = Math.PI / 180;
258
278
  // `actor.runtime.quat`; everything else rotates by the Transform's euler
259
279
  // degrees.
260
280
  export function syncActors(world, runtime, sprites, dt = 0) {
281
+ if (runtime.skipsUnchangedActors === true && world.disposed !== true) {
282
+ syncActorsSkipping(world, runtime, sprites, dt);
283
+ return;
284
+ }
285
+ if (world.skipping.on) stopSkipping(world);
261
286
  // A scene is keyed by its content as well as its path (`sceneKey`), so a
262
287
  // town and a mounted game that both call theirs `scenes/main.scene` are
263
288
  // different scenes here.
@@ -345,7 +370,26 @@ export function resizeWorld(world, width, height) {
345
370
  world.camera.updateProjectionMatrix();
346
371
  }
347
372
 
348
- export function renderWorld(world) {
373
+ // `runtime` is given by the player, whose scene may have asked for shadows
374
+ // near the view only (`"engine": { "shadows": { "distance": n } }`,
375
+ // nearshadows.js). The editors give none and draw every scene the one way.
376
+ export function renderWorld(world, runtime) {
377
+ // A world with nothing of the mode's, whose scene did not ask (or which is
378
+ // being disposed): the two statements this function always was.
379
+ const distance = runtime?.nearShadowDistance ?? 0;
380
+ if (!world.nearShadows && !(distance > 0 && world.disposed !== true)) {
381
+ drawWorld(world);
382
+ return;
383
+ }
384
+ renderWithNearShadows(
385
+ world,
386
+ distance,
387
+ () => fitShadowBias(world),
388
+ () => world.composer.render()
389
+ );
390
+ }
391
+
392
+ function drawWorld(world) {
349
393
  fitShadowBias(world);
350
394
  world.composer.render();
351
395
  }
@@ -374,11 +418,425 @@ function fitShadowBias(world) {
374
418
  }
375
419
 
376
420
  export function disposeWorld(world) {
377
- for (const entry of world.nodes.values()) releaseActorNode(world, entry);
378
- world.nodes.clear();
379
- for (const parked of world.parked.values()) {
380
- for (const entry of parked.values()) releaseActorNode(world, entry);
421
+ // Releasing a node runs `dispose` listeners, which may sync this world
422
+ // again. From here on it never skips (`syncActors` reads `disposed`), so
423
+ // such a sync writes nothing down; what was written down before goes now,
424
+ // and again after the listeners have run, whether or not one throws.
425
+ world.disposed = true;
426
+ // A `dispose` listener on the near-shadow mode's map that throws does not
427
+ // keep the rest from being released.
428
+ try {
429
+ dropNearShadows(world);
430
+ } finally {
431
+ disposeNodes(world);
432
+ }
433
+ }
434
+
435
+ function disposeNodes(world) {
436
+ world.skipping.on = false;
437
+ leavingTheEngine(world);
438
+ forgetEverything(world);
439
+ try {
440
+ for (const entry of world.nodes.values()) releaseActorNode(world, entry);
441
+ world.nodes.clear();
442
+ for (const parked of world.parked.values()) {
443
+ for (const entry of parked.values()) releaseActorNode(world, entry);
444
+ }
445
+ world.parked.clear();
446
+ world.renderer.dispose();
447
+ } finally {
448
+ forgetEverything(world);
449
+ }
450
+ }
451
+
452
+ //
453
+ // Scenes that set `"engine": { "skipUnchangedActors": true }`
454
+ //
455
+ // `syncActors` for such a scene. It draws what `syncActors` draws; what it
456
+ // leaves out is building, for every actor on every frame, a signature whose
457
+ // inputs read as they did when the node was built, and (in ActorNode)
458
+ // recomputing matrices nothing has moved.
459
+ //
460
+ // The rule it is built to:
461
+ //
462
+ // Fast-path state (snapshots, pass marks, cached signatures) is trusted only
463
+ // across a span in which no code outside the engine has run. A pass in which
464
+ // the engine calls out (any callback), is re-entered, or sees the scene
465
+ // change, finishes exactly as main would and leaves no fast-path state
466
+ // behind.
467
+ //
468
+ // How: `world.generation` moves whenever code outside the engine may run inside
469
+ // a pass, and `world.syncDepth` says whether a pass is already running. A pass
470
+ // notes the generation it started at and looks again before each actor; once
471
+ // it has moved, the rest of the pass does for each actor what `syncActors`
472
+ // does (the signature built and compared, the rotation set) and writes nothing
473
+ // down, and when the outermost pass ends everything written down before is
474
+ // dropped. It is dropped as well when the outermost pass ends by throwing,
475
+ // whatever the generation says. A pass entered while another is running starts
476
+ // that way. There are no marks on entries: each pass has its own `seen`, as
477
+ // `syncActors` has.
478
+ //
479
+ // The generation is moved in one place, `leavingTheEngine`, called BEFORE the
480
+ // engine does anything in a pass that can run someone else's code. Nothing is
481
+ // inferred afterwards from what changed. three.js runs listeners
482
+ // (EventDispatcher) from `add`, `remove`, `removeFromParent`, `clear` and
483
+ // `attach` on an object (`added`, `removed`, `childadded`, `childremoved`) and
484
+ // from `dispose` on a geometry, material, texture or render target. A pass
485
+ // reaches those through, and only through:
486
+ // - `swapSceneNodes` (a scene change: nodes added, removed, released);
487
+ // - `syncGround` when the ground's signature differs (the old material
488
+ // disposed), asked beforehand by `groundIsDressed`;
489
+ // - `buildNode` (a node built: its old one released, the new one added, and
490
+ // for an instanced model `makeInstances`);
491
+ // - `releaseNode` (a node removed, its meshes disposed, `removeInstances`);
492
+ // - `drawInstances` (an instanced mesh replaced: removed, disposed, added).
493
+ // Whether it will replace one is its own business, so a world that has
494
+ // instances runs every pass main's way from the start;
495
+ // and it calls a deck's function in one place:
496
+ // - `scene.userData.groundHeight` (motion.js `airSpeed`), while a walking
497
+ // model's parts are animated. A scene that has one runs every pass main's
498
+ // way from the start; a node moved under something else that has one moves
499
+ // the generation before that node is animated.
500
+ // `syncActors` called from any of those, keyed or not, is the re-entry.
501
+ // Building a model (`takeModel`, `buildModelNode`, `copyModel`, `fillNode`)
502
+ // adds to objects that were made a moment ago and that nothing can be
503
+ // listening to; it happens inside `buildNode` regardless. Nothing else in a
504
+ // pass leaves the engine: reading plain components and the deck's `sprites`
505
+ // and `files` tables, `runtime.getActors`, three.js math, and building
506
+ // signatures from plain data (`JSON.stringify` calls no one for those). A
507
+ // scene whose components are not plain stored data is outside the key's terms
508
+ // (CLAUDE.md).
509
+ //
510
+ // What is written down, and where:
511
+ // - `world.snapshots`, a WeakMap from a node entry to what the node was built
512
+ // from (the Shape and Model as remembered, the art read, the model
513
+ // signature) and how it was last turned. Dropped by putting a new WeakMap
514
+ // in its place. An entry that is released, or held by someone else, holds
515
+ // none of it.
516
+ // - `world.modelSigs`, a Map from a model file to its signature and the reads
517
+ // it was built from. Cleared.
518
+ // - `world.sigEpoch`, `world.syncCount`, `world.generation`, `world.syncDepth`,
519
+ // `world.skipping.on`: numbers and a flag.
520
+ // - on an ActorNode, `computedFrom`: numbers only (actornode.js), so it can
521
+ // hold nothing; cleared when its node is released, when the world leaves
522
+ // the skipping path or is disposed, and by the node itself when it finds
523
+ // the switch off.
524
+ // Snapshots are kept from one pass to the next, across which deck code does
525
+ // run; they are not trusted there but read against the live components and
526
+ // node on every use.
527
+
528
+ // How many model files' signatures are kept before the lot is dropped and
529
+ // built again as needed.
530
+ const MODEL_SIGS_LIMIT = 512;
531
+
532
+ // Called before the engine, inside a pass, does anything that can run code
533
+ // that is not the engine's. See the list above.
534
+ function leavingTheEngine(world) {
535
+ world.generation += 1;
536
+ }
537
+
538
+ // The scene now playing did not ask: every node is a plain Group again and
539
+ // nothing read from the scene that did is kept. If a pass of a scene that did
540
+ // ask is running underneath (this sync was called from inside it), it is told.
541
+ function stopSkipping(world) {
542
+ world.skipping.on = false;
543
+ leavingTheEngine(world);
544
+ forgetEverything(world);
545
+ }
546
+
547
+ // Drops everything a skipping pass wrote down about the scene.
548
+ function forgetSnapshots(world) {
549
+ world.snapshots = new WeakMap();
550
+ world.modelSigs.clear();
551
+ }
552
+
553
+ // And what each node, playing or parked, remembers of its own matrices.
554
+ function forgetEverything(world) {
555
+ forgetSnapshots(world);
556
+ const forget = (entry) => {
557
+ if (entry.node.computedFrom) entry.node.computedFrom = null;
558
+ };
559
+ world.nodes.forEach(forget);
560
+ for (const parked of world.parked.values()) parked.forEach(forget);
561
+ }
562
+
563
+ function syncActorsSkipping(world, runtime, sprites, dt) {
564
+ // Entered while a pass is running: that pass is no longer alone.
565
+ if (world.syncDepth > 0) leavingTheEngine(world);
566
+ const outermost = world.syncDepth === 0;
567
+ const started = world.generation;
568
+ world.skipping.on = true;
569
+ world.syncDepth += 1;
570
+ let finished = false;
571
+ try {
572
+ skippingPass(world, runtime, sprites, dt, outermost ? started : -1);
573
+ finished = true;
574
+ } finally {
575
+ world.syncDepth -= 1;
576
+ if (outermost && (!finished || world.generation !== started)) forgetSnapshots(world);
577
+ }
578
+ }
579
+
580
+ // One pass. `started` is the generation it may trust its state at; a pass
581
+ // entered inside another is given one that never matches.
582
+ function skippingPass(world, runtime, sprites, dt, started) {
583
+ beginPass(world, runtime, sprites);
584
+ if (world.generation === started) {
585
+ world.syncCount += 1;
586
+ world.sigEpoch += 1;
587
+ }
588
+ const seen = new Set();
589
+ for (const actor of runtime.getActors()) {
590
+ const t = actor.components.Transform;
591
+ if (!t) continue;
592
+ seen.add(actor.id);
593
+ const entry = placeActor(world, actor, t, sprites, runtime.files, started);
594
+ animateModelParts(entry, dt);
595
+ animateMotion(entry, dt, actor);
596
+ }
597
+ // While the pass was alone every actor seen has its node and no node was
598
+ // released, so as many nodes as actors seen means no node has lost its actor.
599
+ if (world.generation !== started || seen.size !== world.nodes.size) releaseUnseen(world, seen);
600
+ if (world.instances.size > 0) {
601
+ leavingTheEngine(world);
602
+ aimInstances(world.camera);
603
+ for (const instances of world.instances.values()) drawInstances(instances, world.camera);
604
+ }
605
+ }
606
+
607
+ // What comes before the actors: the scene's nodes swapped in when the scene
608
+ // has changed, and the ground; and the two things that make every pass of a
609
+ // world one that leaves the engine, a ground-height callback and instancing.
610
+ function beginPass(world, runtime, sprites) {
611
+ const key = runtime.sceneKey ?? runtime.scenePath;
612
+ if (key !== world.scenePath) {
613
+ leavingTheEngine(world);
614
+ swapSceneNodes(world, key, runtime.residentScenes);
615
+ }
616
+ const setting = runtime.data?.ground;
617
+ if (!groundIsDressed(world, setting, sprites)) {
618
+ leavingTheEngine(world);
619
+ syncGround(world, setting, sprites);
620
+ }
621
+ if (typeof world.scene.userData.groundHeight === 'function' || world.instanceModels || world.instances.size > 0) {
622
+ leavingTheEngine(world);
623
+ }
624
+ }
625
+
626
+ // Whether `syncGround` would find the ground as it left it and do nothing:
627
+ // its own test, asked before calling it.
628
+ function groundIsDressed(world, setting, sprites) {
629
+ return `${JSON.stringify(setting ?? null)}|${artRefSignature(setting?.art, sprites)}` === world.groundSig;
630
+ }
631
+
632
+ // One actor's node, found or built, put where its Transform says, and ready
633
+ // to be animated: the skipping way while the pass is alone, `syncActors`'s way
634
+ // once it is not.
635
+ function placeActor(world, actor, t, sprites, files, started) {
636
+ const alone = world.generation === started;
637
+ const entry = alone ? nodeFor(world, actor, sprites, files) : nodeAsMain(world, actor, sprites, files);
638
+ const node = entry.node;
639
+ node.position.set(t.x, t.y, t.z);
640
+ const quat = actor.runtime?.quat;
641
+ if (world.generation === started) turnNode(snapshotOf(world, entry), node, t, quat);
642
+ else if (quat) node.quaternion.set(quat.x, quat.y, quat.z, quat.w);
643
+ else node.rotation.set(t.rotationX * DEG, t.rotationY * DEG, t.rotationZ * DEG);
644
+ // A node moved under something with a ground-height callback of its own,
645
+ // which animating it is about to call.
646
+ if (node.parent !== world.scene && typeof node.parent?.userData?.groundHeight === 'function') {
647
+ leavingTheEngine(world);
381
648
  }
382
- world.parked.clear();
383
- world.renderer.dispose();
649
+ return entry;
650
+ }
651
+
652
+ function releaseUnseen(world, seen) {
653
+ for (const [id, entry] of world.nodes) {
654
+ if (seen.has(id)) continue;
655
+ releaseNode(world, entry);
656
+ world.nodes.delete(id);
657
+ }
658
+ }
659
+
660
+ // `releaseActorNode`, from a skipping pass.
661
+ function releaseNode(world, entry) {
662
+ leavingTheEngine(world);
663
+ entry.node.computedFrom = null;
664
+ releaseActorNode(world, entry);
665
+ }
666
+
667
+ // The signature suffix for a Model component's file: `actorModelSig`'s, for an
668
+ // actor placing that file.
669
+ function modelFileSig(file, sprites, files) {
670
+ return actorModelSig({ components: { Model: { file } } }, sprites, files);
671
+ }
672
+
673
+ // `modelFileSig`, built once and then handed back for as long as everything it
674
+ // was read from reads the same: the file's text, the text of every model it
675
+ // references, each art object those name and whether it has loaded, and the
676
+ // look switch. The reads are written down as the signature is built
677
+ // (`recordReads`) and made again to check it. Actors placing one file share
678
+ // the answer, and within one pass over the actors (one `sprites`, one `files`)
679
+ // it is checked once (`sigEpoch`): it is asked for only while the pass is
680
+ // alone, so nothing outside the engine has run since that check. The tables
681
+ // themselves are not kept, and what is kept is dropped whenever a pass is not
682
+ // alone, when the world is disposed, and past MODEL_SIGS_LIMIT files.
683
+ function modelSigOf(world, file, sprites, files) {
684
+ if (!file) return '';
685
+ let memo = world.modelSigs.get(file);
686
+ if (memo && memo.epoch === world.sigEpoch) return memo.sig;
687
+ if (!memo || !readsTheSame(memo, sprites, files)) {
688
+ const fileReads = [];
689
+ const artReads = [];
690
+ const look = lookIsEnabled();
691
+ const sig = modelFileSig(file, recordReads(sprites, artReads), recordReads(files, fileReads));
692
+ memo = { sig, look, fileReads, artReads: withReadiness(artReads), epoch: 0 };
693
+ if (world.modelSigs.size >= MODEL_SIGS_LIMIT) world.modelSigs.clear();
694
+ world.modelSigs.set(file, memo);
695
+ }
696
+ memo.epoch = world.sigEpoch;
697
+ return memo.sig;
698
+ }
699
+
700
+ function readsTheSame(memo, sprites, files) {
701
+ if (memo.look !== lookIsEnabled()) return false;
702
+ const { fileReads } = memo;
703
+ for (let i = 0; i < fileReads.length; i += 2) {
704
+ if (files?.[fileReads[i]] !== fileReads[i + 1]) return false;
705
+ }
706
+ return artReadsTheSame(memo.artReads, sprites);
707
+ }
708
+
709
+ // `[path, art, ...]` as read, to `[path, art, ready, ...]`: an art's signature
710
+ // is which object it is and whether it has loaded.
711
+ function withReadiness(reads) {
712
+ const out = [];
713
+ for (let i = 0; i < reads.length; i += 2) {
714
+ out.push(reads[i], reads[i + 1], artReady(reads[i + 1]));
715
+ }
716
+ return out;
717
+ }
718
+
719
+ function artReadsTheSame(artReads, sprites) {
720
+ for (let i = 0; i < artReads.length; i += 3) {
721
+ const art = sprites?.[artReads[i]];
722
+ if (art !== artReads[i + 1] || artReady(art) !== artReads[i + 2]) return false;
723
+ }
724
+ return true;
725
+ }
726
+
727
+ // Whether the actor's node signature would come out as it did when `entry`
728
+ // last built it: the Shape and Model components read the same field for
729
+ // field, the art the Shape names is the same objects in the same state, and
730
+ // the model file's signature is the same.
731
+ function looksTheSame(world, entry, actor, sprites, files) {
732
+ const built = world.snapshots.get(entry)?.builtFrom;
733
+ if (!built) return false;
734
+ const components = actor.components;
735
+ const model = components.Model;
736
+ return (
737
+ sameAs(components.Shape, built.shape) &&
738
+ sameAs(model, built.model) &&
739
+ artReadsTheSame(built.artReads, sprites) &&
740
+ modelSigOf(world, model?.file, sprites, files) === built.modelSig
741
+ );
742
+ }
743
+
744
+ // `ensureActorNode` for a pass that is alone: the same signature, compared the
745
+ // same way, but only when `looksTheSame` cannot vouch for the node. A node
746
+ // that has to be built or released ends the pass's being alone first. What a
747
+ // kept node was built from is written down after the signature is compared.
748
+ function nodeFor(world, actor, sprites, files) {
749
+ const entry = world.nodes.get(actor.id);
750
+ if (entry && looksTheSame(world, entry, actor, sprites, files)) return entry;
751
+ const artReads = [];
752
+ const modelSig = modelSigOf(world, actor.components.Model?.file, sprites, files);
753
+ const sig = nodeSignature(actor, recordReads(sprites, artReads), modelSig);
754
+ if (!entry || entry.sig !== sig) {
755
+ return buildNode(world, entry, actor, sig, modelSig, sprites, files);
756
+ }
757
+ snapshotOf(world, entry).builtFrom = {
758
+ shape: remember(actor.components.Shape),
759
+ model: remember(actor.components.Model),
760
+ artReads: withReadiness(artReads),
761
+ modelSig,
762
+ };
763
+ return entry;
764
+ }
765
+
766
+ // `ensureActorNode` as it is, for a pass that is not alone: the signature is
767
+ // built and compared, nothing is read from what was written down and nothing
768
+ // is written. The node is an ActorNode all the same.
769
+ function nodeAsMain(world, actor, sprites, files) {
770
+ const modelSig = actorModelSig(actor, sprites, files);
771
+ const sig = nodeSignature(actor, sprites, modelSig);
772
+ const entry = world.nodes.get(actor.id);
773
+ if (entry && entry.sig === sig) return entry;
774
+ return buildNode(world, entry, actor, sig, modelSig, sprites, files);
775
+ }
776
+
777
+ // What is written down for an entry, made on first use.
778
+ function snapshotOf(world, entry) {
779
+ let snapshot = world.snapshots.get(entry);
780
+ if (!snapshot) {
781
+ snapshot = { builtFrom: undefined, turnedTo: null };
782
+ world.snapshots.set(entry, snapshot);
783
+ }
784
+ return snapshot;
785
+ }
786
+
787
+ function buildNode(world, old, actor, sig, modelSig, sprites, files) {
788
+ leavingTheEngine(world);
789
+ if (old) releaseNode(world, old);
790
+ const entry = { node: new ActorNode(world.skipping), sig };
791
+ entry.node.userData.actorId = actor.id;
792
+ fillNode(world, entry, actor, modelSig, sprites, files);
793
+ world.scene.add(entry.node);
794
+ world.nodes.set(actor.id, entry);
795
+ return entry;
796
+ }
797
+
798
+ function fillNode(world, entry, actor, modelSig, sprites, files) {
799
+ const { Model: placed, Shape: shape } = actor.components;
800
+ const model = placed?.file ? parseModelCached(files?.[placed.file]) : null;
801
+ if (model) {
802
+ addModelRig(world, entry, model, placed, `${placed.file}|${modelSig}`, { sprites, files });
803
+ } else if (shape) {
804
+ entry.node.add(makeShapeMesh(shape, sprites));
805
+ }
806
+ }
807
+
808
+ // The node's rotation for this frame: the body's quaternion, or the
809
+ // Transform's euler degrees. Setting a three.js euler works out its quaternion
810
+ // (six sines and cosines), so the euler is set only when that would change
811
+ // something: when the node's euler is not already these angles, or its
812
+ // quaternion is no longer the one the last set worked out from them.
813
+ function turnNode(snapshot, node, t, quat) {
814
+ const q = node.quaternion;
815
+ if (quat) {
816
+ q.set(quat.x, quat.y, quat.z, quat.w);
817
+ snapshot.turnedTo = null;
818
+ return;
819
+ }
820
+ const x = t.rotationX * DEG;
821
+ const y = t.rotationY * DEG;
822
+ const z = t.rotationZ * DEG;
823
+ const r = node.rotation;
824
+ const was = snapshot.turnedTo;
825
+ // `rotation.set(x, y, z)` stores the three angles, keeps the euler's order,
826
+ // and works the quaternion out from the angles and that order. So it would
827
+ // change nothing exactly when the angles are already these, the order is
828
+ // the one the last set worked with, and the quaternion is the one it left.
829
+ // `Object.is`, so that -0 and 0, which turn out quaternions differing in the
830
+ // sign of a zero, are not taken for each other.
831
+ if (was && r.order === was.order && sameTurn(r, x, y, z) && sameQuaternion(q, was)) return;
832
+ r.set(x, y, z);
833
+ snapshot.turnedTo = { order: r.order, x: q.x, y: q.y, z: q.z, w: q.w };
834
+ }
835
+
836
+ function sameTurn(r, x, y, z) {
837
+ return Object.is(r.x, x) && Object.is(r.y, y) && Object.is(r.z, z);
838
+ }
839
+
840
+ function sameQuaternion(q, was) {
841
+ return Object.is(q.x, was.x) && Object.is(q.y, was.y) && Object.is(q.z, was.z) && Object.is(q.w, was.w);
384
842
  }
@@ -5,7 +5,7 @@
5
5
  "scripts": {
6
6
  "restart": "castle-web restart .",
7
7
  "screenshot": "castle-web screenshot .",
8
- "check": "eslint . && jscpd && node --input-type=module -e \"const { bundleProject } = await import('castle-web-cli/dist/bundle.js'); await bundleProject('.');\""
8
+ "check": "eslint . && jscpd && node scripts/test-static-actors.mjs && node --input-type=module -e \"const { bundleProject } = await import('castle-web-cli/dist/bundle.js'); await bundleProject('.');\""
9
9
  },
10
10
  "jscpd": {
11
11
  "path": [