@wildshard/engine 0.1.22 → 0.1.24

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 (179) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +9 -0
  4. package/lint/sim-players.json +2 -13
  5. package/package.json +36 -3
  6. package/scripts/apfs-clone.mjs +5 -2
  7. package/scripts/app-build/catalogue.ts +39 -8
  8. package/scripts/app-build/serviceWorker.ts +4 -1
  9. package/scripts/app-build/splitOutput.mjs +33 -11
  10. package/scripts/app-build/titlePreloads.mjs +8 -5
  11. package/scripts/bake-road-surfaces.entry.ts +18 -0
  12. package/scripts/bake-road-surfaces.mjs +44 -0
  13. package/scripts/changelog.mjs +2 -1
  14. package/scripts/ci-pack.mjs +3 -3
  15. package/scripts/engine-ci-shard.mjs +11 -0
  16. package/scripts/fight-page-census.mjs +131 -0
  17. package/scripts/goldens/board.py +44 -11
  18. package/scripts/goldens/capture.mjs +18 -6
  19. package/scripts/goldens/native-residency.d.mts +2 -0
  20. package/scripts/goldens/native-residency.mjs +31 -4
  21. package/scripts/grid-road-lag.mjs +209 -0
  22. package/scripts/keep-copy.mjs +172 -0
  23. package/scripts/land.d.mts +4 -1
  24. package/scripts/land.mjs +121 -9
  25. package/scripts/lane-live.mjs +136 -0
  26. package/scripts/leftovers-report.mjs +47 -0
  27. package/scripts/loading-card-proof.mjs +42 -9
  28. package/scripts/loading-flow/benchmax.mjs +59 -7
  29. package/scripts/loading-flow/stalls.d.mts +2 -0
  30. package/scripts/loading-flow/stalls.mjs +13 -0
  31. package/scripts/map-hash.mjs +1 -1
  32. package/scripts/mmo-bots.mjs +5 -3
  33. package/scripts/mmo-grid-proof.mjs +74 -0
  34. package/scripts/mmo-seat-proof.mjs +43 -0
  35. package/scripts/nightly-heads.ts +13 -13
  36. package/scripts/nightly-model.ts +26 -12
  37. package/scripts/nightly-tag.mjs +2 -4
  38. package/scripts/nightly.proof.ts +18 -5
  39. package/scripts/nightly.ts +13 -8
  40. package/scripts/no-astc-boot.mjs +77 -0
  41. package/scripts/page-release/content.mjs +19 -10
  42. package/scripts/page-release/flow.d.mts +3 -2
  43. package/scripts/page-release/flow.mjs +31 -21
  44. package/scripts/page-release/packs.d.mts +5 -0
  45. package/scripts/page-release/packs.mjs +13 -3
  46. package/scripts/page-release/preview.d.mts +2 -0
  47. package/scripts/page-release/preview.mjs +74 -0
  48. package/scripts/page-release.mjs +13 -5
  49. package/scripts/physics-route.json +6 -6
  50. package/scripts/pins-reuse.mjs +1 -0
  51. package/scripts/pins-staging.ts +54 -0
  52. package/scripts/pins.ts +5 -0
  53. package/scripts/ring3.proof.ts +71 -0
  54. package/scripts/ring3.ts +100 -0
  55. package/scripts/road-drive-proof.mjs +269 -0
  56. package/scripts/road-memory-probe.mjs +129 -0
  57. package/scripts/scratch-dir.mjs +33 -14
  58. package/scripts/scratch-sweep.mjs +15 -23
  59. package/scripts/server-release/github.mjs +59 -26
  60. package/scripts/server-release/items.d.mts +7 -0
  61. package/scripts/server-release/items.mjs +28 -0
  62. package/scripts/server-release/publish.mjs +24 -2
  63. package/scripts/server-release/sign.mjs +8 -4
  64. package/scripts/side-parity.mjs +1 -1
  65. package/scripts/test-products.json +1 -0
  66. package/scripts/test_prebuilt_output.py +3 -1
  67. package/scripts/tsconfig.json +2 -0
  68. package/scripts/turn-in-shots.mjs +83 -0
  69. package/scripts/vitest-bench-observe-proof.py +168 -0
  70. package/scripts/vitest-bench.py +122 -77
  71. package/scripts/vitest-ci-files.ts +5 -1
  72. package/scripts/vps/rebuild.sh +3 -1
  73. package/scripts/vps/wildshard-config +106 -1
  74. package/scripts/warm-native-chrome.mjs +9 -3
  75. package/scripts/worker-client-fights.mjs +9 -3
  76. package/scripts/worktree-reap.mjs +36 -140
  77. package/scripts/worktree.mjs +92 -12
  78. package/scripts/zone-gate-proof.mjs +93 -0
  79. package/src/client/engine/audio/audioLog.ts +7 -2
  80. package/src/client/engine/boot/diagnostics.ts +69 -1
  81. package/src/client/engine/boot/sw.ts +3 -1
  82. package/src/client/engine/core/ktx2.ts +33 -10
  83. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  84. package/src/client/engine/models/place.ts +7 -5
  85. package/src/client/engine/pwa/sw.js +83 -10
  86. package/src/client/engine/render/dataLook.ts +14 -7
  87. package/src/client/engine/render/lookLight.ts +64 -20
  88. package/src/client/engine/render/precompile.ts +6 -0
  89. package/src/client/engine/render/tiers.ts +9 -0
  90. package/src/client/engine/ui/Loading.ts +6 -8
  91. package/src/client/engine/ui/lookLightOption.ts +1 -1
  92. package/src/client/engine/ui/playerReload.ts +5 -5
  93. package/src/client/game/audio/cueDirector.ts +2 -1
  94. package/src/client/game/boot/bytes.generated.ts +4 -1
  95. package/src/client/game/boot/versions.generated.ts +8 -5
  96. package/src/client/game/boss/arenaRoom.ts +4 -3
  97. package/src/client/game/boss/roamingProjection.ts +1 -1
  98. package/src/client/game/devScene/hook.ts +1 -1
  99. package/src/client/game/devScene/liveLook.ts +1 -1
  100. package/src/client/game/grid/cellClip.ts +70 -6
  101. package/src/client/game/grid/dataCellKit.ts +9 -1
  102. package/src/client/game/grid/gateCard.css +9 -0
  103. package/src/client/game/grid/gateCard.ts +67 -0
  104. package/src/client/game/grid/live.ts +17 -3
  105. package/src/client/game/grid/liveSession.ts +15 -5
  106. package/src/client/game/grid/neighbourLife.ts +10 -1
  107. package/src/client/game/grid/neighbourPanels.ts +29 -2
  108. package/src/client/game/grid/pageEntry.ts +21 -0
  109. package/src/client/game/grid/products.ts +21 -7
  110. package/src/client/game/grid/regionalWorld.ts +5 -0
  111. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  112. package/src/client/game/grid/roadLook.ts +5 -73
  113. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  114. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  115. package/src/client/game/grid/roadTilePool.ts +4 -0
  116. package/src/client/game/grid/session.ts +58 -16
  117. package/src/client/game/grid/softWallLook.ts +6 -1
  118. package/src/client/game/plugin/ui.ts +3 -0
  119. package/src/client/game/population/signals.ts +1 -1
  120. package/src/client/game/quest/chapterDirector.ts +1 -0
  121. package/src/client/game/session/play.ts +3 -0
  122. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  123. package/src/client/game/shardfile/clientSource.ts +5 -2
  124. package/src/client/game/shardfile/clientWorker.ts +25 -8
  125. package/src/client/game/shardfile/look.ts +1 -1
  126. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  127. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  128. package/src/client/game/shardfile/slabRanges.ts +145 -0
  129. package/src/client/game/shardfile/wirePage.ts +5 -2
  130. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  131. package/src/client/host/online/shell.ts +2 -2
  132. package/src/client/host/standalone/shell.ts +4 -1
  133. package/src/cook/game/cookWorker.ts +8 -5
  134. package/src/cook/game/tierTextures.ts +5 -3
  135. package/src/server/engine/net/simWorld.ts +3 -4
  136. package/src/server/game/grid/cellHome.ts +58 -0
  137. package/src/server/game/grid/simulation.ts +32 -8
  138. package/src/server/game/plugin/mover.ts +18 -14
  139. package/src/server/game/plugin/simulation.ts +2 -0
  140. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  141. package/src/server/game/shardfile/declaredKitItems.ts +31 -7
  142. package/src/server/host/bake/headlessWorker.ts +3 -3
  143. package/src/server/host/dedicated/cellWorker.ts +4 -2
  144. package/src/server/host/dedicated/main.ts +7 -4
  145. package/src/server/host/dedicated/packReader.ts +15 -2
  146. package/src/server/host/dedicated/playerStore.ts +1 -1
  147. package/src/server/host/headlessRuntime.ts +11 -6
  148. package/src/server/host/standalone/cellWorld.ts +20 -6
  149. package/src/server/host/standalone/gridServer.ts +20 -6
  150. package/src/server/host/standalone/roadWorld.ts +36 -0
  151. package/src/server/host/standalone/serverHost.ts +2 -2
  152. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  153. package/src/shared/engine/physics/gridBorders.ts +15 -1
  154. package/src/shared/engine/physics/transferWalls.ts +9 -4
  155. package/src/shared/engine/sim/snapshot.ts +5 -5
  156. package/src/shared/game/grid/allocator.ts +8 -1
  157. package/src/shared/game/grid/gateCount.ts +27 -0
  158. package/src/shared/game/grid/zoneWalls.ts +64 -0
  159. package/src/shared/game/ledger.ts +13 -4
  160. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  161. package/src/shared/game/quest/ledger.ts +3 -3
  162. package/src/shared/game/shardfile/items.ts +9 -1
  163. package/src/shared/game/strings.ts +2 -0
  164. package/src/shared/host/headlessJourney.ts +3 -3
  165. package/src/shared/host/headlessTape.ts +7 -6
  166. package/src/shared/host/releaseRows.ts +4 -1
  167. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  168. package/src/test/engine/simState.ts +134 -0
  169. package/src/test/game/builtProduct.ts +6 -0
  170. package/src/test/game/headless/admittedProductCache.ts +61 -0
  171. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  172. package/src/test/game/headless/nativeBounds.ts +27 -0
  173. package/src/test/game/headless/processUsage.ts +22 -0
  174. package/src/test/game/headless/productSession.ts +39 -0
  175. package/src/test/game/headless/ropeBodies.ts +60 -0
  176. package/src/test/game/headless/worker.ts +34 -0
  177. package/src/test/game/headlessNative.ts +114 -0
  178. package/src/test/game/headlessWorker.ts +43 -0
  179. package/src/test/tsconfig.game.json +3 -0
@@ -348,6 +348,8 @@ function askPrecache(): void {
348
348
  };
349
349
  ask(reg.active);
350
350
  if (reg.waiting?.state === 'installed') post(reg.waiting);
351
+ // STALESHELL: an update installing now downloads its generation in its install (sw.js); this page's control resumes it too
352
+ if (reg.installing !== null && reg.active !== null) post(reg.installing);
351
353
  const installing = reg.installing;
352
354
  ask(installing); // it may have activated while the control frames ran
353
355
  if (!precacheAsked && installing !== null) pageScope.listen(installing, 'statechange', () => { ask(installing); });
@@ -385,7 +387,7 @@ async function register(s: ServiceWorkerContainer): Promise<void> {
385
387
  watch(reg);
386
388
  // DL1 (sp-x2): this page is loading. A waiting update (and the active worker, when this page is uncontrolled) sees
387
389
  // none of its fetches, so tell them to step their precache aside; this page's control resumes it (PRECACHE).
388
- if (!controlReached) for (const w of [reg.waiting, sw?.controller === null ? reg.active : null]) {
390
+ if (!controlReached) for (const w of [reg.waiting, reg.active === null ? null : reg.installing, sw?.controller === null ? reg.active : null]) {
389
391
  // oxlint-disable-next-line unicorn/require-post-message-target-origin -- ServiceWorker.postMessage has no targetOrigin parameter.
390
392
  if (w !== null && w !== undefined) try { w.postMessage({ type: 'PAUSE' }); } catch { /* a retired worker has nothing to pause */ }
391
393
  }
@@ -40,10 +40,20 @@ import { workSlice } from '../../../shared/engine/core/workSlice';
40
40
  import { TIER } from './tier';
41
41
  import { prepareKtx2Zstd, unsupercompressKtx2 } from './ktx2Zstd';
42
42
  import { parseKtx2 } from '@wildshard/format/ktx2Cost';
43
+ import { waitFor } from '../../../shared/engine/boot/waits';
44
+ import { bootTask } from '../../../shared/engine/boot/timing';
43
45
 
44
- /** where scripts/app-build/basis.ts copies three's transcoder: versioned by three's revision, so the SW / HTTP caches never mix two */
45
46
  /** Before transcoding `files`: start what their parses will need (the raw-texel zstd decoder) from the caller's stack. */
46
47
  export function prepareKtx2Decode(files: Iterable<Uint8Array | undefined>): void { prepareKtx2Zstd(files); }
48
+ /** Whether a named native WebGL compressed format sampled correctly at every mip on this device.
49
+ * The name is a format label from the texture capability probe, for example SRGB8_ALPHA8_ASTC_6x6.
50
+ * Unknown formats and a device without a completed WebGL2 probe return false. */
51
+ export function nativeCompressedFormatSupported(format: string): boolean {
52
+ const probe = ktx2Probe();
53
+ return probe.ran && probe.formats.some(row => row.format === format && row.ok);
54
+ }
55
+
56
+ /** The transcoder path is versioned by three's revision, keeping SW and HTTP caches compatible. */
47
57
  export const BASIS_PATH: Parameters<KTX2Loader['setTranscoderPath']>[0] = `/basis/r${THREE.REVISION}/`;
48
58
 
49
59
  let loader: KTX2Loader | null = null;
@@ -303,21 +313,33 @@ const reading = new Map<string, Promise<ArrayBuffer>>();
303
313
  * ReadableStream nobody here listens to (T10: its enqueue / close were ~200 ms of a Pine cold entry at phone 4x). Same
304
314
  * URL resolution (the page's modifier on the default manager), credentials, headers and status rule, then the loader's
305
315
  * own parse. */
306
- export function loadKtx2(target: Pick<KTX2Loader, 'manager' | 'path' | 'requestHeader' | 'withCredentials' | 'parse'>, url: string): Promise<THREE.CompressedTexture> {
316
+ export function loadKtx2(target: Pick<KTX2Loader, 'manager' | 'path' | 'requestHeader' | 'withCredentials' | 'parse'>, url: string, signal?: AbortSignal): Promise<THREE.CompressedTexture> {
317
+ signal?.throwIfAborted();
307
318
  const resolved = target.manager.resolveURL(target.path + url);
308
- let bytes = reading.get(resolved);
319
+ let bytes = signal === undefined ? reading.get(resolved) : undefined;
309
320
  if (bytes === undefined) {
310
- bytes = fetch(resolved, { headers: target.requestHeader, credentials: target.withCredentials ? 'include' : 'same-origin' }).then(response => {
321
+ bytes = bootTask(`texture:read ${resolved}`, () => waitFor('Reading texture', fetch(resolved, {
322
+ headers: target.requestHeader, credentials: target.withCredentials ? 'include' : 'same-origin',
323
+ ...(signal === undefined ? {} : {signal}),
324
+ }).then(response => {
311
325
  if (response.status !== 200 && response.status !== 0) throw new Error(`fetch for "${response.url}" responded with ${String(response.status)}: ${response.statusText}`);
312
326
  return response.arrayBuffer();
313
- });
314
- reading.set(resolved, bytes);
327
+ }), 'file', resolved));
328
+ if (signal === undefined) reading.set(resolved, bytes);
315
329
  const read = bytes;
316
330
  const clear = (): void => { if (reading.get(resolved) === read) reading.delete(resolved); };
317
331
  read.finally(clear).catch(() => undefined);
318
332
  }
319
- return bytes.then(buffer => new Promise<THREE.CompressedTexture>((resolve, reject) => { target.parse(buffer, resolve, reject); }));
333
+ return bytes.then(buffer => {
334
+ signal?.throwIfAborted();
335
+ return bootTask(`texture:decode ${resolved}`, () => waitFor('Preparing texture', new Promise<THREE.CompressedTexture>((resolve, reject) => {
336
+ target.parse(buffer, texture => {
337
+ if (signal?.aborted === true) { texture.dispose(); reject(new Error('KTX2 read aborted', {cause: signal.reason})); } else resolve(texture);
338
+ }, reject);
339
+ }), 'worker', resolved));
340
+ });
320
341
  }
342
+
321
343
  function load(url: string, keep: boolean): Promise<THREE.CompressedTexture> {
322
344
  let p = transcoded.get(url);
323
345
  if (p === undefined) {
@@ -334,11 +356,12 @@ function load(url: string, keep: boolean): Promise<THREE.CompressedTexture> {
334
356
  * A KTX2 file at its own URL (a shardfile product's named blob, not the stand-in of another file) as a CompressedTexture
335
357
  * on the page's loader, in any texture mode: one transcode per file per wave, flipY = false (the file keeps its encoded
336
358
  * orientation), its mips dropped from JS once uploaded. The caller sets its sampler and colour space, then fences it with
337
- * `prepareCompressedTexture`.
359
+ * `prepareCompressedTexture`. An optional signal owns an isolated, cancellable read.
338
360
  */
339
- export async function ktx2File(url: string): Promise<THREE.CompressedTexture> {
361
+ export async function ktx2File(url: string, signal?: AbortSignal): Promise<THREE.CompressedTexture> {
340
362
  if (texMode() !== 'ktx2') markGpuOnly('KTX2 product files on the image path (their mips are dropped from JS once uploaded)');
341
- const t = (await load(url, true)).clone();
363
+ // Cancellable callers own their read and parsed texture; abort cannot cancel a shared wave.
364
+ const t = signal === undefined ? (await load(url, true)).clone() : await loadKtx2(ktx2Loader(), url, signal);
342
365
  t.flipY = false;
343
366
  t.generateMipmaps = false;
344
367
  sources.share(t, url, 0);
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { pageScope } from '../../../shared/engine/app/resources';
10
10
  import type { Scope } from '../../../shared/engine/app/scope';
11
+ import { waitFor } from '../../../shared/engine/boot/waits';
11
12
 
12
13
  const HEADER = 80, LEVEL = 24, SCHEME_ZSTD = 2;
13
14
  /** level data starts at a multiple of this in the rewritten file (the spec's lcm(texel block size, 4) for every format) */
@@ -143,7 +144,7 @@ export async function unsupercompressKtx2(buffer: ArrayBuffer): Promise<ArrayBuf
143
144
  const bytes = new Uint8Array(buffer), levels = zstdLevels(bytes);
144
145
  if (levels === null) return buffer;
145
146
  try {
146
- const decoded = await decodeLevels(levels.map(level => ({ data: bytes.slice(level.offset, level.offset + level.length), size: level.size })));
147
+ const decoded = await waitFor('Preparing texture data', decodeLevels(levels.map(level => ({ data: bytes.slice(level.offset, level.offset + level.length), size: level.size }))), 'worker');
147
148
  if (decoded.length !== levels.length || decoded.some((data, i) => data.byteLength !== levels[i]?.size)) return buffer;
148
149
  const plain = plainKtx2(bytes, levels, decoded);
149
150
  return plain.buffer instanceof ArrayBuffer ? plain.buffer : buffer;
@@ -36,6 +36,7 @@ import { FrameCamera } from '../world/frameCamera';
36
36
  import { geometryBoundsSteps } from '../world/geometryBounds';
37
37
  import { keepShadowWhole } from '../world/shadowChunks';
38
38
  import { withTier } from '../explore/tiers';
39
+ import { TIER_CONFIG } from '../core/tier';
39
40
  import { loadingSpecimen } from './gear';
40
41
  import { specimenReady, paramsOf, seedOf, type ModelBuild, type ModelBuildVisit, type ModelContext, type ModelDef, type ModelPart, type Placement } from './model';
41
42
  import { drawnHullOwn, drawnHullWorld, placeCollider, poseGeometry, poseOf, type Pose } from './colliders';
@@ -423,10 +424,11 @@ function collideCopy<P extends object>(def: ModelDef<P>, params: P, pose: Pose,
423
424
  }
424
425
  }
425
426
 
426
- /** level start distances: 0 for the model's own parts, then each LOD's `from` */
427
- const levelsOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.from)];
428
- /** each level's dissolve band before its start (`ModelLod.fade`; level 0 has none) */
429
- const fadesOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.fade ?? 0)];
427
+ /** level start distances: 0 for the model's own parts, then each LOD's `from`, times the tier's `placedLodScale` (NB5: the
428
+ * phone's smaller pixels per metre switch levels nearer; the desktop's 1 keeps the authored distances) */
429
+ const levelsOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.from * TIER_CONFIG.placedLodScale)];
430
+ /** each level's dissolve band before its start (`ModelLod.fade`; level 0 has none), scaled with its start */
431
+ const fadesOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => (l.fade ?? 0) * TIER_CONFIG.placedLodScale)];
430
432
 
431
433
  /** A callback belongs to one place call, so nested builders cannot mix their copies. */
432
434
  type BuildOptions<P extends object> = PlaceOptions & { readonly visitBuild?: (build: ModelBuildVisit<P>) => void };
@@ -908,7 +910,7 @@ function drawSingle<P extends object>(def: ModelDef<P>, pls: readonly Placement<
908
910
  lod.addLevel(obj, 0);
909
911
  (def.lods ?? []).forEach((l, k) => {
910
912
  const lp = partsOf(buildModel(def, o, p, new Rng(seedOf(def) ^ Math.imul(k + 1, 0x9e3779b9)), pls.slice(i, i + 1), k + 1), def.id, o.draw);
911
- lod.addLevel(lp.length === 0 ? new THREE.Object3D() : wrap(lp.map((x) => meshOf(x)), `${def.id}:lod${k + 1}`), l.from);
913
+ lod.addLevel(lp.length === 0 ? new THREE.Object3D() : wrap(lp.map((x) => meshOf(x)), `${def.id}:lod${k + 1}`), l.from * TIER_CONFIG.placedLodScale);
912
914
  });
913
915
  obj = lod;
914
916
  }
@@ -52,11 +52,11 @@ const immutable = url => NAMED.has(url.pathname) || url.pathname.startsWith('/b/
52
52
  || /^[a-f0-9]{8,64}$/.test(url.searchParams.get('v') ?? '');
53
53
  const isHtml = response => /\btext\/html\b/i.test(response.headers.get('content-type') ?? '');
54
54
  /* PAGE-SIZE PZ10 (J276): content on the content base (`https://packs.wildshard.io/content/<set>/`, baked from the boot
55
- * bank by serviceWorker.ts; '' when content is on the page) lives in one cross-build cache, keyed by exact URL: every key
56
- * there is content-named, so a copy is good for every build that names it, and no activate touches it. Only a CORS 200 is
55
+ * bank by serviceWorker.ts; '' when content is on the page) lives in one cross-build cache. NB11 removes the set folder
56
+ * only from content-named or per-file-versioned keys; mutable files retain their release URL. No activate touches it. Only a CORS 200 is
57
57
  * kept: an opaque body cannot be checked and is padded against quota, and a range never stands for the whole file. */
58
- /** @type {{ base: string, files: string[] }} one parsed value: the bundler would fold a literal base into its origin */
59
- const { base: CONTENT_BASE, files: CONTENT_FILES } = JSON.parse('__CONTENT__');
58
+ /** @type {{ base: string, files: string[], versions?: Record<string, string> }} one parsed value: the bundler would fold a literal base into its origin */
59
+ const { base: CONTENT_BASE, files: CONTENT_FILES, versions: CONTENT_VERSIONS = {} } = JSON.parse('__CONTENT__');
60
60
  /** OF5: the server book on the content base is solo-only too (a URL there, its path under the base's folder). */
61
61
  const CONTENT_PRECACHE = CONTENT_FILES.filter(href => !WORLD || !SOLO_ONLY.test(new URL(href).pathname));
62
62
  const CONTENT_CACHE = cacheName('ws-content-v1', CHANNEL);
@@ -78,6 +78,23 @@ const keepContent = response => (response.type === 'cors' || SAME_ORIGIN_BASE &&
78
78
  * @param {Request | string} input @param {RequestInit} init */
79
79
  const corsRequest = (input, init = {}) => new Request(input, { ...init, mode: 'cors', credentials: 'omit' });
80
80
 
81
+ /** NB11: a release's set folder changes when any content changes. Only a
82
+ * content-named file or a build-declared content hash can leave that folder.
83
+ * Mutable metadata keeps its exact release URL; channel stores remain separate. */
84
+ function contentKey(href) {
85
+ if (CONTENT_URL === undefined) return href;
86
+ const address = new URL(href);
87
+ if (address.origin !== CONTENT_URL.origin || !address.pathname.startsWith(CONTENT_URL.pathname)) return href;
88
+ const path = address.pathname.slice(CONTENT_URL.pathname.length - 1);
89
+ const version = CONTENT_VERSIONS[path];
90
+ if (!CONTENT.test(path) && !PAGE_PART.test(path) && !OWN_NAMED.test(path)
91
+ && !/^[a-f0-9]{8,64}$/.test(address.searchParams.get('v') ?? '') && version === undefined) return href;
92
+ const key = new URL(`/__ws_content__/v1${path}`, CONTENT_URL.origin);
93
+ key.search = address.search;
94
+ if (!key.searchParams.has('v') && version !== undefined) key.searchParams.set('v', version);
95
+ return key.href;
96
+ }
97
+
81
98
  // Keep the current worker's hot handles. WebKit can take a second to reopen
82
99
  // a cache during navigation; a rejected open must remain retryable.
83
100
  const stores = new Map();
@@ -143,9 +160,35 @@ workerScope.listen(self, 'install', event => {
143
160
  const namedShell = SHELL_FILES.filter(path => immutable(new URL(abs(path))));
144
161
  await Promise.all([precache(shell, SHELL_FILES.filter(path => !namedShell.includes(path))),
145
162
  precache(assets, namedShell, true)]);
163
+ // STALESHELL (QA 11-15 row 32, Jake: "the cache PWA one has to swap out new code"): an update (a worker already runs
164
+ // this origin) takes over by itself, so the next boot is the new build and nobody waits on a reload that never
165
+ // activates it. When the running build is whole on this device (its generation is held, so it boots offline), the new
166
+ // one first downloads its own whole generation here, in the background while the player plays; a download cut short
167
+ // (bad Wi-Fi) fails the install, the running build stays whole and nothing of the new one boots, and the browser's next
168
+ // update check resumes from what the shared cache already holds. A running build that is not whole has nothing to keep:
169
+ // it can't boot offline, and its document names code a newer deploy took off the server (Jake's phone sat on v0.1.19's
170
+ // title through every reload), so the new worker takes over after its shell. A first visit stays shell-only (DL1).
171
+ const running = self.registration?.active;
172
+ if (running === null || running === undefined) return;
173
+ const runningBuild = await buildOfWorker(running);
174
+ if (runningBuild !== undefined && await (await caches.open(BOOKS)).match(bookKey(runningBuild)) !== undefined) await precacheGeneration();
175
+ await self.skipWaiting();
146
176
  })());
147
177
  });
148
178
 
179
+ /** The build a worker serves (its `BUILD` reply, which every worker since the MF1 rewrite answers), or undefined after 3 s. */
180
+ function buildOfWorker(worker) {
181
+ return new Promise(resolve => {
182
+ workerScope.timeout(3000, () => { resolve(undefined); }); // the first answer wins
183
+ const done = build => { resolve(build); };
184
+ try {
185
+ const channel = new MessageChannel();
186
+ channel.port1.onmessage = event => { done(typeof event.data?.build === 'string' && event.data.build !== '' ? event.data.build : undefined); };
187
+ worker.postMessage({ type: 'BUILD' }, [channel.port2]);
188
+ } catch { done(undefined); }
189
+ });
190
+ }
191
+
149
192
  // DL1: the build's hashed code is precached only when a page reports control (PRECACHE), so a cold visit's level
150
193
  // download has the link to itself. Chunks that page already loaded come from the HTTP cache (force-cache).
151
194
  // Only a completely precached build is a generation; a failed precache never evicts working code and is asked again.
@@ -217,14 +260,14 @@ async function precacheQueue(cache, urls, content = false) {
217
260
  await whilePaused();
218
261
  const path = pending.shift();
219
262
  if (path === undefined) return;
220
- const key = abs(path), control = new AbortController();
263
+ const address = abs(path), key = content ? contentKey(address) : address, control = new AbortController();
221
264
  inflight.add(control);
222
265
  try {
223
266
  const held = await cache.match(key, MATCH);
224
267
  if (held !== undefined && !isHtml(held)) continue;
225
268
  if (held !== undefined) await cache.delete(key);
226
269
  if (content) {
227
- const response = await fetch(corsRequest(key, { cache: 'force-cache', signal: control.signal }));
270
+ const response = await fetch(corsRequest(address, { cache: 'force-cache', signal: control.signal }));
228
271
  if (!keepContent(response)) throw new Error(`Precache failed: ${path} (${response.type} ${response.status})`);
229
272
  await cache.put(key, response);
230
273
  continue;
@@ -397,10 +440,11 @@ async function networkFirst(request, name, event) {
397
440
  * @param {Request} request */
398
441
  async function contentRead(request) {
399
442
  const reload = request.cache === 'reload' || request.cache === 'no-store';
443
+ const key = contentKey(request.url);
400
444
  let cache;
401
445
  try {
402
446
  cache = await store(CONTENT_CACHE);
403
- const held = reload ? undefined : await cache.match(request.url, MATCH);
447
+ const held = reload ? undefined : await cache.match(key, MATCH) ?? (key === request.url ? undefined : await cache.match(request.url, MATCH));
404
448
  if (held !== undefined && !isHtml(held)) return held;
405
449
  } catch { stores.delete(CONTENT_CACHE); /* Storage denial keeps online fetch working. */ }
406
450
  let response;
@@ -409,10 +453,37 @@ async function contentRead(request) {
409
453
  try { response = await fetch(corsRequest(request)); }
410
454
  catch { return fetch(request); }
411
455
  }
412
- if (cache !== undefined && keepContent(response)) await cache.put(request.url, response.clone()).catch(() => undefined);
456
+ if (cache !== undefined && keepContent(response)) await cache.put(key, response.clone()).catch(() => undefined);
413
457
  return response;
414
458
  }
415
459
 
460
+ /** The document baked into this worker: its build's own page, whatever URL asked (the page reads its route from the URL). */
461
+ const bakedDocument = () => new Response(DOCUMENT, { headers: { ...DOCUMENT_HEADERS, 'content-type': 'text/html;charset=utf-8', 'cache-control': 'no-store' } });
462
+ /** STALESHELL: how long a navigation waits on the network before a worker whose code is not all held answers with its own
463
+ * document anyway (offline, or a link that never answers). */
464
+ const NAVIGATION_WAIT_MS = 6000;
465
+ let generationHeld = false;
466
+ /** Whether this build's whole generation is held (its book is written only once every file is). Only a yes is remembered. */
467
+ async function holdsGeneration() {
468
+ if (generationHeld) return true;
469
+ try { generationHeld = await (await store(BOOKS)).match(bookKey(BUILD)) !== undefined; } catch { return false; }
470
+ return generationHeld;
471
+ }
472
+ /** STALESHELL (QA 11-15 row 32: Jake's phone sat on v0.1.19's title for good, "8 of 8 files", then "still waiting"): this
473
+ * worker answers a navigation with its own document only when it holds that document's whole generation, so the page boots
474
+ * complete from the cache, offline too. A worker that holds less (it never reached control on this build) can't promise the
475
+ * code its document names, and a newer deploy has removed it from the server: the network's page answers, and the baked
476
+ * document only when the network can't (offline, or no answer in NAVIGATION_WAIT_MS). The request's own URL is kept either
477
+ * way: a `/slug/<x>` stays itself.
478
+ * @param {Request} request */
479
+ async function navigation(request) {
480
+ if (await holdsGeneration()) return bakedDocument();
481
+ const waited = new Promise(resolve => { workerScope.timeout(NAVIGATION_WAIT_MS, () => { resolve(undefined); }); });
482
+ const online = fetch(request).then(response => response.type === 'opaqueredirect' || response.ok && isHtml(response) ? response : undefined,
483
+ () => undefined);
484
+ return await Promise.race([online, waited]) ?? bakedDocument();
485
+ }
486
+
416
487
  workerScope.listen(self, 'fetch', event => {
417
488
  const request = event.request, url = new URL(request.url);
418
489
  // A diagnostic document must reach its own host route, not the cached game
@@ -429,8 +500,10 @@ workerScope.listen(self, 'fetch', event => {
429
500
  if (url.pathname === '/version.json' || url.pathname === '/sw.js' || url.pathname.startsWith('/api/')) return;
430
501
  if (request.mode === 'navigate' || url.pathname === '/' || url.pathname === '/index.html') {
431
502
  const received=diagnosticNow();
432
- event.respondWith(new Response(DOCUMENT, { headers: { ...DOCUMENT_HEADERS, 'content-type': 'text/html;charset=utf-8', 'cache-control': 'no-store' } }));
433
- bootPublish(event,[{operation:'sw:navigation-handler-and-delivery',url:request.url,start:received,end:diagnosticNow(),result:'complete'}]);
503
+ event.respondWith(navigation(request).then(response => {
504
+ bootPublish(event,[{operation:'sw:navigation-handler-and-delivery',url:request.url,start:received,end:diagnosticNow(),result:'complete'}]);
505
+ return response;
506
+ }));
434
507
  return;
435
508
  }
436
509
  if (PAGE_PART.test(url.pathname)) {
@@ -66,7 +66,9 @@ export interface DataLookSpec {
66
66
  readonly light?: {
67
67
  readonly rim: LookRim | null; readonly pools: LookPools | null; readonly heightFogDensity: number;
68
68
  /** B2: real lamps, a warm bounce and a sky-derived environment; absent or null: none */
69
- readonly lamps?: readonly LookLamp[] | null; readonly bounce?: LookBounce | null; readonly environment?: LookEnvironment | null;
69
+ readonly lamps?: readonly LookLamp[] | null;
70
+ /** AP28: how many lamps light a frame, the nearest the camera; absent: `DESKTOP_LAMPS` */
71
+ readonly lampsLit?: number; readonly bounce?: LookBounce | null; readonly environment?: LookEnvironment | null;
70
72
  /** TEMPLATES-CLEANROOM M4: the sun's shadow look and glow motes; absent or null: the engine's shadows, no motes */
71
73
  readonly shadow?: LookShadow | null; readonly motes?: LookMotes | null;
72
74
  };
@@ -237,6 +239,8 @@ function cellTone(spec: { readonly neutral?: boolean; readonly aces?: boolean; r
237
239
  * A level look from data: the engine's clean chain, the gradient dome, the engine fog, key light and ambient turned by
238
240
  * the keys on the engine clock, and the LUT last in the grade. Nothing is patched into another material.
239
241
  */
242
+ const lampEye = new THREE.Vector3();
243
+
240
244
  export function dataLook(spec: DataLookSpec): LookStrategy {
241
245
  if (spec.keys.length === 0) throw new Error('[look] a data look needs at least one key');
242
246
  const linear = spec.keys[0]?.fog.near !== undefined;
@@ -270,9 +274,9 @@ ${mist ? `
270
274
  shader.fragmentShader = `#ifdef USE_FOG\nuniform float wsLookFogNear; uniform float wsLookFogFar; uniform float wsLookFogEnabled;\n#endif\n${patched}`;
271
275
  };
272
276
  const owned: { dome: THREE.Mesh<THREE.SphereGeometry, THREE.Material> | null; lut: LookupTexture | null; pools: THREE.Object3D | null; rim: boolean;
273
- lamps: ReturnType<typeof lampLights> | null; bounce: ReturnType<typeof bounceLight> | null; environment: THREE.WebGLRenderTarget | null;
277
+ lamps: ReturnType<typeof lampLights> | null; eye: THREE.Camera | null; bounce: ReturnType<typeof bounceLight> | null; environment: THREE.WebGLRenderTarget | null;
274
278
  glow: THREE.Object3D[] | null; fx: EngineEffects | null; exposure: ExposureEffect | null; clock: DayCycle | null;
275
- chain: { vignette: { offset: number; darkness: number }; radius: number } | null } = { dome: null, lut: null, pools: null, rim: false, lamps: null, bounce: null, environment: null, glow: null,
279
+ chain: { vignette: { offset: number; darkness: number }; radius: number } | null } = { dome: null, lut: null, pools: null, rim: false, lamps: null, eye: null, bounce: null, environment: null, glow: null,
276
280
  fx: null, exposure: null, clock: null, chain: null };
277
281
  // AP17: what `liveLook` last set (the light rows and the LUT are compared with the build's, never set)
278
282
  let day = spec.day, dayOverride = spec.dayOverride;
@@ -312,7 +316,9 @@ ${mist ? `
312
316
  return true;
313
317
  },
314
318
  // the sky builds before the composer: the level scope takes the dome and the LUT here
315
- mode: 'extend', chain: 'clean', compose: ({ engineChain, scene, scope, fx, renderer }) => {
319
+ mode: 'extend', chain: 'clean', compose: ({ engineChain, scene, scope, fx, renderer, camera }) => {
320
+ // AP28: the lamps nearest this camera light
321
+ owned.eye = camera; scope.onDispose(() => { if (owned.eye === camera) owned.eye = null; });
316
322
  const rim = spec.light?.rim ?? null, pools = spec.light?.pools ?? null, lamps = spec.light?.lamps ?? null;
317
323
  if (rim !== null && !owned.rim) {
318
324
  owned.rim = true; scope.onDispose(() => { owned.rim = false; });
@@ -335,7 +341,7 @@ ${mist ? `
335
341
  }
336
342
  if (lamps !== null && owned.lamps === null) {
337
343
  // B2: real lamps, once per look like the pools
338
- const group = lampLights(lamps);
344
+ const group = lampLights(lamps, spec.light?.lampsLit);
339
345
  owned.lamps = group;
340
346
  scene.add(group); scope.onDispose(() => { group.removeFromParent(); for (const light of group.children) if (light instanceof THREE.Light) light.dispose(); if (owned.lamps === group) owned.lamps = null; });
341
347
  }
@@ -343,7 +349,8 @@ ${mist ? `
343
349
  if (owned.glow === null && ((lamps?.some((lamp) => lamp.halo !== undefined) ?? false) || motes !== null)) {
344
350
  // M4.8: the lamps' halos (one instanced draw) and the motes (one points draw), once per look like the lamps
345
351
  const glow: (THREE.Mesh | THREE.Points)[] = [];
346
- const halos = lamps === null ? null : lampHalos(lamps);
352
+ // a following lamp's halo would stay at its offset: AP24b lights it, its halo waits
353
+ const halos = lamps === null ? null : lampHalos(lamps.filter((lamp) => lamp.follow === undefined));
347
354
  if (halos !== null) glow.push(halos);
348
355
  if (motes !== null) glow.push(lookMotes(motes));
349
356
  owned.glow = glow;
@@ -436,7 +443,7 @@ ${mist ? `
436
443
  owned.lut = await lutTexture(spec.lut);
437
444
  return { clock, horizon: now.fog.clone(), lut: owned.lut, clouds: dome,
438
445
  bind: (t) => { targets = t; apply(); },
439
- update: (dt) => { clock.update(dt); apply(); flicker += dt; owned.lamps?.update?.(flicker); if (owned.glow !== null) tickGlow(owned.glow, flicker); },
446
+ update: (dt) => { clock.update(dt); apply(); flicker += dt; owned.lamps?.update?.(flicker, owned.eye?.getWorldPosition(lampEye)); if (owned.glow !== null) tickGlow(owned.glow, flicker); },
440
447
  rebuild: () => undefined, attachPost: () => undefined };
441
448
  },
442
449
  };
@@ -21,7 +21,7 @@
21
21
  * All of it waits behind Settings ▸ Debug ▸ Look ▸ "Look light" (read at load; default on): with the row off, a look that
22
22
  * declares every setting draws as one that declares none. TEMPLATES-CLEANROOM M4.9 gates it per field on the phone tier
23
23
  * instead of all or nothing: a phone keeps the environment, bounce, pools, rim, height fog and shadow look, at most
24
- * `PHONE_LAMPS` lamps, half the motes, and no bloom or AO.
24
+ * `PHONE_LAMPS` lamps lit, the nearest (AP28), half the motes, and no bloom or AO.
25
25
  */
26
26
  import * as THREE from 'three';
27
27
  import type { LookBounce, LookEnvironment, LookLamp, LookLight, LookPools, LookRim } from '@wildshard/format/look-light';
@@ -42,6 +42,8 @@ export interface LookLightResolved {
42
42
  readonly rim: LookRim | null;
43
43
  readonly pools: LookPools | null;
44
44
  readonly lamps: readonly LookLamp[] | null;
45
+ /** AP28: how many of `lamps` light a frame, the nearest the eye (`PHONE_LAMPS` on a phone, `DESKTOP_LAMPS` else) */
46
+ readonly lampsLit: number;
45
47
  readonly bounce: LookBounce | null;
46
48
  readonly environment: LookEnvironment | null;
47
49
  /** M4.2: the sun's shadow look; null: the engine's */
@@ -61,10 +63,12 @@ const NO_HEIGHT_FOG = { fogHeight: -20, fogHeightFalloff: 0, fogHeightDensity: 0
61
63
 
62
64
  /** M4.9: at most this many of a look's lamps light on the phone tier (each costs every lit draw a light-loop step) */
63
65
  export const PHONE_LAMPS = 4;
66
+ /** SHARD-SOURCE AP28: at most this many of a look's lamps light a desktop frame (shard-format `LOOK_LIGHT_LIT_MAX`) */
67
+ export const DESKTOP_LAMPS = 16;
64
68
 
65
69
  /**
66
70
  * Resolve a look's light settings; `on` is the Debug row ("Look light"), `tier` the page's. Off, or nothing declared: as
67
- * before. The phone tier keeps the cheap fields (M4.9): no bloom or AO, the first `PHONE_LAMPS` lamps, half the motes.
71
+ * before. The phone tier keeps the cheap fields (M4.9): no bloom or AO, the nearest `PHONE_LAMPS` lamps lit (AP28), half the motes.
68
72
  */
69
73
  export function lookLightManifest(look: LookLightSource, on: boolean, tier = 'desktop'): LookLightResolved {
70
74
  const phone = tier === 'phone';
@@ -76,7 +80,8 @@ export function lookLightManifest(look: LookLightSource, on: boolean, tier = 'de
76
80
  ao: light?.ao === undefined || phone ? null : { intensity: light.ao.intensity, radius: light.ao.radius },
77
81
  rim: light?.rim ?? null,
78
82
  pools: light?.pools ?? null,
79
- lamps: light?.lamps === undefined ? null : phone ? light.lamps.slice(0, PHONE_LAMPS) : light.lamps,
83
+ lamps: light?.lamps ?? null,
84
+ lampsLit: phone ? PHONE_LAMPS : DESKTOP_LAMPS,
80
85
  bounce: light?.bounce ?? null,
81
86
  environment: light?.environment ?? null,
82
87
  shadow: light?.shadow ?? null,
@@ -156,29 +161,68 @@ export function bounceLight(bounce: LookBounce): { light: THREE.DirectionalLight
156
161
  return { light, aim };
157
162
  }
158
163
 
164
+ /** SHARD-SOURCE AP24b: what a following lamp rides (`lamps[].follow`), or null while that actor is not in the world. */
165
+ export type LampFollowResolve = (actor: string, bone: string | undefined) => THREE.Object3D | null;
166
+ const lampFollows = new WeakMap<THREE.Object3D, LampFollowResolve>();
167
+ /** The page's actor lookup for the following lamps drawn under `root` (its scene); returns the undo. */
168
+ export function setLampFollow(root: THREE.Object3D, resolve: LampFollowResolve): () => void {
169
+ lampFollows.set(root, resolve);
170
+ return () => { if (lampFollows.get(root) === resolve) lampFollows.delete(root); };
171
+ }
172
+ const rootOf = (object: THREE.Object3D): THREE.Object3D => { let at = object; while (at.parent !== null) at = at.parent; return at; };
173
+
174
+ /** a lamp group's frame step: `time` drives the flicker, `eye` (world) picks the nearest lamps when more than `lit` exist */
175
+ export type LampUpdate = (time: number, eye?: THREE.Vector3Like) => void;
176
+
159
177
  /**
160
- * The look's lamps (B2): one shadowless point light each, physical decay unless the lamp sets its own (M4.3). `update`
161
- * flickers the lamps that declare a flicker (two incommensurate sines per lamp, so no two lamps pulse together); it is
162
- * null when none does.
178
+ * The look's lamps (B2): a pool of at most `lit` shadowless point lights (AP28: 16 on a desktop, `PHONE_LAMPS` on a phone),
179
+ * physical decay unless a lamp sets its own (M4.3). The pool's size never changes, so no shader recompiles as lamps come and
180
+ * go: `update` gives its lights to the lamps nearest `eye`, places each following lamp (AP24b) at its offset in its actor's
181
+ * or bone's frame (dark while that actor is absent), and flickers the lamps that declare a flicker (two incommensurate sines
182
+ * per lamp, so no two pulse together). It is null when nothing moves: at most `lit` fixed lamps and no flicker, drawn
183
+ * exactly as before.
163
184
  */
164
- export function lampLights(lamps: readonly LookLamp[]): THREE.Group & { update: ((time: number) => void) | null } {
165
- const group = Object.assign(new THREE.Group(), { update: null as ((time: number) => void) | null });
185
+ export function lampLights(lamps: readonly LookLamp[], lit: number = DESKTOP_LAMPS): THREE.Group & { update: LampUpdate | null } {
186
+ const group = Object.assign(new THREE.Group(), { update: null as LampUpdate | null });
166
187
  group.name = 'look-light-lamps';
167
- const flickering: { light: THREE.PointLight; base: number; rate: number; amount: number; phase: number }[] = [];
168
- lamps.forEach((lamp, i) => {
169
- const light = new THREE.PointLight(new THREE.Color().setRGB(lamp.colour[0], lamp.colour[1], lamp.colour[2], THREE.LinearSRGBColorSpace), lamp.intensity, lamp.distance, lamp.decay ?? 2);
170
- light.position.set(lamp.at[0], lamp.at[1], lamp.at[2]); light.castShadow = false;
188
+ const rows = lamps.map((lamp, i) => ({ lamp, phase: i * 2.399, at: new THREE.Vector3(...lamp.at), place: new THREE.Vector3(...lamp.at), live: lamp.follow === undefined,
189
+ colour: new THREE.Color().setRGB(lamp.colour[0], lamp.colour[1], lamp.colour[2], THREE.LinearSRGBColorSpace) }));
190
+ const pool = rows.slice(0, Math.max(0, Math.min(rows.length, lit))).map((row) => {
191
+ const light = new THREE.PointLight(row.colour, row.live ? row.lamp.intensity : 0, row.lamp.distance, row.lamp.decay ?? 2);
192
+ light.position.copy(row.place); light.castShadow = false;
171
193
  group.add(light);
172
- if (lamp.flicker !== undefined && lamp.flicker.amount > 0) flickering.push({ light, base: lamp.intensity, rate: lamp.flicker.rate, amount: lamp.flicker.amount, phase: i * 2.399 });
194
+ return light;
173
195
  });
174
- if (flickering.length > 0) {
175
- group.update = (time) => {
176
- for (const f of flickering) {
177
- const w = Math.sin(time * f.rate * 2.1 + f.phase) * 0.6 + Math.sin(time * f.rate * 5.3 + f.phase * 1.7) * 0.4;
178
- f.light.intensity = f.base * (1 - f.amount * 0.5 + f.amount * 0.5 * w);
196
+ const following = rows.filter((row) => row.lamp.follow !== undefined), crowded = rows.length > pool.length;
197
+ const flickers = rows.some((row) => (row.lamp.flicker?.amount ?? 0) > 0);
198
+ if (following.length === 0 && !crowded && !flickers) return group;
199
+ const eyeLocal = new THREE.Vector3(), chosen: typeof rows = [];
200
+ group.update = (time, eye) => {
201
+ if (following.length > 0) {
202
+ const resolve = lampFollows.get(rootOf(group));
203
+ for (const row of following) {
204
+ const follow = row.lamp.follow, target = follow === undefined || resolve === undefined ? null : resolve(follow.actor, follow.bone);
205
+ row.live = target !== null;
206
+ // the bone's world matrix is renewed only inside render: renew it here, or the lamp trails a frame behind (review)
207
+ if (target !== null) { target.updateWorldMatrix(true, false); group.updateWorldMatrix(true, false); group.worldToLocal(target.localToWorld(row.place.copy(row.at))); }
179
208
  }
180
- };
181
- }
209
+ }
210
+ chosen.length = 0;
211
+ for (const row of rows) if (row.live) chosen.push(row);
212
+ if (crowded && eye !== undefined) {
213
+ group.worldToLocal(eyeLocal.copy(eye));
214
+ chosen.sort((a, b) => a.place.distanceToSquared(eyeLocal) - b.place.distanceToSquared(eyeLocal));
215
+ }
216
+ pool.forEach((light, i) => {
217
+ const row = chosen[i];
218
+ if (row === undefined) { light.intensity = 0; return; }
219
+ const flicker = row.lamp.flicker;
220
+ light.color.copy(row.colour); light.distance = row.lamp.distance; light.decay = row.lamp.decay ?? 2; light.position.copy(row.place);
221
+ if (flicker === undefined || flicker.amount <= 0) { light.intensity = row.lamp.intensity; return; }
222
+ const w = Math.sin(time * flicker.rate * 2.1 + row.phase) * 0.6 + Math.sin(time * flicker.rate * 5.3 + row.phase * 1.7) * 0.4;
223
+ light.intensity = row.lamp.intensity * (1 - flicker.amount * 0.5 + flicker.amount * 0.5 * w);
224
+ });
225
+ };
182
226
  return group;
183
227
  }
184
228
 
@@ -121,6 +121,12 @@ export function registerExteriorLighting(scene: THREE.Scene, owner: Scope, root:
121
121
  owner.onDispose(() => { held.roots.delete(root); if (held.roots.size === 0) exteriorLighting.delete(scene); });
122
122
  }
123
123
 
124
+ /** The exterior lighting a scene declares (`registerExteriorLighting`): its root count and environment height, for proofs. */
125
+ export function exteriorLightingState(scene: THREE.Object3D): { readonly roots: number; readonly environment: unknown } | null {
126
+ const state = exteriorLighting.get(scene as THREE.Scene);
127
+ return state === undefined ? null : { roots: state.roots.size, environment: state.environment === null ? null : Reflect.get(state.environment.image ?? {}, 'height') };
128
+ }
129
+
124
130
  /** Hidden registered siblings cannot draw on this entered frame. Keep its entire hierarchy and any visible roots;
125
131
  * ordinary boot has no exclusion. Borrowed roots and their visibility are never changed. */
126
132
  export function entryFrameExclusions(scene: THREE.Scene, future?: THREE.Object3D): ReadonlySet<THREE.Object3D> | undefined {
@@ -49,6 +49,13 @@ export const TIER_TABLE = {
49
49
  // every PMREM environment's cube size (pmremSize.ts; 0 = each source's own): one size, so no lit program compiles twice
50
50
  // for two shards' environments (the HDR backdrops' 128 cube, a 512-wide equirect, drawn at Driftwood's 64)
51
51
  pmremCube: 64,
52
+ // NINE-DRAGON-BENCHMAX NB5 (mini-ninefps, 2026-11-15): a placed model's LOD start distances times this. The phone's
53
+ // portrait camera (vertical FOV ~100°, 874 px at 1×) draws a copy at 0.36× the desktop window's pixels per metre
54
+ // (1496x717 @2, ~70°), 0.72× at 2×: at 0.6 every level still switches at about the projected size the desktop switches at
55
+ placedLodScale: 0.6,
56
+ // NINE-DRAGON-BENCHMAX NB8 (mini-ninetris, 2026-11-15): a resident slab chunk's triangles in k-d order, drawn as the run
57
+ // its camera can see (`slabRanges.ts`): Nine's phone spawn view 0.56 to ~0.47 M slab triangles, other views ~half
58
+ slabRanges: true,
52
59
  },
53
60
  desktop: {
54
61
  maxTexture: 4096, layerSize: 1024, dpr: 1.5, ao: true,
@@ -74,6 +81,8 @@ export const TIER_TABLE = {
74
81
  pickupItemDist: 90, pickupOrbDist: 200,
75
82
  godRaysSamples: 60, godRaysScale: 0.5, volumetricSteps: 14, volumetricScale: 1, smaa: 'high' as 'off' | 'low' | 'high', bloomLevels: 8,
76
83
  pmremCube: 0,
84
+ placedLodScale: 1,
85
+ slabRanges: false,
77
86
  },
78
87
  };
79
88
 
@@ -19,7 +19,7 @@ import { loadingCacheText, loadingDownloadText, loadingDownloadFraction, loading
19
19
  import { LoadingTimeline, installLoadingTimeline, type LoadingPath, type LoadingRow, type LoadingGap } from '../../../shared/engine/boot/timeline';
20
20
  import {loadingFraction} from '../boot/weights';
21
21
  import {TimeLeftClock,timeLeftSeconds,timeLeftText} from '../boot/timeLeft';
22
- import {diagnosticBuild,diagnosticStep,safeBootDiagnostics} from '../boot/diagnostics';
22
+ import {compactBootDiagnostics,diagnosticBuild,diagnosticStep} from '../boot/diagnostics';
23
23
  import { isDev, onDev } from '../core/devMode';
24
24
  import { getSetting, onSetting } from './Settings';
25
25
  import { listenTap } from '../input/dom';
@@ -715,14 +715,13 @@ export class Loading {
715
715
  for (const [key, ms] of Object.entries(times)) setData(this.root, `${key}Ms`, String(Math.round(ms)));
716
716
  }
717
717
 
718
- /** LS4: everything the card leaves out, for Jake to paste. The full LS1 timeline rides at the end. */
718
+ /** LS4/NB15: the card facts and a compact LS1 digest for Jake to paste. */
719
719
  diagnosticsText(): string {
720
- const localTiming = bootTiming()?.read(), timing=safeBootDiagnostics(localTiming), transfer = this.downloadProgress(), times = this.phaseTimes();
721
- const all = this.timeline.snapshot(), summary = timing?.['summary'];
720
+ const localTiming = bootTiming()?.read(), timing=compactBootDiagnostics(localTiming), transfer = this.downloadProgress(), times = this.phaseTimes();
721
+ const all = this.timeline.snapshot();
722
722
  const lines = [
723
723
  `Wildshard boot diagnostics · ${new Date().toISOString()}`,
724
- // LD3 (J208): a human reads the cause first; the same lines lead the JSON below
725
- ...(Array.isArray(summary) ? summary.filter((line): line is string => typeof line === 'string') : []),
724
+ ...timing.summary,
726
725
  `build ${diagnosticBuild(localTiming?.build)} · ${this.tierText()} · ${innerWidth}x${innerHeight} @${devicePixelRatio}x · ${this.lowPowerLine()}`,
727
726
  `total ${seconds(times.total)} · start ${seconds(times.start)} · download ${seconds(times.download)} · load ${seconds(times.load)}${this.finished ? '' : ' · not ready'}`,
728
727
  `download ${loadingCacheText(transfer)} · files ${transfer.filesDone} of ${transfer.filesTotal} · ${transfer.complete ? 'complete' : 'open'}${transfer.error === null ? '' : ' · error (private text omitted)'}`,
@@ -732,8 +731,7 @@ export class Loading {
732
731
  ...all.rows.map(row => ` ${row.number}. ${diagnosticStep(row.key,row.number)} · ${row.state} · ${Math.round(row.ms)} ms`),
733
732
  ...all.gaps.map(gap => ` gap · ${gap.state} · ${Math.round(gap.ms)} ms`),
734
733
  'This page\'s files are named by path; other URLs use local report IDs; free text, details and errors are omitted.',
735
- 'timeline (LS1):',
736
- JSON.stringify(timing ?? null),
734
+ ...timing.timeline,
737
735
  ];
738
736
  return lines.join('\n');
739
737
  }
@@ -19,7 +19,7 @@ export function lookLightSaved(): boolean {
19
19
  }
20
20
  /**
21
21
  * Whether the settings draw on this page: the row on. TEMPLATES-CLEANROOM M4.9: the phone tier draws them too, gated per
22
- * field (`lookLightManifest`: no bloom or AO, at most 4 lamps, half the motes), not all or nothing; `tier` stays for callers.
22
+ * field (`lookLightManifest`: no bloom or AO, the nearest 4 lamps lit, half the motes), not all or nothing; `tier` stays for callers.
23
23
  */
24
24
  export function lookLightOn(_tier: string = TIER): boolean { return lookLightSaved(); }
25
25
  /** Save the row's value (the page reloads to apply it). */