@wildshard/engine 0.1.22 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/index.html +17 -4
- package/lint/engine-sides.json +9 -0
- package/lint/sim-players.json +2 -13
- package/package.json +36 -3
- package/scripts/apfs-clone.mjs +5 -2
- package/scripts/app-build/catalogue.ts +39 -8
- package/scripts/app-build/serviceWorker.ts +4 -1
- package/scripts/app-build/splitOutput.mjs +33 -11
- package/scripts/app-build/titlePreloads.mjs +8 -5
- package/scripts/bake-road-surfaces.entry.ts +18 -0
- package/scripts/bake-road-surfaces.mjs +44 -0
- package/scripts/changelog.mjs +2 -1
- package/scripts/ci-pack.mjs +3 -3
- package/scripts/engine-ci-shard.mjs +11 -0
- package/scripts/fight-page-census.mjs +131 -0
- package/scripts/goldens/board.py +44 -11
- package/scripts/goldens/capture.mjs +18 -6
- package/scripts/goldens/native-residency.d.mts +2 -0
- package/scripts/goldens/native-residency.mjs +31 -4
- package/scripts/grid-road-lag.mjs +209 -0
- package/scripts/keep-copy.mjs +172 -0
- package/scripts/land.d.mts +4 -1
- package/scripts/land.mjs +121 -9
- package/scripts/lane-live.mjs +136 -0
- package/scripts/leftovers-report.mjs +47 -0
- package/scripts/loading-card-proof.mjs +42 -9
- package/scripts/loading-flow/benchmax.mjs +59 -7
- package/scripts/loading-flow/stalls.d.mts +2 -0
- package/scripts/loading-flow/stalls.mjs +13 -0
- package/scripts/map-hash.mjs +1 -1
- package/scripts/mmo-bots.mjs +5 -3
- package/scripts/mmo-grid-proof.mjs +74 -0
- package/scripts/mmo-seat-proof.mjs +43 -0
- package/scripts/nightly-heads.ts +13 -13
- package/scripts/nightly-model.ts +26 -12
- package/scripts/nightly-tag.mjs +2 -4
- package/scripts/nightly.proof.ts +18 -5
- package/scripts/nightly.ts +13 -8
- package/scripts/no-astc-boot.mjs +77 -0
- package/scripts/page-release/content.mjs +19 -10
- package/scripts/page-release/flow.d.mts +3 -2
- package/scripts/page-release/flow.mjs +31 -21
- package/scripts/page-release/packs.d.mts +5 -0
- package/scripts/page-release/packs.mjs +13 -3
- package/scripts/page-release/preview.d.mts +2 -0
- package/scripts/page-release/preview.mjs +74 -0
- package/scripts/page-release.mjs +13 -5
- package/scripts/physics-route.json +6 -6
- package/scripts/pins-reuse.mjs +1 -0
- package/scripts/pins-staging.ts +54 -0
- package/scripts/pins.ts +5 -0
- package/scripts/ring3.proof.ts +71 -0
- package/scripts/ring3.ts +100 -0
- package/scripts/road-drive-proof.mjs +269 -0
- package/scripts/road-memory-probe.mjs +129 -0
- package/scripts/scratch-dir.mjs +33 -14
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/server-release/github.mjs +59 -26
- package/scripts/server-release/items.d.mts +7 -0
- package/scripts/server-release/items.mjs +28 -0
- package/scripts/server-release/publish.mjs +24 -2
- package/scripts/server-release/sign.mjs +8 -4
- package/scripts/side-parity.mjs +1 -1
- package/scripts/test-products.json +1 -0
- package/scripts/test_prebuilt_output.py +3 -1
- package/scripts/tsconfig.json +2 -0
- package/scripts/turn-in-shots.mjs +83 -0
- package/scripts/vitest-bench-observe-proof.py +168 -0
- package/scripts/vitest-bench.py +122 -77
- package/scripts/vitest-ci-files.ts +5 -1
- package/scripts/vps/rebuild.sh +3 -1
- package/scripts/vps/wildshard-config +106 -1
- package/scripts/warm-native-chrome.mjs +9 -3
- package/scripts/worker-client-fights.mjs +9 -3
- package/scripts/worktree-reap.mjs +36 -140
- package/scripts/worktree.mjs +92 -12
- package/scripts/zone-gate-proof.mjs +93 -0
- package/src/client/engine/audio/audioLog.ts +7 -2
- package/src/client/engine/boot/diagnostics.ts +69 -1
- package/src/client/engine/boot/sw.ts +3 -1
- package/src/client/engine/core/ktx2.ts +33 -10
- package/src/client/engine/core/ktx2Zstd.ts +2 -1
- package/src/client/engine/models/place.ts +7 -5
- package/src/client/engine/pwa/sw.js +83 -10
- package/src/client/engine/render/dataLook.ts +14 -7
- package/src/client/engine/render/lookLight.ts +64 -20
- package/src/client/engine/render/precompile.ts +6 -0
- package/src/client/engine/render/tiers.ts +9 -0
- package/src/client/engine/ui/Loading.ts +6 -8
- package/src/client/engine/ui/lookLightOption.ts +1 -1
- package/src/client/engine/ui/playerReload.ts +5 -5
- package/src/client/game/audio/cueDirector.ts +2 -1
- package/src/client/game/boot/bytes.generated.ts +4 -1
- package/src/client/game/boot/versions.generated.ts +8 -5
- package/src/client/game/boss/arenaRoom.ts +4 -3
- package/src/client/game/boss/roamingProjection.ts +1 -1
- package/src/client/game/devScene/hook.ts +1 -1
- package/src/client/game/devScene/liveLook.ts +1 -1
- package/src/client/game/grid/cellClip.ts +70 -6
- package/src/client/game/grid/dataCellKit.ts +9 -1
- package/src/client/game/grid/gateCard.css +9 -0
- package/src/client/game/grid/gateCard.ts +67 -0
- package/src/client/game/grid/live.ts +17 -3
- package/src/client/game/grid/liveSession.ts +15 -5
- package/src/client/game/grid/neighbourLife.ts +10 -1
- package/src/client/game/grid/neighbourPanels.ts +29 -2
- package/src/client/game/grid/pageEntry.ts +21 -0
- package/src/client/game/grid/products.ts +21 -7
- package/src/client/game/grid/regionalWorld.ts +5 -0
- package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
- package/src/client/game/grid/roadLook.ts +5 -73
- package/src/client/game/grid/roadLookPlatform.ts +11 -6
- package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
- package/src/client/game/grid/roadTilePool.ts +4 -0
- package/src/client/game/grid/session.ts +58 -16
- package/src/client/game/grid/softWallLook.ts +6 -1
- package/src/client/game/plugin/ui.ts +3 -0
- package/src/client/game/population/signals.ts +1 -1
- package/src/client/game/quest/chapterDirector.ts +1 -0
- package/src/client/game/session/play.ts +3 -0
- package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
- package/src/client/game/shardfile/clientSource.ts +5 -2
- package/src/client/game/shardfile/clientWorker.ts +25 -8
- package/src/client/game/shardfile/look.ts +1 -1
- package/src/client/game/shardfile/runtimeProduct.ts +9 -5
- package/src/client/game/shardfile/slabLibrary.ts +37 -0
- package/src/client/game/shardfile/slabRanges.ts +145 -0
- package/src/client/game/shardfile/wirePage.ts +5 -2
- package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
- package/src/client/host/online/shell.ts +2 -2
- package/src/client/host/standalone/shell.ts +4 -1
- package/src/cook/game/cookWorker.ts +8 -5
- package/src/cook/game/tierTextures.ts +5 -3
- package/src/server/engine/net/simWorld.ts +3 -4
- package/src/server/game/grid/cellHome.ts +58 -0
- package/src/server/game/grid/simulation.ts +32 -8
- package/src/server/game/plugin/mover.ts +18 -14
- package/src/server/game/plugin/simulation.ts +2 -0
- package/src/server/game/shardfile/dataRespawn.ts +47 -0
- package/src/server/game/shardfile/declaredKitItems.ts +31 -7
- package/src/server/host/bake/headlessWorker.ts +3 -3
- package/src/server/host/dedicated/cellWorker.ts +4 -2
- package/src/server/host/dedicated/main.ts +7 -4
- package/src/server/host/dedicated/packReader.ts +15 -2
- package/src/server/host/dedicated/playerStore.ts +1 -1
- package/src/server/host/headlessRuntime.ts +11 -6
- package/src/server/host/standalone/cellWorld.ts +20 -6
- package/src/server/host/standalone/gridServer.ts +20 -6
- package/src/server/host/standalone/roadWorld.ts +36 -0
- package/src/server/host/standalone/serverHost.ts +2 -2
- package/src/shared/engine/entities/AnimalSim.ts +10 -0
- package/src/shared/engine/physics/gridBorders.ts +15 -1
- package/src/shared/engine/physics/transferWalls.ts +9 -4
- package/src/shared/engine/sim/snapshot.ts +5 -5
- package/src/shared/game/grid/allocator.ts +8 -1
- package/src/shared/game/grid/gateCount.ts +27 -0
- package/src/shared/game/grid/zoneWalls.ts +64 -0
- package/src/shared/game/ledger.ts +13 -4
- package/src/shared/game/loot/platformCatalogue.ts +14 -0
- package/src/shared/game/quest/ledger.ts +3 -3
- package/src/shared/game/shardfile/items.ts +9 -1
- package/src/shared/game/strings.ts +2 -0
- package/src/shared/host/headlessJourney.ts +3 -3
- package/src/shared/host/headlessTape.ts +7 -6
- package/src/shared/host/releaseRows.ts +4 -1
- package/src/shared/host/standalone/harnessPlace.ts +4 -0
- package/src/test/engine/simState.ts +134 -0
- package/src/test/game/builtProduct.ts +6 -0
- package/src/test/game/headless/admittedProductCache.ts +61 -0
- package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
- package/src/test/game/headless/nativeBounds.ts +27 -0
- package/src/test/game/headless/processUsage.ts +22 -0
- package/src/test/game/headless/productSession.ts +39 -0
- package/src/test/game/headless/ropeBodies.ts +60 -0
- package/src/test/game/headless/worker.ts +34 -0
- package/src/test/game/headlessNative.ts +114 -0
- package/src/test/game/headlessWorker.ts +43 -0
- package/src/test/tsconfig.game.json +3 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { CHUNK_HALF, ENTRY_WIDTH } from '@wildshard/engine/core/config';
|
|
2
|
+
import type { ReadinessEdge } from '@wildshard/engine/physics/readinessWalls';
|
|
3
|
+
import type { GridCell } from './assembly';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* ZONE-ENTRY ZE5 (J352, Jake 2026-11-15: "high walls, impermeable walls. The only places you can enter a cell are the four road
|
|
7
|
+
* entrances [...] a 10-meter buffer going into the zone. So the actual physical wall is going to be 10 meters in"): the wall round
|
|
8
|
+
* every cell but the home. It stands on the cell's edge line, open only at its four entryways, where it steps 10 m in: two side
|
|
9
|
+
* walls along the entry asphalt's sides and the gate across its inner end. The pocket between them is the buffer, floored by the
|
|
10
|
+
* entry socket. Each piece is a readiness edge (`ReadinessWalls`), as tall as a cell (`CELL_ABOVE` over `CELL_BELOW`), so no jump,
|
|
11
|
+
* boost or fall clears it. The page and the server's road (ZE6) lay the same lines; the home is never walled.
|
|
12
|
+
*/
|
|
13
|
+
/** How far the gate stands inside the cell's edge: the buffer's depth. */
|
|
14
|
+
export const BUFFER_DEPTH = 10;
|
|
15
|
+
/** A wall's half thickness, as `ReadinessWalls` builds it. */
|
|
16
|
+
const HALF_THICK = 0.25;
|
|
17
|
+
|
|
18
|
+
/** Which piece of a cell's wall an edge is. */
|
|
19
|
+
export type ZoneWallPart = 'edge' | 'side' | 'gate';
|
|
20
|
+
/** A wall piece with its part and its side of the cell. */
|
|
21
|
+
export interface ZoneWallEdge extends ReadinessEdge { readonly part: ZoneWallPart; readonly side: 'north' | 'east' | 'south' | 'west' }
|
|
22
|
+
|
|
23
|
+
const SIDES = [{ side: 'north', x: 0, z: 1 }, { side: 'east', x: 1, z: 0 }, { side: 'south', x: 0, z: -1 }, { side: 'west', x: -1, z: 0 }] as const;
|
|
24
|
+
|
|
25
|
+
/** The wall round `cell`, in the frame whose origin is `home.origin`: per side two edge runs either side of the entryway, two
|
|
26
|
+
* buffer sides and the gate. Every piece's inner face is on the cell's line (the edge) or the buffer's (sides, gate). */
|
|
27
|
+
export function zoneWallEdges(cell: GridCell, home: Readonly<{ origin: Readonly<{ x: number; z: number }> }>): ZoneWallEdge[] {
|
|
28
|
+
const cx = cell.origin.x - home.origin.x, cz = cell.origin.z - home.origin.z, open = ENTRY_WIDTH / 2;
|
|
29
|
+
const edges: ZoneWallEdge[] = [];
|
|
30
|
+
for (const { side, x: nx, z: nz } of SIDES) {
|
|
31
|
+
// `across` runs out of the cell through this side, `along` runs along it; a wall facing x (axis 'x') is thin in x
|
|
32
|
+
const facing: 'x' | 'z' = nx !== 0 ? 'x' : 'z', running: 'x' | 'z' = facing === 'x' ? 'z' : 'x';
|
|
33
|
+
const at = (across: number, along: number): { x: number; z: number } => facing === 'x' ? { x: cx + nx * across, z: cz + along } : { x: cx + along, z: cz + nz * across };
|
|
34
|
+
const piece = (part: ZoneWallPart, axis: 'x' | 'z', across: number, along: number, halfLength: number): ZoneWallEdge =>
|
|
35
|
+
({ instance: cell.instance, ...at(across, along), axis, halfLength, floor: 0, part, side });
|
|
36
|
+
// the edge line either side of the opening, past the corner by a wall's thickness so two sides meet with no gap
|
|
37
|
+
const run = (CHUNK_HALF + 2 * HALF_THICK - open) / 2, mid = open + run;
|
|
38
|
+
edges.push(piece('edge', facing, CHUNK_HALF + HALF_THICK, mid, run), piece('edge', facing, CHUNK_HALF + HALF_THICK, -mid, run));
|
|
39
|
+
// the buffer's two sides, from the gate's back face out to the edge line's outer face, just outside the 8 m asphalt
|
|
40
|
+
const depth = (BUFFER_DEPTH + 4 * HALF_THICK) / 2, centre = CHUNK_HALF + 2 * HALF_THICK - depth;
|
|
41
|
+
edges.push(piece('side', running, centre, open + HALF_THICK, depth), piece('side', running, centre, -(open + HALF_THICK), depth));
|
|
42
|
+
// the gate across the buffer's inner end, its face BUFFER_DEPTH in from the edge
|
|
43
|
+
edges.push(piece('gate', facing, CHUNK_HALF - BUFFER_DEPTH - HALF_THICK, 0, open + 2 * HALF_THICK));
|
|
44
|
+
}
|
|
45
|
+
return edges;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The cells a page walls: every cell but its home. */
|
|
49
|
+
export function walledCells<Cell extends Readonly<{ instance: string }>>(assembly: Readonly<{ cells: readonly Cell[] }>, home: Readonly<{ instance: string }>): Cell[] {
|
|
50
|
+
return assembly.cells.filter(cell => cell.instance !== home.instance);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** ZE8: the walled cell whose buffer the feet (grid metres) stand in, or null. The buffer is the 8 m wide pocket from an entryway's
|
|
54
|
+
* edge line to its gate, in the cell's own frame; the home has none. */
|
|
55
|
+
export function bufferAt<Cell extends Readonly<{ instance: string; origin: Readonly<{ x: number; z: number }> }>>(cells: readonly Cell[], home: Readonly<{ instance: string }>, feet: Readonly<{ x: number; z: number }>): Cell | null {
|
|
56
|
+
const open = ENTRY_WIDTH / 2;
|
|
57
|
+
for (const cell of cells) {
|
|
58
|
+
if (cell.instance === home.instance) continue;
|
|
59
|
+
const x = feet.x - cell.origin.x, z = feet.z - cell.origin.z;
|
|
60
|
+
const across = Math.max(Math.abs(x), Math.abs(z)), along = Math.abs(x) >= Math.abs(z) ? z : x;
|
|
61
|
+
if (across <= CHUNK_HALF && across >= CHUNK_HALF - BUFFER_DEPTH && Math.abs(along) <= open) return cell;
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
@@ -17,6 +17,17 @@ export interface LedgerInstance { id: string; shard: string; cell?: readonly [nu
|
|
|
17
17
|
export interface LedgerRewardPolicy { id: string; quantity: number; repeat?: { everyTicks: number; maxGrants: number } }
|
|
18
18
|
/** Catalogue grants default to one item, once per stable instance and shard, independent of author facts or revisions. */
|
|
19
19
|
export interface LedgerCatalogueItem { id: string; maxTier: number; reward?: LedgerRewardPolicy }
|
|
20
|
+
/** Refuse every inadmissible mapping at world load, before a player or save exists. */
|
|
21
|
+
export function admitLedgerRewards(input: unknown, catalogue: readonly LedgerCatalogueItem[]): readonly LedgerRule[] {
|
|
22
|
+
const items = new Map(catalogue.map(item => [item.id, item]));
|
|
23
|
+
if (items.size !== catalogue.length || catalogue.some(item => !Number.isSafeInteger(item.maxTier) || item.maxTier < 0)) throw new Error('Invalid platform catalogue');
|
|
24
|
+
const rules = parseLedgerRules(input);
|
|
25
|
+
for (const rule of rules) for (const reward of rule.rewards) if (reward.kind === 'catalogue') {
|
|
26
|
+
const item = items.get(reward.item);
|
|
27
|
+
if (item === undefined || reward.tier > item.maxTier || reward.quantity !== (item.reward?.quantity ?? 1)) throw new Error('Reward is outside the platform catalogue policy');
|
|
28
|
+
}
|
|
29
|
+
return rules;
|
|
30
|
+
}
|
|
20
31
|
/** A grant is confirmed only by a durable save write; a pending receipt may be retried. */
|
|
21
32
|
export interface LedgerReceipt {
|
|
22
33
|
id: string; status: 'granted' | 'duplicate' | 'pending';
|
|
@@ -37,8 +48,7 @@ export class Ledger {
|
|
|
37
48
|
constructor(store: SaveStore, instances: readonly LedgerInstance[], mappings: readonly { shard: string; revision: number; rules: readonly LedgerRule[] }[], catalogue: readonly LedgerCatalogueItem[]) {
|
|
38
49
|
this.instances = new Map(instances.map((instance) => [instance.id, instance.shard]));
|
|
39
50
|
if (this.instances.size !== instances.length) throw new Error('Duplicate ledger instance');
|
|
40
|
-
|
|
41
|
-
if (items.size !== catalogue.length || catalogue.some((item) => !Number.isSafeInteger(item.maxTier) || item.maxTier < 0)) throw new Error('Invalid platform catalogue');
|
|
51
|
+
admitLedgerRewards([], catalogue);
|
|
42
52
|
this.catalogue = new Map(catalogue.map((item) => [item.id, structuredClone(item.reward ?? { id: item.id, quantity: 1 })]));
|
|
43
53
|
const policies = [...this.catalogue.values()];
|
|
44
54
|
if (new Set(policies.map((policy) => policy.id)).size !== policies.length || policies.some((policy) => policy.id.length === 0 || policy.id.length > 128
|
|
@@ -47,10 +57,9 @@ export class Ledger {
|
|
|
47
57
|
this.rules = new Map();
|
|
48
58
|
for (const mapping of mappings) {
|
|
49
59
|
if (!Number.isSafeInteger(mapping.revision) || mapping.revision < 1) throw new Error('Invalid ledger revision');
|
|
50
|
-
for (const rule of
|
|
60
|
+
for (const rule of admitLedgerRewards(mapping.rules, catalogue)) {
|
|
51
61
|
const key = JSON.stringify([mapping.shard, mapping.revision, rule.fact]);
|
|
52
62
|
if (this.rules.has(key)) throw new Error('Duplicate ledger mapping');
|
|
53
|
-
for (const reward of rule.rewards) if (reward.kind === 'catalogue' && (items.get(reward.item) === undefined || reward.tier > (items.get(reward.item) ?? -1) || reward.quantity !== this.catalogue.get(reward.item)?.quantity)) throw new Error('Reward is outside the platform catalogue policy');
|
|
54
63
|
this.rules.set(key, { revision: mapping.revision, rule });
|
|
55
64
|
}
|
|
56
65
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as v from 'valibot';
|
|
2
|
+
|
|
3
|
+
/** MMO-PLAN MP3.4 / Q37: api-server's /api/items.json, copied into a signed release. */
|
|
4
|
+
export interface PlatformItemCatalogue { readonly version: 1; readonly items: readonly { readonly id: string; readonly maxTier: number }[] }
|
|
5
|
+
export const MAX_ITEM_CATALOGUE_BYTES = 1_048_576;
|
|
6
|
+
const item = v.strictObject({ id: v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9._-]{0,127}$/u)), maxTier: v.pipe(v.number(), v.safeInteger(), v.minValue(0)) });
|
|
7
|
+
const document: v.GenericSchema<PlatformItemCatalogue> = v.strictObject({ version: v.literal(1), items: v.pipe(v.array(item), v.maxLength(4096)) });
|
|
8
|
+
const schema = v.pipe(document, v.check(value => new Set(value.items.map(row => row.id)).size === value.items.length, 'Duplicate platform item'));
|
|
9
|
+
export function readPlatformItemCatalogue(input: unknown): PlatformItemCatalogue { return v.parse(schema, input); }
|
|
10
|
+
/** Stable bytes make an unchanged catalogue keep its digest across releases and API row ordering. */
|
|
11
|
+
export function platformItemCatalogueBytes(input: unknown): Uint8Array {
|
|
12
|
+
const value = readPlatformItemCatalogue(input), items = [...value.items].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
13
|
+
return new TextEncoder().encode(JSON.stringify({ version: value.version, items }));
|
|
14
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SaveStore } from '@wildshard/engine/saves/store';
|
|
2
2
|
import type { Shardfile } from '@wildshard/format/shardSchema';
|
|
3
|
-
import { Ledger, LedgerEmitter, type LedgerReceipt } from '../ledger';
|
|
3
|
+
import { Ledger, LedgerEmitter, type LedgerReceipt, type LedgerCatalogueItem } from '../ledger';
|
|
4
4
|
import type { RuntimeFacts } from '../plugin/runtimeRows';
|
|
5
5
|
|
|
6
6
|
/** Check the profile slot without invoking its fresh-state fallback or granting a fact. */
|
|
@@ -8,9 +8,9 @@ export function admittedQuestLedger(saves: SaveStore): boolean { return new Ledg
|
|
|
8
8
|
|
|
9
9
|
/** One declared ledger over the caller's original SaveStore and placement.
|
|
10
10
|
* Runtime adapters and native page features share this exact grant owner. */
|
|
11
|
-
export function createQuestLedger(saves: SaveStore, source: Pick<Shardfile, 'identity' | 'ledger'>, instance: string): RuntimeFacts {
|
|
11
|
+
export function createQuestLedger(saves: SaveStore, source: Pick<Shardfile, 'identity' | 'ledger'>, instance: string, catalogue: readonly LedgerCatalogueItem[] = []): RuntimeFacts {
|
|
12
12
|
const identity = { instance, shard: source.identity.slug, revision: source.identity.revision };
|
|
13
|
-
const ledger = new Ledger(saves, [{ id: instance, shard: identity.shard }], [{ shard: identity.shard, revision: identity.revision, rules: source.ledger }],
|
|
13
|
+
const ledger = new Ledger(saves, [{ id: instance, shard: identity.shard }], [{ shard: identity.shard, revision: identity.revision, rules: source.ledger }], catalogue);
|
|
14
14
|
const emit = (name: string, entity: string): LedgerReceipt => {
|
|
15
15
|
const rule = source.ledger.find((row) => row.fact === name);
|
|
16
16
|
if (rule === undefined) throw new Error(`Undeclared ledger fact ${name}`);
|
|
@@ -95,7 +95,15 @@ export function leverProfile(row: { readonly id: string; readonly profile?: unkn
|
|
|
95
95
|
/** The owned lines a lever's server seat publishes to its holder: rounds in the gun (tube and chamber), the reserve, a reload under
|
|
96
96
|
* way (0 or 1) and whether the player has taken it (0 or 1). A line at zero is dropped from `owned`, so absent reads as zero. */
|
|
97
97
|
export function leverLines(id: string): { readonly rounds: string; readonly reserve: string; readonly reloading: string; readonly taken: string } {
|
|
98
|
-
return { rounds: `${id}.rounds`, reserve: `${id}.reserve`, reloading: `${id}.reloading`, taken:
|
|
98
|
+
return { rounds: `${id}.rounds`, reserve: `${id}.reserve`, reloading: `${id}.reloading`, taken: takenLine(id) };
|
|
99
|
+
}
|
|
100
|
+
/** The owned line that says a player has taken a declared weapon off its rack (a lever's, TC-E1; a melee weapon's, TC-E4). */
|
|
101
|
+
export function takenLine(id: string): string { return `${id}.taken`; }
|
|
102
|
+
/** TEMPLATE-E2E TC-E4: the declared melee weapons a rack hands over (an item scene's take, action 3), other than the loadout's
|
|
103
|
+
* primary. Each starts on its rack for every player and comes to hand when that player takes it. */
|
|
104
|
+
export function rackMeleeRows(shard: { readonly items: { readonly rows: readonly { readonly id: string; readonly kind?: string; readonly family?: string }[]; readonly loadout: { readonly primary: string | null } }; readonly targets: { readonly itemActions?: readonly { readonly item: string; readonly action: number }[] | undefined } }): ReadonlySet<string> {
|
|
105
|
+
const melee = new Set(shard.items.rows.filter(row => row.kind === 'weapon' && row.family === 'kit.melee').map(row => row.id));
|
|
106
|
+
return new Set((shard.targets.itemActions ?? []).flatMap(row => row.action === 3 && melee.has(row.item) && row.item !== shard.items.loadout.primary ? [row.item] : []));
|
|
99
107
|
}
|
|
100
108
|
/** Normal equipment factory result plus authoritative fixed-step runtimes, scoped to the one session. */
|
|
101
109
|
export interface DeclaredItems {
|
|
@@ -92,6 +92,8 @@ export const GAME_STRINGS = {
|
|
|
92
92
|
/** G119: on the border shimmer while a crossing waits for its durable save, and when that save fails (the crossing retries) */
|
|
93
93
|
saving: 'SAVING…',
|
|
94
94
|
saveFailed: 'SAVE FAILED, RETRY',
|
|
95
|
+
/** ZE8: the gate card's line under a walled cell's name, over its count */
|
|
96
|
+
gatePreparing: 'Preparing to enter',
|
|
95
97
|
off: 'Off',
|
|
96
98
|
on: 'On',
|
|
97
99
|
},
|
|
@@ -6,7 +6,6 @@ import { floorBelow } from '@wildshard/engine/physics/query';
|
|
|
6
6
|
import { diagnosticNow } from '@wildshard/engine/core/clock';
|
|
7
7
|
import { walkingSpeed } from '@wildshard/engine/player/walk';
|
|
8
8
|
import type { AnimalSim } from '@wildshard/engine/entities/AnimalSim';
|
|
9
|
-
import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
|
|
10
9
|
|
|
11
10
|
export interface WalkPoint { readonly x:number;readonly z:number;readonly jump?:boolean|number;readonly jumpAt?:number }
|
|
12
11
|
export interface WalkStall { readonly tick:number;readonly waypoint:number;readonly x:number;readonly y:number;readonly z:number }
|
|
@@ -97,8 +96,9 @@ export interface HeadlessJourneySample {readonly commands:readonly HeadlessComma
|
|
|
97
96
|
* its script/decision/finite-state refusals. The parent request watchdog still
|
|
98
97
|
* preempts a blocked worker. This proof does not encode a resumable checkpoint.
|
|
99
98
|
* `capture` sees the placed start with no commands, then every committed tick. */
|
|
100
|
-
export function runHeadlessJourney(host:SimHost,step:(commands:readonly HeadlessCommand[])=>void,input:HeadlessJourneyPlan,capture?:(sample:HeadlessJourneySample)=>void):HeadlessJourneyReport {
|
|
101
|
-
const player=
|
|
99
|
+
export function runHeadlessJourney(host:SimHost,step:(commands:readonly HeadlessCommand[])=>void,input:HeadlessJourneyPlan,capture?:(sample:HeadlessJourneySample)=>void,playerId='actor.player'):HeadlessJourneyReport {
|
|
100
|
+
const player=host.players.get(playerId);if(player===undefined)throw new RangeError(`Unknown journey player ${playerId}`);
|
|
101
|
+
const plan=v.parse(HeadlessJourneyPlanSchema,input),cursor=new PhysicsRouteCursor(plan.points,{once:plan.once===true,edge:plan.inside!==undefined}),initial=host.state.tick;
|
|
102
102
|
let distance=0,maxTickMicros=0,out=0,ticks=0;
|
|
103
103
|
const observe=(commands:readonly HeadlessCommand[]):void=>{const p=player.position;capture?.({commands,x:p.x,y:p.y,z:p.z,grounded:player.fall.grounded});};
|
|
104
104
|
const held=new Map<AnimalSim,boolean>();
|
|
@@ -2,7 +2,6 @@ import * as v from 'valibot';
|
|
|
2
2
|
import type {SimHost} from '@wildshard/engine/sim';
|
|
3
3
|
import {PhysicsRouteCursor,type WalkPoint} from './headlessJourney';
|
|
4
4
|
import type {HeadlessCommand,HeadlessEffect} from './tickProtocol';
|
|
5
|
-
import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
|
|
6
5
|
|
|
7
6
|
export interface HeadlessTapeSegment {id:string;ticks:number;commands:HeadlessCommand[];route?:WalkPoint[];frames?:HeadlessCommand[][]}
|
|
8
7
|
export interface HeadlessTapePlan {version:1;observe:string[];segments:HeadlessTapeSegment[]}
|
|
@@ -38,12 +37,14 @@ export function headlessTapeReportSchema(effect:v.GenericSchema<HeadlessEffect>)
|
|
|
38
37
|
}
|
|
39
38
|
/** Private worker-side execution of an already admitted offline tape. Every
|
|
40
39
|
* repeated command still enters the existing native owner and fixed tick.
|
|
41
|
-
* The worker keeps its request watchdog; the reply is terminal observations.
|
|
40
|
+
* The worker keeps its request watchdog; the reply is terminal observations.
|
|
41
|
+
* playerId names the seat driven by step and observed throughout the tape. */
|
|
42
42
|
export function runTrustedHeadlessTape(host:SimHost,step:(commands:readonly HeadlessCommand[])=>void,
|
|
43
|
-
effects:()=>readonly HeadlessEffect[],plan:HeadlessTapePlan):HeadlessTapeReport {
|
|
43
|
+
effects:()=>readonly HeadlessEffect[],plan:HeadlessTapePlan,playerId='actor.player'):HeadlessTapeReport {
|
|
44
44
|
if(host.scope.disposed||host.scope.disposing)throw new Error('Tape owner retired');
|
|
45
45
|
const owners=plan.observe.map(id=>{const owner=host.adapters.get(id);if(owner===undefined)throw new Error(`Missing tape observation owner ${id}`);return {id,owner};});
|
|
46
|
-
const player=
|
|
46
|
+
const player=host.players.get(playerId);if(player===undefined)throw new RangeError(`Unknown tape player ${playerId}`);
|
|
47
|
+
const initial=host.state.tick,observations:HeadlessTapeObservation[]=[],encoder=new TextEncoder();let bytes=0;
|
|
47
48
|
for(const segment of plan.segments){
|
|
48
49
|
let peakY=player.position.y;const emitted:HeadlessEffect[]=[];
|
|
49
50
|
const cursor=segment.route===undefined?null:new PhysicsRouteCursor(segment.route,{once:true});
|
|
@@ -88,12 +89,12 @@ export function runTrustedHeadlessTape(host:SimHost,step:(commands:readonly Head
|
|
|
88
89
|
/** A resident tape owner stays pinned across streamed parts as well as inside
|
|
89
90
|
* each ordinary terminal plan. No part may silently rebind an observation. */
|
|
90
91
|
export function createTrustedHeadlessTape(host:SimHost,step:(commands:readonly HeadlessCommand[])=>void,
|
|
91
|
-
effects:()=>readonly HeadlessEffect[]):(plan:HeadlessTapePlan)=>HeadlessTapeReport {
|
|
92
|
+
effects:()=>readonly HeadlessEffect[],playerId='actor.player'):(plan:HeadlessTapePlan)=>HeadlessTapeReport {
|
|
92
93
|
let pinned:{id:string;owner:unknown}[]|undefined;
|
|
93
94
|
return plan=>{
|
|
94
95
|
const owners=plan.observe.map(id=>({id,owner:host.adapters.get(id)}));
|
|
95
96
|
if(pinned===undefined)pinned=owners;
|
|
96
97
|
else if(owners.length!==pinned.length||owners.some((row,index)=>row.id!==pinned?.[index]?.id||row.owner!==pinned[index]?.owner))throw new Error('Tape observation owner changed between parts');
|
|
97
|
-
return runTrustedHeadlessTape(host,step,effects,plan);
|
|
98
|
+
return runTrustedHeadlessTape(host,step,effects,plan,playerId);
|
|
98
99
|
};
|
|
99
100
|
}
|
|
@@ -14,10 +14,13 @@ export interface ReleaseFile {
|
|
|
14
14
|
readonly bundle?: { readonly name: string; readonly sha256: string };
|
|
15
15
|
/** The address clients dial. For the first sitting this is the quick tunnel's name (C22). */
|
|
16
16
|
readonly socket?: string;
|
|
17
|
+
/** Q37: immutable trusted item data, copied from the API before this release is signed. */
|
|
18
|
+
readonly items?: { readonly path: string; readonly sha256: string; readonly bytes: number };
|
|
17
19
|
}
|
|
18
20
|
const Whole = v.pipe(v.number(), v.integer(), v.minValue(0));
|
|
19
21
|
/** A release file's body, once its signature has held. */
|
|
20
22
|
export const ReleaseSchema: v.GenericSchema<ReleaseFile> = v.object({ channel: v.picklist(['production', 'staging', 'preview']), serial: Whole, engineBuild: v.pipe(v.string(), v.minLength(1)), saveEpoch: v.pipe(Whole, v.minValue(1)), shards: v.array(v.object({ slug: v.string(), revision: Whole })),
|
|
21
|
-
bundle: v.exactOptional(v.object({ name: v.pipe(v.string(), v.minLength(1)), sha256: v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/u)) })), socket: v.exactOptional(v.string())
|
|
23
|
+
bundle: v.exactOptional(v.object({ name: v.pipe(v.string(), v.minLength(1)), sha256: v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/u)) })), socket: v.exactOptional(v.string()),
|
|
24
|
+
items: v.exactOptional(v.pipe(v.strictObject({ path: v.pipe(v.string(), v.regex(/^assets\/catalogue\/items-[0-9a-f]{64}\.json$/u)), sha256: v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/u)), bytes: v.pipe(v.number(), v.safeInteger(), v.minValue(1), v.maxValue(1_048_576)) }), v.check(row => row.path === `assets/catalogue/items-${row.sha256}.json`, 'Item catalogue digest and path disagree'))) });
|
|
22
25
|
/** The file on R2: the body as signed, and its signature in hex (C20). */
|
|
23
26
|
export const SignedSchema: v.GenericSchema<{ readonly body: string; readonly signature: string }> = v.object({ body: v.string(), signature: v.string() });
|
|
@@ -8,6 +8,10 @@ export interface HarnessHits { readonly hits: number }
|
|
|
8
8
|
/** A Developer's `?bossGod`: a fight's blows stop reaching a player, as the page's own rule stops them on a page. */
|
|
9
9
|
export interface HarnessGod { readonly god: true }
|
|
10
10
|
export const isHarnessGod = (value: unknown): value is HarnessGod => typeof value === 'object' && value !== null && 'god' in value && value.god === true;
|
|
11
|
+
/** A golden camera's spectator: every creature in the world the player stands in holds where it is, from now on, so none
|
|
12
|
+
* wakes, charges or bites the player the camera streams round (Pine's bear den killed it, and the shot streamed round spawn). */
|
|
13
|
+
export interface HarnessStill { readonly still: true }
|
|
14
|
+
export const isHarnessStill = (value: unknown): value is HarnessStill => typeof value === 'object' && value !== null && 'still' in value && value.still === true;
|
|
11
15
|
/** Raise one of this player's flags, for a door whose quest step a proof can't reach in its minutes (a thrall hunt at night). */
|
|
12
16
|
export interface HarnessFlag { readonly flag: string }
|
|
13
17
|
export const isHarnessFlag = (value: unknown): value is HarnessFlag => typeof value === 'object' && value !== null && 'flag' in value && typeof value.flag === 'string';
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- A witness's continuation hash is a sha256 of the canonical state.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import RAPIER, { RigidBodyType, type Collider, type World } from '@dimforge/rapier3d-simd';
|
|
4
|
+
import { Physics } from '../../shared/engine/physics/Physics';
|
|
5
|
+
import { decodeSimSnapshot, type SimSnapshot, type SimSnapshotBytes } from '../../shared/engine/sim/snapshot';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A sim snapshot's native physics as restored world state, the one canonical form of "the same world" (SF72, E435).
|
|
9
|
+
*
|
|
10
|
+
* Rapier's snapshot bytes are not canonical: `takeSnapshot(restoreSnapshot(x))` can differ from `x` by a few records
|
|
11
|
+
* (Driftwood's quest checkpoint: two 13-byte records swapped near offset 194 k of 3.3 MB, the broad phase's pair order),
|
|
12
|
+
* and repeated round trips keep permuting them, with no step in between and every body, collider and contact the same.
|
|
13
|
+
* Whether it shows hangs on where a dynamic body rests, so a byte check of a restore flakes about one run in two on the
|
|
14
|
+
* wrong checkpoint. So a restore or a replay is judged on the world the bytes restore to: every rigid body (type,
|
|
15
|
+
* enabled, asleep, pose, velocities, mass, damping, gravity scale, CCD, dominance), every collider (parent, enabled,
|
|
16
|
+
* collision and solver groups, sensor, shape type, pose, friction, restitution, density) in the arenas' own order, and
|
|
17
|
+
* every contact of a dynamic body's collider (partners by handle; per manifold its contacts' distances and impulses, the
|
|
18
|
+
* solver's warm start). Numbers compare exactly: a 1-ULP pose difference still fails. Identical bytes need no restore.
|
|
19
|
+
*/
|
|
20
|
+
export interface PhysicsState {
|
|
21
|
+
/** the state, flattened (booleans as 0 / 1, a missing parent as -1) */
|
|
22
|
+
readonly values: number[];
|
|
23
|
+
/** [index of a record's first value, what the record is], ascending: names the first difference */
|
|
24
|
+
readonly marks: [number, string][];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const bodyType = (t: RigidBodyType): number => t === RigidBodyType.Dynamic ? 0 : t === RigidBodyType.Fixed ? 1 : t === RigidBodyType.KinematicPositionBased ? 2 : 3;
|
|
28
|
+
|
|
29
|
+
function contacts(world: World, collider: Collider, out: number[]): void {
|
|
30
|
+
const partners: Collider[] = [];
|
|
31
|
+
world.contactPairsWith(collider, other => { partners.push(other); });
|
|
32
|
+
partners.sort((a, b) => a.handle - b.handle);
|
|
33
|
+
out.push(partners.length);
|
|
34
|
+
for (const other of partners) {
|
|
35
|
+
out.push(other.handle);
|
|
36
|
+
world.contactPair(collider, other, (manifold, flipped) => {
|
|
37
|
+
const n = manifold.numContacts();
|
|
38
|
+
out.push(flipped ? 1 : 0, n);
|
|
39
|
+
for (let i = 0; i < n; i++) out.push(manifold.contactDist(i), manifold.contactImpulse(i));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The world `bytes` restore to, as state. */
|
|
45
|
+
export function physicsState(bytes: ArrayLike<number>): PhysicsState {
|
|
46
|
+
const physics = new Physics(RAPIER, Uint8Array.from(bytes)), world = physics.world, values: number[] = [], marks: [number, string][] = [];
|
|
47
|
+
try {
|
|
48
|
+
world.forEachRigidBody(rb => {
|
|
49
|
+
marks.push([values.length, `rigid body ${String(rb.handle)}`]);
|
|
50
|
+
const t = rb.translation(), r = rb.rotation(), v = rb.linvel(), w = rb.angvel();
|
|
51
|
+
values.push(rb.handle, bodyType(rb.bodyType()), rb.isEnabled() ? 1 : 0, rb.isSleeping() ? 1 : 0, t.x, t.y, t.z, r.x, r.y, r.z, r.w,
|
|
52
|
+
v.x, v.y, v.z, w.x, w.y, w.z, rb.mass(), rb.linearDamping(), rb.angularDamping(), rb.gravityScale(), rb.isCcdEnabled() ? 1 : 0, rb.dominanceGroup());
|
|
53
|
+
});
|
|
54
|
+
world.forEachCollider(c => {
|
|
55
|
+
marks.push([values.length, `collider ${String(c.handle)}`]);
|
|
56
|
+
const t = c.translation(), r = c.rotation(), parent = c.parent();
|
|
57
|
+
values.push(c.handle, parent?.handle ?? -1, c.isEnabled() ? 1 : 0, c.collisionGroups(), c.solverGroups(), c.isSensor() ? 1 : 0, c.shapeType(),
|
|
58
|
+
t.x, t.y, t.z, r.x, r.y, r.z, r.w, c.friction(), c.restitution(), c.density());
|
|
59
|
+
if (parent?.bodyType() === RigidBodyType.Dynamic) { marks.push([values.length, `contacts of collider ${String(c.handle)}`]); contacts(world, c, values); }
|
|
60
|
+
});
|
|
61
|
+
} finally { physics.dispose(); }
|
|
62
|
+
return { values, marks };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Do two byte arrays hold the same bytes? */
|
|
66
|
+
export function sameBytes(a: ArrayLike<number>, b: ArrayLike<number>): boolean {
|
|
67
|
+
if (a.length !== b.length) return false;
|
|
68
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Where two physics states first differ (`null`: the same world, exactly). */
|
|
73
|
+
export function physicsDifference(a: PhysicsState, b: PhysicsState): string | null {
|
|
74
|
+
const n = Math.max(a.values.length, b.values.length);
|
|
75
|
+
for (let i = 0; i < n; i++) {
|
|
76
|
+
const x = a.values[i], y = b.values[i];
|
|
77
|
+
if (x !== undefined && y !== undefined && Object.is(x, y)) continue;
|
|
78
|
+
let at = '';
|
|
79
|
+
for (const [start, label] of a.marks) { if (start > i) break; at = label; }
|
|
80
|
+
return `${at || 'the world'}: value ${String(i)} is ${String(x)}, expected ${String(y)}`;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Version 1's field order for a player. */
|
|
86
|
+
const V1_PLAYER_FIELDS = ['id', 'position', 'yaw', 'health', 'motor', 'walk', 'moveScale', 'impulse', 'fall', 'shove', 'board', 'swim', 'jump', 'dash', 'dodge', 'traversals'] as const;
|
|
87
|
+
/** A player in the version 1 shape: one velocity back out into each mode's. Footing never was a version 1 field. */
|
|
88
|
+
function versionOnePlayer(player: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
|
89
|
+
const velocity = (player['velocity'] ?? [0, 0, 0]) as readonly [number, number, number], [x, y, z] = velocity;
|
|
90
|
+
const board = player['board'] as Record<string, unknown> | undefined, swim = player['swim'] as ({ on: boolean } & Record<string, unknown>) | undefined;
|
|
91
|
+
const riding = board !== undefined || swim?.on === true, airborne = player['airborne'] === true, vy = riding ? 0 : y;
|
|
92
|
+
const mapped: Record<string, unknown> = { ...player,
|
|
93
|
+
...(riding || (x === 0 && z === 0) ? {} : { walk: { x, z } }),
|
|
94
|
+
...(board === undefined && (airborne || vy !== 0) ? { fall: { vy, grounded: !airborne } } : {}),
|
|
95
|
+
...(board === undefined ? {} : { board: { velocity: [...velocity], ...board, ground: !airborne } }),
|
|
96
|
+
...(swim === undefined ? {} : { swim: { on: swim.on, velocity: swim.on ? [...velocity] : [0, 0, 0], diving: swim['diving'], climbTo: swim['climbTo'], climbCooldown: swim['climbCooldown'], stroke: swim['stroke'], stood: swim['stood'] } }) };
|
|
97
|
+
const out: Record<string, unknown> = {};
|
|
98
|
+
for (const key of V1_PLAYER_FIELDS) if (mapped[key] !== undefined) out[key] = mapped[key];
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
/** A one-player snapshot's fields in the version 1 shape, in order: the form every recorded digest and checkpoint hash was
|
|
102
|
+
* taken in. Comparing there is what proves the version 3 engine reaches exactly the state version 1 did. A room keeps
|
|
103
|
+
* its `players`: no version 1 record of one exists. */
|
|
104
|
+
function versionOneFields(fields: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
|
105
|
+
const players = fields['players'], out: Record<string, unknown> = {};
|
|
106
|
+
if (!Array.isArray(players) || players.length !== 1) return { ...fields };
|
|
107
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
108
|
+
if (key === 'version' || key === 'apiVersion') out[key] = 1;
|
|
109
|
+
else if (key === 'players') out['player'] = versionOnePlayer((players as readonly Record<string, unknown>[])[0] ?? {});
|
|
110
|
+
else out[key] = value;
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
// The wire's number form: JSON.stringify would lose a -0.
|
|
115
|
+
function wireText(value: unknown): string {
|
|
116
|
+
if (typeof value === 'number' && Object.is(value, -0)) return '-0';
|
|
117
|
+
if (Array.isArray(value)) return `[${value.map(wireText).join(',')}]`;
|
|
118
|
+
if (value !== null && typeof value === 'object') return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}:${wireText(item)}`).join(',')}}`;
|
|
119
|
+
return JSON.stringify(value);
|
|
120
|
+
}
|
|
121
|
+
/** A one-player wire as the version 1 writer left it, byte for byte: what a witness records, so its checkpoints stay real
|
|
122
|
+
* version 1 saves that every continuation proof loads through the migration. */
|
|
123
|
+
export function simWireV1(wire: string): string {
|
|
124
|
+
const { format, snapshot } = JSON.parse(wire) as { format: string; snapshot: Record<string, unknown> };
|
|
125
|
+
return wireText({ format, version: 1, snapshot: versionOneFields(snapshot) });
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The sha256 of a snapshot in canonical form, a witness's continuation hash: every field but the physics bytes as JSON,
|
|
129
|
+
* then the physics as restored world state, each value's exact float64 bits (so -0, NaN payloads and 1 ULP all count).
|
|
130
|
+
*/
|
|
131
|
+
export function canonicalSimDigest(snapshot: SimSnapshot | SimSnapshotBytes | string): string {
|
|
132
|
+
const { physics, ...rest } = typeof snapshot === 'string' ? decodeSimSnapshot(snapshot) : snapshot;
|
|
133
|
+
return createHash('sha256').update(JSON.stringify(versionOneFields(rest))).update('\0').update(new Uint8Array(Float64Array.from(physicsState(physics).values).buffer)).digest('hex');
|
|
134
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Native scenarios run from the repository root.
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { readBuiltShardfile } from '../../../scripts/built-product.mjs';
|
|
4
|
+
|
|
5
|
+
/** Products come from CI's normal build or the matching immutable local cache, never a test build. */
|
|
6
|
+
export function builtProduct(name: string): string { return readBuiltShardfile(resolve('.'), name); }
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Exact product identity comes from its content-addressed index.
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Distinguish full products and slices with identical slugs.
|
|
4
|
+
import { resolve, sep } from 'node:path';
|
|
5
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Preserve native product URLs.
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Check the loaded descriptor against the cache identity.
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { loadHeadlessProduct } from '../../../server/host/headlessProduct';
|
|
10
|
+
import { carryOutputDescriptor, outputDescriptor } from '../../../shared/game/shardfile/outputDescriptor';
|
|
11
|
+
import { productClosureFile, type ShardProduct } from '../../../shared/game/shardfile/shardProduct';
|
|
12
|
+
import { shardProductData } from '../../../shared/game/shardfile/productData';
|
|
13
|
+
import { nodeNamedJsonCheck } from '../../../shared/game/shardfile/outputChecksNode';
|
|
14
|
+
|
|
15
|
+
export type ProductMode = 'full' | 'slice' | 'server';
|
|
16
|
+
|
|
17
|
+
/** A test file's admitted data only. Each borrower owns its source and byte arrays;
|
|
18
|
+
* worlds, residents and RNG never enter this cache. Rejected loads can retry. */
|
|
19
|
+
export function createAdmittedProductCache(load: typeof loadHeadlessProduct = loadHeadlessProduct) {
|
|
20
|
+
const products = new Map<string, Promise<{ product: ShardProduct; bytes: Map<string, Promise<Uint8Array>> }>>();
|
|
21
|
+
return async (directory: string, mode: ProductMode): Promise<{ product: ShardProduct; assets: Map<string, Uint8Array> }> => {
|
|
22
|
+
const root = resolve(directory);
|
|
23
|
+
// Read the index each time: a changed product at the same path cannot reuse
|
|
24
|
+
// a previous admission, even when its slug and revision stayed the same.
|
|
25
|
+
const identity = await readFile(`${root}/shard.json`, 'utf8');
|
|
26
|
+
const key = JSON.stringify([root, mode, identity]);
|
|
27
|
+
let pending = products.get(key);
|
|
28
|
+
if (pending === undefined) {
|
|
29
|
+
pending = load(root).then(product => {
|
|
30
|
+
if (outputDescriptor(product.shardfile)?.indexHash !== createHash('sha256').update(identity).digest('hex')) throw new Error('Headless product changed during cache admission');
|
|
31
|
+
return { product, bytes: new Map<string, Promise<Uint8Array>>() };
|
|
32
|
+
});
|
|
33
|
+
products.set(key, pending);
|
|
34
|
+
void pending.catch(() => { products.delete(key); });
|
|
35
|
+
}
|
|
36
|
+
const held = await pending;
|
|
37
|
+
const bytes = async (ref: string): Promise<Uint8Array> => {
|
|
38
|
+
let reading = held.bytes.get(ref);
|
|
39
|
+
if (reading === undefined) {
|
|
40
|
+
reading = productClosureFile(held.product, ref).then(value => value.slice());
|
|
41
|
+
held.bytes.set(ref, reading);
|
|
42
|
+
void reading.catch(() => { held.bytes.delete(ref); });
|
|
43
|
+
}
|
|
44
|
+
return (await reading).slice();
|
|
45
|
+
};
|
|
46
|
+
const source = structuredClone(held.product.shardfile);
|
|
47
|
+
carryOutputDescriptor(held.product.shardfile, source);
|
|
48
|
+
const product = shardProductData(source, pathToFileURL(root + sep).href, bytes, true, false, nodeNamedJsonCheck, { files: true });
|
|
49
|
+
const descriptor = outputDescriptor(source);
|
|
50
|
+
if (descriptor === undefined) throw new Error('Missing admitted headless inventory');
|
|
51
|
+
// Full inventory in every mode: the worker performs its own admission and
|
|
52
|
+
// must receive page assets too, not a filtered server-only bank.
|
|
53
|
+
const assets = new Map(await Promise.all(descriptor.index.files.map(async file => {
|
|
54
|
+
const ref = file.commons === true ? `commons:${file.hash}` : file.hash;
|
|
55
|
+
return [ref, await bytes(ref)] as const;
|
|
56
|
+
})));
|
|
57
|
+
return { product, assets };
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const admittedProduct = createAdmittedProductCache();
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** One checked replay request may run while its recorder captures the next
|
|
2
|
+
* bounded part. A failed request is observed immediately and drains before
|
|
3
|
+
* another part can be offered; no request or watchdog is replaced. */
|
|
4
|
+
export function checkedReplayPipeline<T>(consume:(part:T)=>Promise<void>):{
|
|
5
|
+
offer:(part:T)=>Promise<void>;check:()=>void;finish:()=>Promise<void>;stop:()=>Promise<void>;
|
|
6
|
+
} {
|
|
7
|
+
type Outcome={ok:true}|{ok:false;error:unknown};
|
|
8
|
+
let pending:Promise<Outcome>|undefined,failure:{error:unknown}|undefined,closed=false,offering=false;
|
|
9
|
+
const check=():void=>{if(failure!==undefined)throw failure.error;if(closed)throw new Error('Replay pipeline owner ended');};
|
|
10
|
+
const drain=async():Promise<void>=>{
|
|
11
|
+
const result=await pending;if(result!==undefined&&!result.ok)throw result.error;
|
|
12
|
+
};
|
|
13
|
+
return {check,offer:async part=>{
|
|
14
|
+
check();if(offering)throw new Error('Replay pipeline already has a pending offer');offering=true;
|
|
15
|
+
try{await drain();check();
|
|
16
|
+
pending=(async():Promise<Outcome>=>{try{await consume(part);return {ok:true};}
|
|
17
|
+
catch(error){failure={error};return {ok:false,error};}})();
|
|
18
|
+
}finally{offering=false;}
|
|
19
|
+
},finish:async()=>{check();if(offering)throw new Error('Replay pipeline has an unsettled offer');await drain();check();closed=true;},
|
|
20
|
+
stop:async()=>{closed=true;await pending;}};
|
|
21
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {installBounds} from '../../../client/engine/world/bounds';
|
|
2
|
+
import {floorBelow} from '../../../shared/engine/physics/query';
|
|
3
|
+
import type {Bounds} from '../../../shared/engine/level/spec';
|
|
4
|
+
import type {SimHost} from '../../../server/engine/sim';
|
|
5
|
+
import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
|
|
6
|
+
|
|
7
|
+
const declared=new WeakMap<SimHost,Bounds>();
|
|
8
|
+
const installed=new WeakSet<SimHost>();
|
|
9
|
+
/** Retain authored bounds without adding work to ordinary native replay. */
|
|
10
|
+
export function registerNativeWalkBounds(host:SimHost,bounds:Bounds|undefined):void {
|
|
11
|
+
if(bounds!==undefined)declared.set(host,bounds);
|
|
12
|
+
}
|
|
13
|
+
/** Activate the page's unchanged bounds owner only for native walk proofs. */
|
|
14
|
+
export function installNativeWalkBounds(host:SimHost):void {
|
|
15
|
+
const bounds=declared.get(host);if(bounds===undefined||installed.has(host))return;
|
|
16
|
+
installed.add(host);
|
|
17
|
+
const spawn=(x:number,z:number,yaw:number,y:number):void=>{leadPlayer(host).resetPose({x,y,z},yaw);};
|
|
18
|
+
installBounds({addSystem:(spec,scope)=>{
|
|
19
|
+
scope.onDispose(host.onStep(spec.id,dt=>{spec.run(dt,host.clock.now);},undefined,'afterBodies'));
|
|
20
|
+
}},host.scope,bounds,{
|
|
21
|
+
player:{position:leadPlayer(host).position,get yaw(){return leadPlayer(host).yaw;},
|
|
22
|
+
get onGround(){return leadPlayer(host).fall.grounded;},get hover(){return leadPlayer(host).board.on;},spawn},
|
|
23
|
+
suspended:()=>false,
|
|
24
|
+
floorAt:(x,z)=>floorBelow(host.physics,x,z,leadPlayer(host).position.y+0.6,1.2,leadPlayer(host).motor.collider),
|
|
25
|
+
toSpawn:()=>{const {at,yaw}=host.level.player;spawn(at.x,at.z,yaw,at.y);},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Write only a short diagnostic to the native child's existing stdout.
|
|
2
|
+
import {writeSync} from 'node:fs';
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- A process-wide CPU sample belongs to the recorder, not each worker thread.
|
|
4
|
+
import {isMainThread} from 'node:worker_threads';
|
|
5
|
+
|
|
6
|
+
let registered=false;
|
|
7
|
+
|
|
8
|
+
/** Observe complete real recorder processes without changing their verdict or simulation. */
|
|
9
|
+
export function recordNativeProcessUsage():void {
|
|
10
|
+
const entry=process.argv[1]?.replaceAll('\\','/').split('/').at(-1);
|
|
11
|
+
if(!isMainThread||registered)return;
|
|
12
|
+
registered=true;
|
|
13
|
+
process.once('exit',exitCode=>{
|
|
14
|
+
try{
|
|
15
|
+
const cpu=process.cpuUsage(),resources=process.resourceUsage();
|
|
16
|
+
writeSync(process.stdout.fd,JSON.stringify({diagnostic:'native-process-usage',entry,exitCode,
|
|
17
|
+
wallMs:process.uptime()*1000,userCpuMs:cpu.user/1000,systemCpuMs:cpu.system/1000,maxRssKiB:resources.maxRSS})+'\n');
|
|
18
|
+
}catch{
|
|
19
|
+
// A missing optional sample is no evidence; reporting cannot mask the original test verdict.
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-unassigned-import -- Install portable Math before simulation modules.
|
|
2
|
+
import '../../../shared/engine/core/portableMathFirst';
|
|
3
|
+
import {HeadlessSimulation} from '../../../server/host/headless';
|
|
4
|
+
import {loadHeadlessProduct} from '../../../server/host/headlessProduct';
|
|
5
|
+
import {productHeadlessSections} from '../../../shared/host/headlessSections';
|
|
6
|
+
import {outputDescriptor} from '../../../shared/game/shardfile/outputDescriptor';
|
|
7
|
+
import {builtProduct} from '../builtProduct';
|
|
8
|
+
import {createNativeProofWorker} from '../headlessWorker';
|
|
9
|
+
import {admittedProduct} from './admittedProductCache';
|
|
10
|
+
|
|
11
|
+
export type ProductSimulation = Pick<HeadlessSimulation, 'verbTape' | 'verbTapePart' | 'streamVerbTape' | 'journey' | 'walkLeg' | 'step' | 'dispose' | 'quarantined' | 'checkpoint'>;
|
|
12
|
+
export interface ProductSessionOptions {
|
|
13
|
+
/** Trusted proof composition owned by the consumer. Omit to run the product's ordinary native runtime. */
|
|
14
|
+
prepare?: URL;
|
|
15
|
+
snapshot?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Start replay admission while its caller records native input. A failed
|
|
19
|
+
* admission is observed immediately, even before the caller asks for ready(). */
|
|
20
|
+
export async function beginProductSession(slug: string, options: ProductSessionOptions = {}): Promise<{
|
|
21
|
+
ready: () => Promise<ProductSimulation>; assets: ReadonlyMap<string, Uint8Array>;
|
|
22
|
+
product: Awaited<ReturnType<typeof loadHeadlessProduct>>;
|
|
23
|
+
}> {
|
|
24
|
+
const directory = builtProduct(slug), {product,assets} = await admittedProduct(directory,'full'), source = product.shardfile;
|
|
25
|
+
if (outputDescriptor(source) === undefined) throw new Error('Missing admitted headless inventory');
|
|
26
|
+
const sections = productHeadlessSections(product);
|
|
27
|
+
const pending = options.prepare === undefined
|
|
28
|
+
? HeadlessSimulation.create(source, assets, options.snapshot, {deadline: 'advisory', sections, product: directory})
|
|
29
|
+
: createNativeProofWorker(source, assets, options.prepare, {sections, directory, ...(options.snapshot === undefined ? {} : {snapshot: options.snapshot})});
|
|
30
|
+
const outcome = (async () => {try {return {ok: true as const, sim: await pending};} catch (error) {return {ok: false as const, error};}})();
|
|
31
|
+
return {product, assets, ready: async () => {const result = await outcome; if (!result.ok) throw result.error; return result.sim;}};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function openProductSession(slug: string, options: ProductSessionOptions = {}): Promise<{
|
|
35
|
+
sim: ProductSimulation; product: Awaited<ReturnType<typeof loadHeadlessProduct>>;
|
|
36
|
+
}> {
|
|
37
|
+
const session = await beginProductSession(slug, options);
|
|
38
|
+
return {sim: await session.ready(), product: session.product};
|
|
39
|
+
}
|