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,666 @@
1
+ // Tests over device tiers (code/client/tiers.js): where a device starts (its
2
+ // GPU, its memory, a slow visit remembered for a week), the frame-time judge
3
+ // (median windows, never back up, hidden pages and swaps ignored), storage that
4
+ // throws, the player's own Auto / Low / High winning, and the low picture's
5
+ // levers put on and taken off exactly on a fake physics-3d world. Last, the hub
6
+ // system with the deck's `hub.tiers` absent: nothing of the tiers is made, run
7
+ // or read. `npm run check` runs this.
8
+
9
+ import assert from 'node:assert/strict';
10
+ import fs from 'node:fs';
11
+ import { register } from 'node:module';
12
+ import {
13
+ CHECK_EVERY_MS,
14
+ FIRST_WINDOW_MS,
15
+ MODE_KEY,
16
+ REMEMBER_MS,
17
+ TIER_KEY,
18
+ WINDOW_MS,
19
+ classify,
20
+ hintedTier,
21
+ initialTier,
22
+ makeJudge,
23
+ makeLevers,
24
+ makeTiers,
25
+ median,
26
+ readMode,
27
+ weakGpu,
28
+ } from '../code/client/tiers.js';
29
+
30
+ let n = 0;
31
+ function test(name, fn) {
32
+ try {
33
+ fn();
34
+ } catch (err) {
35
+ console.error(`not ok: ${name}`);
36
+ throw err;
37
+ }
38
+ n += 1;
39
+ }
40
+
41
+ function memoryStorage(init = {}) {
42
+ const map = new Map(Object.entries(init));
43
+ return {
44
+ map,
45
+ getItem: (k) => (map.has(k) ? map.get(k) : null),
46
+ setItem: (k, v) => map.set(k, String(v)),
47
+ };
48
+ }
49
+ const throwing = {
50
+ getItem() {
51
+ throw new Error('SecurityError');
52
+ },
53
+ setItem() {
54
+ throw new Error('QuotaExceededError');
55
+ },
56
+ };
57
+
58
+ // Frames of `ms` each from `t` for `seconds`; returns what the judge said and
59
+ // the time after.
60
+ function run(judge, t, ms, seconds, counts = true) {
61
+ const said = [];
62
+ for (const end = t + seconds * 1000; t < end; t += ms) {
63
+ const v = judge.feed(ms, t, counts);
64
+ if (v) {
65
+ said.push(v);
66
+ }
67
+ }
68
+ return { said, t };
69
+ }
70
+
71
+ test('weak GPUs by renderer string', () => {
72
+ for (const gpu of [
73
+ 'PowerVR Rogue GE8320',
74
+ 'PowerVR Rogue GE8100',
75
+ 'Mali-G52 MC2',
76
+ 'Mali-G52 MC1',
77
+ 'Mali-G51',
78
+ 'Mali-T720',
79
+ 'Mali-T830 MP2',
80
+ 'Adreno (TM) 306',
81
+ 'Adreno (TM) 418',
82
+ 'Adreno (TM) 506',
83
+ 'ANGLE (Qualcomm, Adreno (TM) 505, OpenGL ES 3.2)',
84
+ ]) {
85
+ assert.equal(weakGpu(gpu), true, gpu);
86
+ }
87
+ for (const gpu of ['Mali-G52 MC4', 'Mali-G57 MC2', 'Mali-G610', 'Adreno (TM) 610', 'Adreno (TM) 730', 'Apple GPU', 'PowerVR Rogue GM9446', null, undefined, 42]) {
88
+ assert.equal(weakGpu(gpu), false, String(gpu));
89
+ }
90
+ });
91
+
92
+ test('hints: a weak GPU or 2 GB is low, anything else high', () => {
93
+ assert.deepEqual(hintedTier({ gpu: 'Mali-G52 MC2', deviceMemory: 4 }), { tier: 'low', reason: 'gpu' });
94
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 2 }), { tier: 'low', reason: 'memory' });
95
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 1 }), { tier: 'low', reason: 'memory' });
96
+ assert.deepEqual(hintedTier({ gpu: 'Adreno (TM) 640', deviceMemory: 4 }), { tier: 'high', reason: 'auto' });
97
+ assert.deepEqual(hintedTier({}), { tier: 'high', reason: 'auto' });
98
+ });
99
+
100
+ test('a slow visit is remembered for a week, then tried from high again', () => {
101
+ const now = 1_000_000_000_000;
102
+ const at = (ago) => memoryStorage({ [TIER_KEY]: JSON.stringify({ tier: 'low', at: now - ago }) });
103
+ assert.deepEqual(initialTier({ storage: at(1000), now }), { tier: 'low', reason: 'remembered' });
104
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS - 1), now }), { tier: 'low', reason: 'remembered' });
105
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS + 1), now }), { tier: 'high', reason: 'auto' });
106
+ assert.deepEqual(initialTier({ storage: at(-60000), now }), { tier: 'high', reason: 'auto' }, 'a time from the future is not trusted');
107
+ const junk = memoryStorage({ [TIER_KEY]: '{not json' });
108
+ assert.deepEqual(initialTier({ storage: junk, now }), { tier: 'high', reason: 'auto' });
109
+ assert.deepEqual(initialTier({ storage: at(REMEMBER_MS + 1), now, gpu: 'Mali-G51' }), { tier: 'low', reason: 'gpu' });
110
+ });
111
+
112
+ test('storage that throws reads as nothing stored and never throws', () => {
113
+ assert.equal(readMode(throwing), 'auto');
114
+ assert.deepEqual(initialTier({ storage: throwing, now: 1 }), { tier: 'high', reason: 'auto' });
115
+ assert.equal(readMode(null), 'auto');
116
+ const t = makeTiers({ storage: throwing, clock: () => 5, deviceMemory: 8 });
117
+ assert.equal(t.set('low'), true);
118
+ assert.equal(t.handle.current, 'low');
119
+ assert.equal(readMode(memoryStorage({ [MODE_KEY]: '"sideways"' })), 'auto');
120
+ });
121
+
122
+ test('median', () => {
123
+ assert.equal(median([]), 0);
124
+ assert.equal(median([3, 1, 2]), 2);
125
+ assert.equal(median([4, 1, 2, 3]), 2.5);
126
+ });
127
+
128
+ test('the judge: a slow first window is low; a fast device never is', () => {
129
+ let j = makeJudge();
130
+ let r = run(j, 0, 60, FIRST_WINDOW_MS / 1000 + 0.2);
131
+ assert.deepEqual(r.said, ['low'], 'median 60 ms over the first 5 s');
132
+ j = makeJudge();
133
+ r = run(j, 0, 16, 120);
134
+ assert.deepEqual(r.said, [], 'two minutes at 60 fps');
135
+ j = makeJudge();
136
+ r = run(j, 0, 35, 120);
137
+ assert.deepEqual(r.said, [], '35 ms frames are not slow');
138
+ });
139
+
140
+ test('the judge: big single frames do not decide (median, not mean)', () => {
141
+ const j = makeJudge();
142
+ let said = null;
143
+ for (let t = 0, i = 0; t < 60000; i += 1) {
144
+ const ms = i % 10 === 0 ? 900 : 16;
145
+ t += ms;
146
+ said = j.feed(ms, t, true) ?? said;
147
+ }
148
+ assert.equal(said, null);
149
+ });
150
+
151
+ test('the judge: after the first window, any slow 10 s window is low', () => {
152
+ const j = makeJudge();
153
+ let r = run(j, 0, 16, 30);
154
+ assert.deepEqual(r.said, []);
155
+ // Six slow seconds inside a mostly fast window are not enough.
156
+ r = run(j, r.t, 60, 6);
157
+ r = run(j, r.t, 16, 30);
158
+ assert.deepEqual(r.said, []);
159
+ r = run(j, r.t, 60, WINDOW_MS / 1000 * 2 + 0.5);
160
+ assert.deepEqual(r.said, ['low']);
161
+ });
162
+
163
+ test('the judge never moves back up, and says low once', () => {
164
+ const j = makeJudge();
165
+ let r = run(j, 0, 70, 6);
166
+ assert.deepEqual(r.said, ['low']);
167
+ r = run(j, r.t, 70, 30);
168
+ assert.deepEqual(r.said, [], 'said once');
169
+ r = run(j, r.t, 10, 60);
170
+ assert.deepEqual(r.said, []);
171
+ assert.equal(j.done, true);
172
+ });
173
+
174
+ test('the judge ignores frames that do not count, and gaps', () => {
175
+ let j = makeJudge();
176
+ // Slow frames under a swap (counts false) say nothing.
177
+ let r = run(j, 0, 80, 30, false);
178
+ assert.deepEqual(r.said, []);
179
+ // A slow stretch broken by a swap before 5 s: both halves start over.
180
+ j = makeJudge();
181
+ r = run(j, 0, 60, 4);
182
+ r = run(j, r.t, 60, 0.5, false);
183
+ r = run(j, r.t, 60, 4);
184
+ assert.deepEqual(r.said, []);
185
+ // A gap (the page hidden: no frames) splits a window as well.
186
+ j = makeJudge();
187
+ r = run(j, 0, 60, 4);
188
+ j.feed(30000, r.t + 30000, true);
189
+ r = run(j, r.t + 30000, 60, 4);
190
+ assert.deepEqual(r.said, []);
191
+ });
192
+
193
+ test('makeTiers: the judge drops a slow device to low and remembers it', () => {
194
+ const storage = memoryStorage();
195
+ const t = makeTiers({ storage, clock: () => 1234, deviceMemory: 8, levers: fakeLevers() });
196
+ const scene = { three: { renderer: {} } };
197
+ for (let now = 0; now < 7000; now += 60) {
198
+ t.frame(scene, true, now);
199
+ }
200
+ assert.equal(t.handle.current, 'low');
201
+ assert.equal(t.handle.reason, 'slow');
202
+ assert.deepEqual(JSON.parse(storage.map.get(TIER_KEY)), { tier: 'low', at: 1234 });
203
+ // A later visit starts low.
204
+ const again = makeTiers({ storage, clock: () => 1234 + 60000, deviceMemory: 8, levers: fakeLevers() });
205
+ again.frame(scene, true, 0);
206
+ assert.deepEqual([again.handle.current, again.handle.reason], ['low', 'remembered']);
207
+ });
208
+
209
+ test('makeTiers: a hidden page and frames that do not count are not judged', () => {
210
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 8, levers: fakeLevers() });
211
+ const scene = { three: { renderer: {} } };
212
+ for (let now = 0; now < 30000; now += 60) {
213
+ t.frame(scene, false, now);
214
+ }
215
+ assert.equal(t.handle.current, 'high');
216
+ globalThis.document = { hidden: true };
217
+ try {
218
+ for (let now = 30000; now < 60000; now += 60) {
219
+ t.frame(scene, true, now);
220
+ }
221
+ } finally {
222
+ delete globalThis.document;
223
+ }
224
+ assert.equal(t.handle.current, 'high');
225
+ });
226
+
227
+ test('makeTiers: the GPU string from the renderer places a weak phone low', () => {
228
+ const gl = {
229
+ RENDERER: 1,
230
+ getExtension: (name) => (name === 'WEBGL_debug_renderer_info' ? { UNMASKED_RENDERER_WEBGL: 2 } : null),
231
+ getParameter: (p) => (p === 2 ? 'Mali-G52 MC2' : 'WebKit WebGL'),
232
+ };
233
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 4, levers: fakeLevers() });
234
+ t.frame({ three: { renderer: { getContext: () => gl } } }, true, 0);
235
+ assert.deepEqual([t.handle.current, t.handle.reason], ['low', 'gpu']);
236
+ const broken = makeTiers({ storage: memoryStorage(), deviceMemory: 4, levers: fakeLevers() });
237
+ broken.frame({ three: { renderer: { getContext: () => { throw new Error('lost'); } } } }, true, 0);
238
+ assert.equal(broken.handle.current, 'high');
239
+ });
240
+
241
+ test('makeTiers: Low or High picked by hand wins over auto, and is kept', () => {
242
+ const now = 10 * REMEMBER_MS;
243
+ const storage = memoryStorage({ [TIER_KEY]: JSON.stringify({ tier: 'low', at: now - 1000 }), [MODE_KEY]: '"high"' });
244
+ const levers = fakeLevers();
245
+ const t = makeTiers({ storage, clock: () => now, deviceMemory: 8, levers });
246
+ const scene = { three: { renderer: {} } };
247
+ t.frame(scene, true, 0);
248
+ assert.deepEqual([t.handle.current, t.handle.reason, t.handle.mode], ['high', 'manual', 'high']);
249
+ assert.equal(levers.applied, 0);
250
+ // Slow frames do not move a player's High.
251
+ for (let ms = 0; ms < 30000; ms += 80) {
252
+ t.frame(scene, true, ms);
253
+ }
254
+ assert.equal(t.handle.current, 'high');
255
+ t.handle.set('auto');
256
+ assert.equal(storage.map.get(MODE_KEY), '"auto"');
257
+ t.frame(scene, true, 30100);
258
+ assert.deepEqual([t.handle.current, t.handle.reason], ['low', 'remembered']);
259
+ assert.equal(levers.applied, 1);
260
+ t.handle.set('high');
261
+ t.frame(scene, true, 30200);
262
+ assert.equal(levers.restored, 1, 'High takes the low picture off');
263
+ assert.equal(t.handle.set('ultra'), false);
264
+ assert.equal(t.handle.mode, 'high');
265
+ // A fresh page reads the pick back.
266
+ assert.equal(makeTiers({ storage, levers: fakeLevers() }).handle.mode, 'high');
267
+ });
268
+
269
+ function fakeLevers() {
270
+ const lv = { active: false, hidden: 0, applied: 0, restored: 0 };
271
+ lv.apply = () => {
272
+ lv.active = true;
273
+ lv.applied += 1;
274
+ };
275
+ lv.restore = () => {
276
+ lv.active = false;
277
+ lv.restored += 1;
278
+ };
279
+ return lv;
280
+ }
281
+
282
+ test('classify', () => {
283
+ assert.equal(classify({ Transform: {}, Model: {} }), 'decor');
284
+ assert.equal(classify({ Transform: {}, Shape: {} }), 'decor');
285
+ assert.equal(classify({ Transform: {} }), 'decor');
286
+ assert.equal(classify({ Transform: {}, Shape: {}, Solid: {} }), 'static');
287
+ assert.equal(classify({ Transform: {}, Model: {}, Lookable: {}, Shape: {}, Solid: {} }), 'static');
288
+ assert.equal(classify({ Transform: {}, Shape: {}, Solid: {}, Body: {}, HubNpc: {}, Model: {} }), 'npc');
289
+ for (const extra of ['HubDoor', 'HubPad', 'HubSeat', 'TownSign', 'TownStatue', 'Body', 'Ball', 'Player', 'Spinner']) {
290
+ assert.equal(classify({ Transform: {}, Shape: {}, [extra]: {} }), 'game', extra);
291
+ }
292
+ });
293
+
294
+ // A fake physics-3d world: nodes that can be taken out of and put back into
295
+ // the scene, a sun and a renderer that remember what was set.
296
+ class Obj {
297
+ constructor(name, at = [0, 0, 0]) {
298
+ this.name = name;
299
+ this.parent = null;
300
+ this.children = [];
301
+ this.position = { x: at[0], y: at[1], z: at[2] };
302
+ }
303
+ add(o) {
304
+ o.parent?.remove(o);
305
+ o.parent = this;
306
+ this.children.push(o);
307
+ return this;
308
+ }
309
+ remove(o) {
310
+ const i = this.children.indexOf(o);
311
+ if (i >= 0) {
312
+ this.children.splice(i, 1);
313
+ o.parent = null;
314
+ }
315
+ return this;
316
+ }
317
+ }
318
+
319
+ function fakeWorld(actors) {
320
+ const root = new Obj('scene');
321
+ const sun = Object.assign(new Obj('sun'), { isLight: true, castShadow: true });
322
+ const sky = Object.assign(new Obj('sky'), { isLight: true, castShadow: false });
323
+ root.add(sun);
324
+ root.add(sky);
325
+ // The renderer and composer record every property read of theirs: Low
326
+ // never touches either (the GPU hint's getContext is read once, by
327
+ // makeTiers, never by the levers).
328
+ const touched = [];
329
+ const watched = (name) =>
330
+ new Proxy(
331
+ {},
332
+ {
333
+ get(_, key) {
334
+ touched.push(`${name}.${String(key)}`);
335
+ return undefined;
336
+ },
337
+ set(_, key) {
338
+ touched.push(`${name}.${String(key)}=`);
339
+ return true;
340
+ },
341
+ },
342
+ );
343
+ const world = {
344
+ scene: root,
345
+ camera: { position: { x: 0, y: 2, z: 0 } },
346
+ renderer: watched('renderer'),
347
+ composer: watched('composer'),
348
+ nodes: new Map(),
349
+ scenePath: 'scenes/main.scene',
350
+ };
351
+ for (const a of actors) {
352
+ const node = new Obj(a.id, a.at ?? [0, 0, 0]);
353
+ root.add(node);
354
+ world.nodes.set(a.id, { node });
355
+ }
356
+ const byId = new Map(actors.map((a) => [a.id, a]));
357
+ const scene = {
358
+ content: null,
359
+ data: {},
360
+ scenePath: 'scenes/main.scene',
361
+ readFromFile: () => ({ actors: actors.filter((a) => !a.spawned).map((a) => ({ id: a.id })) }),
362
+ getActor: (id) => byId.get(id),
363
+ };
364
+ return { world, scene, sun, sky, touched, parents: () => new Map([...world.nodes].map(([id, e]) => [id, e.node.parent])) };
365
+ }
366
+
367
+ const TOWN = [
368
+ { id: 'lamp', components: { Transform: {}, Model: {} }, at: [3, 0, 3] },
369
+ { id: 'wall-near', components: { Transform: {}, Shape: {}, Solid: {} }, at: [10, 0, 0] },
370
+ { id: 'wall-far', components: { Transform: {}, Shape: {}, Solid: {} }, at: [60, 0, 0] },
371
+ { id: 'npc-near', components: { Transform: {}, Body: {}, HubNpc: {}, Model: {} }, at: [0, 0, 15] },
372
+ { id: 'npc-far', components: { Transform: {}, Body: {}, HubNpc: {}, Model: {} }, at: [0, 0, 25] },
373
+ { id: 'door', components: { Transform: {}, Shape: {}, HubDoor: {} }, at: [80, 0, 0] },
374
+ { id: 'pad', components: { Transform: {}, Shape: {}, HubPad: {} }, at: [0, 0, 1] },
375
+ // What a player wears, spawned at runtime: Transform + Shape, never hidden.
376
+ { id: 'wear:p1:0', components: { Transform: {}, Shape: {} }, at: [1, 0, 1], spawned: true },
377
+ ];
378
+ const bounds = (r) => () => ({ dx: 0, dy: 0, dz: 0, r });
379
+ const drawn = (world, id) => world.nodes.get(id).node.parent === world.scene;
380
+
381
+ test('levers: low takes out decor, far scenery and far NPCs, keeps gameplay and spawned actors', () => {
382
+ const { world, scene, sun, sky, touched } = fakeWorld(TOWN);
383
+ const lv = makeLevers({ boundsOf: bounds(0) });
384
+ lv.apply(world, scene, 0);
385
+ assert.equal(drawn(world, 'lamp'), false);
386
+ assert.equal(drawn(world, 'wall-near'), true);
387
+ assert.equal(drawn(world, 'wall-far'), false);
388
+ assert.equal(drawn(world, 'npc-near'), true);
389
+ assert.equal(drawn(world, 'npc-far'), false);
390
+ assert.equal(drawn(world, 'door'), true, 'a door is drawn at any distance');
391
+ assert.equal(drawn(world, 'pad'), true);
392
+ assert.equal(drawn(world, 'wear:p1:0'), true, 'a spawned actor is never hidden');
393
+ assert.equal(lv.hidden, 3);
394
+ assert.equal(sun.castShadow, false);
395
+ assert.equal(sky.castShadow, false);
396
+ assert.deepEqual(touched, [], 'the renderer and composer are not touched');
397
+ });
398
+
399
+ test('levers: a big building is drawn while any of it is within 30 m', () => {
400
+ const { world, scene } = fakeWorld(TOWN);
401
+ makeLevers({ boundsOf: bounds(35) }).apply(world, scene, 0);
402
+ assert.equal(drawn(world, 'wall-far'), true);
403
+ });
404
+
405
+ test('levers: distances are looked at again at a low rate, not every frame', () => {
406
+ const { world, scene } = fakeWorld(TOWN);
407
+ const lv = makeLevers({ boundsOf: bounds(0) });
408
+ lv.apply(world, scene, 0);
409
+ assert.equal(drawn(world, 'wall-far'), false);
410
+ world.camera.position = { x: 55, y: 2, z: 0 };
411
+ lv.apply(world, scene, CHECK_EVERY_MS / 2);
412
+ assert.equal(drawn(world, 'wall-far'), false, 'not before the next look');
413
+ lv.apply(world, scene, CHECK_EVERY_MS + 1);
414
+ assert.equal(drawn(world, 'wall-far'), true, 'walked up to it');
415
+ assert.equal(drawn(world, 'wall-near'), false, 'and away from the other one');
416
+ });
417
+
418
+ test('levers: what the engine puts back (a parked scene returning, a rebuild) is taken out again at once', () => {
419
+ const { world, scene } = fakeWorld(TOWN);
420
+ const lv = makeLevers({ boundsOf: bounds(0) });
421
+ lv.apply(world, scene, 0);
422
+ // world3d.js swapSceneNodes: the town parked (out of the scene, a new
423
+ // nodes map), then put back (every node added to the scene again).
424
+ const parked = world.nodes;
425
+ for (const e of parked.values()) {
426
+ world.scene.remove(e.node);
427
+ }
428
+ world.nodes = new Map();
429
+ world.scenePath = 'pack:scenes/race.scene';
430
+ lv.apply(world, scene, 10);
431
+ world.nodes = parked;
432
+ world.scenePath = 'scenes/main.scene';
433
+ for (const e of parked.values()) {
434
+ world.scene.add(e.node);
435
+ }
436
+ assert.equal(drawn(world, 'lamp'), true);
437
+ lv.apply(world, scene, 20);
438
+ assert.equal(drawn(world, 'lamp'), false, 'not waiting for the next look');
439
+ assert.equal(drawn(world, 'npc-far'), false);
440
+ // A new decor node built by the engine (an actor added) is caught too.
441
+ const node = new Obj('vase', [2, 0, 2]);
442
+ world.scene.add(node);
443
+ world.nodes.set('vase', { node });
444
+ scene.getActor = ((get) => (id) => (id === 'vase' ? { components: { Transform: {}, Model: {} } } : get(id)))(scene.getActor);
445
+ scene.data = {};
446
+ scene.readFromFile = () => ({ actors: [...TOWN.filter((a) => !a.spawned), { id: 'vase' }] });
447
+ lv.apply(world, scene, 30);
448
+ assert.equal(node.parent, null);
449
+ });
450
+
451
+ test('levers: another deck behind a door keeps only the shadow lever', () => {
452
+ const { world, scene, sun } = fakeWorld(TOWN);
453
+ const lv = makeLevers({ boundsOf: bounds(0) });
454
+ lv.apply(world, scene, 0);
455
+ assert.equal(drawn(world, 'lamp'), false);
456
+ lv.apply(world, scene, 10, { actors: false });
457
+ assert.equal(drawn(world, 'lamp'), true);
458
+ assert.equal(drawn(world, 'wall-far'), true);
459
+ assert.equal(sun.castShadow, false);
460
+ });
461
+
462
+ test('levers: high again restores node parents and lights exactly', () => {
463
+ const { world, scene, sun, sky, touched, parents } = fakeWorld(TOWN);
464
+ // One node under something other than the scene root.
465
+ const holder = new Obj('holder');
466
+ world.scene.add(holder);
467
+ holder.add(world.nodes.get('lamp').node);
468
+ const before = parents();
469
+ const order = world.scene.children.length;
470
+ const lv = makeLevers({ boundsOf: bounds(0) });
471
+ lv.apply(world, scene, 0);
472
+ // A node the engine released while it was out stays out.
473
+ const gone = world.nodes.get('npc-far').node;
474
+ world.nodes.delete('npc-far');
475
+ before.delete('npc-far');
476
+ lv.restore(world);
477
+ assert.deepEqual(parents(), before);
478
+ assert.equal(gone.parent, null);
479
+ assert.equal(world.scene.children.length, order - 1);
480
+ assert.equal(sun.castShadow, true);
481
+ assert.equal(sky.castShadow, false, 'a light that cast no shadow still casts none');
482
+ assert.deepEqual(touched, []);
483
+ assert.equal(lv.active, false);
484
+ assert.equal(lv.hidden, 0);
485
+ // And low again works the same after.
486
+ lv.apply(world, scene, 1000);
487
+ assert.equal(drawn(world, 'wall-far'), false);
488
+ assert.equal(sun.castShadow, false);
489
+ });
490
+
491
+ // Regressions from phones and review.
492
+
493
+ test('Low keeps the full render resolution: the pixel ratio is never read or set, across Low/High switches', () => {
494
+ // Measured on phones, a render scale of 1 bought 2-9% and made Low jagged
495
+ // on 2x screens, so Low leaves the renderer and composer alone. The only
496
+ // read of the renderer is the GPU hint, once.
497
+ const { world, scene, touched } = fakeWorld(TOWN);
498
+ const t = makeTiers({ storage: memoryStorage(), deviceMemory: 1, levers: makeLevers({ boundsOf: bounds(0) }) });
499
+ const s = { ...scene, three: world };
500
+ let now = 0;
501
+ const frames = () => {
502
+ for (let i = 0; i < 3; i += 1) {
503
+ t.frame(s, true, (now += 16));
504
+ }
505
+ };
506
+ frames();
507
+ assert.equal(t.handle.current, 'low');
508
+ assert.equal(drawn(world, 'lamp'), false, 'Low is on');
509
+ for (let round = 0; round < 3; round += 1) {
510
+ t.handle.set('high');
511
+ frames();
512
+ assert.equal(drawn(world, 'lamp'), true, `High, round ${round + 1}`);
513
+ t.handle.set('low');
514
+ frames();
515
+ assert.equal(drawn(world, 'lamp'), false, `Low, round ${round + 1}`);
516
+ }
517
+ t.handle.set('auto');
518
+ frames();
519
+ t.handle.set('high');
520
+ frames();
521
+ assert.deepEqual(touched, ['renderer.getContext'], 'only the GPU hint, read once');
522
+ });
523
+
524
+ test('levers: a Shape that says solid blocks, so it is scenery, not decor (review P1)', () => {
525
+ assert.equal(classify({ Transform: {}, Shape: { solid: true } }), 'static');
526
+ assert.equal(classify({ Transform: {}, Shape: { solid: true }, Model: {} }), 'static');
527
+ assert.equal(classify({ Transform: {}, Shape: { solid: false } }), 'decor');
528
+ const actors = [
529
+ { id: 'wall', components: { Transform: {}, Shape: { kind: 'box', solid: true } }, at: [4, 0, 0] },
530
+ { id: 'wall-far', components: { Transform: {}, Shape: { kind: 'box', solid: true } }, at: [70, 0, 0] },
531
+ ];
532
+ const { world, scene } = fakeWorld(actors);
533
+ makeLevers({ boundsOf: bounds(0) }).apply(world, scene, 0);
534
+ assert.equal(drawn(world, 'wall'), true, 'a near wall that blocks is drawn');
535
+ assert.equal(drawn(world, 'wall-far'), false, 'far scenery is not');
536
+ });
537
+
538
+ test('the judge forgets half a window when the mode changes or a frame cannot count (review P2)', () => {
539
+ const storage = memoryStorage();
540
+ const t = makeTiers({ storage, clock: () => 1, deviceMemory: 8, levers: fakeLevers() });
541
+ const scene = { three: { renderer: {} } };
542
+ let now = 0;
543
+ const slow = (ms, counts = true) => {
544
+ for (const end = now + ms; now < end; ) {
545
+ now += 60;
546
+ t.frame(scene, counts, now);
547
+ }
548
+ };
549
+ slow(4800);
550
+ t.handle.set('high');
551
+ slow(2000);
552
+ t.handle.set('auto');
553
+ slow(120);
554
+ assert.equal(t.handle.current, 'high', 'slow frames from before High are gone');
555
+ assert.equal(storage.map.has(TIER_KEY), false, 'and nothing is remembered');
556
+ slow(4800);
557
+ slow(120, false);
558
+ slow(120);
559
+ assert.equal(t.handle.current, 'high', 'a frame that cannot count starts the window over');
560
+ slow(5200);
561
+ assert.equal(t.handle.current, 'low', 'a whole slow window still decides');
562
+ });
563
+
564
+ test('levers: a hidden node the engine rebuilds in place is taken out at once (review P2)', () => {
565
+ const { world, scene } = fakeWorld(TOWN);
566
+ const lv = makeLevers({ boundsOf: bounds(0) });
567
+ lv.apply(world, scene, 0);
568
+ assert.equal(drawn(world, 'lamp'), false);
569
+ // world3d.js ensureActorNode: the look changed, the old node released, a
570
+ // new entry in the same map under the same id, same size.
571
+ const node = new Obj('lamp', [3, 0, 3]);
572
+ world.scene.add(node);
573
+ world.nodes.set('lamp', { node });
574
+ lv.apply(world, scene, 10);
575
+ assert.equal(node.parent, null, 'not drawn for the rest of the 500 ms');
576
+ // And a hidden node simply put back is caught the same way.
577
+ world.scene.add(world.nodes.get('npc-far').node);
578
+ lv.apply(world, scene, 20);
579
+ assert.equal(drawn(world, 'npc-far'), false);
580
+ });
581
+
582
+ // The hub system with `hub.tiers` absent: never a call into tiers.js, never a
583
+ // storage read, no harness handle. tiers.js is stubbed for hub.js so any call
584
+ // is counted.
585
+ const sdkStub = 'export const Hub = undefined;';
586
+ const packStub = 'export const loadPack = () => Promise.reject(new Error("no")); export const cachedPacks = () => []; export const matchesOwn = () => false; export const resolveDeckDoor = () => Promise.reject(new Error("no"));';
587
+ const mediaStub = 'export const initialMedia = {}; export const playMedia = () => {}; export const stopMedia = () => {};';
588
+ const tiersStub = `
589
+ export function makeTiers() {
590
+ globalThis.__tiersMade = (globalThis.__tiersMade ?? 0) + 1;
591
+ return { mode: 'auto', set() {}, frame() { globalThis.__tiersFrames = (globalThis.__tiersFrames ?? 0) + 1; }, handle: { stub: true } };
592
+ }`;
593
+ const url = (src) => 'data:text/javascript,' + encodeURIComponent(src);
594
+ register(
595
+ url(`
596
+ export async function resolve(specifier, context, next) {
597
+ if (specifier === 'castle-web-sdk') return { url: ${JSON.stringify(url(sdkStub))}, shortCircuit: true };
598
+ if (specifier.startsWith('@imports/castle.physics-2d/engine/')) return { url: ${JSON.stringify(url(mediaStub))}, shortCircuit: true };
599
+ if (specifier === '../client/pack.js') return { url: ${JSON.stringify(url(packStub))}, shortCircuit: true };
600
+ if (specifier === '../client/tiers.js' && context.parentURL?.endsWith('/code/systems/hub.js')) return { url: ${JSON.stringify(url(tiersStub))}, shortCircuit: true };
601
+ return next(specifier, context);
602
+ }`),
603
+ );
604
+ const { installSystem } = await import('../code/systems/hub.js');
605
+ const { deck } = await import('../code/client/state.js');
606
+
607
+ {
608
+ let storageReads = 0;
609
+ Object.defineProperty(globalThis, 'localStorage', {
610
+ configurable: true,
611
+ get() {
612
+ storageReads += 1;
613
+ throw new Error('storage must not be read');
614
+ },
615
+ });
616
+ let system;
617
+ installSystem({ registerSystem: (s) => (system = s) });
618
+ let graphics = 0;
619
+ system.chrome = { setGraphics: () => (graphics += 1) };
620
+ const scene = { three: { renderer: {} }, content: null };
621
+ const mp = { placed: () => true };
622
+ globalThis.__hub = {};
623
+ test('hub.tiers absent: no tiers system is registered, nothing made, run or read', () => {
624
+ assert.equal(deck.tiers, false, 'off unless castle.json says so');
625
+ const late = [];
626
+ system.registerLate({ registerSystem: (s) => late.push(s) });
627
+ assert.equal(late.length, 1, 'only the late system the hub always had');
628
+ assert.equal(globalThis.__tiersMade, undefined);
629
+ assert.equal(globalThis.__tiersFrames, undefined);
630
+ assert.equal(system.tiers, undefined);
631
+ assert.equal(graphics, 0, 'no Graphics row');
632
+ assert.equal(storageReads, 0);
633
+ assert.equal('tier' in globalThis.__hub, false);
634
+ // deviceTier itself is guarded as well.
635
+ system.deviceTier(scene, mp, 0);
636
+ assert.equal(globalThis.__tiersMade, undefined);
637
+ });
638
+ test('hub.tiers true: a system of its own, made once, run each frame, a harness handle', () => {
639
+ deck.tiers = true;
640
+ const late = [];
641
+ system.registerLate({ registerSystem: (s) => late.push(s) });
642
+ assert.equal(late.length, 2);
643
+ late[1].afterBehaviors({ ...scene, multiplayer: mp });
644
+ late[1].afterBehaviors({ ...scene, multiplayer: mp });
645
+ assert.equal(globalThis.__tiersMade, 1);
646
+ assert.equal(globalThis.__tiersFrames, 2);
647
+ assert.equal(graphics, 1);
648
+ assert.deepEqual(globalThis.__hub.tier, { stub: true });
649
+ deck.tiers = false;
650
+ });
651
+ delete globalThis.localStorage;
652
+ }
653
+
654
+ test('hub.js reaches the tiers only through a system registered behind the opt-in', () => {
655
+ const src = fs.readFileSync(new URL('../code/systems/hub.js', import.meta.url), 'utf8');
656
+ assert.equal(src.match(/makeTiers\(/g)?.length, 1);
657
+ assert.equal(src.match(/this\.deviceTier\(/g)?.length, 1);
658
+ assert.match(src, /\n {4}if \(Hub\.deck\.tiers\) \{\n {6}scene\.registerSystem\(\{ afterBehaviors: \(s\) => this\.deviceTier\(/);
659
+ const afterBehaviors = src.slice(src.indexOf(' afterBehaviors(scene) {'), src.indexOf('\n }\n', src.indexOf(' afterBehaviors(scene) {')));
660
+ assert.doesNotMatch(afterBehaviors, /deviceTier|tiers/i, 'the per-frame update is the one it was');
661
+ const body = src.slice(src.indexOf(' deviceTier(scene, mp, now) {'));
662
+ assert.match(body, /^ {2}deviceTier\(scene, mp, now\) \{\n {4}if \(!Hub\.deck\.tiers\) \{\n {6}return;\n {4}\}/);
663
+ assert.equal(src.match(/this\.tiers\b/g)?.length, body.slice(0, body.indexOf('\n }\n')).match(/this\.tiers\b/g)?.length, 'this.tiers only inside deviceTier');
664
+ });
665
+
666
+ console.log(`test-tiers: ${n} passed`);