@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
@@ -20,15 +20,18 @@ import type { HeadlessRuntimeInput } from '../headlessRuntime';
20
20
  import { StandaloneGrid } from './gridServer';
21
21
  import { isHarnessFlag, isHarnessGod, isHarnessHits, isHarnessJoin, isHarnessMove, isHarnessPlace } from '../../../shared/host/standalone/harnessPlace';
22
22
  import { WorkerLoopback } from '../../../shared/host/standalone/workerLoopback';
23
- import { isDevColliders, swapDevBoxes } from '@wildshard/engine/game/devColliders';
23
+ import { isDevColliders, isDevGround, swapDevBoxes, swapDevGround } from '@wildshard/engine/game/devColliders';
24
+ import { isDevRestart, withDevGameplay, type DevGameplay, type DevPlace, type DevRestarted } from '@wildshard/engine/game/devGameplay';
25
+ import type { Shardfile } from '@wildshard/format/shardSchema';
24
26
  import { ProgressSaves, ProgressWatch } from './progressWatch';
25
27
 
26
28
  type Boot = Extract<ShellMessage, { kind: 'boot' }>;
27
29
  /** How the composition reaches what a worker and a Node test get differently. */
28
30
  export interface StandaloneServerOptions {
29
31
  readonly control: MessagePort; readonly game: MessagePort;
30
- /** Read and verify a shard's server inputs: the home cell's, and each cell's as the grid admits it. */
31
- readonly load: (boot: Boot, slug: string) => Promise<HeadlessRuntimeInput>;
32
+ /** Read and verify a shard's server inputs: the home cell's, and each cell's as the grid admits it. `patch` (DEVSERVER, SHARD-SOURCE
33
+ * AP19) changes the read shardfile before the input is made of it. */
34
+ readonly load: (boot: Boot, slug: string, patch?: (shard: Shardfile) => Shardfile) => Promise<HeadlessRuntimeInput>;
32
35
  /** The road's collision, read once a grid session boots. A lone cell has no road and never asks; a proof that stays in a cell needs none. */
33
36
  readonly strips?: (boot: Boot) => Promise<readonly GridCollisionStrip[]>;
34
37
  /** A save read back but would not restore, and boot moved to the one before it. */
@@ -84,26 +87,69 @@ export function runStandaloneServer(options: StandaloneServerOptions): { dispose
84
87
  changed.poll(now);
85
88
  };
86
89
 
90
+ /** The grid's boot options for `message`; `patch` changes the watched shard's read shardfile (AP19's restart), never a neighbour's. */
91
+ const gridOptions = (message: Boot, local: ForwardedStorage, patch?: (shard: Shardfile) => Shardfile): Parameters<typeof StandaloneGrid.boot>[0] => {
92
+ const { arrival, residents } = options.proof ?? {}, watched = new Set([message.slug]);
93
+ return { slug: message.slug, build: message.build, book, saves, storage: local, savePrefix: message.savePrefix, now: diagnosticNow, ...(message.lone === true ? { lone: true } : {}),
94
+ load: slug => options.load(message, slug, watched.has(slug) ? patch : undefined), strips: () => options.strips?.(message) ?? Promise.resolve([]), stepped, ...(options.onSaveRefused === undefined ? {} : { refused: options.onSaveRefused }), ...(options.reports === undefined ? {} : { reports: options.reports }),
95
+ ...(arrival === undefined ? {} : { arrival }), ...(residents === undefined ? {} : { residents }), ...(options.goto === undefined ? {} : { goto: options.goto }) };
96
+ };
97
+
87
98
  const boot = async (message: Boot): Promise<void> => {
88
99
  bootMark('server:boot-configuration');
89
100
  storage = new ForwardedStorage(message.saves, write => { post({ kind: 'write', ...write }); });
90
- const local = storage, { arrival, residents } = options.proof ?? {};
101
+ const local = storage;
91
102
  installWorkerIdentity(message.savePrefix);
92
103
  allowDeveloperBoost(); // this server is the player's own device; a page only sends the button with Developer on
93
104
  installSaveEnvironment({ storage: saveScope => saveScope === 'session' ? null : local, persistent: () => true, persist: () => Promise.resolve(false) });
94
- const server = await bootTask('server:world-boot', () => StandaloneGrid.boot({ slug: message.slug, build: message.build, book, saves, storage: local, savePrefix: message.savePrefix, now: diagnosticNow, ...(message.lone === true ? { lone: true } : {}),
95
- load: slug => options.load(message, slug), strips: () => options.strips?.(message) ?? Promise.resolve([]), stepped, ...(options.onSaveRefused === undefined ? {} : { refused: options.onSaveRefused }), ...(options.reports === undefined ? {} : { reports: options.reports }),
96
- ...(arrival === undefined ? {} : { arrival }), ...(residents === undefined ? {} : { residents }), ...(options.goto === undefined ? {} : { goto: options.goto }) }));
105
+ const server = await bootTask('server:world-boot', () => StandaloneGrid.boot(gridOptions(message, local)));
97
106
  grid = server;
98
107
  const { restored } = server;
99
108
  if (restored?.ledger !== undefined) book.restore(restored.ledger);
100
109
  server.connect(new WorkerLoopback(game));
101
110
  watch.look(server.host, book.filed); // where the world stands before its first tick: what that tick moves is progress
102
111
  // SHARD-SOURCE AP5: `wildshard watch`'s part colliders, in this world as in the page's (DEVSERVER only: the define folds it away)
103
- const devBoxes = new Map<string, Scope>();
104
- if (options.harness !== undefined) options.harness.onmessage = (event: MessageEvent<unknown>): void => { const [port] = event.ports; if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevColliders(event.data)) swapDevBoxes(server.host.physics, server.host.scope, devBoxes, event.data.wildshardDevColliders, event.data.boxes); else if (isHarnessJoin(event.data) && port !== undefined) server.join(event.data, new WorkerLoopback(port)); else if (isHarnessFlag(event.data)) server.raise(event.data.flag); else if (isHarnessMove(event.data)) server.place(event.data, event.data.move); else if (isHarnessPlace(event.data)) server.place(event.data); else if (isHarnessHits(event.data)) server.hardHits(event.data.hits); else if (isHarnessGod(event.data)) server.bossGod(); };
112
+ // and (AP18) its ground: the heightfield, the height query, and the players lifted out of a hill raised under them
113
+ const devBoxes = new Map<string, Scope>(), devGround: { scope: Scope | null } = { scope: null };
114
+ const groundPorts = { heightQuery: (heightAt: (x: number, z: number) => number) => { grid?.host.setHeightQuery(heightAt); }, players: () => (grid ?? server).host.players.entries(),
115
+ place: (at: { x: number; y: number; z: number; yaw: number }, player: string) => { try { grid?.place(at, player); } catch (cause) { console.warn('[devGround] a player stays where it was', cause); } } };
116
+ // AP19: `wildshard watch`'s soft restart. Save, put the world down, boot it again on the new sections from that save (its
117
+ // progress and its player's place), give the page its new link and put the player where the page says it stands. The page
118
+ // sends its held boxes and ground again once this answers.
119
+ let restarting = false;
120
+ const restart = typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ ? async (gameplay: DevGameplay, at: DevPlace | null, link: MessagePort, reply: MessagePort): Promise<void> => {
121
+ const started = diagnosticNow(), old = grid;
122
+ const answer = (ok: boolean, reason?: string): void => { reply.postMessage({ ok, ms: Math.round(diagnosticNow() - started), ...(reason === undefined ? {} : { reason }) } satisfies DevRestarted, []); reply.close(); };
123
+ if (old === undefined || restarting) { answer(false, 'no world to restart'); return; }
124
+ // the clock comes back only as it was: a hidden tab's or a failed world's server stays paused
125
+ const running = clock?.running ?? false;
126
+ restarting = true; clock?.pause();
127
+ try {
128
+ await saveWorld();
129
+ old.dispose(); grid = undefined;
130
+ for (const held of devBoxes.values()) held.dispose();
131
+ devBoxes.clear(); devGround.scope?.dispose(); devGround.scope = null;
132
+ const next = await StandaloneGrid.boot(gridOptions(message, local, shard => withDevGameplay(shard, gameplay)));
133
+ grid = next;
134
+ next.connect(new WorkerLoopback(link));
135
+ if (at !== null) next.place(at);
136
+ watch.look(next.host, book.filed);
137
+ next.open();
138
+ answer(true);
139
+ } catch (cause) { answer(false, cause instanceof Error ? cause.message : String(cause)); }
140
+ finally { restarting = false; if (running) clock?.start(); }
141
+ } : null;
142
+ if (options.harness !== undefined) options.harness.onmessage = (event: MessageEvent<unknown>): void => {
143
+ const [port, reply] = event.ports, live = grid;
144
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && restart !== null && isDevRestart(event.data) && port !== undefined && reply !== undefined) { void restart(event.data.wildshardDevRestart, event.data.at, port, reply); return; }
145
+ // while a restart runs there is no world: the page sends its boxes and ground again once it answers
146
+ if (live === undefined) return;
147
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevColliders(event.data)) swapDevBoxes(live.host.physics, live.host.scope, devBoxes, event.data.wildshardDevColliders, event.data.boxes);
148
+ else if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevGround(event.data)) swapDevGround(live.host.physics, live.host.scope, devGround, event.data.wildshardDevGround, groundPorts);
149
+ else if (isHarnessJoin(event.data) && port !== undefined) live.join(event.data, new WorkerLoopback(port)); else if (isHarnessFlag(event.data)) live.raise(event.data.flag); else if (isHarnessMove(event.data)) live.place(event.data, event.data.move); else if (isHarnessPlace(event.data)) live.place(event.data); else if (isHarnessHits(event.data)) live.hardHits(event.data.hits); else if (isHarnessGod(event.data)) live.bossGod();
150
+ };
105
151
  clock = new ServerClock({ now: diagnosticNow, wait: (ms, run) => { const timer = scope.timeout(ms, run); return () => { scope.cancelTimer(timer); }; },
106
- step: () => { try { server.tick(); progress(server); } catch (error) { fail(error); } } });
152
+ step: () => { const live = grid; if (live === undefined) return; try { live.tick(); progress(live); } catch (error) { fail(error); } } });
107
153
  options.proof?.booted?.(server);
108
154
  bootMark('server:booted-send');
109
155
  post({ kind: 'booted', tick: server.host.state.tick, restored: restored !== undefined });
@@ -1,7 +1,7 @@
1
1
  import type { Rapier } from '@wildshard/engine/physics/rapier';
2
2
  import { bootTask, bootProgress, bootTiming } from '@wildshard/engine/boot/timing';
3
3
  import { isOutputIndex } from '@wildshard/format/outputAddress';
4
- import { parseShardfile } from '@wildshard/format/shardSchema';
4
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
5
5
  import { contentHash } from '@wildshard/engine/game/shardfile/contentHash';
6
6
  import { nodeNamedJsonCheck, nodeOutputDescriptorChecks } from '@wildshard/engine/game/shardfile/outputChecksNode';
7
7
  import { carryOutputDescriptor, isBuildValidatedOutput, outputDescriptor, resolveOutputDescriptor, serverReadsFile } from '@wildshard/engine/game/shardfile/outputDescriptor';
@@ -133,12 +133,13 @@ function serverPackReader(root: string, slug: string, build: () => string, sourc
133
133
  * P1-E5.2: the worker's product reader, loadHeadlessProduct over `fetch`. It verifies the same index, sizes and SHA-256
134
134
  * addresses with the same checks; only where the bytes come from differs.
135
135
  */
136
- export function fetchServerProduct(base: string, rapier: Rapier, held?: HeldRead): Promise<HeadlessRuntimeInput> {
137
- return readServerProduct(new URL(base, globalThis.location.href).href, workerBuild, serverBytes, rapier, held);
136
+ export function fetchServerProduct(base: string, rapier: Rapier, held?: HeldRead, patch?: (shard: Shardfile) => Shardfile): Promise<HeadlessRuntimeInput> {
137
+ return readServerProduct(new URL(base, globalThis.location.href).href, workerBuild, serverBytes, rapier, held, undefined, patch);
138
138
  }
139
139
  /** A shard's server inputs under `root`, whichever server is reading: `source` is what differs. `hash`, a placed slug's shardfile (SA47),
140
- * lets a slug the build's book lacks open from the cook's index. */
141
- export async function readServerProduct(root: string, build: () => string, source: ServerRead, rapier: Rapier, held?: HeldRead, hash?: string): Promise<HeadlessRuntimeInput> {
140
+ * lets a slug the build's book lacks open from the cook's index. `patch` (DEVSERVER, SHARD-SOURCE AP19: `withDevGameplay`) changes
141
+ * the read shardfile before the product is made of it. */
142
+ export async function readServerProduct(root: string, build: () => string, source: ServerRead, rapier: Rapier, held?: HeldRead, hash?: string, patch?: (shard: Shardfile) => Shardfile): Promise<HeadlessRuntimeInput> {
142
143
  const slug = new URL('.', root).pathname.split('/').at(-2) ?? '';
143
144
  // C2: all of it is in the pack this build's book names, the server class only there (J91). The page lends what it holds
144
145
  // (DL25), so that moves no bytes. A host with no book, or one offline after a new build, reads what the device kept.
@@ -155,8 +156,9 @@ export async function readServerProduct(root: string, build: () => string, sourc
155
156
  // on bytes its build has already checked and the page has just read without checking. As on the page, only a build's own verdict
156
157
  // for exactly these bytes spares the checks. A product with none, an outside one, keeps them.
157
158
  const assembled = await bootTask('server:descriptor-read-and-verification', () => resolveOutputDescriptor(input, { offline: false, firstParty: true, hash: contentHash, read, checks: nodeOutputDescriptorChecks }));
158
- const built = isBuildValidatedOutput(assembled), shard = built ? assembled : parseShardfile(assembled);
159
- if (!built) carryOutputDescriptor(assembled, shard);
159
+ const built = isBuildValidatedOutput(assembled), parsed = built ? assembled : parseShardfile(assembled);
160
+ if (!built) carryOutputDescriptor(assembled, parsed);
161
+ const shard = patch === undefined ? parsed : patch(parsed);
160
162
  const descriptor = outputDescriptor(shard);
161
163
  if (descriptor === undefined) throw new Error('Standalone output has no verified index');
162
164
  const files = new Map<string, { readonly path: string; readonly hash: string; readonly bytes: number }>();
@@ -37,7 +37,7 @@ export function runServerWorker(event: MessageEvent<unknown>): void {
37
37
  const [control, game, harness, reads] = event.ports;
38
38
  if (control === undefined || game === undefined) return;
39
39
  const held = reads === undefined ? undefined : askHeldReads(reads);
40
- runStandaloneServer({ control, game, ...harness === undefined ? {} : { harness }, ...typeof start.goto === 'string' ? { goto: start.goto } : {}, load: async (boot, slug) => fetchServerProduct(new URL(`../${slug}/`, new URL(boot.base, globalThis.location.href)).href, await rapierOf(held), held),
40
+ runStandaloneServer({ control, game, ...harness === undefined ? {} : { harness }, ...typeof start.goto === 'string' ? { goto: start.goto } : {}, load: async (boot, slug, patch) => fetchServerProduct(new URL(`../${slug}/`, new URL(boot.base, globalThis.location.href)).href, await rapierOf(held), held, patch),
41
41
  strips: boot => fetchGridCollision(boot.base),
42
42
  onSaveRefused: error => { console.warn('Standalone save refused, falling back', error); } });
43
43
  }
@@ -50,6 +50,16 @@ const HELD_SLICE_MIN_MS = 4;
50
50
  let heldSliceAt = Number.NEGATIVE_INFINITY;
51
51
  /** Frames drawn while held, for `heldFrameTurn`. */
52
52
  let heldFrames = 0;
53
+ /** GRID-CROSSING GC6 (QA 11-14 row 6, Jake on staging: a 37 s card crossing into Nalati at 2992x1434@2): a build the traveller
54
+ * is about to need (the world of the cell ahead, its entry on the road) is on the crossing's critical path. Its slices then
55
+ * get URGENT_BUILD_MS after each drawn frame, whatever the display's rate and whether the next vsync is due: the ordinary
56
+ * quarter of the fastest display interval gave a 120 Hz screen 2 ms a frame, and at 30 fps that is 6% of the wall clock, so
57
+ * an 11 s world took 30 s. The grid sets it while such a build runs; off by default. */
58
+ export const URGENT_BUILD_MS = 8;
59
+ let urgent = false;
60
+ export function setBuildUrgent(on: boolean): void { urgent = on; }
61
+ /** Whether a build the traveller is about to need is running (`setBuildUrgent`). */
62
+ export function buildUrgent(): boolean { return urgent; }
53
63
  /** Whether the traveller waits for the build (a grid cell's loading screen shows); the grid sets it, off by default.
54
64
  * The page sets it through `setBuildHeldTimed` (`heldTiming.ts`), which also times each held interval on Developer pages. */
55
65
  export function setBuildHeld(on: boolean): void {
@@ -104,6 +114,7 @@ export function frameBudgetSpent(budgetMs: number, now: number = diagnosticNow()
104
114
  // D110: a frame that overran its interval (drawn after the next was due: a phone at 4x CPU) is due the moment it lands,
105
115
  // so the due rule would end every slice before it starts and no sliced build would run again; after such a frame the
106
116
  // builds get their ordinary slice instead
117
+ if (urgent) return presenting(now) && now - lastDrawn >= Math.min(budgetMs, URGENT_BUILD_MS);
107
118
  const overran = lastDrawn - lastFrameAt >= interval - DUE_SLACK_MS;
108
119
  return presenting(now) && (now - lastDrawn >= Math.min(budgetMs, interval / 4, BUILD_FRAME_MS / 2) || (!overran && frameDue(now)));
109
120
  }
@@ -175,5 +186,5 @@ export function paceYield(plain: () => Promise<void>, owner?: Scope, budgetMs?:
175
186
  }
176
187
 
177
188
  function yieldDue(budgetMs: number | undefined, now: number): boolean {
178
- return !held && frameDue(now) || (budgetMs !== undefined && frameBudgetSpent(budgetMs, now));
189
+ return !held && (!urgent || budgetMs === undefined) && frameDue(now) || (budgetMs !== undefined && frameBudgetSpent(budgetMs, now));
179
190
  }
@@ -1,16 +1,21 @@
1
1
  import type { Collider } from '@dimforge/rapier3d-simd';
2
2
  import type { Scope } from '../app/scope';
3
3
  import { withOwner } from '../app/ownership';
4
- import { decodeTerrainTile } from '@wildshard/format/terrainTileBytes';
4
+ import { decodeTerrainTile, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
5
5
  import type { Physics } from './Physics';
6
6
  import { groups } from './groups';
7
- import { tagCollider } from './surface';
7
+ import { isTerrainCollider, tagCollider } from './surface';
8
8
 
9
9
  /** Install the baked critical heightfield in the local physics world; the owning scope removes it on unload. */
10
10
  export function addBakedTerrainCollider(physics: Physics, bytes: Uint8Array, scope: Scope): Collider {
11
- const data = decodeTerrainTile(bytes), r = data.resolution;
11
+ const data = decodeTerrainTile(bytes);
12
12
  if (data.colours !== undefined) throw new Error('Collider terrain must contain heights only');
13
- const heights = new Float32Array(r * r);
13
+ return addTerrainTileCollider(physics, data, scope);
14
+ }
15
+
16
+ /** A heights lattice (row-major, as the wire carries it) as the world's ground heightfield, owned by `scope`. */
17
+ export function addTerrainTileCollider(physics: Physics, data: Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>, scope: Scope): Collider {
18
+ const r = data.resolution, heights = new Float32Array(r * r);
14
19
  for (let z = 0; z < r; z++) for (let x = 0; x < r; x++) heights[x * r + z] = data.heights[z * r + x] ?? 0;
15
20
  const collider = withOwner(scope, () => physics.world.createCollider(physics.R.ColliderDesc.heightfield(r - 1, r - 1, heights, { x: data.size, y: 1, z: data.size })
16
21
  .setTranslation(data.x + data.size / 2, 0, data.z + data.size / 2).setCollisionGroups(groups('WORLD')).setFriction(0.9)));
@@ -18,3 +23,14 @@ export function addBakedTerrainCollider(physics: Physics, bytes: Uint8Array, sco
18
23
  // Physics already owns the scoped handle and forgets its capture before freeing a replaced world.
19
24
  return collider;
20
25
  }
26
+
27
+ /**
28
+ * SHARD-SOURCE AP18 (DEVSERVER): `wildshard watch`'s new ground. The lattice goes in as the world's heightfield under
29
+ * `scope`, then every other terrain heightfield leaves the world (the boot's, or the last swap's). Returns how many went.
30
+ */
31
+ export function swapTerrainCollider(physics: Physics, data: Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>, scope: Scope): number {
32
+ const fresh = addTerrainTileCollider(physics, data, scope), old: Collider[] = [];
33
+ physics.world.forEachCollider(collider => { if (collider !== fresh && isTerrainCollider(collider)) old.push(collider); });
34
+ for (const collider of old) physics.world.removeCollider(collider, true);
35
+ return old.length;
36
+ }
@@ -2,6 +2,8 @@ import type { Scope } from '@wildshard/engine/app/scope';
2
2
  import { withOwner } from '@wildshard/engine/app/ownership';
3
3
  import type { Physics } from '@wildshard/engine/physics/Physics';
4
4
  import { groups } from '@wildshard/engine/physics/groups';
5
+ import { swapTerrainCollider } from '@wildshard/engine/physics/terrainTiles';
6
+ import { terrainTileHeight, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
5
7
 
6
8
  /**
7
9
  * SHARD-SOURCE AP5 (J347): a watched part's solid boxes, as the dev hook's `swapColliders` hands them to a physics world.
@@ -45,3 +47,61 @@ export function swapDevBoxes(physics: Physics, owner: Scope, held: Map<string, S
45
47
  }
46
48
  old?.dispose();
47
49
  }
50
+
51
+ /** SHARD-SOURCE AP18: a watched shard's whole ground, heights only (row-major, as the wire carries a terrain tile). */
52
+ export type DevGround = Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>;
53
+ /** The harness-port message that carries the new ground to the in-page server. */
54
+ export interface DevGroundMessage { readonly wildshardDevGround: DevGround }
55
+
56
+ export const isDevGround = (value: unknown): value is DevGroundMessage => {
57
+ if (typeof value !== 'object' || value === null || !('wildshardDevGround' in value)) return false;
58
+ const ground = value.wildshardDevGround;
59
+ if (typeof ground !== 'object' || ground === null || !('resolution' in ground) || !('x' in ground) || !('z' in ground) || !('size' in ground) || !('heights' in ground)) return false;
60
+ const { resolution, x, z, size, heights } = ground;
61
+ return typeof resolution === 'number' && Number.isInteger(resolution) && resolution >= 2 && resolution <= 257 && [x, z, size].every(n => typeof n === 'number' && Number.isFinite(n))
62
+ && (size as number) > 0 && heights instanceof Float32Array && heights.length === resolution * resolution && heights.every(Number.isFinite);
63
+ };
64
+
65
+ /**
66
+ * Where feet at (x, y, z) stand once new solids are in: on the ground when they are under it, or on top of a box they are
67
+ * inside. Null when they are in neither (nothing to lift). A box's top is its highest point, a fair floor for a dev swap.
68
+ */
69
+ export function liftedFeet(x: number, y: number, z: number, heightAt: ((x: number, z: number) => number) | null, boxes: readonly DevBox[]): number | null {
70
+ let lifted: number | null = null;
71
+ if (heightAt !== null) { const ground = heightAt(x, z); if (y < ground - 0.02) lifted = ground; }
72
+ for (const box of boxes) {
73
+ const [qx, qy, qz, qw] = box.rotation, dx = x - box.centre[0], dy = (lifted ?? y) + 0.05 - box.centre[1], dz = z - box.centre[2];
74
+ // into the box's frame: the conjugate rotation, v + 2w(-q x v) + 2(-q x (-q x v))
75
+ const cx = -qy * dz + qz * dy, cy = -qz * dx + qx * dz, cz = -qx * dy + qy * dx;
76
+ const lx = dx + 2 * (qw * cx + (-qy * cz + qz * cy)), ly = dy + 2 * (qw * cy + (-qz * cx + qx * cz)), lz = dz + 2 * (qw * cz + (-qx * cy + qy * cx));
77
+ if (Math.abs(lx) > box.half[0] || Math.abs(ly) > box.half[1] || Math.abs(lz) > box.half[2]) continue;
78
+ // the box's world y extent: |R row y| . half
79
+ const r1 = 2 * (qx * qy + qw * qz), r2 = 1 - 2 * (qx * qx + qz * qz), r3 = 2 * (qy * qz - qw * qx);
80
+ const top = box.centre[1] + Math.abs(r1) * box.half[0] + Math.abs(r2) * box.half[1] + Math.abs(r3) * box.half[2];
81
+ if (top > (lifted ?? y)) lifted = top;
82
+ }
83
+ return lifted;
84
+ }
85
+
86
+ /** The new ground's height law, as the page's terrain field (`clientGround`) reads a collider: 0 off the lattice. */
87
+ export const devGroundHeight = (ground: DevGround): ((x: number, z: number) => number) => (x, z) => x < ground.x || z < ground.z || x > ground.x + ground.size || z > ground.z + ground.size ? 0 : terrainTileHeight(ground, x, z);
88
+
89
+ /**
90
+ * The in-page server's half of a ground swap: the new heightfield (in `held`'s scope, the last swap's going), the new
91
+ * height query, and every player under it lifted onto it (`place`: the wire counts it and the client snaps).
92
+ */
93
+ export function swapDevGround(physics: Physics, owner: Scope, held: { scope: Scope | null }, ground: DevGround, ports: {
94
+ readonly heightQuery: (heightAt: (x: number, z: number) => number) => void;
95
+ readonly players: () => Iterable<readonly [string, { readonly position: { readonly x: number; readonly y: number; readonly z: number }; readonly yaw: number }]>;
96
+ readonly place: (at: { x: number; y: number; z: number; yaw: number }, player: string) => void;
97
+ }): void {
98
+ const old = held.scope, scope = owner.child('devGround');
99
+ swapTerrainCollider(physics, ground, scope);
100
+ held.scope = scope; old?.dispose();
101
+ const heightAt = (x: number, z: number): number => terrainTileHeight(ground, x, z, { boundary: 'clamp' });
102
+ ports.heightQuery(heightAt);
103
+ for (const [id, player] of ports.players()) {
104
+ const y = liftedFeet(player.position.x, player.position.y, player.position.z, heightAt, []);
105
+ if (y !== null) ports.place({ x: player.position.x, y, z: player.position.z, yaw: player.yaw }, id);
106
+ }
107
+ }
@@ -0,0 +1,41 @@
1
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
2
+ import { carryOutputDescriptor } from '@wildshard/engine/game/shardfile/outputDescriptor';
3
+
4
+ /**
5
+ * SHARD-SOURCE AP19 (J347): `wildshard watch`'s soft restart. A watched shard's quests, encounters, spawns or scripts
6
+ * changed: the in-page server restarts its world on the new sections, from a save it takes first (so progress and the
7
+ * player's place carry over), and the page rebuilds its quest views. These are the sections it takes; anything else (the
8
+ * state schema, the look, the ground) is a new shell or the hook's other calls. DEVSERVER-only on both sides, as
9
+ * `devColliders.ts` is (engine `scripts/check-devserver.mjs` refuses `wildshardDevRestart` in a production bundle).
10
+ */
11
+ // `questNpcs` and `clientScripts` are not here: only the page reads them and the hook rebuilds only the quest views, so a change
12
+ // to either is a new shell.
13
+ export const DEV_GAMEPLAY_SECTIONS = ['quests', 'questHost', 'encounters', 'directors', 'creatures', 'crowds', 'hooks', 'ledger', 'sim'] as const;
14
+ export type DevGameplaySection = typeof DEV_GAMEPLAY_SECTIONS[number];
15
+ /** The new rows of each section the watched source declares now; a section left out keeps the shell's. */
16
+ export type DevGameplay = Partial<Pick<Shardfile, DevGameplaySection>>;
17
+ /** Where the page's player stands: the restarted world puts its player there. */
18
+ export interface DevPlace { readonly x: number; readonly y: number; readonly z: number; readonly yaw: number }
19
+ /** The harness-port message that restarts the in-page server; its ports are the new game link and the reply's. */
20
+ export interface DevRestartMessage { readonly wildshardDevRestart: DevGameplay; readonly at: DevPlace | null }
21
+ /** The worker's answer on the reply port. */
22
+ export interface DevRestarted { readonly ok: boolean; readonly ms: number; readonly reason?: string }
23
+
24
+ const SECTIONS: ReadonlySet<string> = new Set(DEV_GAMEPLAY_SECTIONS);
25
+
26
+ export const isDevRestart = (value: unknown): value is DevRestartMessage => {
27
+ if (typeof value !== 'object' || value === null || !('wildshardDevRestart' in value) || !('at' in value)) return false;
28
+ const { wildshardDevRestart: gameplay, at } = value;
29
+ if (typeof gameplay !== 'object' || gameplay === null || Array.isArray(gameplay) || !Object.keys(gameplay).every(key => SECTIONS.has(key))) return false;
30
+ return at === null || (typeof at === 'object' && 'x' in at && 'y' in at && 'z' in at && 'yaw' in at && [at.x, at.y, at.z, at.yaw].every(n => typeof n === 'number' && Number.isFinite(n)));
31
+ };
32
+
33
+ /** `shard` with `gameplay`'s sections in place of its own, checked as a whole shardfile; the output descriptor carries over. */
34
+ export function withDevGameplay(shard: Shardfile, gameplay: DevGameplay): Shardfile {
35
+ const merged: Record<string, unknown> = { ...shard };
36
+ for (const section of DEV_GAMEPLAY_SECTIONS) if (gameplay[section] !== undefined) merged[section] = gameplay[section];
37
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- JSON wire normalization, as the product reader parses it
38
+ const next = parseShardfile(JSON.parse(JSON.stringify(merged)));
39
+ carryOutputDescriptor(shard, next);
40
+ return next;
41
+ }