@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
@@ -263,6 +263,9 @@ export class ClientScriptViews {
263
263
  ports.scope.onDispose(() => { this.dispose(); });
264
264
  }
265
265
 
266
+ /** ZE3a: draw the particles or not (a frozen neighbour's are hidden: their pool's first draw linked its program on the road). */
267
+ show(visible: boolean): void { if (this.pool !== null) this.pool.points.visible = visible; }
268
+
266
269
  /** Put every composed view back to the base it had before `apply` (run before the views write their own pose). */
267
270
  restore(): void {
268
271
  for (const p of this.posed) {
@@ -14,7 +14,7 @@ export function installPopulationSignals(ctx: ShardContext, scope: Scope, effect
14
14
  if(typeof x!=='number'||typeof zOrY!=='number')return;
15
15
  if(view.name.startsWith('creature.signal:')) {
16
16
  const name=view.name.slice('creature.signal:'.length);
17
- ctx.app.events.emit('creature.signal',{name,x,z:zOrY});notice(notices?.signal(name,view.tick/60)??null);
17
+ ctx.app.events.emit('creature.signal',{name,x,z:zOrY});wirePage.drew(view.name);notice(notices?.signal(name,view.tick/60)??null);
18
18
  } else if(view.name.startsWith('creature.sound:')&&typeof third==='number') {
19
19
  ctx.app.events.emit('creature.sound',{cue:view.name.slice('creature.sound:'.length),x,y:zOrY,z:third});
20
20
  } else if(view.name==='creature.knockdown'&&typeof third==='number') {
@@ -156,6 +156,7 @@ function wiredQuestSpawns(ctx: ShardContext, rows: QuestSpawnPageRows, flags: Fl
156
156
  const [id, x = 0, y = 0, z = 0] = args, cue = rows.cues.find(row => row.id === id);
157
157
  if (cue?.kind === 'sound') bank.shot(cue.name, { at: { x, y, z } });
158
158
  else if (cue?.kind === 'puff' && puffs.length < 64) puffs.push({ x, y, z });
159
+ if (cue !== undefined) wirePage.drew(name);
159
160
  }));
160
161
  ctx.scope.onDispose(flags.onChange((flag, on) => {
161
162
  const effects = complete.get(flag);
@@ -4,6 +4,7 @@ import { ownedSave } from '../../../shared/game/saves';
4
4
  import type { GridSession as DeclarationGridSession } from '../grid/session';
5
5
  import { exitSessionToTitle } from './exitToTitle';
6
6
  import { initialHomeMetadataRequired } from '../grid/homeMetadata';
7
+ import { enterZone } from '../grid/pageEntry';
7
8
  import { timeClientPreparation } from '../shardfile/preparationTiming';
8
9
  import type { Physics } from '@wildshard/engine/physics/Physics';
9
10
  import type { Audio } from '@wildshard/engine/audio/Audio';
@@ -176,6 +177,8 @@ async function buildPlay(ctx: Awaited<ReturnType<typeof loadoutStage>>) : Promis
176
177
  },
177
178
  prepareSkyLayers: () => game.warmSkyLayers(),
178
179
  ...(ctx.session.residency === undefined ? {} : { residency: ctx.session.residency }),
180
+ // ZE10 (J352): a gate's count reached 0: the full loading screen, and that cell becomes the home
181
+ enterZone: (instance) => { enterZone(instance); },
179
182
  onFixed: (fn) => { game.onFixed('post', fn, 'game.grid.session'); },
180
183
  frame: { prepareDisplay: pass => game.preparePostPass(pass), scene: game.rootScene, camera: game.camera, composer: () => game.composer, post: () => game.post, sunDir: () => game.sky.sunDir, cinematic: () => game.regionCinematic(), slices: () => game.depthSlices,
181
184
  // G321: the frame blends the camera's field of view by owner; the shadow cascades follow it
@@ -23,14 +23,15 @@ export function installClientBossTelegraph(ctx: ShardContext, input: unknown): v
23
23
  new MeshBasicMaterial({ color: view.color, transparent: true, opacity: 0, depthWrite: false, side: DoubleSide, fog: false }));
24
24
  wall.name = view.system; wall.visible = false; ctx.root.add(wall); ctx.scope.own(wall.geometry); ctx.scope.own(wall.material); ctx.scope.onDispose(() => { wall.removeFromParent(); });
25
25
  /** A page on a server holds no body to read a strike off: the server says it, until it stops saying so. */
26
- const heard = { through: 0, aim: 0, x: 0, z: 0, fresh: false, at: Number.NEGATIVE_INFINITY }, name = `${BOSS_STRIKE}${strike.id}`;
26
+ const heard = { through: 0, aim: 0, x: 0, z: 0, fresh: 0, at: Number.NEGATIVE_INFINITY }, name = `${BOSS_STRIKE}${strike.id}`;
27
27
  wirePage.whenLive(ctx.scope, client => client.onView(call => {
28
28
  if (call.name !== name) return;
29
29
  const [through = 0, aim = 0, x = 0, z = 0] = call.args;
30
- Object.assign(heard, { through, aim, x, z, fresh: true });
30
+ Object.assign(heard, { through, aim, x, z, fresh: heard.fresh + 1 });
31
31
  }));
32
32
  ctx.system({ id: view.system, phase: 'update', run: (_dt, t) => {
33
- if (heard.fresh) { heard.fresh = false; heard.at = t; } // the clock's the frame's: a slow frame still shows what it heard
33
+ // the clock's the frame's: a slow frame still shows what it heard, and counts every word it draws (EG-15's census)
34
+ if (heard.fresh > 0) { wirePage.drew(name, heard.fresh); heard.fresh = 0; heard.at = t; }
34
35
  const live = t - heard.at < HEARD_FOR;
35
36
  wall.visible = live;
36
37
  if (!live) return;
@@ -54,6 +54,9 @@ export interface PageResidencyBoot {
54
54
  */
55
55
  /** GC13: the page's playing envelope: the phone tier's 1.0 GB (G65), else the shared caps' */
56
56
  export function pagePlayingBytes(tier: Tier = TIER): number { return tier === 'phone' ? PHONE_PLAYING_BYTES : CONTENT_CAPS.playing; }
57
+ /** GC13: the page's loading envelope. A phone has no headroom past G65's 1.0 GB (two worlds on the road peaked at 1.28 GB), so a
58
+ * world is never built beside the one being left: that one goes first. Else the shared caps' loading figure. */
59
+ export function pageLoadingBytes(tier: Tier = TIER): number { return tier === 'phone' ? PHONE_PLAYING_BYTES : CONTENT_CAPS.loading; }
57
60
 
58
61
  export function preparePageResidency(manifest: Pick<ShardManifest, 'slug' | 'shardfile' | 'runtimeCost'>, configuredSlug?: string, memory: MemoryAdmission = new MemoryAdmission(() => MEMORY_GATES.reportOnly || isDev())): PageResidencyBoot {
59
62
  const mode = bootPageMode(configuredSlug ?? manifest.slug);
@@ -61,7 +64,7 @@ export function preparePageResidency(manifest: Pick<ShardManifest, 'slug' | 'sha
61
64
  if (mode !== 'grid' && (!measuredHome || manifest.runtimeCost === undefined)) return { mode, instance: null, memory };
62
65
  const instance = mode === 'grid' ? pageGridInstance() : manifest.slug;
63
66
  if (instance === null) throw new Error('Grid residency requires the consumed home instance');
64
- const residency = new PageResidency(new ResidencyAllocator({ memory, playing: pagePlayingBytes() }));
67
+ const residency = new PageResidency(new ResidencyAllocator({ memory, playing: pagePlayingBytes(), loading: pageLoadingBytes() }));
65
68
  try {
66
69
  if (measuredHome) {
67
70
  if (manifest.runtimeCost === undefined) throw new Error('Grid runtime home requires reviewed memory measurements before bootstrap');
@@ -104,7 +107,7 @@ function clientSource(admitted: AdmittedProduct, options: ProductOptions, bindin
104
107
  const sections = outputDescriptor(source)?.sections;
105
108
  if (sections !== undefined) prepareClientModuleGroups(source, sections);
106
109
  const ownedBindings = { ...bindings,
107
- ...(bindings.allocator === undefined && bindings.residency === undefined && options.memory !== undefined ? { allocator: new ResidencyAllocator({ memory: options.memory, playing: pagePlayingBytes() }) } : {}),
110
+ ...(bindings.allocator === undefined && bindings.residency === undefined && options.memory !== undefined ? { allocator: new ResidencyAllocator({ memory: options.memory, playing: pagePlayingBytes(), loading: pageLoadingBytes() }) } : {}),
108
111
  ...(options.firstParty ? {} : { instance: admitted.instance ?? '' }) };
109
112
  const residency = clientResidency(source, ownedBindings);
110
113
  const assets = new ClientAssets(source, admitted.assets, options);
@@ -6,7 +6,7 @@ import type { LiveGridWire } from '../grid/liveSession';
6
6
  import { chosenCell, gotoHosted, pageGoto } from '../../../shared/game/grid/pageMode';
7
7
  import type { SystemSpec } from '@wildshard/engine/app/systems';
8
8
  import type { Player } from '@wildshard/engine/player/Player';
9
- import { Vector3, type Object3D } from 'three';
9
+ import { Scene, Vector3, type Object3D } from 'three';
10
10
  import { appIdentity } from '@wildshard/engine/app/identity';
11
11
  import { bootMark, bootTask } from '@wildshard/engine/boot/timing';
12
12
  import { SEAT_GRACE_MS, seatedInTime } from './seatGrace';
@@ -58,6 +58,7 @@ import { OWNED_ROW } from '../../../shared/game/loot/ownedRows';
58
58
  import { declaredKitSlots } from '../../../shared/game/shardfile/items';
59
59
  import { earlyStandalone, serverRoute } from './serverRoute';
60
60
  import { worldHosted } from '../grid/oneWayIn';
61
+ import { setLampFollow } from '@wildshard/engine/render/lookLight';
61
62
 
62
63
  type Creatures = Pick<RowBodiesView, 'animals' | 'spawn' | 'retire' | 'onWindup' | 'presentHit' | 'presentDeath' | 'presentReward'>;
63
64
  /** What a grid page lends: its crossing follows the server, and its creatures are the entered cell's. */
@@ -139,7 +140,7 @@ const onlineLeaving: OnlineLeaving = {
139
140
  settle: () => { void (async () => { (await import('@wildshard/engine/boot/browserChunkRecovery')).settleRefusedBuild(); })(); },
140
141
  };
141
142
  interface OnlineModule { readonly startOnline: (config: BuildWorld & { keep: ReleaseKeep; leaving: OnlineLeaving; loaded: string; build: string; identity: (name?: string) => NetIdentity; grid?: { readonly cell: string; readonly cells: readonly string[]; readonly placed: (cell: string, at: { readonly x: number; readonly y: number; readonly z: number; readonly yaw: number }) => void; readonly reenter: (cell: string) => void; readonly goto?: boolean } }) => Promise<Shell> }
142
- interface Shell { readonly redials?: true; devColliders?: (name: string, boxes: readonly DevBox[]) => void; pause: () => void; hold: (on: boolean) => void; bossGod: () => void; raise: (flag: string) => void; join: (id: string, x: number, y: number, z: number) => { readonly client: NetClient; readonly move: (x: number, y: number, z: number) => void }; readonly client: NetClient; readonly booted: Promise<{ readonly restored: boolean }>; place: (x: number, y: number, z: number, yaw: number) => void; hardHits: (by: number) => void; ready: () => void; leave?: () => Promise<void>; save: () => Promise<{ readonly tick: number; readonly ok: boolean }>; probe: () => Promise<{ readonly tickMs: number }>; dispose: () => void }
143
+ interface Shell { readonly redials?: true; devColliders?: (name: string, boxes: readonly DevBox[]) => void; pause: () => void; hold: (on: boolean) => void; bossGod: () => void; still: () => void; raise: (flag: string) => void; join: (id: string, x: number, y: number, z: number) => { readonly client: NetClient; readonly move: (x: number, y: number, z: number) => void }; readonly client: NetClient; readonly booted: Promise<{ readonly restored: boolean }>; place: (x: number, y: number, z: number, yaw: number) => void; hardHits: (by: number) => void; ready: () => void; leave?: () => Promise<void>; save: () => Promise<{ readonly tick: number; readonly ok: boolean }>; probe: () => Promise<{ readonly tickMs: number }>; dispose: () => void }
143
144
 
144
145
  const SAVE_EVERY_MS = 30_000;
145
146
  /** How long the card waits for the server's first rows, and how often it looks. A server that has booted says them in a tick. */
@@ -166,6 +167,10 @@ export interface WorkerClientReport {
166
167
  owned: Readonly<Record<string, number>>; sky: number | null; day: number | null;
167
168
  /** What this page drew of what it only hears, by name. */
168
169
  drawn: Readonly<Record<string, number>>;
170
+ /** EG-15: every view word the server said to this page, by name: what `drawn` is held against (scripts/fight-page-census.mjs). */
171
+ heard: Readonly<Record<string, number>>;
172
+ /** Of those, the words for a view this page hasn't built (`wirePage.unbuilt`): not drawn, and not dark. */
173
+ offstage: Readonly<Record<string, number>>;
169
174
  /** Movers this page holds, the poses rows have given them, and the highest drift rows have laid. */
170
175
  movers: number; posed: number; sand: number;
171
176
  /** Bodies this page made and the rows put away, by kind: what its own sim still builds. */
@@ -175,9 +180,15 @@ export interface WorkerClientReport {
175
180
  /** What corrections disagreed on, and server-owned transitions that were deliberately not corrections. */
176
181
  missed: Readonly<NetPlayer['predictor']['missed']>; misses: readonly (readonly number[])[]; authoritative: Readonly<NetPlayer['predictor']['authoritative']>;
177
182
  }
178
- /** A fight as a proof reads it: its row, where its body stands and the server's name for it. */
179
- export type WorkerClientFight = EncounterRow & { readonly at: { readonly x: number; readonly y: number; readonly z: number } | null; readonly name: string | null };
180
- declare global { interface Window { __onlinePlayers?: () => OtherPlayers['shown']; __workerClientFights?: () => readonly WorkerClientFight[]; __workerClientHits?: (by: number) => void; __workerClientTravel?: (to: ShardSlug) => void;__workerClientSky?: (name: string) => void; __workerClientTime?: (pick: OptionValue<'time'>) => void; __workerClientRow?: (name: string) => number | undefined; __workerClientFlag?: (flag: string) => void; __workerClientDevColliders?: (name: string, boxes: readonly DevBox[]) => void; __workerClientRows?: (kind: string) => readonly { readonly x: number; readonly y: number; readonly z: number }[]; __workerClientGate?: (flag: string) => boolean; __workerClientBot?: (id: string, x: number, y: number, z: number) => { readonly move: (x: number, y: number, z: number) => void; readonly press: (id: string) => void; readonly end: () => void }; __workerClient?: () => WorkerClientReport; __workerClientSave?: () => Promise<void> } }
183
+ /** A fight as a proof reads it: its row, where its body stands and the server's name for it. `shown` (EG-15): the page's body for that row
184
+ * is in the scene and visible; null when the page holds no row body for it (an open arena draws its own, off its view words). */
185
+ export type WorkerClientFight = EncounterRow & { readonly at: { readonly x: number; readonly y: number; readonly z: number } | null; readonly name: string | null; readonly shown: boolean | null };
186
+ /** Whether an object is drawn: visible, and so is every parent up to a scene. */
187
+ function inScene(object: Object3D): boolean {
188
+ for (let at: Object3D | null = object; at !== null; at = at.parent) { if (!at.visible) return false; if (at instanceof Scene) return true; }
189
+ return false;
190
+ }
191
+ declare global { interface Window { __onlinePlayers?: () => OtherPlayers['shown']; __workerClientFights?: () => readonly WorkerClientFight[]; __workerClientHits?: (by: number) => void; __workerClientStill?: () => void; __workerClientTravel?: (to: ShardSlug) => void;__workerClientSky?: (name: string) => void; __workerClientTime?: (pick: OptionValue<'time'>) => void; __workerClientRow?: (name: string) => number | undefined; __workerClientFlag?: (flag: string) => void; __workerClientDevColliders?: (name: string, boxes: readonly DevBox[]) => void; __workerClientRows?: (kind: string) => readonly { readonly x: number; readonly y: number; readonly z: number }[]; __workerClientGate?: (flag: string) => boolean; __workerClientBot?: (id: string, x: number, y: number, z: number) => { readonly move: (x: number, y: number, z: number) => void; readonly press: (id: string) => void; readonly end: () => void }; __workerClient?: () => WorkerClientReport; __workerClientSave?: () => Promise<void> } }
181
192
 
182
193
  /** The page's pose inputs, as acts short enough to go. */
183
194
  function poseActs(names: ReadonlySet<string>): readonly string[] {
@@ -429,6 +440,8 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
429
440
  wirePage.led = () => net.predictor.leading; wirePage.rowBody = handle => bodies.get(handle)?.body ?? null;
430
441
  wirePage.namedBody = id => { for (const [handle, { body }] of bodies) if (client.entities.get(handle)?.id === id) return body; return null; };
431
442
  scope.onDispose(() => { wirePage.unbind(); wirePage.led = () => false; wirePage.rowBody = () => null; wirePage.namedBody = () => null; });
443
+ // SHARD-SOURCE AP24b: a look lamp that follows an actor rides its body, or one of its bones, by the server's name for it
444
+ scope.onDispose(setLampFollow(ports.scene, (actor, bone) => { const body = wirePage.namedBody(actor); return body === null ? null : bone === undefined ? body.mesh : body.mesh.skeleton.getBoneByName(bone) ?? null; }));
432
445
  // J116: the lock's body by the server's name for it
433
446
  net.lockTarget = () => {
434
447
  if (lockOn.state !== 'locked' || lockOn.target === null) return undefined;
@@ -475,9 +488,11 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
475
488
  if (shell.redials === true) others = new (await import('@wildshard/engine/net/otherPlayers')).OtherPlayers(client, ports.scene, scope, player.position);
476
489
  if (new URLSearchParams(location.search).has('bossGod')) shell.bossGod();
477
490
  bootMark('server:ready-send'); shell.ready();
478
- const started = diagnosticNow(), report: WorkerClientReport = { drawn: wirePage.drawn, frames: 0, framesPerSecond: 0, ticksPerSecond: 0, correctionsPerMinute: 0, corrections: 0, retired: {}, spawnMs: {}, missed: net.predictor.missed, misses: net.predictor.misses, authoritative: net.predictor.authoritative, worstOffset: 0, queue: 0, replaysPerFrame: 0, delayMs: 0, jitterMs: 0, interpHeld: 0, interpStarved: 0, mainMsP95: 0, workerTickMs: 0, rows: 0, attacks: 0, hits: 0, kills: 0, refused: 0, held: 0, dropped: 0, hp: 0, falls: 0, closed: null, x: 0, z: 0, cell: 0, serverX: 0, serverZ: 0, restored, savedTick: -1, savedOk: false, receipts: [], quests: {}, flags: [], paid: 0, fights: [], owned: {}, sky: null, day: null, clawed: false, own: null, movers: 0, posed: 0, sand: 0 };
491
+ const heard: Record<string, number> = {};
492
+ const started = diagnosticNow(), report: WorkerClientReport = { drawn: wirePage.drawn, heard, offstage: wirePage.offstage, frames: 0, framesPerSecond: 0, ticksPerSecond: 0, correctionsPerMinute: 0, corrections: 0, retired: {}, spawnMs: {}, missed: net.predictor.missed, misses: net.predictor.misses, authoritative: net.predictor.authoritative, worstOffset: 0, queue: 0, replaysPerFrame: 0, delayMs: 0, jitterMs: 0, interpHeld: 0, interpStarved: 0, mainMsP95: 0, workerTickMs: 0, rows: 0, attacks: 0, hits: 0, kills: 0, refused: 0, held: 0, dropped: 0, hp: 0, falls: 0, closed: null, x: 0, z: 0, cell: 0, serverX: 0, serverZ: 0, restored, savedTick: -1, savedOk: false, receipts: [], quests: {}, flags: [], paid: 0, fights: [], owned: {}, sky: null, day: null, clawed: false, own: null, movers: 0, posed: 0, sand: 0 };
479
493
  if (unseated) void shell.booted.then(answer => { report.restored = answer.restored; bootMark('server:seated-late'); return undefined; }, () => undefined);
480
494
  scope.onDispose(client.onLedger(receipt => { report.receipts.push(`${receipt.grant}:${receipt.name}`); }));
495
+ scope.onDispose(client.onView(({ name }) => { heard[name] = (heard[name] ?? 0) + 1; }));
481
496
  const contacts: NetCombatEvent[] = [];
482
497
  scope.onDispose(client.onTravel(() => { contacts.length = 0; }));
483
498
  scope.onDispose(client.onCombat(event => {
@@ -531,7 +546,7 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
531
546
  let inputs = poses.get(id);
532
547
  if (inputs === undefined) { inputs = {}; poses.set(id, inputs); }
533
548
  inputs[field] = value;
534
- for (const [handle, { body }] of bodies) if (client.entities.get(handle)?.id === id) { body.mem[field] = value; break; }
549
+ for (const [handle, { body }] of bodies) if (client.entities.get(handle)?.id === id) { body.mem[field] = value; wirePage.drew(name); break; }
535
550
  }));
536
551
  const decks = new NetMovers(client, wirePage.movers, player.position);
537
552
  scope.onDispose(net.world.addMover(decks));
@@ -590,6 +605,7 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
590
605
  window.__workerClient = () => ({ ...report });
591
606
  window.__onlinePlayers = () => others?.shown ?? [];
592
607
  window.__workerClientHits = by => { shell.hardHits(by); };
608
+ window.__workerClientStill = () => { shell.still(); };
593
609
  window.__workerClientFlag = flag => { shell.raise(flag); };
594
610
  // SHARD-SOURCE AP5: the dev hook's `swapColliders` reaches the in-page server here (DEVSERVER only: the define folds it away)
595
611
  if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) window.__workerClientDevColliders = (name, boxes) => { shell.devColliders?.(name, boxes); };
@@ -616,7 +632,8 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
616
632
  const out: WorkerClientFight[] = [];
617
633
  for (const fight of wirePage.encounters()) {
618
634
  const body = client.latest === null ? null : client.fields(client.latest, fight.body);
619
- out.push({ ...fight, at: body === null ? null : { x: Number(body['x']), y: Number(body['y']), z: Number(body['z']) }, name: client.entities.get(fight.body)?.id ?? null });
635
+ const held = bodies.get(fight.body)?.body.mesh ?? null;
636
+ out.push({ ...fight, at: body === null ? null : { x: Number(body['x']), y: Number(body['y']), z: Number(body['z']) }, name: client.entities.get(fight.body)?.id ?? null, shown: held === null ? null : inScene(held) });
620
637
  }
621
638
  return out;
622
639
  };
@@ -23,6 +23,6 @@ export function shardfileLook(look: Shardfile['look'], assets?: ReadonlyMap<stri
23
23
  // exposure and vignette); the bloom radius rides the bloom, which the row and the tier gate
24
24
  return dataLook({ day: look.day ?? DATA_LOOK_DAY, dayOverride: look.dayOverride, keys: look.keys, lut, neutral: look.grade.tone === 'neutral', aces: look.grade.tone === 'aces',
25
25
  exposure: look.grade.exposure, vignette: look.grade.vignette ?? null, bloomRadius: resolved.bloom.radius, sky: look.sky?.graph ?? null,
26
- light: { rim: resolved.rim, pools: resolved.pools, heightFogDensity: resolved.atmosphere.fogHeightDensity, lamps: resolved.lamps, bounce: resolved.bounce, environment: resolved.environment,
26
+ light: { rim: resolved.rim, pools: resolved.pools, heightFogDensity: resolved.atmosphere.fogHeightDensity, lamps: resolved.lamps, lampsLit: resolved.lampsLit, bounce: resolved.bounce, environment: resolved.environment,
27
27
  shadow: resolved.shadow, motes: resolved.motes } });
28
28
  }
@@ -12,6 +12,7 @@ import { ClientAssets } from './clientAssets';
12
12
  import { buildYield, pacedResolve, workSlice, type WorkSlice } from '@wildshard/engine/core/workSlice';
13
13
  import { pageScope } from '@wildshard/engine/app/resources';
14
14
  import { waitFor } from '@wildshard/engine/boot/waits';
15
+ import { bootTask } from '@wildshard/engine/boot/timing';
15
16
  import { currentOwner } from '@wildshard/engine/app/ownership';
16
17
  import { shardProductData } from '../../../shared/game/shardfile/productData';
17
18
  import { absentShardProduct, type ShardProduct } from '../../../shared/game/shardfile/shardProduct';
@@ -374,12 +375,15 @@ export async function runtimeLookMaterials(ctx: Pick<ShardContext, 'scope' | 'ga
374
375
  }));
375
376
  shard = { ...shard, look: { ...look, families: [], materials }, terrain: null, props: null };
376
377
  }
377
- const assets = new Map(product.assets.retained);
378
- const files = Object.values(shard.look.materials).flatMap(entry => entry.family === 'graph' && 'file' in entry ? [entry.file] : []);
379
- for (const ref of files) assets.set(ref, await product.assets.read(ref));
380
- for (const ref of new Set([...materialTextureRefs(shard.look.materials), ...keptGraphFileTextureRefs(shard.look.materials, hash => assets.get(hash))])) assets.set(ref, await product.assets.read(ref));
378
+ const assets = await bootTask(`look:material-inputs ${source.identity.slug}`, async () => {
379
+ const files = new Map(product.assets.retained);
380
+ const graphFiles = Object.values(shard.look.materials).flatMap(entry => entry.family === 'graph' && 'file' in entry ? [entry.file] : []);
381
+ for (const ref of graphFiles) files.set(ref, await product.assets.read(ref));
382
+ for (const ref of new Set([...materialTextureRefs(shard.look.materials), ...keptGraphFileTextureRefs(shard.look.materials, hash => files.get(hash))])) files.set(ref, await product.assets.read(ref));
383
+ return files;
384
+ });
381
385
  if (ctx.scope.disposed) throw new Error('Runtime look scope unloaded while reading materials');
382
- return clientMaterials(shard, assets, renderer, ctx.scope, { trustedGraphs: true, ...(graphs === undefined ? {} : { graphs }), ...(units === undefined ? {} : { units }) });
386
+ return bootTask(`look:material-compile ${source.identity.slug}`, () => clientMaterials(shard, assets, renderer, ctx.scope, { trustedGraphs: true, ...(graphs === undefined ? {} : { graphs }), ...(units === undefined ? {} : { units }) }));
383
387
  }
384
388
 
385
389
  /** Prepare the requested original graph materials for resident effects and boss storms. */
@@ -13,12 +13,44 @@ import { runtimeProduct } from './runtimeProduct';
13
13
  import { SharedTileBuilds, type TileContent } from './tileContent';
14
14
  import type { ControlRefinement } from './controlRefinement';
15
15
  import { tilesSettling } from './tileDriver';
16
+ import { TIER_CONFIG } from '@wildshard/engine/core/tier';
17
+ import { cullSlabRanges, spatialSlabRanges, type SlabRanges } from './slabRanges';
16
18
 
17
19
  type WholeLibrary = Extract<WorldScenesSection['libraries'][number], { kind: 'whole' }>;
18
20
  type SlabTile = WorldSceneSlabLibrary['tiles'][number];
19
21
  /** the bake's tag on each slab mesh (`sharddev/bake/slabs.ts`): its key, tile and place in its file */
20
22
  const SlabTag = v.object({ key: v.string(), tile: v.number(), chunk: v.number() });
21
23
  const EMPTY: ReadonlySet<number> = new Set();
24
+ /** NB8: each phone chunk geometry's leaf tree (`slabRanges.ts`): built on a read in play before its first upload; a read
25
+ * under the loader's settle (Nine's whole resident bank, ~0.2 s at CPU x4 on NB1's readyFrame) waits in LATE and is
26
+ * built after the settle, a few chunks a work slice, its reordered index uploaded again */
27
+ const RANGES = new WeakMap<BufferGeometry, SlabRanges>();
28
+ const LATE = new WeakSet<BufferGeometry>();
29
+ const waiting: { readonly part: InstancedMesh; readonly geometry: BufferGeometry; readonly scope: Scope }[] = [];
30
+ let draining = false;
31
+ function slabRuns(part: InstancedMesh, geometry: BufferGeometry, scope: Scope): void {
32
+ const ranges = RANGES.get(geometry);
33
+ if (ranges !== undefined) { cullSlabRanges(part, ranges); return; }
34
+ if (!LATE.has(geometry)) return;
35
+ waiting.push({ part, geometry, scope });
36
+ if (!draining) { draining = true; void drainLate().finally(() => { draining = false; }); }
37
+ }
38
+ async function drainLate(): Promise<void> {
39
+ while (tilesSettling()) await new Promise<void>(resolve => { pageScope.timeout(250, resolve); });
40
+ const slice = workSlice();
41
+ for (let entry = waiting.shift(); entry !== undefined; entry = waiting.shift()) {
42
+ const { part, geometry, scope } = entry;
43
+ if (scope.disposed || scope.disposing) continue;
44
+ let ranges = RANGES.get(geometry);
45
+ if (ranges === undefined && LATE.has(geometry)) {
46
+ LATE.delete(geometry);
47
+ const built = spatialSlabRanges(geometry);
48
+ if (built !== null) { RANGES.set(geometry, built); ranges = built; }
49
+ }
50
+ if (ranges !== undefined) cullSlabRanges(part, ranges);
51
+ if (slice.due()) await slice.yield();
52
+ }
53
+ }
22
54
 
23
55
  function slabMesh(node: Object3D): node is Mesh { return node instanceof Mesh; }
24
56
  function materialList(mesh: Mesh): Material[] { return Array.isArray(mesh.material) ? mesh.material : [mesh.material]; }
@@ -59,6 +91,10 @@ async function readSlabChunks(owner: Scope, product: ShardProduct, tile: number,
59
91
  const row = file.chunks[index];
60
92
  if (row === undefined || tag.chunk !== index || tag.tile !== tile || tag.key !== row.key) throw new Error('Slab chunk differs from its row');
61
93
  const geometry = nativeWholeGeometry(mesh, 'take');
94
+ if (TIER_CONFIG.slabRanges) {
95
+ if (tilesSettling()) LATE.add(geometry);
96
+ else { const ranges = spatialSlabRanges(geometry); if (ranges !== null) RANGES.set(geometry, ranges); }
97
+ }
62
98
  const [x0, y0, z0, x1, y1, z1] = row.box, [sx, sy, sz, radius] = row.sphere;
63
99
  geometry.boundingBox = new Box3(new Vector3(x0, y0, z0), new Vector3(x1, y1, z1));
64
100
  geometry.boundingSphere = new Sphere(new Vector3(sx, sy, sz), radius);
@@ -236,6 +272,7 @@ export class SlabLibrary {
236
272
  part.name = `${mesh.name}:slab:${String(tile)}:${String(index)}`; part.matrixAutoUpdate = false;
237
273
  part.castShadow = key.castShadow; part.receiveShadow = key.receiveShadow; part.renderOrder = key.renderOrder;
238
274
  part.layers.mask = key.layers; part.frustumCulled = key.frustumCulled;
275
+ if (key.frustumCulled) slabRuns(part, geometry, scope);
239
276
  drawn.push(part); parts.push({ part, anchor: mesh, scope });
240
277
  }
241
278
  // All keys share one publication cursor. A CPU-budget yield alone can
@@ -0,0 +1,145 @@
1
+ import { BufferAttribute, type BufferGeometry, type Camera, Frustum, Matrix4, type Object3D, WebGLCoordinateSystem } from 'three';
2
+ import { drawNeutral } from '@wildshard/engine/render/drawNeutral';
3
+
4
+ /**
5
+ * NINE-DRAGON-BENCHMAX NB8: a slab chunk draws only the run of its triangles the camera can see. A resident cell's slab
6
+ * chunk (`sharddev/bake/slabs.ts`) is up to 4 MB of one key in source order, so its bounds span the fragment (Nine's
7
+ * kit chunks reach 190 m) and the object's frustum test keeps nearly every chunk: the phone's spawn view drew 37 of 49
8
+ * chunks, 0.56 M triangles. Splitting chunks in the bake does not pay (NB9: more draws, the spawn view keeps its
9
+ * triangles); ordering each chunk's triangles along a k-d tree of their centroids, then drawing the one contiguous run
10
+ * from its first to its last leaf whose box meets the frustum, cuts triangles with no new draw, no extension, no new
11
+ * program and no change to the shard's bytes. The index is reordered before its first upload; vertices are untouched.
12
+ */
13
+ export interface SlabRanges {
14
+ /** per node: box min xyz, max xyz in the geometry's own frame */
15
+ readonly boxes: Float32Array;
16
+ /** per node, the root first: left child, right child (-1 for a leaf), first triangle, end triangle */
17
+ readonly nodes: Int32Array;
18
+ readonly triangles: number;
19
+ }
20
+
21
+ /** triangles per leaf: a leaf's box test costs ~6 plane checks, and 256 triangles of a wall kit is a few metres */
22
+ export const SLAB_LEAF_TRIANGLES = 256;
23
+
24
+ /**
25
+ * Reorder `geometry`'s index along a k-d tree of its triangles' centroids (each node split at the middle of its longest
26
+ * extent, to leaves of at most `leaf` triangles), before upload, and return that tree; null when the chunk is one leaf
27
+ * (nothing below the object's own test) or has no index or positions. Each level is one linear partition pass.
28
+ */
29
+ export function spatialSlabRanges(geometry: BufferGeometry, leaf: number = SLAB_LEAF_TRIANGLES): SlabRanges | null {
30
+ const index = geometry.index, position = geometry.getAttribute('position');
31
+ if (index === null || position === undefined || index.count % 3 !== 0) return null;
32
+ const triangles = index.count / 3;
33
+ if (triangles <= leaf) return null;
34
+ const source = index.array, corners = new Uint32Array(source);
35
+ // the bake's positions are plain float32 xyz; any other layout is read through the attribute
36
+ const plain = position instanceof BufferAttribute && position.itemSize === 3 && !position.normalized && position.array instanceof Float32Array;
37
+ const xyz = plain ? position.array : new Float32Array(position.count * 3);
38
+ if (!plain) for (let v = 0; v < position.count; v++) { xyz[v * 3] = position.getX(v); xyz[v * 3 + 1] = position.getY(v); xyz[v * 3 + 2] = position.getZ(v); }
39
+ // centroids (times three) and triangle ids, permuted together so every pass reads front to back
40
+ const cx = new Float32Array(triangles), cy = new Float32Array(triangles), cz = new Float32Array(triangles), order = new Uint32Array(triangles);
41
+ for (let t = 0; t < triangles; t++) {
42
+ const a = (corners[t * 3] ?? 0) * 3, b = (corners[t * 3 + 1] ?? 0) * 3, c = (corners[t * 3 + 2] ?? 0) * 3;
43
+ cx[t] = (xyz[a] ?? 0) + (xyz[b] ?? 0) + (xyz[c] ?? 0); cy[t] = (xyz[a + 1] ?? 0) + (xyz[b + 1] ?? 0) + (xyz[c + 1] ?? 0); cz[t] = (xyz[a + 2] ?? 0) + (xyz[b + 2] ?? 0) + (xyz[c + 2] ?? 0);
44
+ order[t] = t;
45
+ }
46
+ const rows: number[] = [];
47
+ // top-down: a node's row is [left, right, first triangle, end triangle]; the root is node 0, children follow it
48
+ const build = (lo: number, hi: number): number => {
49
+ const node = rows.length / 4; rows.push(-1, -1, lo, hi);
50
+ if (hi - lo <= leaf) return node;
51
+ let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;
52
+ for (let i = lo; i < hi; i++) {
53
+ const x = cx[i] ?? 0, y = cy[i] ?? 0, z = cz[i] ?? 0;
54
+ if (x < x0) x0 = x; if (y < y0) y0 = y; if (z < z0) z0 = z; if (x > x1) x1 = x; if (y > y1) y1 = y; if (z > z1) z1 = z;
55
+ }
56
+ const ex = x1 - x0, ey = y1 - y0, ez = z1 - z0, key = ex >= ey && ex >= ez ? cx : ey >= ez ? cy : cz;
57
+ const cut = key === cx ? (x0 + x1) / 2 : key === cy ? (y0 + y1) / 2 : (z0 + z1) / 2;
58
+ let i = lo, j = hi - 1;
59
+ while (i <= j) {
60
+ if ((key[i] ?? 0) < cut) { i++; continue; }
61
+ // swap row i with row j and look at the new row i again
62
+ let t: number;
63
+ t = cx[i] ?? 0; cx[i] = cx[j] ?? 0; cx[j] = t; t = cy[i] ?? 0; cy[i] = cy[j] ?? 0; cy[j] = t;
64
+ t = cz[i] ?? 0; cz[i] = cz[j] ?? 0; cz[j] = t; t = order[i] ?? 0; order[i] = order[j] ?? 0; order[j] = t; j--;
65
+ }
66
+ // every centroid on one side of the middle (all equal along the axis): split the run in half as it stands
67
+ const mid = i === lo || i === hi ? (lo + hi) >> 1 : i;
68
+ const left = build(lo, mid), right = build(mid, hi);
69
+ rows[node * 4] = left; rows[node * 4 + 1] = right;
70
+ return node;
71
+ };
72
+ build(0, triangles);
73
+ // the index in its new order, then each leaf's box read front to back, then every parent's (children follow parents)
74
+ for (let t = 0; t < triangles; t++) {
75
+ const from = (order[t] ?? 0) * 3;
76
+ source[t * 3] = corners[from] ?? 0; source[t * 3 + 1] = corners[from + 1] ?? 0; source[t * 3 + 2] = corners[from + 2] ?? 0;
77
+ }
78
+ const nodes = Int32Array.from(rows), count = nodes.length / 4, boxes = new Float32Array(count * 6);
79
+ for (let node = count - 1; node >= 0; node--) {
80
+ const left = nodes[node * 4] ?? -1, right = nodes[node * 4 + 1] ?? -1;
81
+ if (left >= 0) {
82
+ for (let k = 0; k < 3; k++) {
83
+ boxes[node * 6 + k] = Math.min(boxes[left * 6 + k] ?? 0, boxes[right * 6 + k] ?? 0);
84
+ boxes[node * 6 + 3 + k] = Math.max(boxes[left * 6 + 3 + k] ?? 0, boxes[right * 6 + 3 + k] ?? 0);
85
+ }
86
+ continue;
87
+ }
88
+ let bx0 = Infinity, by0 = Infinity, bz0 = Infinity, bx1 = -Infinity, by1 = -Infinity, bz1 = -Infinity;
89
+ for (let c = (nodes[node * 4 + 2] ?? 0) * 3, end = (nodes[node * 4 + 3] ?? 0) * 3; c < end; c++) {
90
+ const v = (source[c] ?? 0) * 3, x = xyz[v] ?? 0, y = xyz[v + 1] ?? 0, z = xyz[v + 2] ?? 0;
91
+ if (x < bx0) bx0 = x; if (y < by0) by0 = y; if (z < bz0) bz0 = z; if (x > bx1) bx1 = x; if (y > by1) by1 = y; if (z > bz1) bz1 = z;
92
+ }
93
+ boxes[node * 6] = bx0; boxes[node * 6 + 1] = by0; boxes[node * 6 + 2] = bz0; boxes[node * 6 + 3] = bx1; boxes[node * 6 + 4] = by1; boxes[node * 6 + 5] = bz1;
94
+ }
95
+ index.needsUpdate = true;
96
+ return { boxes, nodes, triangles };
97
+ }
98
+
99
+ const frustum = new Frustum(), clip = new Matrix4();
100
+ function visible(boxes: Float32Array, node: number): boolean {
101
+ for (const plane of frustum.planes) {
102
+ const { x, y, z } = plane.normal, at = node * 6;
103
+ // the box corner furthest along the plane's normal
104
+ const px = x > 0 ? boxes[at + 3] ?? 0 : boxes[at] ?? 0, py = y > 0 ? boxes[at + 4] ?? 0 : boxes[at + 1] ?? 0, pz = z > 0 ? boxes[at + 5] ?? 0 : boxes[at + 2] ?? 0;
105
+ if (x * px + y * py + z * pz + plane.constant < 0) return false;
106
+ }
107
+ return true;
108
+ }
109
+ /** the first visible leaf's first triangle under `node`, or -1 */
110
+ function first(ranges: SlabRanges, node: number): number {
111
+ if (!visible(ranges.boxes, node)) return -1;
112
+ const left = ranges.nodes[node * 4] ?? -1;
113
+ if (left < 0) return ranges.nodes[node * 4 + 2] ?? 0;
114
+ const found = first(ranges, left);
115
+ return found >= 0 ? found : first(ranges, ranges.nodes[node * 4 + 1] ?? 0);
116
+ }
117
+ /** the last visible leaf's end triangle under `node`, or -1 */
118
+ function last(ranges: SlabRanges, node: number): number {
119
+ if (!visible(ranges.boxes, node)) return -1;
120
+ const right = ranges.nodes[node * 4 + 1] ?? -1;
121
+ if (right < 0) return ranges.nodes[node * 4 + 3] ?? 0;
122
+ const found = last(ranges, right);
123
+ return found >= 0 ? found : last(ranges, ranges.nodes[node * 4] ?? 0);
124
+ }
125
+
126
+ /** The triangle run `[start, end)` of `ranges` that `camera` can see of an object drawn with `world`; when no leaf is in
127
+ * view, the first leaf alone, so a parked warm still issues a real draw and builds its pipeline. */
128
+ export function visibleSlabRun(ranges: SlabRanges, world: Matrix4, camera: Camera): readonly [number, number] {
129
+ clip.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(world);
130
+ frustum.setFromProjectionMatrix(clip, WebGLCoordinateSystem, camera.reversedDepth);
131
+ const start = first(ranges, 0);
132
+ if (start < 0) { let node = 0; while ((ranges.nodes[node * 4] ?? -1) >= 0) node = ranges.nodes[node * 4] ?? 0; return [ranges.nodes[node * 4 + 2] ?? 0, ranges.nodes[node * 4 + 3] ?? 0]; }
133
+ return [start, Math.max(start, last(ranges, 0))];
134
+ }
135
+
136
+ /** Draw `part` (whose geometry `ranges` was built on) as its visible run for each camera that renders it; the full
137
+ * range is restored after every draw, so shadow passes, warms, raycasts and bounds read the whole chunk. */
138
+ export function cullSlabRanges(part: Object3D & { geometry: BufferGeometry }, ranges: SlabRanges): void {
139
+ const geometry = part.geometry, { start, count } = geometry.drawRange;
140
+ part.onBeforeRender = drawNeutral((_renderer: unknown, _scene: unknown, camera: Camera): void => {
141
+ const [from, to] = visibleSlabRun(ranges, part.matrixWorld, camera);
142
+ geometry.setDrawRange(from * 3, (to - from) * 3);
143
+ });
144
+ part.onAfterRender = drawNeutral((): void => { geometry.setDrawRange(start, count); });
145
+ }
@@ -111,8 +111,11 @@ export class WirePage {
111
111
  }
112
112
  /** The kind a row spawns as here: its declared species' page kind, else the wire's `kind` (a native body, an older server). */
113
113
  rowKind(species: unknown, kind: string): string { return typeof species === 'string' && species !== '' ? this.speciesKinds.get(species) ?? kind : kind; }
114
- /** Count one thing drawn. */
115
- drew(what: string): void { this.drawn[what] = (this.drawn[what] ?? 0) + 1; }
114
+ /** Count a thing drawn, or `times` of them (a frame that draws every word heard since the last). */
115
+ drew(what: string, times = 1): void { this.drawn[what] = (this.drawn[what] ?? 0) + times; }
116
+ /** Words for a view this page hasn't built (a room nobody entered), by name: heard, and rightly not drawn (EG-15). */
117
+ readonly offstage: Record<string, number> = {};
118
+ unbuilt(what: string): void { this.offstage[what] = (this.offstage[what] ?? 0) + 1; }
116
119
 
117
120
  /** One of this player's lines as the server last said it: 0 for none. */
118
121
  line(name: string): number { return this.client?.owned.get(name) ?? 0; }
@@ -16,6 +16,8 @@ import { prepareLentLooks, setLentParam, setLentTexture } from './lentLooks';
16
16
  import { applyTextureSampler } from './clientMaterials';
17
17
  import type { SceneHandles } from './sceneHandles';
18
18
  import type { ShardProduct } from '../../../shared/game/shardfile/shardProduct';
19
+ import { waitFor } from '@wildshard/engine/boot/waits';
20
+ import { bootTask } from '@wildshard/engine/boot/timing';
19
21
 
20
22
  /** Client-only: load each declared texture under `owner`, lend it to its compiled looks (they are lent first) and
21
23
  * publish a product texture that names a handle, and a volume with its numbers for the world's variant (`cube`). */
@@ -55,7 +57,8 @@ export async function lendWorldSceneTextures(rows: readonly WorldSceneLentTextur
55
57
  /** A baked volume: its deflated RGBA8 voxels as a linear 3D texture (GPU-only once uploaded), lent with its box to its looks. */
56
58
  async function lendVolume(row: Extract<WorldSceneLentTexture, { kind: 'volume' }>, volume: Extract<WorldSceneLentTexture, { kind: 'volume' }>['files']['cell']['phone'],
57
59
  owner: Scope, product: Pick<ShardProduct, 'url'>, handles: SceneHandles): Promise<void> {
58
- const bytes = await fetchDeflatedBytes(product.url(volume.file)), [x, y, z] = volume.size;
60
+ const url = product.url(volume.file);
61
+ const bytes = await bootTask(`texture:volume-inflate ${volume.file}`, () => waitFor('Preparing volume texture', fetchDeflatedBytes(url), 'work', url)), [x, y, z] = volume.size;
59
62
  if (owner.disposed) throw new Error('World scene textures unloaded while loading');
60
63
  if (bytes.length !== x * y * z * 4) throw new Error(`Lent volume ${row.label} size differs`);
61
64
  const texture = owner.own(new Data3DTexture(bytes, x, y, z));
@@ -70,8 +73,8 @@ async function lendVolume(row: Extract<WorldSceneLentTexture, { kind: 'volume' }
70
73
  }
71
74
 
72
75
  /** A product's raw r8 texels as a data texture (its wrap and magnification; trilinear with mipmaps, else linear). */
73
- async function loadRaster(row: Extract<WorldSceneLentTexture, { kind: 'raster' }>, product: Pick<ShardProduct, 'file'>): Promise<Texture> {
74
- const bytes = Uint8Array.from(await product.file(row.file)), [width, height] = row.size;
76
+ async function loadRaster(row: Extract<WorldSceneLentTexture, { kind: 'raster' }>, product: Pick<ShardProduct, 'file' | 'url'>): Promise<Texture> {
77
+ const bytes = Uint8Array.from(await bootTask(`texture:raster-read ${row.file}`, () => waitFor('Reading texture', product.file(row.file), 'file', product.url(row.file)))), [width, height] = row.size;
75
78
  if (bytes.length !== width * height) throw new Error(`Lent raster ${row.label} size differs`);
76
79
  const texture = new DataTexture(bytes, width, height, RedFormat, UnsignedByteType);
77
80
  texture.wrapS = texture.wrapT = row.wrap === 'repeat' ? RepeatWrapping : ClampToEdgeWrapping;
@@ -81,10 +84,11 @@ async function loadRaster(row: Extract<WorldSceneLentTexture, { kind: 'raster' }
81
84
  }
82
85
 
83
86
  /** A product's own KTX2 blob for the tier (its encoded orientation, flipY false), sampled by its row; GPU-only once uploaded. */
84
- async function loadProduct(row: Extract<WorldSceneLentTexture, { kind: 'product' }>, product: Pick<ShardProduct, 'file'>, loader: KTX2Loader | null): Promise<Texture> {
87
+ async function loadProduct(row: Extract<WorldSceneLentTexture, { kind: 'product' }>, product: Pick<ShardProduct, 'file' | 'url'>, loader: KTX2Loader | null): Promise<Texture> {
85
88
  if (loader === null) throw new Error('Product textures need a KTX2 reader');
86
- const bytes = Uint8Array.from(await product.file(row.file[TIER]));
87
- const texture = await new Promise<Texture>((resolve, reject) => { loader.parse(bytes.buffer, resolve, reject); });
89
+ const file = row.file[TIER], url = product.url(file);
90
+ const bytes = Uint8Array.from(await bootTask(`texture:read ${file}`, () => waitFor('Reading texture', product.file(file), 'file', url)));
91
+ const texture = await bootTask(`texture:decode ${file}`, () => waitFor('Preparing texture', new Promise<Texture>((resolve, reject) => { loader.parse(bytes.buffer, resolve, reject); }), 'worker', url));
88
92
  texture.flipY = false; texture.name = row.label;
89
93
  if (row.colour !== undefined) texture.colorSpace = row.colour === 'srgb' ? SRGBColorSpace : LinearSRGBColorSpace;
90
94
  applyTextureSampler(texture, row.sampler);
@@ -95,8 +99,9 @@ async function loadProduct(row: Extract<WorldSceneLentTexture, { kind: 'product'
95
99
 
96
100
  async function blob(url: string): Promise<Blob> {
97
101
  let type = '';
98
- const bytes = await readContent(phoneUrl(url), 25_000_000, {fetch: (address, init) => fetch(address, init),
99
- response: response => {type = response.headers.get('content-type') ?? '';}});
102
+ const path = phoneUrl(url);
103
+ const bytes = await bootTask(`texture:layer-read ${path}`, () => waitFor('Reading texture layer', readContent(path, 25_000_000, {fetch: (address, init) => fetch(address, init),
104
+ response: response => {type = response.headers.get('content-type') ?? '';}}), 'file', path));
100
105
  return new Blob([bytes], {type});
101
106
  }
102
107
 
@@ -116,7 +121,8 @@ async function loadLayers(row: Extract<WorldSceneLentTexture, { kind: 'layers' }
116
121
  const files = await Promise.all(row.layers.map(layer => Promise.all([blob(`${row.base}/${layer.name}.jpg`), layer.alpha ? blob(`${row.base}/${layer.name}-a.jpg`) : null])));
117
122
  for (const [i, [rgb, alpha]] of files.entries()) {
118
123
  if (slice.due()) await slice.yield();
119
- const texels = await decodeLayerTexels(rgb, alpha, size);
124
+ const path = `${row.base}/${row.layers[i]?.name ?? i}`;
125
+ const texels = await bootTask(`texture:layer-decode ${path}`, () => waitFor('Preparing texture layer', decodeLayerTexels(rgb, alpha, size), 'worker', path));
120
126
  if (texels !== null) { data.set(texels, i * size * size * 4); continue; }
121
127
  const colour = await createImageBitmap(rgb), cover = alpha === null ? null : await createImageBitmap(alpha), at = i * size * size * 4;
122
128
  try {
@@ -80,7 +80,7 @@ export interface OnlineShell {
80
80
  progress: () => LinkProgress;
81
81
  dialNow: () => void;
82
82
  why: () => LinkCause;
83
- pause: () => void; resume: () => void; hold: (on: boolean) => void; bossGod: () => void; hardHits: (by: number) => void;
83
+ pause: () => void; resume: () => void; hold: (on: boolean) => void; bossGod: () => void; still: () => void; hardHits: (by: number) => void;
84
84
  place: (x: number, y: number, z: number, yaw: number) => void; raise: (flag: string) => void;
85
85
  /** QA row 16: the player chose to go (the menu's exit, another world). The body leaves now, not after J114's hold.
86
86
  * Resolves once the door has closed the link; a page waits for it at most `atMostLeaveWait`. */
@@ -156,7 +156,7 @@ export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShe
156
156
  const tickOf = (): number => client.latest?.tick ?? 0, idle = (): void => undefined;
157
157
  return { client, voice, redials: true, booted, ready: () => { loaded = true; unseated?.control('ready'); unseated = null; },
158
158
  visible: hiddenMs => { redial.check(hiddenMs); }, retry: () => { redial.retry(); }, progress: () => redial.progress, why: () => redial.why, dialNow: () => { redial.dialNow(); },
159
- pause: idle, resume: idle, hold: idle, bossGod: idle, hardHits: idle, place: idle, raise: idle,
159
+ pause: idle, resume: idle, hold: idle, bossGod: idle, still: idle, hardHits: idle, place: idle, raise: idle,
160
160
  // The door hears a quit on any link of this build: seated, still admitted, or handed a held body back. A link that is down (a redial's
161
161
  // wait) gets a fresh one to say it on, so a held body goes too. No redial follows: the page is going.
162
162
  // FL27: a door that heard the quit closes plainly. A link it closed `stalled` was dropped before the quit reached it (it went out
@@ -11,7 +11,7 @@ import { saveDocuments } from '@wildshard/engine/saves/indexed';
11
11
  import type { SaveStorage } from '@wildshard/engine/saves/store';
12
12
  import { ServerMessageSchema, ShellMessageSchema, type ProbedRow, type ServerMessage, type ShellMessage } from '@wildshard/format/standaloneControl';
13
13
  import { answerHeldReads, type HeldRead } from '../../../shared/host/standalone/heldReads';
14
- import type { HarnessFlag, HarnessGod, HarnessHits, HarnessJoin, HarnessMove, HarnessPlace } from '../../../shared/host/standalone/harnessPlace';
14
+ import type { HarnessFlag, HarnessGod, HarnessHits, HarnessJoin, HarnessMove, HarnessPlace, HarnessStill } from '../../../shared/host/standalone/harnessPlace';
15
15
  import type { DevBox, DevCollidersMessage, DevGround, DevGroundMessage } from '@wildshard/engine/game/devColliders';
16
16
  import { isDevRestart, type DevGameplay, type DevPlace, type DevRestarted, type DevRestartMessage } from '@wildshard/engine/game/devGameplay';
17
17
  import type { ServerWorkerStart } from '../../../server/host/standalone/serverRuntime';
@@ -70,6 +70,8 @@ export interface StandaloneShell {
70
70
  hold: (on: boolean) => void;
71
71
  /** A Developer's `?bossGod`, for the server that lands a fight's blows. */
72
72
  bossGod: () => void;
73
+ /** A golden camera's spectator: every creature in the player's world holds where it is. */
74
+ still: () => void;
73
75
  /** A harness's word that one of this player's flags is up. */
74
76
  raise: (flag: string) => void;
75
77
  /** A proof's second client, a real one on its own link: it stands at this point in this cell, and `move` puts its body elsewhere. */
@@ -173,6 +175,7 @@ export function connectStandalone(config: StandaloneConfig, control: MessagePort
173
175
  place: (x, y, z, yaw) => { harness?.postMessage({ x, y, z, yaw } satisfies HarnessPlace, []); },
174
176
  hardHits: by => { harness?.postMessage({ hits: by } satisfies HarnessHits, []); },
175
177
  bossGod: () => { harness?.postMessage({ god: true } satisfies HarnessGod, []); },
178
+ still: () => { harness?.postMessage({ still: true } satisfies HarnessStill, []); },
176
179
  raise: flag => { harness?.postMessage({ flag } satisfies HarnessFlag, []); },
177
180
  devColliders: (name, boxes) => { if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) harness?.postMessage({ wildshardDevColliders: name, boxes } satisfies DevCollidersMessage, []); },
178
181
  devRestart,