@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,850 @@
1
+ import {
2
+ type IPlaytestBridgeDescription,
3
+ type IPlaytestBridgeV1,
4
+ type IPlaytestContactObservation,
5
+ type IPlaytestGameplayObservation,
6
+ type IPlaytestObservationSnapshot,
7
+ type IPlaytestSampleRequest,
8
+ type IPlaytestStrideObservation,
9
+ type IPlaytestWorldObservation,
10
+ type JsonPrimitive,
11
+ type JsonValue,
12
+ PLAYTEST_CLOCK_GLOBAL,
13
+ PLAYTEST_PROTOCOL_LIMITS,
14
+ type PlaytestClockMode,
15
+ assertJsonSafe,
16
+ requestedPlaytestClockMode,
17
+ } from "@threenative/playtest/protocol";
18
+ import { type IThreePlaytestEntity, installThreePlaytestBridge } from "@threenative/playtest/three";
19
+ import { Object3D, type Object3D as ThreeObject3D, type Vector2 } from "three";
20
+ import type { IAssetLoader } from "./assets.js";
21
+ import { audioRuntimeSnapshot } from "./audio.js";
22
+ import type { EntitySnapshot } from "./entities.js";
23
+ import type { IGameObservationContribution, IGamePluginHooks, IGamePluginRuntime } from "./game.js";
24
+ import { GEOMETRY_CAPTURE_CAPABILITY } from "./geometry-capture.js";
25
+ import { PIPELINE_CENSUS_CAPABILITY } from "./pipeline-census.js";
26
+ import { readRenderChainObservation } from "./render/chain.js";
27
+ import type { ICtx } from "./scene.js";
28
+ import { CORE_VERSION } from "./version.js";
29
+
30
+ const currentAgent = typeof navigator === "undefined" ? "node" : navigator.userAgent;
31
+
32
+ /**
33
+ * Install the playtest bridge into a portable game.
34
+ * @situation expose movement and world observations to a playtest
35
+ * @situation connect a game to the ThreeNative scenario runner
36
+ * @constraint install once in the game's plugin list
37
+ * @example const game = defineGame({ plugins: [playtest()] });
38
+ */
39
+ export function playtest<
40
+ TState extends Record<string, unknown> = Record<string, unknown>,
41
+ TPhysics = undefined,
42
+ >(options: IPlaytestOptions = {}): IGamePluginHooks<TState, TPhysics> {
43
+ let dispose: (() => void) | undefined;
44
+ let attached: Promise<void> | undefined;
45
+ let startSceneEntered: Promise<void> | undefined;
46
+ let disposePipelineCensus: (() => void) | undefined;
47
+ let disposeGeometryCapture: (() => void) | undefined;
48
+ let contactHistory: IPlaytestContactObservation[] = [];
49
+ // The tick a contact happened on, and the tick a published value changed on, are the two
50
+ // halves of "the door opened because the plate was pressed". Both are drained per tick rather
51
+ // than per sample: a sample is a step boundary, and a win arriving 199 ticks into a 200-tick
52
+ // step is indistinguishable at that granularity from one arriving with the contact.
53
+ const watcher = createTransitionWatcher();
54
+ let readTick: (() => number) | undefined;
55
+ return {
56
+ sceneExit: () => {
57
+ contactHistory = [];
58
+ watcher.reset();
59
+ },
60
+ update: (ctx) => {
61
+ const tick = readTick?.();
62
+ if (tick === undefined) return;
63
+ drainContacts(ctx, contactHistory, tick);
64
+ watcher.observe(ctx, tick);
65
+ },
66
+ setup: async (ctx, runtime) => {
67
+ readTick = runtime?.tick;
68
+ const seed = runtime?.seed ?? null;
69
+ // One decision, named once, for both consumers: the freeze below and the bridge's verdict on
70
+ // `advance`. Handing the bridge only a *requested* mode and letting it derive the rest is what
71
+ // let the two disagree — a frozen loop reported as the wall clock publishes a frame rate for a
72
+ // game that was not playing. The deterministic answer is therefore stated rather than derived,
73
+ // and stays `undefined` only when there is no tick producer to be fixed-step about.
74
+ let clockMode: PlaytestClockMode | undefined =
75
+ requestedPlaytestClockMode() ?? (runtime === undefined ? undefined : "fixed-step");
76
+ const wallClock = clockMode === "wall-clock";
77
+ const replayRuntime: IPlaytestWorldObservation["runtime"] =
78
+ runtime?.seed === null || runtime?.seed === undefined
79
+ ? undefined
80
+ : {
81
+ agent: currentAgent,
82
+ core: CORE_VERSION,
83
+ randomState: ctx.random.state,
84
+ rapier: runtime.rapier ?? null,
85
+ step: runtime.step,
86
+ };
87
+ const clockRuntime = runtime as
88
+ | (IGamePluginRuntime & {
89
+ _setClockMode?: (mode: "fixed-step" | "wall-clock") => void;
90
+ })
91
+ | undefined;
92
+ const liveAdvance = runtime === undefined ? undefined : wallClockAdvance(runtime);
93
+ const bridgeOptions: Parameters<typeof installThreePlaytestBridge>[0] = {
94
+ camera: ctx.camera,
95
+ ...(clockMode === undefined ? {} : { clockMode }),
96
+ entities: () => bridgeEntities(ctx),
97
+ components: () => componentObservations(ctx.entities.snapshot()),
98
+ // The live clock has to be driven by the host's own frame pump, so a live run's `advance`
99
+ // waits the span of wall time the count names and reports the ticks that pump ran.
100
+ ...(runtime === undefined
101
+ ? {}
102
+ : {
103
+ fixedStep: async (ticks, options) => {
104
+ // A `goto()` loads asynchronously and a counted batch is synchronous, so ticks
105
+ // spent while it loads simulate no world: a restart is outrun and the run reads
106
+ // a scene that never entered. Counted ticks wait for the scene that owns them.
107
+ await runtime.sceneTransition?.();
108
+ if (clockMode === "wall-clock" && liveAdvance !== undefined)
109
+ return liveAdvance(ticks);
110
+ let ran = runtime.fixedStep(ticks, options);
111
+ // The batch ends early when a `goto()` began inside it; the rest follows the world.
112
+ while (ran > 0 && ran < ticks) {
113
+ await runtime.sceneTransition?.();
114
+ ran += runtime.fixedStep(ticks - ran, options);
115
+ }
116
+ return ran;
117
+ },
118
+ tick: runtime.tick,
119
+ }),
120
+ ...(runtime?.runtimeDiagnosticsSeries === undefined
121
+ ? {}
122
+ : { runtimeDiagnosticsSeries: runtime.runtimeDiagnosticsSeries }),
123
+ // A driven native loop presents nothing between ticks; the render-only operation lets a
124
+ // desktop screenshot draw the standing world without spending a simulation step.
125
+ ...(runtime?.renderCurrent === undefined
126
+ ? {}
127
+ : { renderCurrent: () => runtime.renderCurrent?.() }),
128
+ ...(options.events === undefined ? {} : { events: options.events }),
129
+ gameplay: () => gameplayObservations(ctx, contactHistory, seed, replayRuntime, watcher),
130
+ gameplayChannels: () => gameplayChannels(ctx),
131
+ renderer: ctx.renderer.raw as { getDrawingBufferSize(target: Vector2): Vector2 },
132
+ renderChain: () => {
133
+ const observation = readRenderChainObservation(ctx.renderer);
134
+ return observation === undefined
135
+ ? undefined
136
+ : {
137
+ ...observation,
138
+ contributions: observation.contributions.map((contribution) => ({
139
+ ...contribution,
140
+ })),
141
+ dropped: observation.dropped.map((stage) => ({ ...stage })),
142
+ requested: [...observation.requested],
143
+ stages: [...observation.stages],
144
+ velocity: { ...observation.velocity },
145
+ };
146
+ },
147
+ resources: stateResources(ctx, runtime),
148
+ scene: ctx.scene,
149
+ // A runner advances ticks far faster than a launch completes, and compute dispatch and
150
+ // the first world present are both held behind an opaque loading layer. Published so the
151
+ // runner waits for the world rather than observing a frozen simulation behind a loader.
152
+ startup: () => ({
153
+ phase: ctx.startup.phase,
154
+ progress: ctx.startup.progress,
155
+ ...(ctx.startup.warmup === undefined ? {} : { warmup: ctx.startup.warmup }),
156
+ ...(runtime?.startupCompileSettled === undefined
157
+ ? {}
158
+ : { compileSettled: runtime.startupCompileSettled() }),
159
+ // Wall-clock milestones, so a scenario asserts startup time as an observation instead
160
+ // of reading it off a console marker after the fact.
161
+ ...(runtime?.startupTimeline === undefined
162
+ ? {}
163
+ : { timeline: runtime.startupTimeline() }),
164
+ }),
165
+ };
166
+ const installation = installThreePlaytestBridge(bridgeOptions);
167
+ let clockDisposed = false;
168
+ const clockControl = {
169
+ _clockEpoch: 0,
170
+ _setClockMode: (mode: unknown) => {
171
+ if (clockDisposed) throw new Error("Playtest clock is disposed.");
172
+ if (mode !== "fixed-step" && mode !== "wall-clock")
173
+ throw new Error("Unknown clock mode.");
174
+ clockRuntime?._setClockMode?.(mode);
175
+ if (mode !== clockMode) clockControl._clockEpoch += 1;
176
+ clockMode = mode;
177
+ bridgeOptions.clockMode = mode;
178
+ return { mode, tick: runtime?.tick(), epoch: clockControl._clockEpoch };
179
+ },
180
+ };
181
+ if (clockRuntime?._setClockMode !== undefined) {
182
+ Object.assign(installation.bridge, { _setClockMode: clockControl._setClockMode });
183
+ Object.defineProperty(installation.bridge, "_clockEpoch", {
184
+ get: () => clockControl._clockEpoch,
185
+ });
186
+ }
187
+ const pipelineCensus = runtime?.pipelineCensus;
188
+ if (runtime !== undefined && pipelineCensus !== undefined) {
189
+ disposePipelineCensus = runtime.observations.contribute({
190
+ capabilities: [PIPELINE_CENSUS_CAPABILITY],
191
+ sample: () => ({ pipelineCensus: pipelineCensus() as unknown as JsonValue }),
192
+ });
193
+ }
194
+ const geometryCapture = runtime?.geometryCapture;
195
+ if (runtime !== undefined && geometryCapture !== undefined) {
196
+ disposeGeometryCapture = runtime.observations.contribute({
197
+ capabilities: [GEOMETRY_CAPTURE_CAPABILITY],
198
+ // Nothing is armed, walked or hooked unless this request asked for a capture: the
199
+ // capability says the runtime can answer, not that every sample pays for one.
200
+ sample: async (request) =>
201
+ request.geometry === undefined
202
+ ? {}
203
+ : { geometry: (await geometryCapture(request.geometry)) as unknown as JsonValue },
204
+ });
205
+ }
206
+ installRuntimeChannels(installation.bridge, runtime);
207
+ // A runner announced itself: it is the one consumer of per-frame render samples, so
208
+ // collection turns on exactly for playtest runs and stays off for every plain `pnpm dev`
209
+ // frame. It reads the same predicate as the boot hold below, because gating collection on
210
+ // the browser's half alone left every device and desktop run with an empty
211
+ // `runtimeDiagnosticsSeries` under an advertised `runtime.performance` — a native host
212
+ // announces itself through `TN_PLAYTEST_ENDPOINT`, not through the expected global.
213
+ if (runnerAnnounced()) {
214
+ runtime?.enableRuntimeDiagnostics?.();
215
+ // Same predicate, same reason, one window later. The hold below covers the boot, and the
216
+ // hold ends the moment the runner attaches -- but the runner then pumps live frames for
217
+ // the rAF warmup and for the whole startup wait before it takes its first observation, and
218
+ // every one of those frames advanced the game on the wall clock. So the simulation time a
219
+ // tick-counting scenario sees before its own first tick was a function of how fast the
220
+ // machine booted. The loop is frozen here instead: from the first frame of the run, ticks
221
+ // are the only clock, which is what the run is already counting.
222
+ //
223
+ // A run that asked for the wall clock is the one consumer that wants the opposite: it
224
+ // measures a frame rate for a game, and the frozen loop's presented frames repeat a
225
+ // standing state while the scenario's ticks arrive in bursts — a profile of a game that is
226
+ // not playing. It asked by name, so it is not frozen.
227
+ if (!wallClock) runtime?.freezeClock?.();
228
+ }
229
+ dispose = installation.dispose;
230
+ attached = holdUntilAttached(installation.bridge, options, () => startSceneEntered);
231
+ const cleanup = () => {
232
+ if (!clockDisposed && clockRuntime?._setClockMode !== undefined)
233
+ clockControl._setClockMode("fixed-step");
234
+ clockDisposed = true;
235
+ disposePipelineCensus?.();
236
+ disposePipelineCensus = undefined;
237
+ disposeGeometryCapture?.();
238
+ disposeGeometryCapture = undefined;
239
+ dispose?.();
240
+ dispose = undefined;
241
+ attached = undefined;
242
+ startSceneEntered = undefined;
243
+ contactHistory = [];
244
+ readTick = undefined;
245
+ watcher.reset();
246
+ };
247
+ // Hand the hold to the game rather than blocking this plugin's setup. The game waits after
248
+ // load() has registered setup placeholders but before enter() transfers them into live state.
249
+ // describe() releases a no-setup run and waits for the returned scene-enter signal before it
250
+ // reads entity-derived capabilities.
251
+ if (attached !== undefined) {
252
+ const gate = attached.catch((error: unknown) => {
253
+ cleanup();
254
+ throw error;
255
+ });
256
+ if (runtime?.holdStart === undefined) await gate;
257
+ else {
258
+ startSceneEntered = runtime.holdStart(gate);
259
+ // describe() awaits the same promise when called. Attach a rejection handler now so a
260
+ // setup failure cannot become an unhandled rejection when the runner stops at applySetup.
261
+ void startSceneEntered.catch(() => undefined);
262
+ }
263
+ }
264
+ return cleanup;
265
+ },
266
+ };
267
+ }
268
+
269
+ export const PLAYTEST_ATTACH_TIMEOUT_MS = 30_000;
270
+
271
+ /**
272
+ * Resolves when a runner first calls `describe()`, the handshake every runner performs before
273
+ * it observes anything.
274
+ *
275
+ * Without this, a scenario races the game: a proof that does finite work at startup can finish
276
+ * before the runner takes its first observation, and the assertion then reports
277
+ * TN_PLAYTEST_ASSERTION_TRIVIAL or a zero-delta failure depending only on how fast the device
278
+ * booted. Opt-in, because a game that holds for a runner that never arrives is worse than the
279
+ * race for every non-test caller.
280
+ *
281
+ * Fails closed: if no runner attaches within the timeout, setup throws rather than quietly
282
+ * starting anyway and reproducing the race it was added to remove.
283
+ */
284
+ /** The global a playtest runner sets before the page loads, so a game can tell one is coming. */
285
+ export const PLAYTEST_RUNNER_EXPECTED_GLOBAL = "__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__";
286
+
287
+ /**
288
+ * The clock a consumer asks this game to run on, named in the protocol's own vocabulary. Set before
289
+ * the game module evaluates — a production profile does it in the instrumentation it injects ahead
290
+ * of the bundle, on the browser and on native alike, and the browser runner's `--live-clock` does it
291
+ * in an `addInitScript` ahead of every page script.
292
+ *
293
+ * The read and its failure live in the protocol beside the mode they name, so the loop's clock, the
294
+ * bridge's verdict on it and the producer a game installs itself cannot disagree about it.
295
+ */
296
+ export { PLAYTEST_CLOCK_GLOBAL };
297
+
298
+ /**
299
+ * How long a live advance waits for the pump's own tick past the span its ticks name.
300
+ *
301
+ * The room this buys has to be wall time, not a number of fixed slices, because the thing being
302
+ * waited for is a frame and a frame costs what the machine costs: four slices is 33 ms, which is half
303
+ * a frame on the 15 fps host the old bound claimed to cover and a fraction of one on anything
304
+ * slower — and the 2026-10-04 CI host measured 55-59 ms, where those four slices ended at 50.0 ms
305
+ * and read that slow pump as a dead one. Eight slices only bought 83.3 ms, which is still named
306
+ * against a machine the runner was about to measure. The runner counts a wait in ten-tick pieces, so
307
+ * each piece named a 166 ms span and then a few more slices — and Machinefall's map-walk standing
308
+ * scene died on exactly that at load average 142, with the world plainly drawing at 20 fps in the
309
+ * windows either side. A measurement whose subject is a slow machine cannot refuse to measure one.
310
+ *
311
+ * A one-tick request names exactly one frame interval, so a wait that ended on that boundary ran
312
+ * just before the host's next frame and observed nothing: the 2026-09-28 desktop pair failed on
313
+ * that at 58 mean fps. The tick has to come from the pump, and only a pump that has genuinely
314
+ * stopped may end the wait without one.
315
+ */
316
+ const WALL_CLOCK_PUMP_TIMEOUT_MS = 1_000;
317
+
318
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
319
+
320
+ /**
321
+ * The live-clock stand-in for `runtime.fixedStep`: deliver the span of wall time `ticks` fixed steps
322
+ * would cover, and report the ticks the host's own frame pump ran in it.
323
+ *
324
+ * Waiting rather than stepping is the whole point. The loop is not frozen on this path, so the host
325
+ * keeps presenting frames for the whole span and every one of them advances the game at the fixed
326
+ * step's own rate — a run whose simulation rate is the machine's frame rate, which is what a
327
+ * profile is for. It also means the runner needs nothing new: it still asks for tick counts and
328
+ * still batches them, and a burst costs the wall time it always claimed to cost.
329
+ */
330
+ function wallClockAdvance(runtime: IGamePluginRuntime): (ticks: number) => Promise<number> {
331
+ const stepMs = runtime.step * 1_000;
332
+ return async (ticks) => {
333
+ const before = runtime.tick();
334
+ await sleep(ticks * stepMs);
335
+ // The span is the floor, not the end: a host whose next frame lands just after it has still
336
+ // presented nothing to report. Keep waiting for the pump's own tick, in half-step slices, and
337
+ // never take one here — the loop is the host's, and a tick invented here would be the profile
338
+ // measuring itself. The deadline is the bound, so a pump that has stopped is a fast failure
339
+ // carrying zero rather than a wait that never ends.
340
+ const deadline = Date.now() + WALL_CLOCK_PUMP_TIMEOUT_MS;
341
+ while (runtime.tick() === before && Date.now() < deadline) await sleep(stepMs / 2);
342
+ return runtime.tick() - before;
343
+ };
344
+ }
345
+
346
+ /**
347
+ * Hold when told to, and by default whenever a browser or native runner announced itself.
348
+ *
349
+ * Without it a scenario races the boot, and how much simulation elapses before the first
350
+ * observation depends on how fast the machine renders — measured on action-rpg's combat
351
+ * scenario, player health 90 on SwiftShader and 95 on a real GPU from the same build. Keyed off
352
+ * the runner rather than off the plugin being installed, because every template installs
353
+ * `playtest()` unconditionally and a game that holds for a runner who never arrives is broken
354
+ * for whoever ran `pnpm dev`. Browser runners set the expected global before navigation; native
355
+ * hosts expose `TN_PLAYTEST_ENDPOINT` when a device/desktop transport is attached.
356
+ */
357
+ function shouldHoldUntilAttached(options: IPlaytestOptions): boolean {
358
+ if (options.holdUntilAttached !== undefined) return options.holdUntilAttached;
359
+ return runnerAnnounced();
360
+ }
361
+
362
+ /**
363
+ * Whether a runner announced itself, whichever lane it came from.
364
+ *
365
+ * Browser runners set the expected global before navigation; a native host exposes
366
+ * `TN_PLAYTEST_ENDPOINT` when a device or desktop transport is attached. Both decisions that
367
+ * depend on an announcement — holding the boot, and turning per-frame render collection on — read
368
+ * this one predicate: they were written separately once, and the collection half shipped with only
369
+ * the browser branch, so every device and desktop run answered an advertised
370
+ * `runtime.performance` with an empty series.
371
+ */
372
+ function runnerAnnounced(): boolean {
373
+ const host = globalThis as Record<string, unknown>;
374
+ return host[PLAYTEST_RUNNER_EXPECTED_GLOBAL] === true || host.TN_PLAYTEST_ENDPOINT !== undefined;
375
+ }
376
+
377
+ function holdUntilAttached(
378
+ bridge: IPlaytestBridgeV1,
379
+ options: IPlaytestOptions,
380
+ startSceneEntered: () => Promise<void> | undefined,
381
+ ): Promise<void> | undefined {
382
+ if (!shouldHoldUntilAttached(options)) return undefined;
383
+ const timeoutMs = options.attachTimeoutMs ?? PLAYTEST_ATTACH_TIMEOUT_MS;
384
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
385
+ throw new Error(`TN_PLAYTEST_ATTACH_TIMEOUT_INVALID: ${String(options.attachTimeoutMs)}`);
386
+ }
387
+ const describe = bridge.describe;
388
+ const applySetup = bridge.applySetup;
389
+ return new Promise<void>((resolve, reject) => {
390
+ let settled = false;
391
+ const timer = setTimeout(() => {
392
+ settled = true;
393
+ reject(
394
+ new Error(
395
+ `TN_PLAYTEST_ATTACH_TIMEOUT: no playtest runner applied setup or called describe() within ${timeoutMs}ms.`,
396
+ ),
397
+ );
398
+ }, timeoutMs);
399
+ // Node keeps the process alive for a pending timer; a held game must not outlive its host.
400
+ timer.unref?.();
401
+ const release = () => {
402
+ if (settled) return;
403
+ settled = true;
404
+ clearTimeout(timer);
405
+ resolve();
406
+ };
407
+ const fail = (error: unknown) => {
408
+ if (settled) return;
409
+ settled = true;
410
+ clearTimeout(timer);
411
+ reject(error);
412
+ };
413
+ if (applySetup !== undefined) {
414
+ bridge.applySetup = async (request) => {
415
+ try {
416
+ const confirmation = await applySetup(request);
417
+ release();
418
+ return confirmation;
419
+ } catch (error) {
420
+ fail(error);
421
+ throw error;
422
+ }
423
+ };
424
+ }
425
+ bridge.describe = async () => {
426
+ release();
427
+ await startSceneEntered();
428
+ return describe();
429
+ };
430
+ });
431
+ }
432
+
433
+ export interface IPlaytestOptions {
434
+ readonly events?: () => JsonValue[];
435
+ /**
436
+ * Hold start-scene entry until a runner attaches. Defaults on for an announced runner.
437
+ */
438
+ readonly holdUntilAttached?: boolean;
439
+ /** Milliseconds to wait when `holdUntilAttached` is set. Default {@link PLAYTEST_ATTACH_TIMEOUT_MS}. */
440
+ readonly attachTimeoutMs?: number;
441
+ }
442
+
443
+ function installRuntimeChannels(
444
+ bridge: IPlaytestBridgeV1,
445
+ runtime: IGamePluginRuntime | undefined,
446
+ ): void {
447
+ const describe = bridge.describe;
448
+ bridge.describe = () =>
449
+ Promise.resolve(describe()).then((description) =>
450
+ addRuntimeCapabilities(description, runtime?.observations.contributions() ?? []),
451
+ );
452
+ const sample = bridge.sample;
453
+ bridge.sample = (request) =>
454
+ Promise.resolve(sample(request)).then((snapshot) =>
455
+ addRuntimeObservations(snapshot, request, runtime?.observations.contributions() ?? []),
456
+ );
457
+ }
458
+ function addRuntimeCapabilities(
459
+ description: IPlaytestBridgeDescription,
460
+ contributions: readonly IGameObservationContribution[],
461
+ ): IPlaytestBridgeDescription {
462
+ const capabilities = [...description.capabilities];
463
+ const contributed = contributions.flatMap(({ capabilities }) => capabilities);
464
+ for (const capability of ["runtime.audio", "runtime.world", ...contributed]) {
465
+ if (!capabilities.includes(capability)) capabilities.push(capability);
466
+ }
467
+ return { ...description, capabilities };
468
+ }
469
+ async function addRuntimeObservations(
470
+ snapshot: IPlaytestObservationSnapshot,
471
+ request: IPlaytestSampleRequest,
472
+ contributions: readonly IGameObservationContribution[],
473
+ ): Promise<IPlaytestObservationSnapshot> {
474
+ const result: Record<string, unknown> = { ...snapshot };
475
+ for (const contribution of contributions) {
476
+ // Awaited in order: an observation that waits for a presented frame — a geometry capture —
477
+ // cannot be produced inside the request that asked for it, and the collision check below has
478
+ // to see the slices in a stable order.
479
+ const slice = await contribution.sample(request);
480
+ if (typeof slice !== "object" || slice === null || Array.isArray(slice)) {
481
+ throw new TypeError("A runtime observation contribution must return a top-level object.");
482
+ }
483
+ assertJsonSafe(slice, "$.runtimeContribution");
484
+ for (const [key, value] of Object.entries(slice)) {
485
+ if (Object.hasOwn(result, key)) {
486
+ throw new Error(
487
+ `TN_PLAYTEST_OBSERVATION_COLLISION: top-level key '${key}' already exists.`,
488
+ );
489
+ }
490
+ result[key] = value;
491
+ }
492
+ }
493
+ // quality-allow: every contributed value is validated as JSON-safe immediately above.
494
+ return result as unknown as IPlaytestObservationSnapshot;
495
+ }
496
+ function runtimeObservation(
497
+ seed: number | null,
498
+ replayRuntime: IPlaytestWorldObservation["runtime"],
499
+ ): { audio: ReturnType<typeof audioRuntimeSnapshot>; world: IPlaytestWorldObservation } {
500
+ return {
501
+ audio: audioRuntimeSnapshot(),
502
+ world: {
503
+ seed,
504
+ ...(replayRuntime === undefined ? {} : { runtime: replayRuntime }),
505
+ },
506
+ };
507
+ }
508
+ function bridgeEntities<TState extends Record<string, unknown>, TPhysics>(
509
+ ctx: ICtx<TState, TPhysics>,
510
+ ): IThreePlaytestEntity[] {
511
+ return [
512
+ { id: "camera.main", object: ctx.camera },
513
+ ...Object.keys(ctx.entities.snapshot()).flatMap((id) => {
514
+ const object = entityObject(ctx.entities.get(id));
515
+ return object === undefined ? [] : [{ id, object }];
516
+ }),
517
+ ];
518
+ }
519
+ function entityObject(entity: object | undefined): ThreeObject3D | undefined {
520
+ if (entity instanceof Object3D) return entity;
521
+ const candidate =
522
+ (entity as { mesh?: unknown; object?: unknown } | undefined)?.mesh ??
523
+ (entity as { mesh?: unknown; object?: unknown } | undefined)?.object;
524
+ return candidate instanceof Object3D ? candidate : undefined;
525
+ }
526
+ function gameplayObservations<TState extends Record<string, unknown>, TPhysics>(
527
+ ctx: ICtx<TState, TPhysics>,
528
+ contactHistory: IPlaytestContactObservation[],
529
+ seed: number | null,
530
+ replayRuntime: IPlaytestWorldObservation["runtime"],
531
+ watcher: ITransitionWatcher,
532
+ ): IPlaytestGameplayObservation {
533
+ const animation: IPlaytestGameplayObservation["animation"] = {};
534
+ const states: IPlaytestGameplayObservation["states"] = {};
535
+ const snapshot = ctx.entities.snapshot();
536
+ for (const id of Object.keys(snapshot)) {
537
+ const entity = ctx.entities.get(id) as
538
+ | {
539
+ animation?: {
540
+ advancedFrames?: unknown;
541
+ current?: unknown;
542
+ finished?: unknown;
543
+ stride?: unknown;
544
+ };
545
+ state?: unknown;
546
+ }
547
+ | undefined;
548
+ const finished =
549
+ typeof entity?.animation?.finished === "boolean" ? entity.animation.finished : undefined;
550
+ if (
551
+ typeof entity?.animation?.current === "string" &&
552
+ typeof entity.animation.advancedFrames === "number"
553
+ ) {
554
+ const stride = strideObservation(entity.animation.stride);
555
+ animation[id] = {
556
+ advancedFrames: entity.animation.advancedFrames,
557
+ clip: entity.animation.current,
558
+ ...(finished === undefined ? {} : { finished }),
559
+ ...(stride === undefined ? {} : { stride }),
560
+ };
561
+ }
562
+ if (typeof entity?.state === "string") states[id] = entity.state;
563
+ }
564
+ const channels = gameplayChannels(ctx);
565
+ // The per-tick update hook has already drained everything that happened since the last sample
566
+ // and stamped each event with its tick. This final drain catches a run whose bridge is sampled
567
+ // without the loop having ticked — a paused game, a wall-clock scenario — and stamps those with
568
+ // the tick the loop last reported. Contacts are never dropped for want of a tick.
569
+ const contacts = channels.includes("runtime.contacts")
570
+ ? drainContacts(ctx, contactHistory, watcher.lastTick())
571
+ : undefined;
572
+ const tags = channels.includes("runtime.tags") ? tagCounts(snapshot) : undefined;
573
+ const transitions = watcher.read();
574
+ return {
575
+ animation,
576
+ ...(contacts === undefined ? {} : { contacts }),
577
+ states,
578
+ ...(tags === undefined ? {} : { tags }),
579
+ ...(transitions === undefined ? {} : { transitions }),
580
+ ...runtimeObservation(seed, replayRuntime),
581
+ };
582
+ }
583
+ /**
584
+ * Read an animation player's stride report, or report nothing.
585
+ *
586
+ * A partially shaped report is dropped whole rather than filled in: a stride number the producer
587
+ * did not measure would be read downstream as a measurement, and the one thing this harness may
588
+ * never do is hand back an unmeasured zero. `strideSync: false` still reports — that is the
589
+ * override being honest about what it turned off.
590
+ */
591
+ function strideObservation(value: unknown): IPlaytestStrideObservation | undefined {
592
+ if (typeof value !== "object" || value === null) return undefined;
593
+ const report = value as Record<string, unknown>;
594
+ const numbers = ["clipGroundSpeed", "groundSpeed", "rate"] as const;
595
+ const flags = ["overridden", "synced"] as const;
596
+ if (!numbers.every((key) => typeof report[key] === "number" && Number.isFinite(report[key])))
597
+ return undefined;
598
+ if (!flags.every((key) => typeof report[key] === "boolean")) return undefined;
599
+ return {
600
+ clipGroundSpeed: report.clipGroundSpeed as number,
601
+ groundSpeed: report.groundSpeed as number,
602
+ overridden: report.overridden as boolean,
603
+ rate: report.rate as number,
604
+ synced: report.synced as boolean,
605
+ };
606
+ }
607
+
608
+ type GameplayChannel = "runtime.contacts" | "runtime.tags" | "runtime.transitions";
609
+ interface IContactEvent {
610
+ /** The area that observed the contact, when the source reports one. */
611
+ readonly area?: object;
612
+ readonly body: object;
613
+ readonly entity?: string;
614
+ readonly started: boolean;
615
+ }
616
+ interface IContactSource {
617
+ drainContacts(): readonly IContactEvent[];
618
+ }
619
+
620
+ function gameplayChannels<TState extends Record<string, unknown>, TPhysics>(
621
+ _ctx: ICtx<TState, TPhysics>,
622
+ ): GameplayChannel[] {
623
+ return ["runtime.contacts", "runtime.tags", "runtime.transitions"];
624
+ }
625
+ function drainContacts<TState extends Record<string, unknown>, TPhysics>(
626
+ ctx: ICtx<TState, TPhysics>,
627
+ history: IPlaytestContactObservation[],
628
+ tick: number | undefined,
629
+ ): IPlaytestContactObservation[] {
630
+ // Build the value→id index without extracting debug fields. First id wins per value, matching
631
+ // the insertion-order find it replaced.
632
+ const idsByEntity = new Map<object, string>();
633
+ ctx.entities.forEach((id, registered) => {
634
+ for (const value of objectGraphValues(registered))
635
+ if (!idsByEntity.has(value)) idsByEntity.set(value, id);
636
+ });
637
+ ctx.entities.forEach((_id, registered) => {
638
+ for (const source of entitySources(registered)) {
639
+ for (const event of source.drainContacts()) {
640
+ const entity = idsByEntity.get(event.body);
641
+ // The area's own `entity` option names the far side of the contact. A game that
642
+ // registered the area under a scene-registry id has already named it, and requiring the
643
+ // option again meant a demonstrably firing trigger reported no contact at all — a green
644
+ // `contacts` assertion over a run whose own state proved the overlap happened.
645
+ const other =
646
+ event.entity ??
647
+ (event.area === undefined ? undefined : idsByEntity.get(event.area)) ??
648
+ idsByEntity.get(source);
649
+ if (entity === undefined || other === undefined) continue;
650
+ history.push({
651
+ entity,
652
+ kind: event.started ? "trigger" : "trigger.exit",
653
+ ...(tick === undefined ? {} : { tick }),
654
+ with: other,
655
+ });
656
+ if (history.length > PLAYTEST_PROTOCOL_LIMITS.maxEventsPerDrain) history.shift();
657
+ }
658
+ }
659
+ });
660
+ return [...history];
661
+ }
662
+ /**
663
+ * When a published value changed, and to what — the other half of "because".
664
+ *
665
+ * A run has always been able to say *a contact happened* and *the state reads `won`*. Nothing
666
+ * related the two, and a scenario could only compare at step boundaries, where a win arriving one
667
+ * tick after the contact and a win arriving 199 ticks later inside the same step are the same
668
+ * observation. That is exactly the shape of a game whose terminal state comes from a timer or a
669
+ * distance check and merely happens to land near a contact.
670
+ *
671
+ * The watcher diffs the published surface once per tick and records every change with the tick it
672
+ * happened on. It watches what a scenario can name: each registered entity's `state`, and the
673
+ * top-level primitive fields of the game's own published state. A deeper path is not watched, and
674
+ * an assertion about one fails closed rather than being answered from a value nobody diffed.
675
+ */
676
+ export const PLAYTEST_TRANSITION_LOG_LIMIT = 512;
677
+
678
+ export interface IPlaytestTransition {
679
+ from: JsonPrimitive;
680
+ /** `states.<entity>` for a registered entity, or `state.<field>` for a published field. */
681
+ path: string;
682
+ tick: number;
683
+ to: JsonPrimitive;
684
+ }
685
+
686
+ interface ITransitionWatcher {
687
+ lastTick(): number | undefined;
688
+ observe<TState extends Record<string, unknown>, TPhysics>(
689
+ ctx: ICtx<TState, TPhysics>,
690
+ tick: number,
691
+ ): void;
692
+ read(): IPlaytestTransition[] | undefined;
693
+ reset(): void;
694
+ }
695
+
696
+ function primitiveOrUndefined(value: unknown): JsonPrimitive | undefined {
697
+ if (value === null) return null;
698
+ if (typeof value === "string" || typeof value === "boolean") return value;
699
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
700
+ }
701
+
702
+ function createTransitionWatcher(): ITransitionWatcher {
703
+ let previous = new Map<string, JsonPrimitive>();
704
+ let log: IPlaytestTransition[] = [];
705
+ let seen = false;
706
+ let tickSeen: number | undefined;
707
+ const record = (path: string, to: JsonPrimitive, tick: number): void => {
708
+ const had = previous.has(path);
709
+ const from = previous.get(path);
710
+ previous.set(path, to);
711
+ // The first value a path ever reports is its initial value, not a transition. Recording it as
712
+ // one would make every scenario's `neverBefore` fail against the game's own starting state.
713
+ if (!had || from === to) return;
714
+ log.push({ from: from as JsonPrimitive, path, tick, to });
715
+ if (log.length > PLAYTEST_TRANSITION_LOG_LIMIT) log.shift();
716
+ };
717
+ return {
718
+ lastTick: () => tickSeen,
719
+ observe: (ctx, tick) => {
720
+ tickSeen = tick;
721
+ seen = true;
722
+ ctx.entities.forEach((id, entity) => {
723
+ const candidate = entity as { state?: unknown };
724
+ if (typeof candidate.state === "string") record(`states.${id}`, candidate.state, tick);
725
+ });
726
+ // The store is read without flushing: a flush is a publish to the UI, and an observer must
727
+ // not change when the game's own subscribers run.
728
+ const state = ctx.state.getState() as Record<string, unknown>;
729
+ for (const key of Object.keys(state)) {
730
+ const value = primitiveOrUndefined(state[key]);
731
+ if (value !== undefined) record(`state.${key}`, value, tick);
732
+ }
733
+ },
734
+ // Absent until the loop has ticked at least once. A run that never ticked has not observed
735
+ // that nothing changed; it has observed nothing, and an assertion against it must say so.
736
+ read: () => (seen ? log.map((entry) => ({ ...entry })) : undefined),
737
+ reset: () => {
738
+ previous = new Map();
739
+ log = [];
740
+ seen = false;
741
+ tickSeen = undefined;
742
+ },
743
+ };
744
+ }
745
+
746
+ function entitySources(entity: object | undefined): IContactSource[] {
747
+ return objectGraphValues(entity).filter(
748
+ (value): value is IContactSource =>
749
+ "drainContacts" in value &&
750
+ typeof (value as { drainContacts?: unknown }).drainContacts === "function",
751
+ );
752
+ }
753
+
754
+ /** Walk registered fields far enough to reach the physics adapter without traversing Three's graph. */
755
+ function objectGraphValues(root: object | undefined): object[] {
756
+ if (root === undefined) return [];
757
+ const values: object[] = [];
758
+ const visited = new Set<object>();
759
+ const visit = (value: unknown, depth: number): void => {
760
+ if (value === null || typeof value !== "object" || visited.has(value)) return;
761
+ visited.add(value);
762
+ values.push(value);
763
+ if (depth >= 4 || value instanceof Object3D) return;
764
+ for (const child of Object.values(value)) visit(child, depth + 1);
765
+ };
766
+ visit(root, 0);
767
+ return values;
768
+ }
769
+
770
+ function tagCounts(snapshot: EntitySnapshot): Record<string, { count: number }> {
771
+ const counts: Record<string, { count: number }> = {};
772
+ for (const fields of Object.values(snapshot)) {
773
+ for (const tag of fields.tags ?? []) counts[tag] = { count: (counts[tag]?.count ?? 0) + 1 };
774
+ }
775
+ return counts;
776
+ }
777
+
778
+ function componentObservations(
779
+ snapshot: EntitySnapshot,
780
+ ): Record<string, Record<string, JsonValue>> {
781
+ const components: Record<string, Record<string, JsonValue>> = {};
782
+ for (const [id, fields] of Object.entries(snapshot)) {
783
+ if (Object.keys(fields).length === 0) continue;
784
+ assertJsonSafe(fields, `$.components.${id}`);
785
+ components[id] = fields as Record<string, JsonValue>;
786
+ }
787
+ return components;
788
+ }
789
+
790
+ function stateResources<TState extends Record<string, unknown>, TPhysics>(
791
+ ctx: ICtx<TState, TPhysics>,
792
+ runtime: IGamePluginRuntime | undefined,
793
+ ) {
794
+ return {
795
+ read: () => {
796
+ ctx.state.flush();
797
+ const state = ctx.state.getState();
798
+ assertJsonSafe(state);
799
+ // A bridge sample is an observation, not a live view. The store's current object is
800
+ // mutated in place by later patches and scene resets; returning it directly makes an
801
+ // earlier `before` sample change when a menu navigates to the next scene.
802
+ const value = cloneJsonValue(state) as Record<string, JsonValue>;
803
+ return Object.fromEntries([
804
+ // `state` is canonical. Keep `GameState` as a compatibility alias until published
805
+ // scenarios have migrated, then remove the alias in a future breaking release.
806
+ ["state", value],
807
+ ["GameState", value],
808
+ // Where every asset was actually served from, on every target and not only in a browser
809
+ // console log: a game whose manifest never loaded runs on the uncompiled source directory
810
+ // and looks healthy, and without this nothing observable says so.
811
+ ["assets", assetResolutions(ctx.assets)],
812
+ ...(runtime?.frameCounts === undefined
813
+ ? []
814
+ : [["__threenativeFrameCounts", runtime.frameCounts()]]),
815
+ ]);
816
+ },
817
+ };
818
+ }
819
+
820
+ /**
821
+ * The asset loader's `resolved` ledger, nested on the dots of each logical path.
822
+ *
823
+ * An observation path addresses a value with dots, so a logical path — which is itself dotted —
824
+ * cannot be a key here without being split first. Nesting keeps it lossless and makes
825
+ * `path: "native-proof.png.via"` read as what it is.
826
+ */
827
+ function assetResolutions(assets: IAssetLoader): Record<string, JsonValue> {
828
+ const nested: Record<string, JsonValue> = {};
829
+ for (const [logical, record] of assets.resolved) {
830
+ const parts = logical.split(".");
831
+ let node = nested;
832
+ for (const part of parts.slice(0, -1)) {
833
+ const child = (node[part] ?? {}) as Record<string, JsonValue>;
834
+ node[part] = child;
835
+ node = child;
836
+ }
837
+ node[parts.at(-1) ?? logical] = { url: record.url, via: record.via };
838
+ }
839
+ return nested;
840
+ }
841
+
842
+ function cloneJsonValue(value: JsonValue): JsonValue {
843
+ if (Array.isArray(value)) return value.map((item) => cloneJsonValue(item));
844
+ if (typeof value === "object" && value !== null) {
845
+ return Object.fromEntries(
846
+ Object.entries(value).map(([key, item]) => [key, cloneJsonValue(item)]),
847
+ );
848
+ }
849
+ return value;
850
+ }