@wildshard/engine 0.1.19 → 0.1.20

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 (79) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +4 -0
  3. package/package.json +4 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/check-devserver.mjs +1 -1
  7. package/scripts/grid-crossing-tour.mjs +11 -4
  8. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  9. package/scripts/land.mjs +2 -1
  10. package/scripts/loading-flow/benchmax.mjs +34 -11
  11. package/scripts/loading-flow/deskbench.mjs +276 -0
  12. package/scripts/loading-flow/stalls.d.mts +17 -3
  13. package/scripts/loading-flow/stalls.mjs +82 -3
  14. package/scripts/nightly-model.ts +9 -6
  15. package/scripts/offline-proof.mjs +7 -1
  16. package/scripts/parity/boot-smoke.mjs +13 -2
  17. package/scripts/pin-format.ts +5 -2
  18. package/scripts/pins-reuse.d.mts +1 -0
  19. package/scripts/pins-reuse.mjs +22 -0
  20. package/scripts/scratch-dir.mjs +95 -0
  21. package/scripts/scratch-sweep.mjs +182 -0
  22. package/scripts/tsconfig.json +2 -12
  23. package/scripts/vps/harden-prometheus.sh +3 -0
  24. package/scripts/worktree-reap.mjs +54 -8
  25. package/scripts/worktree.mjs +19 -5
  26. package/src/client/engine/anim/rigParser.ts +2 -2
  27. package/src/client/engine/core/Game.ts +63 -19
  28. package/src/client/engine/core/gpuOnly.ts +10 -0
  29. package/src/client/engine/core/renderBudget.ts +134 -0
  30. package/src/client/engine/net/redial.ts +40 -5
  31. package/src/client/engine/render/dataLook.ts +70 -7
  32. package/src/client/engine/render/families/pbr.ts +2 -0
  33. package/src/client/engine/render/families/registry.ts +11 -2
  34. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  35. package/src/client/engine/render/look.ts +7 -1
  36. package/src/client/engine/render/precompile.ts +4 -2
  37. package/src/client/engine/render/tiers.ts +4 -1
  38. package/src/client/engine/world/declaredProps.ts +5 -1
  39. package/src/client/engine/world/skyRig.ts +4 -1
  40. package/src/client/engine/world/terrainTileView.ts +64 -23
  41. package/src/client/game/devScene/hook.ts +149 -12
  42. package/src/client/game/devScene/liveLook.ts +21 -0
  43. package/src/client/game/grid/live.ts +45 -8
  44. package/src/client/game/grid/liveSession.ts +23 -4
  45. package/src/client/game/grid/pageEntry.ts +12 -1
  46. package/src/client/game/grid/productInputs.ts +22 -11
  47. package/src/client/game/grid/session.ts +13 -4
  48. package/src/client/game/session/finish.ts +4 -1
  49. package/src/client/game/shardfile/client.ts +24 -7
  50. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  51. package/src/client/game/shardfile/clientViews.ts +36 -8
  52. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  53. package/src/client/game/shardfile/groundMerge.ts +57 -5
  54. package/src/client/game/shardfile/hybrid.ts +2 -0
  55. package/src/client/game/shardfile/look.ts +1 -1
  56. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  57. package/src/client/game/shardfile/tileContent.ts +1 -1
  58. package/src/client/game/shardfile/tileDriver.ts +38 -11
  59. package/src/client/game/shardfile/wirePage.ts +7 -3
  60. package/src/client/game/shardfile/worldScenes.ts +17 -10
  61. package/src/client/host/online/doctor.ts +20 -7
  62. package/src/client/host/online/doctorView.ts +2 -0
  63. package/src/client/host/online/linkScreens.ts +83 -5
  64. package/src/client/host/online/shell.ts +13 -4
  65. package/src/client/host/standalone/shell.ts +37 -1
  66. package/src/server/game/quest/eliteDrops.ts +7 -3
  67. package/src/server/game/riding/nativeTaming.ts +13 -2
  68. package/src/server/host/dedicated/cellHost.ts +14 -2
  69. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  70. package/src/server/host/dedicated/dedicatedRoom.ts +24 -7
  71. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  72. package/src/server/host/dedicated/workerTable.ts +31 -24
  73. package/src/server/host/standalone/serverHost.ts +56 -10
  74. package/src/server/host/standalone/serverProduct.ts +9 -7
  75. package/src/server/host/standalone/serverRuntime.ts +1 -1
  76. package/src/shared/engine/core/framePacing.ts +12 -1
  77. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  78. package/src/shared/game/devColliders.ts +60 -0
  79. package/src/shared/game/devGameplay.ts +41 -0
@@ -12,9 +12,15 @@
12
12
  * tile's vertex colours, say, are left out when a fine tile has none). A merged mesh receives shadow and never casts (as
13
13
  * the tiles), and leaves with its block's last member. Each tile keeps its transformed attributes and its kept triangles
14
14
  * (refreshed when its transform, an attribute's version or its hidden quadrants change), so a rebuild is copies.
15
+ *
16
+ * SHARD-SOURCE AP8: static props and fine terrain tiles merge the same way (`propMerge`): one view mesh per material,
17
+ * receive flag and render order per 250 m block and vertex layout, normals and tangents turned with their positions, so a
18
+ * view draws a material once across tiles. The merged mesh never casts: a member that casts keeps casting itself from
19
+ * SHADOW_LAYER (the shadow pass only, `castShadow` still its tile's shadow disc), so each light's cascades cull it as before.
15
20
  */
16
- import { Box3, BufferAttribute, BufferGeometry, InterleavedBufferAttribute, Matrix4, Mesh, Sphere, Vector3, type Material, type Object3D } from 'three';
21
+ import { Box3, BufferAttribute, BufferGeometry, InterleavedBufferAttribute, Matrix3, Matrix4, Mesh, Sphere, Vector3, type Material, type Object3D } from 'three';
17
22
  import type { Scope } from '@wildshard/engine/app/scope';
23
+ import { SHADOW_LAYER } from '@wildshard/engine/core/shadowLayer';
18
24
 
19
25
  const HALF = 250, COARSE = 125, BLOCK = 250;
20
26
  /** an attribute's change count (an interleaved one counts on its buffer) */
@@ -36,11 +42,15 @@ interface Member {
36
42
  }
37
43
  interface Block { readonly members: Map<Mesh, Member>; merged: Mesh | null; queued: boolean }
38
44
 
45
+ /** How members group into blocks: `quadrant` 250 m blocks (a ground's channels are those every member has), `cell` the
46
+ * 500 m cell by vertex layout, `block` 250 m blocks by vertex layout (props: a member never loses a channel). */
47
+ export type MergeGrouping = 'quadrant' | 'cell' | 'block';
48
+
39
49
  export class GroundMerge {
40
50
  private readonly blocks = new Map<string, Block>();
41
51
  /** `onRebuild`: each new merged mesh, before it draws (its shadow flags, render order or a terrain's mesh slot) */
42
- constructor(private readonly parent: Object3D, private readonly material: Material, private readonly name: string, private readonly onRebuild?: (mesh: Mesh) => void, readonly grouping: 'quadrant' | 'cell' = 'quadrant') {
43
- if (grouping !== 'quadrant' && grouping !== 'cell') throw new Error('Unknown ground merge grouping');
52
+ constructor(private readonly parent: Object3D, private readonly material: Material, private readonly name: string, private readonly onRebuild?: (mesh: Mesh) => void, readonly grouping: MergeGrouping = 'quadrant') {
53
+ if (grouping !== 'quadrant' && grouping !== 'cell' && grouping !== 'block') throw new Error('Unknown ground merge grouping');
44
54
  }
45
55
 
46
56
  /** The tile's ground `mesh` joins (hidden itself) until `scope` ends. Detached meshes are already parent-local;
@@ -100,7 +110,7 @@ export class GroundMerge {
100
110
  const size = this.grouping === 'cell' ? HALF * 2 : BLOCK;
101
111
  const cell = `${String(Math.floor((x + HALF) / size))},${String(Math.floor((z + HALF) / size))}`;
102
112
  if (this.grouping === 'quadrant') return cell;
103
- // A cell merge never drops a channel supplied by another quadrant.
113
+ // A cell (or block) merge never drops a channel supplied by another member.
104
114
  const layout = Object.entries(member.mesh.geometry.attributes).map(([name, attribute]) => `${name}:${String(attribute.itemSize)}:${String(attribute.normalized)}`).sort().join('|');
105
115
  return `${cell}|${layout}`;
106
116
  }
@@ -131,10 +141,13 @@ export class GroundMerge {
131
141
  if (member.mesh.parent === null) toParent.copy(member.mesh.matrix);
132
142
  else toParent.multiplyMatrices(parentInverse, member.mesh.matrixWorld);
133
143
  const transform = toParent.elements.join(',');
144
+ // AP8: a prop's normals and tangents turn with it (a ground's channels copy as they are)
145
+ const turned = this.grouping === 'block' && !isTranslation(toParent), normalMatrix = turned ? new Matrix3().getNormalMatrix(toParent) : null;
134
146
  const attributes = names.map(name => {
135
147
  const attribute = geometry.getAttribute(name);
136
148
  if (attribute.count !== position.count) throw new Error(`Ground merge member lacks ${name}`);
137
- const key = name === 'position' ? transform : '', known = member.attributes.get(name);
149
+ const directed = turned && (name === 'normal' || name === 'tangent') && attribute.itemSize >= 3;
150
+ const key = name === 'position' || directed ? transform : '', known = member.attributes.get(name);
138
151
  if (known !== undefined && known.key === key && known.version === versionOf(attribute)) return known.values;
139
152
  const size = attribute.itemSize, out = new Float32Array(attribute.count * size);
140
153
  if (name === 'position') {
@@ -148,6 +161,14 @@ export class GroundMerge {
148
161
  out[i * 3 + 1] = ((e[1] ?? 0) * x + (e[5] ?? 1) * y + (e[9] ?? 0) * z + (e[13] ?? 0)) * w;
149
162
  out[i * 3 + 2] = ((e[2] ?? 0) * x + (e[6] ?? 0) * y + (e[10] ?? 1) * z + (e[14] ?? 0)) * w;
150
163
  }
164
+ } else if (directed) {
165
+ const m = name === 'normal' ? normalMatrix : new Matrix3().setFromMatrix4(toParent), v = new Vector3();
166
+ if (m === null) throw new Error('Ground merge normal without its matrix');
167
+ for (let i = 0; i < attribute.count; i++) {
168
+ v.set(attribute.getComponent(i, 0), attribute.getComponent(i, 1), attribute.getComponent(i, 2)).applyMatrix3(m).normalize();
169
+ out[i * size] = v.x; out[i * size + 1] = v.y; out[i * size + 2] = v.z;
170
+ if (size === 4) out[i * size + 3] = attribute.getComponent(i, 3);
171
+ }
151
172
  } else {
152
173
  const plain = plainFloats(attribute);
153
174
  if (plain === null) for (let i = 0; i < attribute.count; i++) for (let c = 0; c < size; c++) out[i * size + c] = attribute.getComponent(i, c);
@@ -220,6 +241,12 @@ export class GroundMerge {
220
241
  }
221
242
  }
222
243
 
244
+ /** a transform with no rotation or scale (its upper 3 x 3 the identity) */
245
+ function isTranslation(m: Matrix4): boolean {
246
+ const e = m.elements;
247
+ return e[0] === 1 && e[1] === 0 && e[2] === 0 && e[4] === 0 && e[5] === 1 && e[6] === 0 && e[8] === 0 && e[9] === 0 && e[10] === 1;
248
+ }
249
+
223
250
  const merges = new WeakMap<Object3D, Map<Material, GroundMerge>>();
224
251
  /** The one merge of `material` under `parent` (made on first use; each block empties itself as its last member leaves). */
225
252
  export function groundMerge(parent: Object3D, material: Material, name: string, grouping: 'quadrant' | 'cell' = 'quadrant'): GroundMerge {
@@ -230,3 +257,28 @@ export function groundMerge(parent: Object3D, material: Material, name: string,
230
257
  if (merge.grouping !== grouping) throw new Error('Ground merge grouping changed for its material');
231
258
  return merge;
232
259
  }
260
+
261
+ /** How a merged prop mesh draws: whether it receives shadow, and its render order (each its own merge). */
262
+ export interface PropDraw { readonly receive: boolean; readonly order: number }
263
+ const propMerges = new WeakMap<Object3D, Map<Material, Map<string, GroundMerge>>>();
264
+ /** SHARD-SOURCE AP8: the one static prop merge of `material` drawn as `draw` under `parent`: 250 m blocks by vertex layout. */
265
+ export function propMerge(parent: Object3D, material: Material, draw: PropDraw): GroundMerge {
266
+ let byMaterial = propMerges.get(parent);
267
+ if (byMaterial === undefined) { byMaterial = new Map(); propMerges.set(parent, byMaterial); }
268
+ let byDraw = byMaterial.get(material);
269
+ if (byDraw === undefined) { byDraw = new Map(); byMaterial.set(material, byDraw); }
270
+ const key = `${String(draw.receive)}|${String(draw.order)}`;
271
+ let merge = byDraw.get(key);
272
+ if (merge === undefined) {
273
+ merge = new GroundMerge(parent, material, 'props.merged', (mesh) => { mesh.castShadow = false; mesh.receiveShadow = draw.receive; mesh.renderOrder = draw.order; }, 'block');
274
+ byDraw.set(key, merge);
275
+ }
276
+ return merge;
277
+ }
278
+
279
+ /** AP8: `mesh` joins its merge for the view; it keeps drawing only into the shadow maps (SHADOW_LAYER) while it may cast. */
280
+ export function mergeView(parent: Object3D, mesh: Mesh, material: Material, scope: Scope): void {
281
+ if (mesh.material !== material) throw new Error('Prop merge member draws another material');
282
+ propMerge(parent, material, { receive: mesh.receiveShadow, order: mesh.renderOrder }).add(mesh, scope);
283
+ mesh.visible = true; mesh.layers.set(SHADOW_LAYER);
284
+ }
@@ -399,6 +399,8 @@ export class HybridRuntimeSession {
399
399
  timings(): { readonly current: Readonly<Pick<HybridHookTiming, 'instance' | 'hook' | 'start'>> | null; readonly completed: readonly HybridHookTiming[] } {
400
400
  return { current: this.currentHook, completed: [...this.completedHooks] };
401
401
  }
402
+ /** GC6: the cells whose entry is being prepared on the road (for the tour's trace) */
403
+ preparing(): readonly string[] { return [...this.installations.keys()]; }
402
404
  /** Finish an actually requested entry before its frame transfer. Neighbours use inert prepare() only.
403
405
  * A source must leave first; entered services and parent runtime slots publish only at enter(). */
404
406
  prepareEntry(instance: string, signal?: AbortSignal): Promise<boolean> {
@@ -22,7 +22,7 @@ export function shardfileLook(look: Shardfile['look'], assets?: ReadonlyMap<stri
22
22
  // B2: `grade.tone` is a grade choice, not a light setting: it holds on every tier, with or without the row (so do M4.7's
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
- exposure: look.grade.exposure, vignette: look.grade.vignette ?? null, bloomRadius: resolved.bloom.radius,
25
+ exposure: look.grade.exposure, vignette: look.grade.vignette ?? null, bloomRadius: resolved.bloom.radius, sky: look.sky?.graph ?? null,
26
26
  light: { rim: resolved.rim, pools: resolved.pools, heightFogDensity: resolved.atmosphere.fogHeightDensity, lamps: resolved.lamps, bounce: resolved.bounce, environment: resolved.environment,
27
27
  shadow: resolved.shadow, motes: resolved.motes } });
28
28
  }
@@ -2,6 +2,7 @@ import { Box3, BufferGeometry, InstancedBufferAttribute, InstancedMesh, Mesh, Sp
2
2
  import * as v from 'valibot';
3
3
  import { prepareRigLoader } from '@wildshard/engine/anim/rig';
4
4
  import type { Scope } from '@wildshard/engine/app/scope';
5
+ import { pageScope } from '@wildshard/engine/app/resources';
5
6
  import { ownSceneResource } from '@wildshard/engine/app/sceneOwnership';
6
7
  import { workSlice } from '@wildshard/engine/core/workSlice';
7
8
  import { nativeWholeGeometry } from '@wildshard/engine/models/nativeGeometry';
@@ -11,6 +12,7 @@ import type { ShardProduct } from '../../../shared/game/shardfile/shardProduct';
11
12
  import { runtimeProduct } from './runtimeProduct';
12
13
  import { SharedTileBuilds, type TileContent } from './tileContent';
13
14
  import type { ControlRefinement } from './controlRefinement';
15
+ import { tilesSettling } from './tileDriver';
14
16
 
15
17
  type WholeLibrary = Extract<WorldScenesSection['libraries'][number], { kind: 'whole' }>;
16
18
  type SlabTile = WorldSceneSlabLibrary['tiles'][number];
@@ -21,6 +23,12 @@ const EMPTY: ReadonlySet<number> = new Set();
21
23
  function slabMesh(node: Object3D): node is Mesh { return node instanceof Mesh; }
22
24
  function materialList(mesh: Mesh): Material[] { return Array.isArray(mesh.material) ? mesh.material : [mesh.material]; }
23
25
 
26
+ /** NB3: the longest a loader publication waits for one more bank read before it publishes what it holds */
27
+ const GATHER_MS = 250;
28
+
29
+ /** One slab part waiting to publish: its instanced chunk, the anchor it joins, and the holder scope that retires it. */
30
+ export interface SlabPart { readonly part: InstancedMesh; readonly anchor: Mesh; readonly scope: Scope }
31
+
24
32
  /** a tile's chunks in file order, then each file's chunk order (as its build returns their geometries) */
25
33
  const chunksOf = (entry: SlabTile): readonly WorldSceneSlabChunk[] => entry.files.flatMap(file => file.chunks);
26
34
 
@@ -76,17 +84,25 @@ export class SlabLibrary {
76
84
  private readonly entries = new Map<number, SlabTile>();
77
85
  private readonly keys = new Map<string, WorldSceneSlabKey>();
78
86
  private serial = 0;
79
- private publication: Promise<void> = Promise.resolve();
87
+ /** the parts waiting for the one publication cursor, and whether it is running (`publish`) */
88
+ private readonly waiting: { readonly parts: readonly SlabPart[]; readonly mount: () => Promise<void>; readonly done: () => void; readonly fail: (error: unknown) => void }[] = [];
89
+ private publishing = false;
90
+ private readonly bounds: ReadonlyMap<number, ShardProduct['shardfile']['tiles'][number]['bounds']>;
91
+ private readonly product: ShardProduct;
92
+ /** bank reads running now, and the publication waiting for one to finish (NB3: the loader's gather) */
93
+ private reads = 0;
94
+ private readonly readDone: (() => void)[] = [];
80
95
  constructor(owner: Scope, product: ShardProduct, private readonly whole: WholeLibrary, private readonly row: WorldSceneSlabLibrary,
81
96
  private readonly queue: ControlRefinement, private readonly cover: (tile: number) => Promise<void>,
82
- private readonly prepare?: (part: InstancedMesh, owner: Scope, anchor: Mesh) => Promise<void>) {
97
+ private readonly prepare?: (parts: readonly SlabPart[]) => Promise<void>) {
83
98
  if (row.of !== whole.id) throw new Error('Slab library covers another library');
84
99
  for (const key of row.keys) {
85
100
  if (key.castFrom !== undefined) throw new Error('Slab key casting from a band has no run-time draw');
86
101
  for (const source of key.sources) { if (this.keys.has(source)) throw new Error('Slab source belongs to two keys'); this.keys.set(source, key); }
87
102
  }
88
103
  for (const model of whole.models) if (!this.keys.has(model.id)) throw new Error(`Slab library omits refine model ${model.id}`);
89
- const bounds = new Map(product.shardfile.tiles.filter(tile => tile.lod === 0).map(tile => [tile.z * 8 + tile.x, tile.drawBounds ?? tile.bounds] as const));
104
+ const bounds = this.bounds = new Map(product.shardfile.tiles.filter(tile => tile.lod === 0).map(tile => [tile.z * 8 + tile.x, tile.drawBounds ?? tile.bounds] as const));
105
+ this.product = product;
90
106
  const declared = new Set(product.shardfile.files.filter(file => file.kind === 'glb').map(file => file.hash));
91
107
  for (const entry of row.tiles) {
92
108
  for (const tile of entry.covers ?? [entry.tile]) if (!bounds.has(tile)) throw new Error(`Slabs require a declared fine tile: ${String(tile)}`);
@@ -94,38 +110,87 @@ export class SlabLibrary {
94
110
  this.entries.set(entry.tile, entry);
95
111
  }
96
112
  this.builds = new SharedTileBuilds(owner, async (tile, scope) => {
97
- const entry = this.entries.get(tile); if (entry === undefined) throw new Error('Missing slab tile');
98
- const chunks: BufferGeometry[] = [];
99
- let box = bounds.get(tile);
100
- if (entry.covers !== undefined) {
101
- const min: [number, number, number] = [Infinity, Infinity, Infinity], max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
102
- for (const logical of entry.covers) {
103
- const covered = bounds.get(logical); if (covered === undefined) throw new Error('Missing slab logical bounds');
104
- for (const axis of [0, 1, 2] as const) { min[axis] = Math.min(min[axis], covered.min[axis]); max[axis] = Math.max(max[axis], covered.max[axis]); }
105
- }
106
- box = { min, max };
113
+ this.reads++;
114
+ try { return await this.read(tile, scope); }
115
+ finally { this.reads--; for (const wake of this.readDone.splice(0)) wake(); }
116
+ });
117
+ }
118
+ /** One storage bank's chunk geometries: read and decoded in the refinement queue, its covered tiles first covered. */
119
+ private async read(tile: number, scope: Scope): Promise<BufferGeometry[]> {
120
+ const { row, queue, bounds, product } = this;
121
+ const entry = this.entries.get(tile); if (entry === undefined) throw new Error('Missing slab tile');
122
+ const chunks: BufferGeometry[] = [];
123
+ let box = bounds.get(tile);
124
+ if (entry.covers !== undefined) {
125
+ const min: [number, number, number] = [Infinity, Infinity, Infinity], max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
126
+ for (const logical of entry.covers) {
127
+ const covered = bounds.get(logical); if (covered === undefined) throw new Error('Missing slab logical bounds');
128
+ for (const axis of [0, 1, 2] as const) { min[axis] = Math.min(min[axis], covered.min[axis]); max[axis] = Math.max(max[axis], covered.max[axis]); }
107
129
  }
108
- // A shared bank is visible wherever any of its actual logical coverage
109
- // is visible. Its storage address alone cannot fence its publication.
110
- const at = { x: entry.covers === undefined || box === undefined ? -250 + (tile % 8 + 0.5) * 62.5 : (box.min[0] + box.max[0]) / 2,
111
- y: box === undefined ? 0 : (box.min[1] + box.max[1]) / 2,
112
- z: entry.covers === undefined || box === undefined ? -250 + (Math.floor(tile / 8) + 0.5) * 62.5 : (box.min[2] + box.max[2]) / 2,
113
- ...(box === undefined ? {} : { bounds: box }) };
114
- await queue.add(`${row.id}:${String(tile)}:${String(this.serial++)}`, at, async () => {
130
+ box = { min, max };
131
+ }
132
+ // A shared bank is visible wherever any of its actual logical coverage
133
+ // is visible. Its storage address alone cannot fence its publication.
134
+ const at = { x: entry.covers === undefined || box === undefined ? -250 + (tile % 8 + 0.5) * 62.5 : (box.min[0] + box.max[0]) / 2,
135
+ y: box === undefined ? 0 : (box.min[1] + box.max[1]) / 2,
136
+ z: entry.covers === undefined || box === undefined ? -250 + (Math.floor(tile / 8) + 0.5) * 62.5 : (box.min[2] + box.max[2]) / 2,
137
+ ...(box === undefined ? {} : { bounds: box }) };
138
+ await queue.add(`${row.id}:${String(tile)}:${String(this.serial++)}`, at, async () => {
139
+ if (scope.disposed || scope.disposing) return;
140
+ for (const logical of entry.covers ?? [tile]) await this.cover(logical);
141
+ for (const file of entry.files) {
115
142
  if (scope.disposed || scope.disposing) return;
116
- for (const logical of entry.covers ?? [tile]) await this.cover(logical);
117
- for (const file of entry.files) {
118
- if (scope.disposed || scope.disposing) return;
119
- let read: readonly BufferGeometry[];
120
- try { read = await readSlabChunks(scope, product, tile, file); }
121
- catch (error) { if (scope.disposed || scope.disposing) return; throw error; }
122
- for (const geometry of read) ownSceneResource(geometry, scope);
123
- chunks.push(...read);
124
- }
125
- });
126
- if (!scope.disposed && !scope.disposing && chunks.length !== chunksOf(entry).length) throw new Error('Slab tile chunk count differs from its row');
127
- return chunks;
143
+ let read: readonly BufferGeometry[];
144
+ try { read = await readSlabChunks(scope, product, tile, file); }
145
+ catch (error) { if (scope.disposed || scope.disposing) return; throw error; }
146
+ for (const geometry of read) ownSceneResource(geometry, scope);
147
+ chunks.push(...read);
148
+ }
128
149
  });
150
+ if (!scope.disposed && !scope.disposing && chunks.length !== chunksOf(entry).length) throw new Error('Slab tile chunk count differs from its row');
151
+ return chunks;
152
+ }
153
+ /**
154
+ * The library's one publication cursor: `parts` are prepared (the native warm and its completed-draw fence) before they
155
+ * mount (`mount`, inside the cursor), never while another publication's preparation runs. In play a publication is one queued part list (one part);
156
+ * NINE-DRAGON-BENCHMAX NB3: under the loader's settle a publication takes every list waiting when it starts, so one warm
157
+ * covers what was ~50 serialized ones on Nine's spawn view (~75 ms each on a cold phone). A failed preparation fails
158
+ * every list it covered; a retired holder's part is left out of the next publication.
159
+ */
160
+ private publish(parts: readonly SlabPart[], mount: () => Promise<void>): Promise<void> {
161
+ return new Promise<void>((resolve, reject) => { this.waiting.push({ parts, mount, done: resolve, fail: reject }); void this.drain(); });
162
+ }
163
+ private async drain(): Promise<void> {
164
+ if (this.publishing) return;
165
+ this.publishing = true;
166
+ try {
167
+ while (this.waiting.length > 0) {
168
+ // under the loader a publication first gathers: while banks are still reading it waits for them (each wait capped
169
+ // at GATHER_MS, so a read that never runs can't hold it), and then takes every part they produced at once
170
+ for (let gathered = true; gathered && tilesSettling() && this.reads > 0;) {
171
+ gathered = await new Promise<boolean>(resolve => {
172
+ let settled = false;
173
+ const settle = (read: boolean): void => { if (!settled) { settled = true; resolve(read); } };
174
+ pageScope.timeout(GATHER_MS, () => { settle(false); });
175
+ this.readDone.push(() => { settle(true); });
176
+ });
177
+ }
178
+ const lists = tilesSettling() ? this.waiting.splice(0) : this.waiting.splice(0, 1);
179
+ const parts = lists.flatMap(list => list.parts).filter(({ scope }) => !scope.disposed && !scope.disposing);
180
+ try { if (this.prepare !== undefined && parts.length > 0) await this.prepare(parts); }
181
+ catch (error) {
182
+ // a holder retired during a shared preparation fails only its own list; the live lists publish again
183
+ const retired = (list: (typeof lists)[number]): boolean => list.parts.some(({ scope }) => scope.disposed || scope.disposing);
184
+ const live = lists.filter(list => !retired(list));
185
+ if (live.length < lists.length && live.length > 0) { for (const list of lists) if (retired(list)) list.fail(error); this.waiting.unshift(...live); }
186
+ else for (const list of lists) list.fail(error);
187
+ continue;
188
+ }
189
+ for (const list of lists) {
190
+ try { await list.mount(); list.done(); } catch (error) { list.fail(error); }
191
+ }
192
+ }
193
+ } finally { this.publishing = false; }
129
194
  }
130
195
  /** an anchor's frozen stand-in until its key's first chunk: no channels (the anchor stays hidden) */
131
196
  geometry(id: string): BufferGeometry | null { return this.whole.models.some(model => model.id === id) ? new BufferGeometry() : null; }
@@ -159,7 +224,7 @@ export class SlabLibrary {
159
224
  const drawn: InstancedMesh[] = [];
160
225
  if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return drawn;
161
226
  scope.onDispose(() => { for (const part of drawn) { part.removeFromParent(); part.dispose(); } drawn.length = 0; });
162
- const slice = workSlice(undefined, scope);
227
+ const slice = workSlice(undefined, scope), parts: SlabPart[] = [];
163
228
  for (const [index, chunk] of chunksOf(entry).entries()) {
164
229
  if (chunk.key !== key.id) continue;
165
230
  if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return drawn;
@@ -171,23 +236,24 @@ export class SlabLibrary {
171
236
  part.name = `${mesh.name}:slab:${String(tile)}:${String(index)}`; part.matrixAutoUpdate = false;
172
237
  part.castShadow = key.castShadow; part.receiveShadow = key.receiveShadow; part.renderOrder = key.renderOrder;
173
238
  part.layers.mask = key.layers; part.frustumCulled = key.frustumCulled;
174
- // All keys share one publication cursor. A CPU-budget yield alone can
175
- // mount several still-culled chunks before a turn first uploads them.
176
- // Preparation lends the actual native geometry to the existing warmer;
177
- // it must finish its completed-draw fence before another key enters.
178
- drawn.push(part);
179
- const prior = this.publication;
180
- let release = (): void => undefined;
181
- this.publication = new Promise<void>(resolve => { release = resolve; });
182
- await prior;
183
- try {
184
- if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return drawn;
185
- if (this.prepare !== undefined) await this.prepare(part, scope, mesh);
186
- if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return drawn;
239
+ drawn.push(part); parts.push({ part, anchor: mesh, scope });
240
+ }
241
+ // All keys share one publication cursor. A CPU-budget yield alone can
242
+ // mount several still-culled chunks before a turn first uploads them.
243
+ // Preparation lends the actual native geometry to the existing warmer;
244
+ // it must finish its completed-draw fence before another key enters.
245
+ // In play one part a publication (and a frame); under the loader's card a
246
+ // publication takes every part waiting then (NB3, `publish`).
247
+ for (let at = 0; at < parts.length;) {
248
+ const batch = tilesSettling() ? parts.slice(at) : parts.slice(at, at + 1);
249
+ at += batch.length;
250
+ if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return drawn;
251
+ await this.publish(batch, async () => {
252
+ if (lifetime.disposed || lifetime.disposing || scope.disposed || scope.disposing) return;
187
253
  if (!laid) lay();
188
- mesh.add(part);
189
- await slice.yield();
190
- } finally { release(); }
254
+ for (const { part } of batch) mesh.add(part);
255
+ await (tilesSettling() ? slice.check() : slice.yield());
256
+ });
191
257
  }
192
258
  return drawn;
193
259
  });
@@ -331,7 +331,7 @@ export function clientRingPorts(instances: ReadonlyMap<string, ClientRingInstanc
331
331
  const tiles = await prepareClientTile(source, assets, key, scope, {
332
332
  terrain: async (bytes, owner) => {
333
333
  const data = await ports.decoder.decode(bytes); if (owner.disposed || owner.disposing) throw new Error('shardfile rings: tile dropped while decoding');
334
- return views.terrain(data, group, owner, false);
334
+ return views.terrain(data, group, owner, false, instance.root);
335
335
  },
336
336
  props: (props, address, bytes, owner, additional) => views.props(props, address, bytes, group, owner, additional, instance.root),
337
337
  });
@@ -24,7 +24,7 @@ import { macrotask } from '@wildshard/engine/boot/plan';
24
24
  import { loadingUnits } from '@wildshard/engine/boot/waits';
25
25
  import { diagnosticNow } from '@wildshard/engine/core/clock';
26
26
  import { bootTask, bootWork } from '@wildshard/engine/boot/timing';
27
- import { FENCE_LANES, SPAWN_VIEW_M, spawnViewUsesCamera } from './controlRefinement';
27
+ import { SPAWN_VIEW_M, spawnViewUsesCamera } from './controlRefinement';
28
28
  import { streamingDistance, streamingOrder, type StreamingBounds, type StreamingPoint, type StreamingView } from './streamingView';
29
29
 
30
30
  /** MF5: the live drivers, and whether the loader is settling them (no world frames under the card since FC2). */
@@ -52,6 +52,8 @@ export async function settleTileDrivers(frame?: () => void, stallMs = 20000): Pr
52
52
  await bootTask('app:spawn-view-tiles', async () => { for (const driver of Array.from(liveDrivers)) await driver.settle(stallMs); });
53
53
  } finally { loaderMode = false; }
54
54
  }
55
+ /** Whether the loader is settling the live drivers now (no frame is presented under its card). */
56
+ export function tilesSettling(): boolean { return loaderMode; }
55
57
  /** DL21: while the loader settles, the render tiles inside its fence across the live drivers and how many are complete (the
56
58
  * spawn view's card counts them); null outside the settle. */
57
59
  export function settlingTiles(): { readonly done: number; readonly total: number; readonly stages: number; readonly stagesTotal: number } | null {
@@ -81,8 +83,8 @@ export class TileDriver {
81
83
  private readonly retried = new Set<string>();
82
84
  private centre: CellTile | null = null;
83
85
  private renderRing: ReadonlySet<number> = new Set();
84
- /** the attaches `step` started, while they run (the loader's settle waits on them): one in play, FENCE_LANES under the
85
- * loader */
86
+ /** the attaches `step` started, while they run (the loader's settle waits on them): one in play, every fence tile under
87
+ * the loader */
86
88
  private readonly inflight = new Set<Promise<void>>();
87
89
  private plan: TileRingPlan | null = null;
88
90
  private coarseScope: Scope | null = null;
@@ -189,7 +191,7 @@ export class TileDriver {
189
191
  }
190
192
 
191
193
  /** Once a frame with the player's cell-local position: retire the tiles outside the rings, then start the nearest wanted
192
- * tile not yet attached (colliders first), one at a time in play; under the loader up to FENCE_LANES at once (DL21: the
194
+ * tile not yet attached (colliders first), one at a time in play; under the loader all at once (DL21, NB3: the
193
195
  * fence's slab reads and decodes then overlap, where one tile at a time held its queue at one job). Render owners retire one tile beyond the attach ring;
194
196
  * collider owners retain the exact 3 x 3 physical ring (D2 B). */
195
197
  step(x: number, z: number): void {
@@ -201,7 +203,10 @@ export class TileDriver {
201
203
  if (plan.retained[layer].has(key)) continue;
202
204
  this.attached[layer].delete(key); tile.scope.dispose();
203
205
  }
204
- const lanes = loaderMode ? FENCE_LANES : 1;
206
+ // NB3: under the loader every fence tile starts at once. A tile's attach mostly awaits shared work (its slab banks'
207
+ // reads and their one publication chain, the refinement queue's FENCE_LANES jobs), so a lane cap left the spawn's
208
+ // slab tiles queued behind the collider ring's builds (Nine: render began ~450 ms in at x4)
209
+ const lanes = loaderMode ? Number.POSITIVE_INFINITY : 1;
205
210
  if (this.inflight.size >= lanes) return;
206
211
  const now = diagnosticNow(), cone = loaderMode || this.view === null ? null : this.view(), streamView = spawnViewUsesCamera() ? this.streamingView?.() ?? null : null;
207
212
  for (const key of this.wantedAt.keys()) if (!wanted.render.has(key)) this.wantedAt.delete(key);
@@ -326,17 +331,39 @@ export class TileDriver {
326
331
  // content (the card names the step's wait; this says which content holds it)
327
332
  const timed = loaderMode, started = timed ? diagnosticNow() : 0, contents: Record<string, number> = {};
328
333
  try {
329
- for (const content of this.contents) {
330
- if (tile.done.has(content)) continue;
331
- if (!content.tiles().has(key)) { tile.done.add(content); continue; }
332
- if (layer === 'render' && content.ready?.() === false) continue;
334
+ /** under the loader, one content's stage of this tile (timed); false when the tile retired meanwhile */
335
+ const stage = async (content: TileContent): Promise<boolean> => {
336
+ if (tile.done.has(content)) return true;
337
+ if (!content.tiles().has(key)) { tile.done.add(content); return true; }
338
+ if (layer === 'render' && content.ready?.() === false) return true;
333
339
  // Cached stages may resolve in microtasks; share the live frame's
334
340
  // budget before admitting another stage, including background tiles.
335
- if (frameBudgetSpent(WORK_SLICE_MS)) await (loaderMode ? task() : this.pause()); // MF5: no frames under the card
336
- if (tile.scope.disposed || tile.scope.disposing) return null;
341
+ if (frameBudgetSpent(WORK_SLICE_MS)) await task(); // MF5: no frames under the card
342
+ if (tile.scope.disposed || tile.scope.disposing) return false;
337
343
  const at = timed ? diagnosticNow() : 0;
338
344
  await (layer === 'render' ? content.attach(key, tile.scope) : content.attachColliders?.(key, tile.scope));
339
345
  if (timed) contents[content.id] = Math.round(diagnosticNow() - at);
346
+ if (tile.scope.disposed || tile.scope.disposing) return false;
347
+ tile.done.add(content);
348
+ return true;
349
+ };
350
+ // NINE-DRAGON-BENCHMAX NB3: under the loader a tile's contents attach together, so the slab keys' publications queue
351
+ // at once and publish as one warm (slabLibrary.ts `publish`); one after another, each waited on its own (~50 serialized
352
+ // warms on Nine's spawn view, ~75 ms each on a cold phone). In play they stay in order, one at a time.
353
+ // allSettled: a failed content rethrows only once its siblings have finished, so the settle's retry never starts a
354
+ // second attach of this key while the first is still running on the scope the catch disposes
355
+ if (loaderMode) {
356
+ const settled = await Promise.allSettled(this.contents.map(stage)), failed = settled.find(row => row.status === 'rejected');
357
+ if (failed !== undefined) throw failed.reason;
358
+ if (!settled.every(row => row.status === 'fulfilled' && row.value)) return null;
359
+ }
360
+ else for (const content of this.contents) {
361
+ if (tile.done.has(content)) continue;
362
+ if (!content.tiles().has(key)) { tile.done.add(content); continue; }
363
+ if (layer === 'render' && content.ready?.() === false) continue;
364
+ if (frameBudgetSpent(WORK_SLICE_MS)) await this.pause();
365
+ if (tile.scope.disposed || tile.scope.disposing) return null;
366
+ await (layer === 'render' ? content.attach(key, tile.scope) : content.attachColliders?.(key, tile.scope));
340
367
  if (tile.scope.disposed || tile.scope.disposing) return null;
341
368
  tile.done.add(content);
342
369
  }
@@ -82,6 +82,8 @@ export class WirePage {
82
82
  private readonly quests = new Map<string, QuestProgress>();
83
83
  private readonly heard = new Set<string>();
84
84
  private readonly feeds = new Map<string, QuestViewFeed>();
85
+ /** each feed's declaration, as text: a changed one makes a new feed */
86
+ private readonly feedWords = new Map<string, string>();
85
87
  private readonly waiting = new Set<Live>();
86
88
  private readonly books = new Set<Flags>();
87
89
  /** The rows a sky reads: none, until the wire is up. */
@@ -140,7 +142,7 @@ export class WirePage {
140
142
  for (const use of this.waiting) use(client);
141
143
  this.waiting.clear();
142
144
  }
143
- unbind(): void { this.client = null; this.press = () => undefined; this.act = () => undefined; this.dayRow = undefined; this.stop = () => undefined; this.encounterRows = null; this.heads = () => false; this.seeded = null; this.purchases.clear(); this.books.clear(); this.feeds.clear(); this.movers.clear(); }
145
+ unbind(): void { this.client = null; this.press = () => undefined; this.act = () => undefined; this.dayRow = undefined; this.stop = () => undefined; this.encounterRows = null; this.heads = () => false; this.seeded = null; this.purchases.clear(); this.books.clear(); this.feeds.clear(); this.feedWords.clear(); this.movers.clear(); }
144
146
  /** A setting's weather or a dev's jump: the server's sky takes it. Only a mode outlives its world. */
145
147
  climate(word: ClimateWord): void {
146
148
  if (word.op !== 'force') this.skyWords.set(word.op, word);
@@ -215,8 +217,10 @@ export class WirePage {
215
217
  }
216
218
  /** A quest view for `def`, over this player's rows. */
217
219
  quest(def: QuestDef): QuestView {
218
- const feed = this.feeds.get(def.id) ?? new QuestViewFeed([def], { quests: this.quests, phased: this.heard });
219
- this.feeds.set(def.id, feed);
220
+ // SHARD-SOURCE AP19 (DEVSERVER): a quest whose declaration changed (`wildshard watch`'s soft restart) gets a feed of its new steps
221
+ const words = typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ ? JSON.stringify(def) : '', held = this.feeds.get(def.id);
222
+ const feed = held !== undefined && this.feedWords.get(def.id) === words ? held : new QuestViewFeed([def], { quests: this.quests, phased: this.heard });
223
+ this.feeds.set(def.id, feed); this.feedWords.set(def.id, words);
220
224
  return feed.quest(def.id);
221
225
  }
222
226
  /** The server's payouts: the page's own go, so a kill pays once. */
@@ -420,18 +420,25 @@ async function buildPrepared(ctx: ShardContext, section: WorldScenesSection, res
420
420
  // reconstructing a union during play.
421
421
  const slabs = section.libraries.find(entry => entry.kind === 'slabs' && entry.of === row.id);
422
422
  if (slabs?.kind !== 'slabs') throw new Error(`Fine refinement requires baked slabs: ${row.id}`);
423
- const whole = new SlabLibrary(owner, product, row, slabs, refinementQueue(), coarse.ensure, async (part, scope, anchor) => {
423
+ const whole = new SlabLibrary(owner, product, row, slabs, refinementQueue(), coarse.ensure, async parts => {
424
424
  const game = ctx.game.runtime?.world?.game;
425
425
  if (game === undefined || game === null) return;
426
- const live = (): boolean => !owner.disposed && !owner.disposing && !scope.disposed && !scope.disposing;
427
- // The native warmer draws connected hidden roots. Borrow the
428
- // key's actual world frame, without exposing a partial anchor.
429
- anchor.updateWorldMatrix(true, false);
430
- const stage = new Group(); stage.visible = false; stage.matrixAutoUpdate = false; stage.matrix.copy(game.rootScene.matrixWorld).invert().multiply(anchor.matrixWorld);
431
- stage.add(part); game.rootScene.add(stage);
432
- const forget = scope.capture('disposers', () => { stage.removeFromParent(); });
433
- try { await game.warmSceneRoots([stage], live, undefined, { drawGeometry: true }); }
434
- finally { forget(); part.removeFromParent(); stage.removeFromParent(); }
426
+ const live = (): boolean => !owner.disposed && !owner.disposing && parts.every(({ scope }) => !scope.disposed && !scope.disposing);
427
+ // The native warmer draws connected hidden roots. Borrow each
428
+ // key's actual world frame, without exposing a partial anchor;
429
+ // one hidden root holds the publication's every part (NB3).
430
+ const root = new Group(); root.visible = false; root.matrixAutoUpdate = false;
431
+ root.matrix.copy(game.rootScene.matrixWorld).invert();
432
+ const staged = parts.map(({ part, anchor, scope }) => {
433
+ anchor.updateWorldMatrix(true, false);
434
+ const stage = new Group(); stage.matrixAutoUpdate = false; stage.matrix.copy(anchor.matrixWorld);
435
+ stage.add(part); root.add(stage);
436
+ const forget = scope.capture('disposers', () => { stage.removeFromParent(); });
437
+ return { part, stage, forget };
438
+ });
439
+ game.rootScene.add(root);
440
+ try { await game.warmSceneRoots([root], live, undefined, { drawGeometry: true }); }
441
+ finally { for (const { part, stage, forget } of staged) { forget(); part.removeFromParent(); stage.removeFromParent(); } root.removeFromParent(); }
435
442
  });
436
443
  refining.set(row.id, whole);
437
444
  libraries.set(row.id, { geometry: id => whole.geometry(id) }); return;
@@ -22,7 +22,9 @@ export const DOCTOR_CHECKS = [
22
22
  export type DoctorId = (typeof DOCTOR_CHECKS)[number]['id'];
23
23
  export type DoctorState = 'wait' | 'run' | 'pass' | 'warn' | 'fail' | 'skip';
24
24
  /** One check as the panel shows it. `value` is what was measured; `hint` says what to do when it is not a pass. */
25
- export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number }
25
+ export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number;
26
+ /** The failure-mode catalogue's id this row's warning stands for (meta MMO-FAILURE-MODES-PLAN; FM4b mode 42, `clock-skew`). */
27
+ readonly failmode?: string }
26
28
 
27
29
  /** What the page knows before any check: its own stamps (`stampBuildDocuments`). */
28
30
  export interface DoctorConfig {
@@ -56,14 +58,14 @@ async function limited<T>(scope: Scope, ms: number, work: (signal: AbortSignal)
56
58
  }
57
59
 
58
60
  /** A check's outcome before it is timed. */
59
- interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string }
61
+ interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string; readonly failmode?: string }
60
62
  const pass = (value: string): Outcome => ({ state: 'pass', value });
61
63
  const warn = (value: string, hint: string): Outcome => ({ state: 'warn', value, hint });
62
64
  const fail = (value: string, hint: string): Outcome => ({ state: 'fail', value, hint });
63
65
  const skip = (value: string): Outcome => ({ state: 'skip', value });
64
66
 
65
67
  /** What the earlier checks learned, for the later ones. */
66
- interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
68
+ export interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
67
69
  /** The release's build has no server book or part on the packs origin: the server cannot move to it. */
68
70
  packsMissing?: boolean }
69
71
 
@@ -238,18 +240,29 @@ function checkJoin(config: DoctorConfig, learned: Learned, ms: number): Promise<
238
240
  });
239
241
  }
240
242
 
241
- function checkLatency(learned: Learned): Outcome {
243
+ /**
244
+ * FM4b mode 42 (`clock-skew`): the device's clock measured more than 30 s off the server's health `now` (or the page's `Date`
245
+ * header). The warning shows the measured offset and the automatic-clock fix; it never claims the offset caused a failed secure
246
+ * connection. An unmeasured clock is `clock unknown`, never a warning.
247
+ */
248
+ const clockSkew = (offsetMs: number, server: boolean): Outcome => ({ state: 'warn', value: '', failmode: 'clock-skew',
249
+ hint: `Check automatic date and time: this device's clock is ${(Math.abs(offsetMs) / 1000).toFixed(0)} s ${offsetMs >= 0 ? 'behind' : 'ahead of'} the ${server ? 'server' : 'page\'s host'}. Set date and time to automatic in its settings, then Run again.` });
250
+
251
+ /** The latency row, with the device clock's measured offset. Exported for its test. */
252
+ export function checkLatency(learned: Learned): Outcome {
242
253
  const offsetMs = learned.serverOffset ?? learned.pageOffset ?? null;
243
254
  const clock = offsetMs === null ? 'clock unknown' : `clock ${offsetMs >= 0 ? '+' : '−'}${(Math.abs(offsetMs) / 1000).toFixed(1)} s${learned.serverOffset === undefined ? ' vs page' : ''}`;
244
- const clockOff = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS;
255
+ const skewed = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS ? clockSkew(offsetMs, learned.serverOffset !== undefined) : null;
245
256
  if (learned.rtt.length === 0) {
257
+ // a clock that is off is worth saying even when the socket gave no pings to time
258
+ if (skewed !== null) return { ...skewed, value: `${learned.joined ? 'no pong' : 'needs the socket'} · ${clock}` };
246
259
  if (!learned.joined) return skip(`needs the socket · ${clock}`);
247
260
  return warn(`no pong · ${clock}`, 'The server answered the join but not the pings. Run the check again.');
248
261
  }
249
262
  const sorted = [...learned.rtt].sort((a, b) => a - b), median = sorted[Math.floor(sorted.length / 2)] ?? 0, min = sorted[0] ?? 0;
250
263
  const fmt = (ms: number): string => ms < 10 ? ms.toFixed(1) : String(Math.round(ms));
251
264
  const value = `${fmt(median)} ms (min ${fmt(min)}) · ${clock}`;
252
- if (clockOff) return warn(value, "This phone's clock is off. Set date and time to automatic in the phone's settings.");
265
+ if (skewed !== null) return { ...skewed, value };
253
266
  if (median > SLOW_MS) return warn(value, 'The link is slow. Play still works, but hits may feel late. Try Wi-Fi closer to the router, or mobile data.');
254
267
  return pass(value);
255
268
  }
@@ -302,7 +315,7 @@ export async function runDoctor(config: DoctorConfig, owner: Scope, show: (row:
302
315
  let outcome: Outcome;
303
316
  // A check's own limit is inside it; this one is the guard for a check that forgot.
304
317
  try { outcome = await limited(scope, ms * 2, () => work[id]()); } catch (error) { outcome = fail(errorText(error), 'This check did not finish. Run the checks again.'); }
305
- const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started) };
318
+ const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started), ...outcome.failmode === undefined ? {} : { failmode: outcome.failmode } };
306
319
  if (scope.disposed) break;
307
320
  rows.push(row); show(row);
308
321
  }