@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
@@ -0,0 +1,116 @@
1
+ /**
2
+ * What a three.js scene says about a surface (meta SHARD-SOURCE AP10 to AP12, `@wildshard/format/scene-render`), drawn on
3
+ * the family's own material after it compiles (`registry.ts`):
4
+ *
5
+ * - **PBR** `blend: 'alpha'` and `opacity`: a see-through surface (a stencil, a sign), drawn after the opaque world with
6
+ * no depth write (three sorts it back to front); `depthOffset`: a polygon offset (a decal on a wall); `sway`: each vertex
7
+ * moves by its `wsSway` attribute (the GLB's `_SWAY` channel, metres) along the wind at about `rate` hertz, phased by
8
+ * where it stands; `uvScroll`: the colour map's uv moves on the look's clock.
9
+ * - **Emissive** `blend: 'alpha'`: an unlit card blended over what is behind it; `card`: every vertex is a camera-facing
10
+ * card corner, `position` its seat and `wsCorner` (the GLB's `_CORNER` channel) the corner's view-space offset;
11
+ * `motion`: the card's `pulse`, `drift` or `rise`, phased by its seat.
12
+ *
13
+ * A see-through surface is marked `userData.sceneAlpha`, so a prop's GLB (opaque by default) never turns it opaque
14
+ * (`declaredProps.ts`). Every number is a uniform; the program changes only with which of these a surface uses. The clock is the emissive
15
+ * look's (`famEmitTime`): with no emissive look the surface holds still.
16
+ */
17
+ import * as THREE from 'three';
18
+ import type { EmissiveMaterialParams, PbrMaterialParams } from '@wildshard/format/materialFamilies';
19
+ import { patchShader, PATCH_ORDER } from '../shaderPatches';
20
+
21
+ /** the attribute a swaying surface reads (GLTFLoader's `_sway`, renamed by its binding's channels) */
22
+ export const SWAY_ATTRIBUTE = 'wsSway';
23
+ /** the attribute a card reads (GLTFLoader's `_corner`) */
24
+ export const CORNER_ATTRIBUTE = 'wsCorner';
25
+
26
+ /** The vertex channels a surface reads, as `PropSurfaceBinding.channels`; null when it reads none. */
27
+ export function sceneSurfaceChannels(entry: unknown): Readonly<Record<string, { readonly attribute: string; readonly itemSize: number }>> | null {
28
+ if (typeof entry !== 'object' || entry === null) return null;
29
+ const row = entry as { readonly family?: unknown; readonly sway?: unknown; readonly card?: unknown };
30
+ if (row.family === 'pbr' && row.sway !== undefined) return { _sway: { attribute: SWAY_ATTRIBUTE, itemSize: 1 } };
31
+ if (row.family === 'emissive' && row.card === true) return { _corner: { attribute: CORNER_ATTRIBUTE, itemSize: 2 } };
32
+ return null;
33
+ }
34
+
35
+ const STILL: THREE.IUniform<number> = { value: 0 };
36
+
37
+ const SWAY_VERTEX = /* glsl */`
38
+ #include <begin_vertex>
39
+ {
40
+ mat4 wsSwayM = modelMatrix;
41
+ vec3 wsSwayAt = ( wsSwayM * vec4( transformed, 1.0 ) ).xyz;
42
+ float wsSwayPh = wsSceneTime * wsSwayWind.z * 6.2831853 + wsSwayAt.x * 0.37 + wsSwayAt.z * 0.29;
43
+ float wsSwayAmt = wsSway * ( 0.7 * sin( wsSwayPh ) + 0.3 * sin( wsSwayPh * 2.3 + 1.7 ) );
44
+ vec3 wsSwayDir = transpose( mat3( wsSwayM ) ) * vec3( wsSwayWind.x, 0.0, wsSwayWind.y );
45
+ transformed += wsSwayDir * wsSwayAmt;
46
+ }
47
+ `;
48
+
49
+ /** PBR: alpha, depth offset, sway and uv scroll (a no-op for a surface with none of them). */
50
+ export function applySceneSurface(m: THREE.MeshStandardMaterial, params: PbrMaterialParams, clock: THREE.IUniform<number> = STILL): void {
51
+ if (params.blend === 'alpha') { m.transparent = true; m.depthWrite = false; m.opacity = params.opacity ?? 1; m.userData['sceneAlpha'] = true; }
52
+ const offset = params.depthOffset ?? 0;
53
+ if (offset !== 0) { m.polygonOffset = true; m.polygonOffsetFactor = offset; m.polygonOffsetUnits = offset; }
54
+ const sway = params.sway, scroll = params.uvScroll;
55
+ if (sway === undefined && scroll === undefined) return;
56
+ const uniforms: Record<string, THREE.IUniform> = {
57
+ wsSceneTime: clock,
58
+ wsSwayWind: { value: new THREE.Vector3(sway?.direction[0] ?? 0, sway?.direction[1] ?? 0, sway?.rate ?? 0) },
59
+ wsUvScroll: { value: new THREE.Vector2(scroll?.[0] ?? 0, scroll?.[1] ?? 0) },
60
+ };
61
+ patchShader(m, 'engine.family.sceneSurface', PATCH_ORDER.material, (shader) => {
62
+ Object.assign(shader.uniforms, uniforms);
63
+ let vs = shader.vertexShader.replace('#include <common>', `#include <common>\nuniform float wsSceneTime;\nuniform vec3 wsSwayWind;\nuniform vec2 wsUvScroll;\n${sway === undefined ? '' : `attribute float ${SWAY_ATTRIBUTE};`}`);
64
+ if (sway !== undefined) vs = vs.replace('#include <begin_vertex>', SWAY_VERTEX);
65
+ if (scroll !== undefined) vs = vs.replace('#include <uv_vertex>', '#include <uv_vertex>\n#ifdef USE_MAP\n\tvMapUv += wsUvScroll * wsSceneTime;\n#endif');
66
+ shader.vertexShader = vs;
67
+ }, { key: (before) => `${before}|scene-surface|${sway === undefined ? '' : 's'}${scroll === undefined ? '' : 'u'}` });
68
+ }
69
+
70
+ const CARD_VERTEX = /* glsl */`
71
+ vec3 wsSeat = transformed;
72
+ float wsPh = fract( sin( dot( wsSeat, vec3( 127.1, 311.7, 74.7 ) ) ) * 43758.5453 );
73
+ vec2 wsC = ${CORNER_ATTRIBUTE};
74
+ float wsT = wsCardTime * wsCardMotion.y;
75
+ wsCardFade = 1.0;
76
+ if ( wsCardMotion.x > 0.5 && wsCardMotion.x < 1.5 ) {
77
+ float s = 0.6 * sin( wsT * 6.2831853 + wsPh * 6.2831853 ) + 0.4 * sin( wsT * 15.1 + wsPh * 12.0 );
78
+ wsC.y *= 1.0 + wsCardMotion.z * s;
79
+ wsC.x *= 1.0 - 0.5 * wsCardMotion.z * s;
80
+ } else if ( wsCardMotion.x > 1.5 && wsCardMotion.x < 2.5 ) {
81
+ wsSeat += vec3( sin( wsT + wsPh * 6.2831853 ), 0.42 * sin( wsT * 2.3 + wsPh * 12.5 ), cos( wsT * 0.83 + wsPh * 6.2831853 ) ) * wsCardMotion.z;
82
+ } else if ( wsCardMotion.x > 2.5 ) {
83
+ float k = fract( wsPh * 7.0 + wsT );
84
+ float a = wsPh * 40.0;
85
+ wsSeat += vec3( cos( a ) * wsCardMotion.w * k, wsCardMotion.z * k, sin( a ) * wsCardMotion.w * k );
86
+ wsCardFade = 1.0 - k;
87
+ wsC *= 1.0 - 0.5 * k;
88
+ }
89
+ vec4 mvPosition = modelViewMatrix * vec4( wsSeat, 1.0 );
90
+ mvPosition.xy += wsC;
91
+ gl_Position = projectionMatrix * mvPosition;
92
+ `;
93
+
94
+ const MOTION_KIND: Readonly<Record<string, number>> = { pulse: 1, drift: 2, rise: 3 };
95
+
96
+ /** Emissive: alpha blend, cards and their motion (a no-op for a plain surface). `clock` is the emissive look's. */
97
+ export function applySceneEmissive(m: THREE.MeshBasicMaterial, params: EmissiveMaterialParams, clock: THREE.IUniform<number>): void {
98
+ if (params.blend === 'alpha') { m.transparent = true; m.depthWrite = false; m.alphaTest = Math.max(m.alphaTest, 0.01); m.userData['sceneAlpha'] = true; }
99
+ if (params.card !== true) return;
100
+ const motion = params.motion;
101
+ const vector = new THREE.Vector4(motion === undefined ? 0 : MOTION_KIND[motion.kind] ?? 0, motion?.rate ?? 0,
102
+ motion === undefined ? 0 : motion.kind === 'pulse' ? motion.amount : motion.kind === 'drift' ? motion.radius : motion.height,
103
+ motion?.kind === 'rise' ? motion.spread : 0);
104
+ const uniforms: Record<string, THREE.IUniform> = { wsCardTime: clock, wsCardMotion: { value: vector } };
105
+ m.userData['sceneCard'] = true;
106
+ patchShader(m, 'engine.family.sceneCard', PATCH_ORDER.material, (shader) => {
107
+ Object.assign(shader.uniforms, uniforms);
108
+ if (!shader.vertexShader.includes('#include <project_vertex>')) throw new Error('scene card: the basic vertex source has no <project_vertex>');
109
+ shader.vertexShader = shader.vertexShader
110
+ .replace('#include <common>', `#include <common>\nuniform float wsCardTime;\nuniform vec4 wsCardMotion;\nattribute vec2 ${CORNER_ATTRIBUTE};\nvarying float wsCardFade;`)
111
+ .replace('#include <project_vertex>', CARD_VERTEX);
112
+ shader.fragmentShader = shader.fragmentShader
113
+ .replace('#include <common>', '#include <common>\nvarying float wsCardFade;')
114
+ .replace('#include <opaque_fragment>', 'outgoingLight *= wsCardFade;\ndiffuseColor.a *= wsCardFade;\n#include <opaque_fragment>');
115
+ }, { key: (before) => `${before}|scene-card` });
116
+ }
@@ -1,7 +1,7 @@
1
1
  import type { Camera, Color, DirectionalLight, Fog, Group, HemisphereLight, Material, Mesh, Object3D, Sprite, Texture, Vector3, PerspectiveCamera, Scene, WebGLRenderer, WebGLRenderTarget } from 'three';
2
2
  import type { BloomEffect, BrightnessContrastEffect, ChromaticAberrationEffect, Effect, EffectComposer, GodRaysEffect, HueSaturationEffect, LookupTexture, LUT3DEffect, NoiseEffect, Pass, ToneMappingEffect, VignetteEffect } from 'postprocessing';
3
3
  import type { N8AOPostPass } from 'n8ao';
4
- import type { LookKey } from './dataLook';
4
+ import type { LiveLook, LookKey } from './dataLook';
5
5
  import type { GradeEffect } from '../core/Grade';
6
6
  import type { DayCycleClock } from '../../../shared/engine/world/dayCycle';
7
7
  import type { SkyRig as Sky } from '../world/skyRig';
@@ -265,6 +265,12 @@ export interface ExtendLook extends LookParts {
265
265
  * hook); the next frame samples them. False: this look can't take them live (a fog kind change), so the page reloads.
266
266
  */
267
267
  liveKeys?: (keys: readonly LookKey[]) => boolean;
268
+ /**
269
+ * SHARD-SOURCE AP17: a data look's keys, sun arc, exposure, tone, vignette and bloom set in place (`wildshard watch`, engine's
270
+ * dev hook v2). False: this change can't go live (a light row, the LUT, a fog kind, an exposure on a chain built without
271
+ * one), so the page reloads.
272
+ */
273
+ liveLook?: (next: LiveLook) => boolean;
268
274
  compose: (c: LookComposeContext) => LookComposition;
269
275
  }
270
276
 
@@ -25,7 +25,7 @@ import { shadowDepthResolver, type ShadowDepthResolver } from './shadowDepthVari
25
25
  import { boundEntryWarmup } from './entryWarmupBound';
26
26
  import { workSlice } from '../../../shared/engine/core/workSlice';
27
27
  import { SHADOW_LAYER } from '../core/shadowLayer';
28
- import { buildHeld, heldBudget, nativeBudgetSpent, presenting } from '../../../shared/engine/core/framePacing';
28
+ import { buildHeld, buildUrgent, heldBudget, nativeBudgetSpent, presenting } from '../../../shared/engine/core/framePacing';
29
29
  import { countedWait, waitFor } from '../../../shared/engine/boot/waits';
30
30
  import { isDev } from '../core/devMode';
31
31
 
@@ -940,7 +940,9 @@ export const LIVE_HELD_PROGRAMS_PER_FRAME = 4;
940
940
  let warmUpHeld = false;
941
941
  /** Whether the traveller waits for a live warm-up (a grid cell's loading screen shows); the grid sets it, off by default. */
942
942
  export function setWarmUpHeld(held: boolean): void { warmUpHeld = held; }
943
- const programsPerFrame = (): number => (warmUpHeld ? LIVE_HELD_PROGRAMS_PER_FRAME : LIVE_PROGRAMS_PER_FRAME);
943
+ /** GC6: an entry warm-up on the road, for the cell the traveller heads into (`buildUrgent`), issues this many a frame. */
944
+ export const LIVE_URGENT_PROGRAMS_PER_FRAME = 2;
945
+ const programsPerFrame = (): number => (warmUpHeld ? LIVE_HELD_PROGRAMS_PER_FRAME : buildUrgent() ? LIVE_URGENT_PROGRAMS_PER_FRAME : LIVE_PROGRAMS_PER_FRAME);
944
946
  let parkedFrozen = false;
945
947
  /** G580 T2: whether a live warm-up freezes its parked (invisible) future root's matrices (`freezeParkedMatrices`); the grid
946
948
  * sets it, off by default. */
@@ -7,6 +7,9 @@ export const TIER_TABLE = {
7
7
  // PF3: the cascades redraw on every Nth drawn frame (skyRig.ts); a held map keeps the matrix it was drawn with, so a
8
8
  // static shadow stays exactly where it was and only a moving caster's shadow steps. 1 = every frame (a level's row may raise it)
9
9
  shadowEvery: 1,
10
+ // NB5: the cascades' staggered cadence (shadowCadence.ts) on every shard, not only a `texelBias: 'phone'` rig (skyRig.ts);
11
+ // the phone keeps its own rule, the desktop takes it (its three cascades were redrawn every frame)
12
+ cascadeStagger: false,
10
13
  // animals shadow as far as the cascade reaches (E90: at 30 m an animal's shadow switched on in plain view)
11
14
  animalShadowDist: 80, animalHideDist: 150, furShells: false,
12
15
  // animal draws (Animal.setDrawLod): fur / hard / eye within animalEyeDist, eyes in the hard material to animalOneDrawDist,
@@ -49,7 +52,7 @@ export const TIER_TABLE = {
49
52
  },
50
53
  desktop: {
51
54
  maxTexture: 4096, layerSize: 1024, dpr: 1.5, ao: true,
52
- cascades: 3, shadowMapSize: 2048, shadowFar: 220, shadowMargin: 120, softShadows: true, shadowEvery: 1,
55
+ cascades: 3, shadowMapSize: 2048, shadowFar: 220, shadowMargin: 120, softShadows: true, shadowEvery: 1, cascadeStagger: true,
53
56
  animalShadowDist: 90, animalHideDist: 400, furShells: true,
54
57
  // PH-P2: an eye is under a pixel past ~20 m at 1600×900 and a hoof tip past ~60 m, so the
55
58
  // phone's draw LOD at 1.3–1.5× its distances. ~150 animals × 3 draws were half of the desktop frame;
@@ -189,12 +189,16 @@ export async function installDeclaredProps(props: DeclaredProps, ports: {
189
189
  // TEMPLATE-E2E LF1-2: an unlit (emissive) surface is its declared colour × intensity, so it takes the mesh's
190
190
  // vertex colours only when it declares them: a lamp baked grey beside measure stone still glows its own amber
191
191
  const unlit = base instanceof MeshBasicMaterial;
192
+ const seeThrough = base.userData['sceneAlpha'] === true;
192
193
  const m = acquireVariant(base, { colour: glb?.color ?? null, roughness: standard?.roughness ?? null, metalness: standard?.metalness ?? null, map: undefined, vertexColours: unlit ? base.vertexColors && vertexColours : vertexColours, flat,
193
- side: source?.side ?? base.side, transparent: source?.transparent ?? base.transparent, opacity: source?.opacity ?? base.opacity,
194
+ // SHARD-SOURCE AP10: a see-through family entry (`blend: 'alpha'`, an alpha card) stays see-through whatever the GLB says
195
+ side: source?.side ?? base.side, transparent: seeThrough || (source?.transparent ?? base.transparent), opacity: seeThrough ? base.opacity : source?.opacity ?? base.opacity,
194
196
  named: { maps: binding.maps, emissive: glb?.emissive ?? null } });
195
197
  source?.dispose(); held.push(m); bases.set(m, base); return m;
196
198
  };
197
199
  o.material = Array.isArray(o.material) ? original.map(convert) : convert(original[0]);
200
+ // SHARD-SOURCE AP11: a card's corners and rise live in the shader, past the seats its bounds hold: never culled
201
+ if ((Array.isArray(o.material) ? o.material : [o.material]).some((m) => m.userData['sceneCard'] === true)) o.frustumCulled = false;
198
202
  o.castShadow = o.userData['castShadow'] !== false; o.receiveShadow = o.userData['receiveShadow'] !== false;
199
203
  });
200
204
  if (disposed) { releaseAll(); throw new Error('Props level unloaded while parsing'); }
@@ -152,7 +152,10 @@ export class SkyRig {
152
152
  // a low sun (golden hour, dawn) grazes flat decks: a shadow style may take more normal bias, or the planks speckle with acne
153
153
  for (const l of this.csm.lights) { l.color.copy(this.sunColor); l.shadow.normalBias = shadows?.normalBias ?? 0.05; l.shadow.radius = shadows?.radius ?? 2; }
154
154
  this.texelBias = shadows?.texelBias === 'phone' && rig.phone;
155
- this.farEveryOther = this.texelBias && this.csm.lights.length > 1;
155
+ // NB5 (QA-FEEDBACK-2026-11-14 rows 2, 3, 5): the desktop's three 2048² cascades take the phone's staggered cadence too
156
+ // (BA-3's A / B, shadowCadence.ts): near every frame, middle every 2nd, far every 4th. Desktop frames run at 60-120, so a
157
+ // far moving caster steps at 15-30 Hz; the shadow pass was ~110 of Driftwood's ~320 draws a frame
158
+ this.farEveryOther = (this.texelBias || TIER_CONFIG.cascadeStagger) && this.csm.lights.length > 1;
156
159
  // E174: the phone rig's shadow maps are depth only at 16 bits (Jake's pick C; shadowVariants.ts): 40 MB, not three's 160
157
160
  if (shadows?.depth16 === 'phone' && rig.phone) {
158
161
  const maps = new ShadowMaps(this.renderer, this.csm, this.shadowFade?.ghosts ?? [], rig.size);
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import { BufferAttribute, BufferGeometry, Mesh, type Material, type Object3D } from 'three';
18
18
  import type { Scope } from '../../../shared/engine/app/scope';
19
- import { gpuOnlyTrees } from '../core/gpuOnly';
19
+ import { gpuOnlyTrees, refillGpuOnly } from '../core/gpuOnly';
20
20
  import { decodeTerrainTile, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
21
21
  import { keepShadowWhole } from './shadowChunks';
22
22
 
@@ -25,9 +25,12 @@ const COARSE = { resolution: 17, size: 125, half: 8 } as const;
25
25
 
26
26
  interface TileState { readonly indices: BufferAttribute; readonly resolution: number }
27
27
  const coarseTiles = new WeakMap<Mesh, TileState>();
28
+ /** Where each installed tile sits on the ground, for `refreshTerrainTile`. */
29
+ const shapes = new WeakMap<Mesh, Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size'>>();
28
30
 
29
31
  /** True when this tile is a coarse tile whose quadrants refinement may hide. */
30
- function isCoarse(data: TerrainTileData): boolean { return data.resolution === COARSE.resolution && data.size === COARSE.size; }
32
+ /** a coarse (L1) terrain tile: no skirt, its quadrants masked under fine tiles */
33
+ export function isCoarse(data: TerrainTileData): boolean { return data.resolution === COARSE.resolution && data.size === COARSE.size; }
31
34
 
32
35
  /** A grid's slope along one axis at sample `at` of `n`: central inside, second-order one-sided on the grid's edge. Sample
33
36
  * `i` of the line is `heights[base + i * stride]` (no closure per vertex: a tile's normals run once per sample at boot). */
@@ -98,29 +101,17 @@ function perimeter(r: number): number[] {
98
101
  */
99
102
  export function installTerrainTile(bytes: Uint8Array | TerrainTileData, ports: { root: Object3D; scope: Scope; material: Material; shadow: boolean; lattice?: TerrainTileData }): Mesh {
100
103
  if (ports.scope.disposed) throw new Error('terrain tile: its scope is already disposed');
101
- const data = bytes instanceof Uint8Array ? decodeTerrainTile(bytes) : bytes, r = data.resolution, colours = data.colours;
102
- if (colours === undefined) throw new Error('terrain tile: a render tile needs vertex colours (a heights-only payload is a collider)');
103
- const coarse = isCoarse(data), ring = coarse ? [] : perimeter(r), grid = r * r, vertices = grid + ring.length;
104
- const gridIndices = (r - 1) ** 2 * 6, total = gridIndices + ring.length * 6;
105
- // a coarse tile has no skirt, so it draws the decoded colours as they are; a skirted tile extends a copy
106
- const positions = new Float32Array(vertices * 3), normals = new Float32Array(vertices * 3), colour = coarse ? colours : new Float32Array(vertices * 3);
107
- const indices = vertices > 65535 ? new Uint32Array(total) : new Uint16Array(total), cell = data.size / (r - 1);
108
- for (let z = 0; z < r; z++) for (let x = 0; x < r; x++) {
109
- const vertex = z * r + x, at = vertex * 3;
110
- positions[at] = x * cell; positions[at + 1] = data.heights[vertex] ?? 0; positions[at + 2] = z * cell;
104
+ const data = bytes instanceof Uint8Array ? decodeTerrainTile(bytes) : bytes, r = data.resolution, coarse = isCoarse(data);
105
+ const { positions, normals, colour, vertices } = tileVertices(data, ports.lattice);
106
+ const ring = coarse ? 0 : vertices - r * r, gridIndices = (r - 1) ** 2 * 6, total = gridIndices + ring * 6;
107
+ const indices = vertices > 65535 ? new Uint32Array(total) : new Uint16Array(total);
108
+ for (let z = 0; z < r - 1; z++) for (let x = 0; x < r - 1; x++) {
111
109
  // Rapier's split: the triangles (x, z) (x, z+1) (x+1, z) and (x+1, z) (x, z+1) (x+1, z+1), diagonal (x+1, z)–(x, z+1).
112
- if (x < r - 1 && z < r - 1) indices.set([vertex, vertex + r, vertex + 1, vertex + 1, vertex + r, vertex + r + 1], (z * (r - 1) + x) * 6);
110
+ const vertex = z * r + x;
111
+ indices.set([vertex, vertex + r, vertex + 1, vertex + 1, vertex + r, vertex + r + 1], (z * (r - 1) + x) * 6);
113
112
  }
114
- if (!coarse) colour.set(colours);
115
- if (ports.lattice === undefined || !latticeNormals(data, ports.lattice, normals)) gridNormals(data, normals);
116
- const depth = data.size / 16;
117
- ring.forEach((border, i) => {
118
- const skirt = grid + i, next = (i + 1) % ring.length, from = border * 3, to = skirt * 3;
119
- positions[to] = positions[from] ?? 0; positions[to + 1] = (positions[from + 1] ?? 0) - depth; positions[to + 2] = positions[from + 2] ?? 0;
120
- for (let c = 0; c < 3; c++) { normals[to + c] = normals[from + c] ?? 0; colour[to + c] = colour[from + c] ?? 0; }
121
- const b = ring[next] ?? border;
122
- indices.set([border, b, skirt, b, grid + next, skirt], gridIndices + i * 6);
123
- });
113
+ const edge = coarse ? [] : perimeter(r), grid = r * r;
114
+ edge.forEach((border, i) => { const next = (i + 1) % edge.length, b = edge[next] ?? border; indices.set([border, b, grid + i, b, grid + next, grid + i], gridIndices + i * 6); });
124
115
  const geometry = ports.scope.own(new BufferGeometry());
125
116
  geometry.setAttribute('position', new BufferAttribute(positions, 3));
126
117
  geometry.setAttribute('normal', new BufferAttribute(normals, 3));
@@ -135,10 +126,60 @@ export function installTerrainTile(bytes: Uint8Array | TerrainTileData, ports: {
135
126
  // a tile is already one shadow-culling piece, and the caller's shadow disc switches its castShadow: never split it (SF16)
136
127
  keepShadowWhole(mesh);
137
128
  if (coarse) coarseTiles.set(mesh, { indices: index, resolution: r });
129
+ shapes.set(mesh, { resolution: r, x: data.x, z: data.z, size: data.size });
138
130
  ports.root.add(mesh); ports.scope.onDispose(() => { mesh.removeFromParent(); coarseTiles.delete(mesh); });
139
131
  return mesh;
140
132
  }
141
133
 
134
+ /** A tile's vertex arrays, its skirt ring after the grid on a fine tile: what `installTerrainTile` uploads. */
135
+ function tileVertices(data: TerrainTileData, lattice: TerrainTileData | undefined): { positions: Float32Array; normals: Float32Array; colour: Float32Array; vertices: number } {
136
+ const r = data.resolution, colours = data.colours;
137
+ if (colours === undefined) throw new Error('terrain tile: a render tile needs vertex colours (a heights-only payload is a collider)');
138
+ const coarse = isCoarse(data), ring = coarse ? [] : perimeter(r), grid = r * r, vertices = grid + ring.length;
139
+ // a coarse tile has no skirt, so it draws the decoded colours as they are; a skirted tile extends a copy
140
+ const positions = new Float32Array(vertices * 3), normals = new Float32Array(vertices * 3), colour = coarse ? colours : new Float32Array(vertices * 3);
141
+ const cell = data.size / (r - 1);
142
+ for (let z = 0; z < r; z++) for (let x = 0; x < r; x++) {
143
+ const at = (z * r + x) * 3;
144
+ positions[at] = x * cell; positions[at + 1] = data.heights[z * r + x] ?? 0; positions[at + 2] = z * cell;
145
+ }
146
+ if (!coarse) colour.set(colours);
147
+ if (lattice === undefined || !latticeNormals(data, lattice, normals)) gridNormals(data, normals);
148
+ const depth = data.size / 16;
149
+ ring.forEach((border, i) => {
150
+ const from = border * 3, to = (grid + i) * 3;
151
+ positions[to] = positions[from] ?? 0; positions[to + 1] = (positions[from + 1] ?? 0) - depth; positions[to + 2] = positions[from + 2] ?? 0;
152
+ for (let c = 0; c < 3; c++) { normals[to + c] = normals[from + c] ?? 0; colour[to + c] = colour[from + c] ?? 0; }
153
+ });
154
+ return { positions, normals, colour, vertices };
155
+ }
156
+
157
+ /**
158
+ * SHARD-SOURCE AP18 (dev only: `wildshard watch`'s ground swap). Cut this installed tile again from a new whole-ground
159
+ * lattice (heights and colours, the 257² the tiles were baked from) and rewrite its vertices in their buffers: the same
160
+ * vertices `installTerrainTile` makes from a tile the bake cut from that lattice. False, and nothing written, when the tile
161
+ * is not one of this module's or its vertices are not the lattice's samples.
162
+ */
163
+ export function refreshTerrainTile(mesh: Mesh, lattice: TerrainTileData): boolean {
164
+ const shape = shapes.get(mesh), colours = lattice.colours;
165
+ if (shape === undefined || colours === undefined) return false;
166
+ const r = shape.resolution, n = lattice.resolution, step = lattice.size / (n - 1), cell = shape.size / (r - 1);
167
+ const heights = new Float32Array(r * r), colour = new Float32Array(r * r * 3);
168
+ for (let z = 0; z < r; z++) for (let x = 0; x < r; x++) {
169
+ const lx = latticeIndex(shape.x + x * cell, lattice.x, step, n), lz = latticeIndex(shape.z + z * cell, lattice.z, step, n);
170
+ if (lx < 0 || lz < 0) return false;
171
+ const at = lz * n + lx, i = z * r + x;
172
+ heights[i] = lattice.heights[at] ?? 0; colour.set(colours.subarray(at * 3, at * 3 + 3), i * 3);
173
+ }
174
+ const fresh = tileVertices({ ...shape, heights, colours: colour }, lattice);
175
+ const geometry = mesh.geometry, position = geometry.getAttribute('position'), normal = geometry.getAttribute('normal'), tint = geometry.getAttribute('color');
176
+ if (!(position instanceof BufferAttribute) || !(normal instanceof BufferAttribute) || !(tint instanceof BufferAttribute) || position.count !== fresh.vertices) return false;
177
+ position.array.set(fresh.positions); position.needsUpdate = true;
178
+ refillGpuOnly(normal, fresh.normals); refillGpuOnly(tint, fresh.colour);
179
+ geometry.computeBoundingBox(); geometry.computeBoundingSphere();
180
+ return true;
181
+ }
182
+
142
183
  /**
143
184
  * Hide a coarse tile's quadrants (0 = −x −z, 1 = +x −z, 2 = −x +z, 3 = +x +z) in place while fine tiles cover them.
144
185
  * The tile's one index buffer is rewritten and its draw range shortened, so no allocation, no extra draw and no
@@ -7,28 +7,56 @@ import { lampLights } from '@wildshard/engine/render/lookLight';
7
7
  import type { LookLamp } from '@wildshard/format/look-light';
8
8
  import type { ShardWater } from '@wildshard/format/water';
9
9
  import { installClientWater } from '../shardfile/clientWater';
10
- import { isDevColliders, swapDevBoxes, type DevBox } from '@wildshard/engine/game/devColliders';
10
+ import { shardfileLiveLook } from './liveLook';
11
+ import type { Shardfile } from '@wildshard/format/shardSchema';
12
+ import { devGroundHeight, isDevColliders, liftedFeet, swapDevBoxes, type DevBox, type DevGround } from '@wildshard/engine/game/devColliders';
13
+ import { swapTerrainCollider } from '@wildshard/engine/physics/terrainTiles';
14
+ import type { HeightfieldBinding } from '@wildshard/engine/world/Heightfield';
15
+ import { decodeTerrainTile, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
16
+ import { refreshTerrainTile } from '@wildshard/engine/world/terrainTileView';
17
+ import type { DevGameplay, DevPlace, DevRestarted } from '@wildshard/engine/game/devGameplay';
18
+ import { diagnosticNow } from '@wildshard/engine/core/clock';
11
19
 
12
20
  /**
13
21
  * SHARD-SOURCE AP5 (J347: engine is the deployed client and server; dev tooling is sharddev's). The dev hook: the one thing
14
22
  * a DEVSERVER page carries for `wildshard watch`. sharddev owns the rest, its WebSocket server and protocol, the part diff
15
23
  * and a page script `watch` injects into the page it serves; that script owns one scope per part and the swap order, and
16
- * calls these five functions on `window.__wildshardDevHook`:
24
+ * calls these functions on `window.__wildshardDevHook`:
17
25
  *
18
26
  * addPart(name, part) draw a new part: meshes, sprites, lamps (the look's lamp lights) and water (the client's water)
19
27
  * replacePart(name, part) build the new part first, then dispose the old part's scope, in one call: no frame shows neither
20
28
  * removePart(name) dispose the part's scope (its boxes stay: the page script calls swapColliders(name, []))
21
- * setLook(look) the data look's day keys (sky, fog, sun, ambient) in place: true, or false when the page's look
22
- * can't take them live and the page must reload
29
+ * setLook(look) v2 (AP17): the look section in place, as the shardfile would carry it: day keys (sky, fog, sun,
30
+ * ambient), the sun's arc, exposure, tone, vignette and bloom (`shardfileLiveLook`); v1 sent
31
+ * the keys only. True, or false when the page's look can't take it live and the page must reload
23
32
  * swapColliders(name, boxes) the part's solid boxes, in the page's world and the in-page server's (the worker, by its
24
- * harness port), new set first, then the old one goes
33
+ * harness port), new set first, then the old one goes; a player inside a new box is lifted
34
+ * onto it (v3)
35
+ * setGround(bytes) v3 (AP18): the whole ground as one terrain tile's wire bytes (`encodeTerrainTile`: the 257²
36
+ * heights and colours the shard's tiles and collider are cut from). The page's heightfield
37
+ * collider, its terrain field (`heightAt`) and every drawn ground tile whose samples changed are
38
+ * swapped; the in-page server takes the same heights; a player under the new ground is lifted
39
+ * onto it. True, or false when the page's ground can't take it (the page must reload)
40
+ * restartGameplay(gameplay) v4 (AP19): the shard's quests, encounters, spawns or scripts changed (`DEV_GAMEPLAY_SECTIONS`,
41
+ * the new rows of each). The in-page server saves, puts its world down and boots it again on
42
+ * the new rows from that save, with the player where the page has it; the page's client rejoins
43
+ * it, the held boxes and ground go to it again, and the quest views are built again from the new
44
+ * quest section. Resolves to what ran, or `ok: false` when the page must reload
25
45
  *
26
46
  * `version` is `DEV_HOOK_VERSION`; sharddev refuses a page with another (its page script) and a client whose build flags
27
47
  * say another (`build-flags.json` `devHook`, written by `scripts/app-build-pipeline.mjs`). Bump it on any change to these
28
48
  * signatures or to `DevPart`. A production build has none of this: `finish.ts` imports it only behind `__DEVSERVER__`, and
29
49
  * `scripts/check-devserver.mjs` refuses a bundle that holds `DEV_HOOK_GLOBAL`.
30
50
  */
31
- export const DEV_HOOK_VERSION = 1;
51
+ export const DEV_HOOK_VERSION = 4;
52
+
53
+ // the in-page server's half of `setGround`, which the standalone shell puts on the window (client/host/standalone/shell.ts)
54
+ declare global { interface Window {
55
+ __workerClientDevGround?: (ground: DevGround) => void;
56
+ /** AP19: the in-page server's soft restart (client/host/standalone/shell.ts) and the quest views' (shardfile/client.ts) */
57
+ __workerClientDevRestart?: (gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>;
58
+ __shardfileDevQuests?: (quests: NonNullable<DevGameplay['quests']>) => Promise<boolean>;
59
+ } }
32
60
  export const DEV_HOOK_GLOBAL = '__wildshardDevHook';
33
61
 
34
62
  export type Rgb = readonly [number, number, number];
@@ -94,8 +122,8 @@ export interface DevPart {
94
122
  readonly water: ShardWater;
95
123
  }
96
124
 
97
- /** The part of a shardfile look a watched page takes live. */
98
- export interface DevLook { readonly keys: readonly LookKey[] }
125
+ /** The look a watched page takes live: its day keys, and (v2, AP17) the whole look section the page's shardfile would carry. */
126
+ export interface DevLook { readonly keys: readonly LookKey[]; readonly look?: Shardfile['look'] }
99
127
 
100
128
  export interface DevHook {
101
129
  readonly version: number;
@@ -104,8 +132,16 @@ export interface DevHook {
104
132
  removePart: (name: string) => void;
105
133
  setLook: (look: DevLook) => boolean;
106
134
  swapColliders: (name: string, boxes: readonly DevBox[]) => void;
135
+ setGround: (ground: Uint8Array) => boolean;
136
+ restartGameplay: (gameplay: DevGameplay) => Promise<DevRestart>;
107
137
  }
108
138
 
139
+ /** What a soft restart did: the server's world restart and the page's quest views, and how long each took (ms). */
140
+ export interface DevRestart { readonly ok: boolean; readonly serverMs: number; readonly questsMs: number | null; readonly reason?: string }
141
+
142
+ /** The page's player, as a dev swap lifts it out of new solids. */
143
+ export interface DevPlayer { readonly position: { readonly x: number; readonly y: number; readonly z: number }; readonly yaw: number; pitch: number; spawn: (x: number, z: number, yaw: number, y?: number) => void }
144
+
109
145
  export interface DevHookPorts {
110
146
  readonly scope: Scope;
111
147
  readonly scene: THREE.Object3D;
@@ -116,6 +152,16 @@ export interface DevHookPorts {
116
152
  readonly look: () => LookStrategy | null;
117
153
  /** the in-page server's half of `swapColliders` (the worker page's harness port); null when the page has none */
118
154
  readonly server: () => ((name: string, boxes: readonly DevBox[]) => void) | null;
155
+ /** the in-page server's half of `setGround` (v3); null when the page has none */
156
+ readonly serverGround?: () => ((ground: DevGround) => void) | null;
157
+ /** the page's player now, for the lift out of new solids (v3); null on a page without one */
158
+ readonly player?: () => DevPlayer | null;
159
+ /** the page's terrain field now (`captureHeightfield`), which a new ground installs into (v3); absent in a test */
160
+ readonly terrainField?: () => HeightfieldBinding;
161
+ /** the in-page server's soft restart (v4); null when the page has none */
162
+ readonly restart?: () => ((gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>) | null;
163
+ /** the page's quest views, built again from a new quest section (v4); null when the page can't */
164
+ readonly quests?: () => ((quests: NonNullable<DevGameplay['quests']>) => Promise<boolean>) | null;
119
165
  readonly watchFrames: (fn: (dt: number) => void) => () => void;
120
166
  }
121
167
 
@@ -222,8 +268,20 @@ export function createDevHook(ports: DevHookPorts): DevHook & { readonly root: T
222
268
  }
223
269
  const setLook = (look: DevLook): boolean => {
224
270
  const current = ports.look();
225
- return current !== null && 'liveKeys' in current && current.liveKeys !== undefined && current.liveKeys(look.keys);
271
+ if (current === null || !('liveKeys' in current)) return false;
272
+ if (look.look !== undefined) return current.liveLook !== undefined && current.liveLook(shardfileLiveLook(look.look));
273
+ return current.liveKeys !== undefined && current.liveKeys(look.keys);
274
+ };
275
+ /** A player now inside new solids stands on them (the server lifts its own: `swapDevGround`). */
276
+ const lift = (heightAt: ((x: number, z: number) => number) | null, boxes: readonly DevBox[]): void => {
277
+ const player = ports.player?.() ?? null;
278
+ if (player === null) return;
279
+ const { x, y, z } = player.position, feet = liftedFeet(x, y, z, heightAt, boxes);
280
+ if (feet === null) return;
281
+ const pitch = player.pitch;
282
+ player.spawn(x, z, player.yaw, feet); player.pitch = pitch;
226
283
  };
284
+
227
285
  // The boxes go into the page's world as it is now. After a grid crossing that is a new world: every held part's boxes
228
286
  // are made again in it, and the old world's sets are disposed (Physics skips removal from a freed world).
229
287
  const swapColliders = (name: string, boxes: readonly DevBox[]): void => {
@@ -239,19 +297,98 @@ export function createDevHook(ports: DevHookPorts): DevHook & { readonly root: T
239
297
  }
240
298
  if (physics !== null) swapDevBoxes(physics, scope, colliders, name, boxes);
241
299
  ports.server()?.(name, boxes);
300
+ lift(null, boxes);
301
+ };
302
+ // AP18: each drawn ground tile keeps a signature of the lattice samples it was last cut from; a swap cuts again only the
303
+ // tiles whose samples changed, and a tile the page streams in later (cut from the boot's bytes) is cut on the next frame.
304
+ let ground: TerrainTileData | null = null, groundScope: Scope | null = null, sweep = 0;
305
+ const cut = new WeakMap<THREE.Mesh, number>();
306
+ const tiles = (): THREE.Mesh[] => {
307
+ const out: THREE.Mesh[] = [];
308
+ ports.scene.traverse(object => { if (object instanceof THREE.Mesh && object.name.startsWith('terrain:')) out.push(object as THREE.Mesh); });
309
+ return out;
310
+ };
311
+ /** Cut every tile whose samples differ from the ones it holds; false when one can't be cut from this lattice. */
312
+ const recut = (lattice: TerrainTileData): boolean => {
313
+ let ok = true;
314
+ for (const mesh of tiles()) {
315
+ const signature = tileSignature(mesh, lattice);
316
+ if (signature === null) { ok = false; continue; }
317
+ if (cut.get(mesh) === signature) continue;
318
+ if (refreshTerrainTile(mesh, lattice)) cut.set(mesh, signature); else ok = false;
319
+ }
320
+ return ok;
321
+ };
322
+ const setGround = (bytes: Uint8Array): boolean => {
323
+ let lattice: TerrainTileData;
324
+ try { lattice = decodeTerrainTile(bytes); } catch { return false; }
325
+ if (lattice.colours === undefined) return false;
326
+ const heights: DevGround = { resolution: lattice.resolution, x: lattice.x, z: lattice.z, size: lattice.size, heights: lattice.heights };
327
+ if (!recut(lattice)) return false;
328
+ const physics = ports.physics(), next = scope.child('devGround');
329
+ if (physics !== null) swapTerrainCollider(physics, heights, next);
330
+ groundScope?.dispose(); groundScope = next;
331
+ const heightAt = devGroundHeight(heights), field = ports.terrainField?.();
332
+ const normalAt = (x: number, z: number, eps = 0.25): [number, number, number] => {
333
+ const dx = heightAt(x - eps, z) - heightAt(x + eps, z), dz = heightAt(x, z - eps) - heightAt(x, z + eps), length = Math.hypot(dx, 2 * eps, dz);
334
+ return [dx / length, 2 * eps / length, dz / length];
335
+ };
336
+ field?.install({ heightAt, normalAt, splatAt: field.field.splatAt });
337
+ ports.serverGround?.()?.(heights);
338
+ ground = lattice;
339
+ lift(heightAt, []);
340
+ return true;
341
+ };
342
+ // AP19: the server's world restarts on the new rows and the quest views are built again, side by side; then the new world
343
+ // takes the boxes and ground watch had swapped into the old one.
344
+ const restartGameplay = async (gameplay: DevGameplay): Promise<DevRestart> => {
345
+ const server = ports.restart?.() ?? null, views = gameplay.quests === undefined ? null : ports.quests?.() ?? null;
346
+ if (server === null) return { ok: false, serverMs: 0, questsMs: null, reason: 'the page has no in-page server' };
347
+ if (gameplay.quests !== undefined && views === null) return { ok: false, serverMs: 0, questsMs: null, reason: 'the page can\'t rebuild its quest views' };
348
+ const player = ports.player?.() ?? null, at = player === null ? null : { x: player.position.x, y: player.position.y, z: player.position.z, yaw: player.yaw };
349
+ const started = diagnosticNow();
350
+ const quests = views === null || gameplay.quests === undefined ? Promise.resolve(null) : views(gameplay.quests).then(ok => ok ? diagnosticNow() - started : -1);
351
+ const [restarted, questsMs] = await Promise.all([server(gameplay, at), quests]);
352
+ if (restarted.ok) {
353
+ for (const [name, boxes] of boxesOf) ports.server()?.(name, boxes);
354
+ if (ground !== null) ports.serverGround?.()?.({ resolution: ground.resolution, x: ground.x, z: ground.z, size: ground.size, heights: ground.heights });
355
+ }
356
+ const ok = restarted.ok && questsMs !== -1;
357
+ return { ok, serverMs: restarted.ms, questsMs: questsMs === null || questsMs < 0 ? null : Math.round(questsMs),
358
+ ...(restarted.reason !== undefined ? { reason: restarted.reason } : questsMs === -1 ? { reason: 'the quest views refused the new quests' } : {}) };
242
359
  };
360
+ scope.onDispose(ports.watchFrames(() => { if (ground !== null && ++sweep % 15 === 0) recut(ground); }));
243
361
  scope.onDispose(() => { for (const held of colliders.values()) held.dispose(); colliders.clear(); });
244
- return { version: DEV_HOOK_VERSION, root, addPart, replacePart, removePart, setLook, swapColliders,
362
+ return { version: DEV_HOOK_VERSION, root, addPart, replacePart, removePart, setLook, swapColliders, setGround, restartGameplay,
245
363
  held: () => ({ geometries: geometries.size, textures: textures.size }) };
246
364
  }
247
365
 
248
366
  /** Put the hook on the window for sharddev's page script, for the page's level. */
249
367
  export function installDevHook(ports: DevHookPorts): DevHook {
250
- const hook = createDevHook(ports), { version, addPart, replacePart, removePart, setLook, swapColliders } = hook;
251
- ports.scope.expose(window, DEV_HOOK_GLOBAL, Object.freeze({ version, addPart, replacePart, removePart, setLook, swapColliders } satisfies DevHook));
368
+ const hook = createDevHook(ports), { version, addPart, replacePart, removePart, setLook, swapColliders, setGround, restartGameplay } = hook;
369
+ ports.scope.expose(window, DEV_HOOK_GLOBAL, Object.freeze({ version, addPart, replacePart, removePart, setLook, swapColliders, setGround, restartGameplay } satisfies DevHook));
252
370
  return hook;
253
371
  }
254
372
 
373
+ /** A tile's lattice window (heights and colours), as one number: the samples a tile at its place and size is cut from. Null
374
+ * when the tile's corners are off the lattice. */
375
+ function tileSignature(mesh: THREE.Mesh, lattice: TerrainTileData): number | null {
376
+ const box = mesh.geometry.boundingBox, colours = lattice.colours;
377
+ if (box === null || colours === undefined) return null;
378
+ const n = lattice.resolution, step = lattice.size / (n - 1), size = box.max.x - box.min.x;
379
+ const x0 = Math.round((mesh.position.x - lattice.x) / step), z0 = Math.round((mesh.position.z - lattice.z) / step), span = Math.round(size / step);
380
+ // one sample more on each side: a tile's normals read its neighbours' heights
381
+ if (x0 < 0 || z0 < 0 || x0 + span >= n || z0 + span >= n) return null;
382
+ let hash = 2166136261;
383
+ const bits = new Uint32Array(1), float = new Float32Array(bits.buffer);
384
+ const mix = (value: number): void => { float[0] = value; hash = Math.imul(hash ^ (bits[0] ?? 0), 16777619); };
385
+ for (let z = Math.max(0, z0 - 1); z <= Math.min(n - 1, z0 + span + 1); z++) for (let x = Math.max(0, x0 - 1); x <= Math.min(n - 1, x0 + span + 1); x++) {
386
+ const at = z * n + x;
387
+ mix(lattice.heights[at] ?? 0); mix(colours[at * 3] ?? 0); mix(colours[at * 3 + 1] ?? 0); mix(colours[at * 3 + 2] ?? 0);
388
+ }
389
+ return hash >>> 0;
390
+ }
391
+
255
392
  function makeMaterial(row: DevMaterial, shared: THREE.DataTexture | null, owned: { dispose: () => void }[]): THREE.Material {
256
393
  let map: THREE.Texture | null = null;
257
394
  if (shared !== null) {
@@ -0,0 +1,21 @@
1
+ import { DATA_LOOK_DAY, type LiveLook } from '@wildshard/engine/render/dataLook';
2
+ import { lookLightManifest } from '@wildshard/engine/render/lookLight';
3
+ import { lookLightOn } from '@wildshard/engine/ui/lookLightOption';
4
+ import { TIER } from '@wildshard/engine/core/tier';
5
+ import type { Shardfile } from '@wildshard/format/shardSchema';
6
+ import { shardfileFileUrl } from '../shardfile/look';
7
+
8
+ /**
9
+ * SHARD-SOURCE AP17: a shardfile's look section as `shardfileLook` (`../shardfile/look.ts`) builds its data look, plus the
10
+ * engine bloom the level grade takes from it (`plugin/context.ts`), for the dev hook's `setLook`: a watched page's look set
11
+ * live from the same data a fresh shell would boot from. Kept beside the hook, not in `shardfile/`, so a dev-only change never
12
+ * moves the shardfile validation revision; `liveLook.test.ts` holds the two in step.
13
+ */
14
+ export function shardfileLiveLook(look: Shardfile['look'], light: boolean = lookLightOn()): LiveLook {
15
+ const resolved = lookLightManifest(look, light, TIER);
16
+ return { day: look.day ?? DATA_LOOK_DAY, dayOverride: look.dayOverride, keys: look.keys, lut: look.grade.lut === null ? null : shardfileFileUrl(look.grade.lut),
17
+ neutral: look.grade.tone === 'neutral', aces: look.grade.tone === 'aces', exposure: look.grade.exposure, vignette: look.grade.vignette ?? null, bloomRadius: resolved.bloom.radius,
18
+ bloom: resolved.bloom,
19
+ light: { rim: resolved.rim, pools: resolved.pools, heightFogDensity: resolved.atmosphere.fogHeightDensity, lamps: resolved.lamps, bounce: resolved.bounce, environment: resolved.environment,
20
+ shadow: resolved.shadow, motes: resolved.motes } };
21
+ }