@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,995 @@
1
+ import type { AutoBatch } from "./auto-batch.js";
2
+ import { updateClusteredMeshes } from "./clustered-mesh.js";
3
+ import type { ComputeDrivenRegistry } from "./compute-driven.js";
4
+ import type { Registry } from "./entities.js";
5
+ import { FrameBudget } from "./frame-budget.js";
6
+ import { isDevLaunch } from "./game-dev-tools.js";
7
+ import {
8
+ combineRenderPerformanceMetrics,
9
+ rendererDrawCallCount,
10
+ rendererPerformanceMetrics,
11
+ resetRendererPerformanceMetrics,
12
+ } from "./game-renderer-metrics.js";
13
+ import { STARTUP_HANDOFF_FRAMES } from "./game-startup.js";
14
+ import type { IGameStartup } from "./game-startup.js";
15
+ import type { IGameConfig, IGamePlatformSource, IGamePluginHooks, PluginCleanup } from "./game.js";
16
+ import { GeometryCapture, rendererBackendIdentity } from "./geometry-capture.js";
17
+ import type { InputMap } from "./input.js";
18
+ import type { PhysicsInterpolation } from "./interpolation.js";
19
+ import type { IAfterPhysicsPhase } from "./loop.js";
20
+ import { FixedStepLoop, type IRenderPerformanceMetrics } from "./loop.js";
21
+ import type { MatrixWorldPass } from "./matrix-world.js";
22
+ import { updateModelLods } from "./model-lod.js";
23
+ import type { ScenePicker } from "./picking.js";
24
+ import { getPlatform } from "./platform.js";
25
+ import type { PointerEvents3D } from "./pointer-events.js";
26
+ import {
27
+ FrameCounters,
28
+ counterDeviceOf,
29
+ createCrossingReader,
30
+ createEngineCounterReader,
31
+ } from "./profiling/FrameCounters.js";
32
+ import {
33
+ createStageReader,
34
+ createWorkReader,
35
+ stageMetersRequested,
36
+ } from "./profiling/FrameStages.js";
37
+ import {
38
+ SPANS,
39
+ SpanRecorder,
40
+ addSpan,
41
+ beginSpan,
42
+ endSpan,
43
+ formatSpansWindow,
44
+ setSpanRecorder,
45
+ spanNow,
46
+ spansRequested,
47
+ } from "./profiling/Spans.js";
48
+ import { countDebug, measureDebug, observeDebugGc } from "./profiling/debug-telemetry.js";
49
+ import {
50
+ RenderListValidator,
51
+ formatValidationReport,
52
+ renderListValidationRequested,
53
+ } from "./profiling/render-list-validate.js";
54
+ import {
55
+ describeSceneShape,
56
+ describeSceneWarning,
57
+ formatSceneWarning,
58
+ sceneWarning,
59
+ } from "./profiling/scene-warning.js";
60
+ import { installSpanProbes } from "./profiling/span-probes.js";
61
+ import { formatProjectionWindow } from "./projection-marker.js";
62
+ import type { RenderCameraCull } from "./render-camera-cull.js";
63
+ import { RenderPassBudget } from "./render-pass-budget.js";
64
+ import type { VirtualShadowNode } from "./render/virtual-shadow.js";
65
+ import type { SceneRenderProjection } from "./renderProjection.js";
66
+ import { resolvePlatformResolutionFloor } from "./renderer-config.js";
67
+ import type { IRendererLike } from "./renderer.js";
68
+ import { rendererFrameGateSkips, rendererWorldPresented } from "./renderer.js";
69
+ import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
70
+ import type { ICtx, Scene, SceneFrame } from "./scene.js";
71
+ import type { Scheduler } from "./schedule.js";
72
+ import { STARTUP_STABLE_WINDOW_MS } from "./startup-readiness.js";
73
+ import type { GameStore } from "./state.js";
74
+ import {
75
+ STATIC_TRANSFORM_MARKER,
76
+ refreshStaticTransforms,
77
+ staticRoots,
78
+ staticTransformCensus,
79
+ } from "./static-transform.js";
80
+ import { resolveTargetFps } from "./target-fps.js";
81
+ import type { IUiBridge } from "./ui-bridge.js";
82
+ import { UI_DEV_METRICS_MESSAGE } from "./ui-bridge.js";
83
+ import type { Viewport } from "./viewport.js";
84
+ import type { IWarmUpOptions } from "./warmup.js";
85
+
86
+ /**
87
+ * The game's own state, as a boot phase sees it: every member is the private field of the same
88
+ * name, so a phase assigns and reads exactly what it did inside the class.
89
+ */
90
+ export interface IGameBootGame<TState extends Record<string, unknown>, TPhysics> {
91
+ /** The cleanups `#teardown` drains in its own release step, in the order they were pushed. */
92
+ readonly cleanup: Array<() => void>;
93
+ readonly computeDriven: ComputeDrivenRegistry;
94
+ readonly config: IGameConfig<TState, TPhysics>;
95
+ readonly platform: IGamePlatformSource | undefined;
96
+ readonly state: GameStore<TState>;
97
+ readonly beforeRenderCallbacks: Set<() => void>;
98
+ readonly activePlugins: Array<IGamePluginHooks<TState, TPhysics>>;
99
+ readonly uiBridge: IUiBridge | undefined;
100
+ readonly sceneFrame: SceneFrame<TState, TPhysics> | undefined;
101
+ readonly sceneEntered: boolean;
102
+ readonly sceneGeneration: number;
103
+ readonly pendingSceneEnter: Promise<void> | undefined;
104
+ readonly paused: boolean;
105
+ readonly aborted: boolean;
106
+ readonly uiReady: boolean;
107
+ // Assigned by a phase, exactly as the field was.
108
+ renderer: IRendererLike | undefined;
109
+ scene: Scene<TState, TPhysics> | undefined;
110
+ sceneName: string | undefined;
111
+ ctx: ICtx<TState, TPhysics> | undefined;
112
+ input: InputMap | undefined;
113
+ viewport: Viewport | undefined;
114
+ picker: ScenePicker | undefined;
115
+ pointerEvents: PointerEvents3D | undefined;
116
+ matrixWorld: MatrixWorldPass | undefined;
117
+ projection: SceneRenderProjection | undefined;
118
+ autoBatch: AutoBatch | undefined;
119
+ cameraCull: RenderCameraCull | undefined;
120
+ entities: Registry | undefined;
121
+ scheduler: Scheduler | undefined;
122
+ afterPhysicsPhase: IAfterPhysicsPhase | undefined;
123
+ frameBudget: FrameBudget | undefined;
124
+ interpolation: PhysicsInterpolation | undefined;
125
+ geometryCapture: GeometryCapture | undefined;
126
+ beforeRenderSnapshots: Array<Array<() => void>>;
127
+ beforeRenderDepth: number;
128
+ hasDepthCoupledOutput: boolean;
129
+ startupGateStarted: boolean;
130
+ onStartSceneEntered: (() => void) | undefined;
131
+ renderMetricsEnabled: boolean;
132
+ uiRevealed: boolean;
133
+ started: boolean;
134
+ resumeScene: string | undefined;
135
+ connectUi(): IUiBridge;
136
+ enterScene(scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean;
137
+ goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void>;
138
+ postUiStartup(): void;
139
+ teardown(ctx?: ICtx<TState, TPhysics>): void;
140
+ warmUpConfiguredExplicitly(): boolean;
141
+ warmUpOptions(): IWarmUpOptions;
142
+ }
143
+
144
+ /** The frame loop, and the instruments that only exist while it runs. */
145
+ export interface IGameFrameLoop {
146
+ /** Stops the loop, where `#teardown` always stopped it. Its frame budget is `game.frameBudget`. */
147
+ readonly dispose: PluginCleanup;
148
+ readonly geometryCapture: GeometryCapture;
149
+ readonly loop: FixedStepLoop;
150
+ }
151
+
152
+ /** The second phase of `#boot`: the scaler, the frame budget, its diagnostics, and the loop. */
153
+ export function startFrameLoop<TState extends Record<string, unknown>, TPhysics>(
154
+ startup: IGameStartup<TState, TPhysics>,
155
+ ): IGameFrameLoop {
156
+ const game = startup.game;
157
+ const {
158
+ afterPhysicsPhase,
159
+ autoBatch,
160
+ camera,
161
+ canvasLayer,
162
+ ctx,
163
+ debug,
164
+ input,
165
+ interpolation,
166
+ loopState,
167
+ now,
168
+ picker,
169
+ pointerEvents,
170
+ projection,
171
+ renderer,
172
+ scheduler,
173
+ startupCompile,
174
+ startupCoverActive,
175
+ startupEnvironment,
176
+ startupReadiness,
177
+ startupShadows,
178
+ threeScene,
179
+ timeline,
180
+ } = startup;
181
+
182
+ // The scaler exists whenever the scale is automatic, which now includes a game that said
183
+ // nothing about it. A pinned number leaves this undefined, which is what makes "pinned" a
184
+ // guarantee rather than a preference the loop may overrule. `maxFps: 0` removes the ceiling,
185
+ // and a scaler with no budget is not a scaler with a loose one, so an uncapped game simply
186
+ // does not get adaptive scaling.
187
+ const initialTarget = resolveTargetFps(game.config, getPlatform());
188
+ let heldTargetFps = initialTarget.targetFps;
189
+ // Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
190
+ renderer.noteTargetFps?.(initialTarget.targetFps);
191
+ const automaticScale = renderer.surface().scaleSource === "auto";
192
+ const createScaler = () =>
193
+ automaticScale && heldTargetFps > 0
194
+ ? new ResolutionScaler({
195
+ // Phones keep the device ladder; a desktop stops before its bottom, where a picture
196
+ // with nothing reconstructing it stops being a faster frame and becomes a blur.
197
+ minScale: resolvePlatformResolutionFloor(getPlatform().os),
198
+ // The adapter family picks the first rung; the first eligible window still decides.
199
+ start:
200
+ renderer.temporalUpscaleStartScale?.() ??
201
+ (renderer.gpuClass === undefined
202
+ ? undefined
203
+ : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class]),
204
+ targetFps: heldTargetFps,
205
+ temporalUpscale: () => renderer.temporalUpscale?.() === true,
206
+ })
207
+ : undefined;
208
+ let scaler = createScaler();
209
+ let temporalStartApplied = renderer.temporalUpscale?.() === true;
210
+ // A class that starts below the ceiling must draw there from the first frame; the scaler only
211
+ // reports a scale, and nothing else would apply it until a window steps.
212
+ if (scaler !== undefined && scaler.scale !== 1)
213
+ renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
214
+ // The panel's own rate, once a window of presented frames can say it. The native host's
215
+ // present counter is the only series there that counts displays rather than loop iterations;
216
+ // on the web one rAF callback is one vblank, so the median presented interval is the period.
217
+ let measuredRefreshHz: number | undefined;
218
+ // The world pass's own draw-call count, kept from the last frame of the window so the
219
+ // projection line can report what the renderer was handed beside what the plan predicted.
220
+ // A plan and a measurement that disagree is the finding; one number pretending to be both
221
+ // is how an optimizer reports a win it did not deliver.
222
+ let loadingFramePresented = false;
223
+ let lastWorldDrawCalls: number | undefined;
224
+ // Completion on the last frame must not make an otherwise compiling window look clean.
225
+ let compilingInWindow = false;
226
+ let lastCompileCount = renderer.compileCount;
227
+ const observeCompilation = (): void => {
228
+ const count = renderer.compileCount;
229
+ compilingInWindow ||= renderer.compiling === true || count !== lastCompileCount;
230
+ lastCompileCount = count;
231
+ };
232
+ // Built here rather than inside the loop so `frameBudget: false` is a single decision with a
233
+ // single owner, and so the render phases below feed the same instrument the loop feeds.
234
+ const frameBudget =
235
+ game.config.frameBudget === false
236
+ ? undefined
237
+ : new FrameBudget({
238
+ ...game.config.frameBudget,
239
+ simulation: {
240
+ tick: () => gameLoop.tick(),
241
+ get step() {
242
+ return gameLoop.step;
243
+ },
244
+ get clockFrozen() {
245
+ return gameLoop.clockFrozen;
246
+ },
247
+ },
248
+ // The scaler reads the same windows the marker reports, so what it acted on and what
249
+ // the record shows are the same measurement rather than two sampling paths.
250
+ onWindow: (reported) => {
251
+ const sink =
252
+ game.config.frameBudget === false ? undefined : game.config.frameBudget?.report;
253
+ const reportInfo = sink ?? console.info;
254
+ const reportWarning = sink ?? console.warn;
255
+ observeCompilation();
256
+ const compileObserved = compilingInWindow;
257
+ compilingInWindow = false;
258
+ // The display's own rate, read once per window from the cadence the loop already
259
+ // measured: the host's present counter where there is one, else the median presented
260
+ // interval, which on the web is the vblank period because rAF is the presentation.
261
+ measuredRefreshHz =
262
+ reported.presentedFps ??
263
+ (reported.presented.p50 > 0 ? 1_000 / reported.presented.p50 : undefined);
264
+ const target = resolveTargetFps(game.config, getPlatform(), measuredRefreshHz);
265
+ renderer.noteTargetFps?.(target.targetFps);
266
+ if (
267
+ scaler !== undefined &&
268
+ target.targetFps > 0 &&
269
+ target.targetFps !== heldTargetFps
270
+ ) {
271
+ heldTargetFps = target.targetFps;
272
+ scaler.retarget(heldTargetFps);
273
+ }
274
+ renderer.observeRenderChainBudget?.(reported);
275
+ game.computeDriven.observeBudget(reported);
276
+ const projection = game.projection;
277
+ // Printed every window, projecting or declined. `TN_RENDER_PROJECTION` says once
278
+ // whether the optimizer engaged; this says, repeatedly, what it is still leaving on
279
+ // the exact lane and whether the renderer agrees with the plan.
280
+ if (projection !== undefined) {
281
+ reportInfo(
282
+ formatProjectionWindow(
283
+ projection.windowReport,
284
+ reported.window,
285
+ lastWorldDrawCalls,
286
+ game.cameraCull?.report,
287
+ game.matrixWorld?.report,
288
+ ),
289
+ );
290
+ }
291
+ if (game.config.frameBudget !== false) game.config.frameBudget?.onWindow?.(reported);
292
+ // The span tree closes on the same window, so the two lines in a log describe the
293
+ // same frames and a reader can subtract one from the other without a second clock.
294
+ const spanWindow = spans?.window();
295
+ if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
296
+ // The scene-shape verdict, on by default in a debug launch, from the census the
297
+ // frame already took. An agent building a scene of the wrong shape reads it in the
298
+ // log before a human ever plays the game and calls it slow.
299
+ const staticCensus = staticTransformCensus();
300
+ if (staticCensus.roots > 0)
301
+ reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
302
+ const validation = renderListValidator?.report();
303
+ if (validation !== undefined) reportInfo(formatValidationReport(validation));
304
+ const warning = devMetricsEnabled
305
+ ? sceneWarning(
306
+ reported,
307
+ describeSceneShape(reported, game.cameraCull?.report),
308
+ target.targetFps,
309
+ renderer.gpuClass?.class,
310
+ )
311
+ : undefined;
312
+ if (warning !== undefined) reportWarning(formatSceneWarning(warning));
313
+ // The same sentence goes to the UI on a dev launch, so a human watching the window
314
+ // and an agent reading the log are told the same thing at the same time. No frame
315
+ // rate rides it: the loop's own rAF rate reads throttled under a compositor or a
316
+ // virtual display, so a number drawn from it lies in exactly the sessions where
317
+ // somebody is trying to measure.
318
+ if (devMetricsEnabled && warning !== undefined && game.uiBridge?.hasPeer() === true) {
319
+ const verdict = describeSceneWarning(warning);
320
+ if (verdict !== postedVerdict) {
321
+ postedVerdict = verdict;
322
+ game.uiBridge.post({ type: UI_DEV_METRICS_MESSAGE, sceneWarning: verdict });
323
+ }
324
+ }
325
+ if (scaler === undefined) return;
326
+ // **Not while the world is still arriving.** The scaler judges the game by closed
327
+ // frame-budget windows, and the windows that close during a launch are not the game:
328
+ // they are asset decode, scene construction and first-use compilation. Measured on
329
+ // sandbox/wildwood, a 46,190-instance forest, the first two windows reported 18.8
330
+ // and 27.3 fps against a 60 fps budget — a deficit large enough that `#rungsToDrop`
331
+ // crossed three rungs at once and the buffer went from 1600x900 to 976x549 before
332
+ // the player had control. It then settled at 0.72, which is 52% of the pixels, and
333
+ // re-probed 0.85 every thirty seconds, missed, and fell back — so the picture went
334
+ // soft a few seconds in and never fully recovered. The owner's report was "after a
335
+ // while everything becomes blurry, and keeps getting worse".
336
+ //
337
+ // Readiness is the right gate rather than a frame count or a timer: it is the moment
338
+ // the framework already defines as "the world is safe to show", it now includes
339
+ // anything the game held startup for, and a host that never reaches it still gets
340
+ // there on the bounded fallbacks inside `StartupReadiness`.
341
+ if (!startupReadiness.ready || compileObserved) return;
342
+ const stepped = scaler.observe(reported);
343
+ if (stepped !== undefined) renderer.setResolutionScale(stepped, scaler.scaleSource);
344
+ },
345
+ // Last, so the engine's own renderer answers this and a game cannot report a
346
+ // resolution it is not drawing at. The window carries it in both pinned and auto
347
+ // modes: turning the convention off does not turn its measurement off.
348
+ readGpuAgeFrames: () => renderer.gpuFrameAge?.(),
349
+ // The world's own count of what the GPU selected, not `info.render.triangles`' upper
350
+ // bound over mesh capacity. Absent until the world's first tally lands.
351
+ readGpuTally: () => startup.gpuTallyProvider?.(),
352
+ // The resolved budget rides the window rather than a marker of its own, so a harness
353
+ // reads the target and the frames it was judged against out of one line. It lags the
354
+ // window by one, because the window is built before this callback runs.
355
+ readTarget: () => resolveTargetFps(game.config, getPlatform(), measuredRefreshHz),
356
+ readSurface: () => {
357
+ observeCompilation();
358
+ return {
359
+ ...renderer.surface(),
360
+ ...(scaler === undefined ? {} : { atFloor: scaler.atFloor }),
361
+ compiling: compilingInWindow,
362
+ };
363
+ },
364
+ });
365
+ game.frameBudget = frameBudget;
366
+ // Per-pass draws and triangles ride the frame budget's window by default. The same property
367
+ // that makes `info.render` an aggregate — one reset per frame before the world render, and
368
+ // nested shadow/reflection renders sharing that counter — is what this recorder unwinds.
369
+ const renderPassBudget =
370
+ frameBudget === undefined
371
+ ? undefined
372
+ : RenderPassBudget.install(renderer.raw as Parameters<typeof RenderPassBudget.install>[0]);
373
+ // Spans are a diagnostic, never a convention: nothing installs them unless `TN_FRAME_SPANS`
374
+ // asks for them, and every call site below is one guarded return when it does not. They wrap
375
+ // three's own render path rather than reimplementing it, so what they measure is the path that
376
+ // ships, and they are removed with the game.
377
+ const spans = spansRequested() ? new SpanRecorder() : undefined;
378
+ if (spans !== undefined) setSpanRecorder(spans);
379
+ const removeSpanProbes =
380
+ spans === undefined
381
+ ? undefined
382
+ : installSpanProbes(renderer.raw as Parameters<typeof installSpanProbes>[0], threeScene);
383
+ // The boundary counts ride the same flag: they wrap every WebGPU command of the frame, which is
384
+ // work a shipped build must not pay for a diagnostic it did not ask for.
385
+ const frameCounters =
386
+ spans === undefined ? undefined : FrameCounters.install(counterDeviceOf(renderer.raw));
387
+ // The engine's own ABI crossings ride every budget window, not the spans flag: one difference of
388
+ // two reads per frame, and the series a fix for repeated crossings is judged on.
389
+ const bridgeCrossings = createCrossingReader();
390
+ // Every engine work counter, per frame, when a playtest bounds them (PRD-748 engine-cost row).
391
+ const engineCounters = createEngineCounterReader();
392
+ if (debug) engineCounters();
393
+ // The parity oracle for the static freeze. Off by default and expensive on purpose: it
394
+ // recomputes every world matrix the long way and throws on the first that disagrees with what
395
+ // the frame is about to draw.
396
+ const renderListValidator = renderListValidationRequested()
397
+ ? new RenderListValidator()
398
+ : undefined;
399
+ if (removeSpanProbes !== undefined) {
400
+ game.cleanup.push(() => {
401
+ removeSpanProbes();
402
+ setSpanRecorder(undefined);
403
+ });
404
+ }
405
+ if (frameCounters !== undefined) game.cleanup.push(() => frameCounters.uninstall());
406
+ if (debug) {
407
+ const stopGc = observeDebugGc();
408
+ if (stopGc !== undefined) game.cleanup.push(stopGc);
409
+ }
410
+ // Holds no hook and does no work between requests, so an idle game pays nothing for it.
411
+ const geometryCapture = new GeometryCapture();
412
+ game.geometryCapture = geometryCapture;
413
+ const budgetNow = (): number => globalThis.performance?.now() ?? Date.now();
414
+ // The stage meters split the render phase (PRD-771): three clock reads a frame and one difference of the
415
+ // engine's running totals. Decided once; `?tnStages=0` turns the whole path off, here and in the engine.
416
+ const stageMeters = frameBudget !== undefined && stageMetersRequested();
417
+ const readStages = stageMeters ? createStageReader(() => renderer.raw) : undefined;
418
+ const readWork = stageMeters ? createWorkReader(() => renderer.raw) : undefined;
419
+ if (!stageMeters)
420
+ (renderer.raw as { setStageMeters?: (enabled: boolean) => void }).setStageMeters?.(false);
421
+ let computeStageMs = 0;
422
+ // The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
423
+ // a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
424
+ // say nothing new.
425
+ const devMetricsEnabled = isDevLaunch();
426
+ let postedVerdict: string | undefined;
427
+ let lastGateSkips = 0;
428
+ let readinessGateSkips = 0;
429
+ const gameLoop: FixedStepLoop = new FixedStepLoop({
430
+ interpolation,
431
+ ...(frameBudget === undefined ? {} : { budget: frameBudget }),
432
+ ...(spans === undefined ? {} : { spans }),
433
+ maxSteps: game.config.maxSteps,
434
+ onBeginFrame: () => {
435
+ // The engine owns this requestAnimationFrame loop instead of delegating to Three's
436
+ // setAnimationLoop(). Three's renderer therefore cannot reset its frame counters for us;
437
+ // a concurrent internal renderer callback can otherwise leave stale work in the first
438
+ // sample after a held playtest start.
439
+ resetRendererPerformanceMetrics(renderer.raw);
440
+ renderer.beginFrame?.();
441
+ },
442
+ onRender: (alpha) => {
443
+ observeCompilation();
444
+ // Before the first world pass compiles anything: the merged meshes it compiles are the ones
445
+ // the player will see. A scene that has not entered has nothing built to settle.
446
+ if (game.sceneEntered) {
447
+ if (debug)
448
+ measureDebug("autoBatch", "renderer", "AutoBatch.update", () => autoBatch.update());
449
+ else autoBatch.update();
450
+ }
451
+ if (!startup.projectionSettled) {
452
+ for (const node of startupShadows) node.startupCovered = false;
453
+ startupShadows.clear();
454
+ threeScene.traverseVisible((object) => {
455
+ if (!object.castShadow || !object.visible) return;
456
+ // A type flag, not instanceof: a value import would pull the shadow nodes into every
457
+ // native bundle, where the engine binds none of them.
458
+ const node = Reflect.get(object, "shadow")?.shadowNode as VirtualShadowNode | undefined;
459
+ if (node?.isVirtualShadowNode === true) {
460
+ startupShadows.add(node);
461
+ node.startupCovered = startupCoverActive();
462
+ }
463
+ });
464
+ }
465
+ renderPassBudget?.beginFrame();
466
+ // Runs on web as well as native, so the two stay one behaviour rather than diverging into
467
+ // a fast path nobody tests. When the world is drawn, reconciliation happens immediately
468
+ // before the render, inside the same frame, so a change the game made this tick reaches
469
+ // the screen this tick instead of the next one. Scenes under its mesh floor get their own
470
+ // graph back and pay nothing.
471
+ // A goto clears the graph before its destination enters, and the projection has to drop
472
+ // those objects on the very next frame. During the first-use hold, however, reconciling a
473
+ // large scene would be more work before the loader has even presented. Present one
474
+ // loader-only frame and keep reconciling skipped until first-use work settles; then the
475
+ // world pass and projection start together behind the still-opaque layer.
476
+ let worldMetrics: IRenderPerformanceMetrics | undefined;
477
+ const firstWorldPass = !startup.worldRendered && game.sceneEntered;
478
+ const explicitWarmUpPending =
479
+ game.warmUpConfiguredExplicitly() && !startup.explicitWarmUpSettled;
480
+ const loaderHasPixels = canvasLayer.scene.children.length > 0;
481
+ const mustPresentLoader =
482
+ firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
483
+ if (firstWorldPass && !explicitWarmUpPending) {
484
+ game.startupGateStarted = true;
485
+ // `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
486
+ // is on it has already happened behind the loading screen, so running it again here
487
+ // would pay the same cost twice.
488
+ startupReadiness.start(
489
+ game.warmUpConfiguredExplicitly()
490
+ ? undefined
491
+ : startupCoverActive()
492
+ ? startupCompile
493
+ : startupEnvironment(),
494
+ );
495
+ }
496
+ // Ordinary render compute waits for startup readiness. Streaming explicitly opts in
497
+ // after compilation so a spawn hold can finish behind the curtain. Present the loader
498
+ // first; charge this admission to the same render phase as normal render compute.
499
+ if (
500
+ game.renderer !== undefined &&
501
+ game.sceneEntered &&
502
+ !explicitWarmUpPending &&
503
+ !mustPresentLoader &&
504
+ (!startupCoverActive() || startupReadiness.compileSettled)
505
+ ) {
506
+ const computeStart = frameBudget === undefined ? 0 : budgetNow();
507
+ computeStageMs = 0;
508
+ beginSpan(SPANS.compute);
509
+ try {
510
+ // The render camera comes with it, because a render-cadence consumer that culls by the
511
+ // view — a streamed world's main batches — has to be driven from here and not from a draw
512
+ // three skips for a mesh that is hidden because it has nothing to draw.
513
+ game.computeDriven.processRender(
514
+ game.renderer,
515
+ camera,
516
+ startupCoverActive() && !startupReadiness.ready,
517
+ gameLoop,
518
+ );
519
+ } finally {
520
+ endSpan(SPANS.compute);
521
+ }
522
+ computeStageMs = frameBudget === undefined ? 0 : budgetNow() - computeStart;
523
+ frameBudget?.addRender(computeStageMs);
524
+ }
525
+ const waitingForFirstUse =
526
+ firstWorldPass &&
527
+ (explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
528
+ let worldPasses: ReturnType<RenderPassBudget["passes"]> | undefined;
529
+ // Before the scene has entered, the world pass runs only under an opaque cover. With nothing
530
+ // over it, the draw presents the clear colour: Hop Garden showed three black frames during
531
+ // `load()` for 0.5 s when the page mounted the canvas. Under the cover it is what compiles the
532
+ // world's pipelines inside the load: skipped, Hop's 10 s first-use compile landed after a
533
+ // playtest's setup had released enter(), and setup.place runs failed.
534
+ if (
535
+ (game.sceneEntered || canvasLayer.opaque) &&
536
+ !mustPresentLoader &&
537
+ !waitingForFirstUse &&
538
+ (!canvasLayer.opaque ||
539
+ (!startupReadiness.ready && canvasLayer.renderWorldDuringStartup) ||
540
+ canvasLayer.keepWorldRendering)
541
+ ) {
542
+ // The projection's own scene when it is faithful, the game's when it is not. Nothing
543
+ // here branches on which: `root` is the single render input either way, so there is no
544
+ // second optional render path to leave untested.
545
+ // The reconcile is bracketed with the render it feeds: its walk, grouping and matrix
546
+ // sync are render-path work, and a frame budget that hid it in `residual` made the
547
+ // optimizer's own cost unmeasurable exactly where the optimizer is engaged.
548
+ const renderStart = frameBudget === undefined ? 0 : budgetNow();
549
+ // Before anything walks: a frozen subtree whose author moved its root thaws here, so the
550
+ // walk that follows sees a transform nobody had to remember to announce.
551
+ refreshStaticTransforms();
552
+ // Camera-rate metadata is an input to scene-owned beforeRender work and the projection
553
+ // palette write, not a post-draw observation. Publish it before either can skip a rig;
554
+ // this pass observes animation only and does not decide draw visibility.
555
+ const drawingBufferHeight = renderer.surface().drawingBufferHeight;
556
+ const cullPrepareStart = spans === undefined ? 0 : spanNow();
557
+ game.cameraCull?.prepareAnimation(
558
+ game.projection?.root ?? threeScene,
559
+ camera,
560
+ drawingBufferHeight,
561
+ );
562
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullPrepareStart);
563
+ // Scene prep that must read the frame's last solved state before the projection packs and
564
+ // the renderer draws. Inside the world-render block it cannot land on a held loader frame.
565
+ if (game.beforeRenderCallbacks.size > 0) {
566
+ let snapshot = game.beforeRenderSnapshots[game.beforeRenderDepth];
567
+ if (snapshot === undefined) {
568
+ snapshot = [];
569
+ game.beforeRenderSnapshots[game.beforeRenderDepth] = snapshot;
570
+ }
571
+ game.beforeRenderDepth += 1;
572
+ snapshot.length = 0;
573
+ for (const callback of game.beforeRenderCallbacks) snapshot.push(callback);
574
+ beginSpan(SPANS.beforeRender);
575
+ try {
576
+ for (const callback of snapshot) {
577
+ if (debug)
578
+ measureDebug(
579
+ `beforeRender.${callback.name || "anonymous"}`,
580
+ "update",
581
+ callback.name || "ctx.beforeRender",
582
+ callback,
583
+ );
584
+ else callback();
585
+ }
586
+ } finally {
587
+ endSpan(SPANS.beforeRender);
588
+ game.beforeRenderDepth -= 1;
589
+ }
590
+ }
591
+ interpolation.render(gameLoop.clockFrozen || game.paused ? 1 : alpha, () => {
592
+ // Let a depth-coupled scene update its output node while the scene pass is still the
593
+ // next render. Ordinary scenes keep the historical hook order and timing.
594
+ const depthCoupledOutput = game.hasDepthCoupledOutput;
595
+ if (depthCoupledOutput && game.sceneEntered) game.scene?.render(ctx);
596
+ // The engine's own walk owns the frame's world matrices, so the count starts here and
597
+ // covers both applications below: the authored scene the projection reconciles from and
598
+ // the root the renderer is actually handed.
599
+ game.matrixWorld?.beginFrame();
600
+ if (game.projection !== undefined) {
601
+ beginSpan(SPANS.reconcile);
602
+ try {
603
+ game.projection.reconcile();
604
+ } finally {
605
+ endSpan(SPANS.reconcile);
606
+ }
607
+ }
608
+ // Virtual geometry ships on by default, so the engine takes the cut rather than waiting
609
+ // for a game to know it should. It runs here, before the render and after the reconcile,
610
+ // because an empty cut has to skip its draw rather than submit a zero-count one — and a
611
+ // scene holding no clustered mesh pays no traversal at all, only the tracked set.
612
+ beginSpan(SPANS.clustered);
613
+ try {
614
+ updateClusteredMeshes(
615
+ game.projection?.root ?? threeScene,
616
+ camera,
617
+ renderer.surfaceDrawingBufferHeight?.() ?? renderer.surface().drawingBufferHeight,
618
+ );
619
+ } finally {
620
+ endSpan(SPANS.clustered);
621
+ }
622
+ // Automatic discrete LOD ships on with the pipeline, so the engine takes the selection
623
+ // too. It shares the render root and the same drawing-buffer height, and a scene with no
624
+ // managed mesh pays only the tracked-set walk.
625
+ beginSpan(SPANS.lod);
626
+ try {
627
+ updateModelLods(
628
+ game.projection?.root ?? threeScene,
629
+ camera,
630
+ renderer.surface().drawingBufferHeight,
631
+ );
632
+ } finally {
633
+ endSpan(SPANS.lod);
634
+ }
635
+ const renderRoot = game.projection?.root ?? threeScene;
636
+ // The cull reads the matrices the renderer will draw. Projection exact proxies carry the
637
+ // authored world matrix in their local matrix, so their own world walk must precede both
638
+ // the cull and the render rather than following the cull.
639
+ renderRoot.matrixWorldAutoUpdate = false;
640
+ game.matrixWorld?.apply(renderRoot);
641
+ // Projected-size cull, per render camera, default on. It writes only `object.visible` —
642
+ // the one per-frame flag the projection's batch key ignores — and restores what it hid
643
+ // immediately after the draw, so the authored scene is untouched between frames. The
644
+ // renderer walks the same root the projection is about to draw, so a declined projection
645
+ // and an active one both get the gate.
646
+ const cullApplyStart = spans === undefined ? 0 : spanNow();
647
+ game.cameraCull?.apply(game.projection?.root ?? threeScene, camera, drawingBufferHeight);
648
+ // Added, not bracketed: the render call sits between the apply and the restore, and a
649
+ // span that contained it would report the world pass as cull work.
650
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullApplyStart);
651
+ const capturing = geometryCapture.armed();
652
+ if (capturing) {
653
+ // The mirror is what the renderer sees; arming the authored scene would attribute the
654
+ // frame to objects that were never submitted.
655
+ geometryCapture.beginFrame({
656
+ camera,
657
+ generation: game.sceneGeneration,
658
+ root: game.projection?.root ?? threeScene,
659
+ tick: gameLoop.tick(),
660
+ viewportHeight: renderer.surface().drawingBufferHeight,
661
+ viewportWidth: renderer.surface().drawingBufferWidth,
662
+ ...(renderPassBudget === undefined
663
+ ? {}
664
+ : { activePassKind: () => renderPassBudget.activeKind() }),
665
+ ...(game.projection === undefined
666
+ ? {}
667
+ : { ownership: game.projection.describeOwnership() }),
668
+ ...(rendererBackendIdentity(renderer.raw) === undefined
669
+ ? {}
670
+ : { backend: rendererBackendIdentity(renderer.raw) as string }),
671
+ });
672
+ }
673
+ // Scene.enter installs the chain after the scaler is created; choose its tier before its first draw.
674
+ if (!temporalStartApplied && scaler !== undefined && renderer.temporalUpscale?.()) {
675
+ scaler = createScaler();
676
+ temporalStartApplied = true;
677
+ if (scaler !== undefined) renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
678
+ }
679
+ const engineStart = readStages === undefined ? 0 : budgetNow();
680
+ renderer.render(renderRoot, camera);
681
+ const engineEnd = readStages === undefined ? 0 : budgetNow();
682
+ startup.renders += 1;
683
+ // Count declined frames without treating them as drawn-frame render cost.
684
+ const gateSkips = rendererFrameGateSkips(renderer.raw);
685
+ if (gateSkips !== undefined) {
686
+ if (gateSkips > lastGateSkips) frameBudget?.addRenderSkip();
687
+ lastGateSkips = gateSkips;
688
+ }
689
+ // *After* the render, because that is where the draw happened. The matrices read here are
690
+ // the ones drawn: the walk above refreshed them and `render()` did not touch them. The
691
+ // frozen roots are passed because the draw root is the projection's mirror when the
692
+ // engine is collapsing, and validating only that reassured about a scene it never
693
+ // looked at. `?.` short-circuits before the spread, so `staticRoots()` is not called
694
+ // at all on a frame without the flag — verified, a million optional calls evaluate the
695
+ // argument zero times — and this stays a single undefined check in a shipped game.
696
+ renderListValidator?.frame(renderRoot, ...staticRoots());
697
+ const cullRestoreStart = spans === undefined ? 0 : spanNow();
698
+ game.cameraCull?.restore();
699
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
700
+ game.projection?.commit();
701
+ renderer.observeRenderChainFrame?.();
702
+ if (frameBudget !== undefined) {
703
+ const renderEnd = budgetNow();
704
+ frameBudget.addRender(renderEnd - renderStart);
705
+ const stages = readStages?.(
706
+ computeStageMs + (engineStart - renderStart),
707
+ engineEnd - engineStart,
708
+ renderEnd - engineEnd,
709
+ );
710
+ if (stages !== undefined) frameBudget.addStages(stages);
711
+ }
712
+ computeStageMs = 0;
713
+ // Read the split before the overlay renders: the overlay is its own draw, not part of the
714
+ // world pass, and the budget window already accounts for it in its own phase.
715
+ worldPasses = renderPassBudget?.passes();
716
+ if (worldPasses !== undefined && worldPasses.length > 0)
717
+ frameBudget?.addRenderPasses(worldPasses);
718
+ // After the passes are read, so the rows reconcile against this frame's own totals.
719
+ if (capturing) geometryCapture.finishFrame(worldPasses ?? []);
720
+ // Resolve the GPU timestamps every frame, not once per reported window.
721
+ //
722
+ // `trackTimestamp` spends two queries per render pass, and three's pool holds 2048.
723
+ // A scene with a post-processing chain runs tens of passes per frame — a cathedral
724
+ // with SSGI, denoise, godrays, SSR and bloom measured 27 — so the pool fills in
725
+ // 2048 / (2 x 27) = 38 frames. The resolve used to be wired to the frame-budget
726
+ // window boundary, 300 frames by default, which is eight times too slow: three
727
+ // warned `Maximum number of queries exceeded`, stopped recording, and every window
728
+ // after the first reported `gpuMs: undefined`. The one instrument that exists so the
729
+ // GPU record is not wall-clock algebra was reading nothing.
730
+ //
731
+ // This does not put the GPU on the frame path. `resolveTimestampsAsync` is
732
+ // fire-and-forget and already catch-guarded, which was the original cadence's only
733
+ // stated concern.
734
+ // Deliberately unspanned. The resolve runs *after* `addRender` closed the render phase,
735
+ // so its milliseconds are in the frame's `residual`, not in `render`. A span for it was
736
+ // measured on the native smoke game at 0.18 ms and showed up as exactly that much
737
+ // negative residual — the tree reporting, correctly, that it had been handed a term from
738
+ // outside the phase it is dividing up. The frame budget already carries this cost.
739
+ renderer.resolveGpuFrame();
740
+ frameBudget?.addGpuPyramidMs(renderer.gpuPyramidMs?.());
741
+ // The budget's GPU series is fed every frame, not read once per reported window. A
742
+ // single window-close read is one instantaneous, lagged `info.render.timestamp` — the
743
+ // sample that made a 17.6 ms frame read as 2.98–10.40 ms. The sample carries the
744
+ // resolved frame id so a resolve still in flight is counted stale, not measured twice.
745
+ //
746
+ // The reading is the frame's own passes out of three's per-pass map, handed out one
747
+ // resolved frame per presented frame. Three's resolve answers with one number for the
748
+ // batch — the last frame in it — so reading that instead dropped every frame a batch
749
+ // caught up on, and because the resolve is asked for on the same 1-in-8 stride the
750
+ // sampler uses, how many frames a batch caught up on was a function of frame rate.
751
+ // The pass recorder is what reads three's per-pass map back into per-frame numbers; a
752
+ // renderer it cannot instrument falls back to the batch's own single number, which is the
753
+ // reading there was before — one sample per resolve rather than one per sampled frame.
754
+ const gpuFrame = renderPassBudget?.nextGpuFrame();
755
+ const gpuSample = gpuFrame === undefined ? renderer.gpuFrameSample?.() : undefined;
756
+ frameBudget?.addGpuMs(
757
+ gpuFrame?.total ?? gpuSample?.ms,
758
+ gpuFrame?.frame ?? gpuSample?.frame,
759
+ );
760
+ // Where one resolved frame's GPU time went: main and shadow come from the pass
761
+ // recorder's per-uid query results, and everything else in that pool (post chain,
762
+ // reflections, HUD) is the remainder. Compute is its own pool.
763
+ if (gpuFrame !== undefined) {
764
+ const computeMs = renderer.gpuComputeMs?.();
765
+ // The recorder hands out a frame only when every pass it recorded resolved, so `total`
766
+ // is the whole frame and never a partial sum; `main` and `shadow` are whole or zero.
767
+ // `other` is the remainder of the frame (post chain, reflection, HUD). `shadowPasses`
768
+ // rides along so a consumer can tell a frame that rendered a shadow from one that drew
769
+ // none, since a real render can resolve to 0 ms.
770
+ frameBudget?.addGpuBucketMs({
771
+ main: gpuFrame.main,
772
+ shadow: gpuFrame.shadow,
773
+ shadowPasses: gpuFrame.shadowPasses,
774
+ other: Math.max(0, gpuFrame.total - gpuFrame.main - gpuFrame.shadow),
775
+ ...(computeMs === undefined ? {} : { compute: computeMs }),
776
+ });
777
+ // The main pass's own GPU series, for the adaptive LOD control loop: the frame
778
+ // budget's `gpuMain` bucket is the record, and this is the same number smoothed on the
779
+ // renderer so a world holding only the renderer can read it. Fed per delivered frame,
780
+ // fresh or not.
781
+ renderer.noteGpuMainMs?.(gpuFrame.main, gpuFrame.frame);
782
+ } else {
783
+ renderer.noteGpuMainMs?.(undefined);
784
+ }
785
+ if (!depthCoupledOutput && game.sceneEntered) game.scene?.render(ctx);
786
+ if (game.sceneEntered) {
787
+ if (!startup.worldRendered) gameLoop.clearRuntimeDiagnostics();
788
+ startup.worldRendered = true;
789
+ }
790
+ if (game.renderMetricsEnabled) {
791
+ const metrics = rendererPerformanceMetrics(renderer.raw);
792
+ worldMetrics =
793
+ worldPasses === undefined || worldPasses.length === 0
794
+ ? metrics
795
+ : { ...metrics, passes: worldPasses.map((pass) => ({ ...pass })) };
796
+ }
797
+ // Read whether or not the game asked for render metrics: the projection line reports
798
+ // the measured draw count, and a convention's measurement does not switch off with the
799
+ // convention that happens to sit beside it.
800
+ lastWorldDrawCalls = rendererDrawCallCount(renderer.raw);
801
+ });
802
+ }
803
+ if (mustPresentLoader) loadingFramePresented = true;
804
+ // Include state written by beforeRender and Scene.render in this frame's UI snapshot.
805
+ if (game.config.stateFlushMs === undefined && startup.stateHandOffFrames === 0)
806
+ game.state.flush();
807
+ // Every frame, including one whose canvas layer is empty: the native UI is composited into
808
+ // the game's own frame whether or not the game draws a HUD of its own, so a frame that
809
+ // skipped this would report work it did pay as `residual`. The host reports what the
810
+ // *previous* frame's composite cost — the only reading that exists when a frame begins —
811
+ // so this charges the phase to the frame that paid it, one frame late rather than never.
812
+ // Absent on the web target and on any host with no overlay, where the work is zero rather
813
+ // than unknown, so an absent global must read as zero and not as a missing measurement.
814
+ // The boundary counts ride the span flag, but the simulation tick does not need them: it is
815
+ // fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
816
+ // without `TN_FRAME_SPANS`. `addCounters` keeps the last tick a caller did provide.
817
+ const crossings = bridgeCrossings();
818
+ if (debug) {
819
+ const matrix = game.matrixWorld?.report;
820
+ if (matrix !== undefined)
821
+ countDebug("matrixWorldVisits", matrix.visited, "scene", "MatrixWorldPass");
822
+ const cull = game.cameraCull?.report;
823
+ if (cull !== undefined) {
824
+ countDebug("cullConsidered", cull.considered, "renderer", "RenderCameraCull");
825
+ countDebug("cullRejected", cull.culled, "renderer", "RenderCameraCull");
826
+ }
827
+ const batch = autoBatch.census;
828
+ countDebug("autoBatchSources", batch.meshes, "renderer", "AutoBatch.census");
829
+ countDebug("autoBatchDraws", batch.draws, "renderer", "AutoBatch.census");
830
+ countDebug("autoBatchRefused", batch.refused, "renderer", "AutoBatch.census");
831
+ countDebug("autoBatchUnsettled", batch.unsettled, "renderer", "AutoBatch.census");
832
+ }
833
+ const boundary = frameCounters?.read();
834
+ const engine = engineCounters();
835
+ // The owned engine's work counts; a JS back end with its own queue counters (`boundary`) outranks them.
836
+ const work = readWork?.(crossings);
837
+ frameBudget?.addCounters({
838
+ ...(work ?? {}),
839
+ ...(boundary ?? {}),
840
+ ...(crossings === undefined ? {} : { bridgeCrossings: crossings }),
841
+ ...(engine === undefined ? {} : { engine }),
842
+ simulationTick: gameLoop.tick(),
843
+ });
844
+ const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
845
+ frameBudget?.addUi(
846
+ typeof uiHost.__tnUiCompositeMs === "function" ? (uiHost.__tnUiCompositeMs() ?? 0) : 0,
847
+ );
848
+ if (canvasLayer.scene.children.length > 0) {
849
+ const overlayStart = frameBudget === undefined ? 0 : budgetNow();
850
+ // The overlay is its own render call and its own frame-budget phase. The span probes sit
851
+ // on `render`, so without this they would charge the HUD's draw to the render phase the
852
+ // spans are explaining — measured on the native smoke game as `coverage 1.03` and a
853
+ // residual of −0.37 ms, two render calls per frame where the phase paid for one. The
854
+ // recorder is unhooked rather than flagged, so every probe takes the same guarded return
855
+ // it takes in a shipped build and the span stack cannot be left half-open.
856
+ if (spans !== undefined) setSpanRecorder(undefined);
857
+ try {
858
+ renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
859
+ } finally {
860
+ if (spans !== undefined) setSpanRecorder(spans);
861
+ }
862
+ frameBudget?.addOverlay(budgetNow() - overlayStart);
863
+ if (!game.renderMetricsEnabled) return undefined;
864
+ const overlayMetrics = rendererPerformanceMetrics(renderer.raw);
865
+ return combineRenderPerformanceMetrics(renderer.kind, worldMetrics, overlayMetrics);
866
+ }
867
+ return game.renderMetricsEnabled ? worldMetrics : undefined;
868
+ },
869
+ onAfterPhysics: (dt) => {
870
+ if (game.paused) return;
871
+ if (debug)
872
+ measureDebug("afterPhysics", "update", "afterPhysicsPhase.run", () =>
873
+ afterPhysicsPhase.run(dt),
874
+ );
875
+ else afterPhysicsPhase.run(dt);
876
+ },
877
+ onUpdate: (dt) => {
878
+ if (game.paused) return;
879
+ if (debug) {
880
+ measureDebug("input", "update", "Input.tick", () => game.input?.tick());
881
+ measureDebug("scheduler", "update", "Scheduler.tick", () => scheduler.tick(dt));
882
+ measureDebug("picking", "update", "PointerEvents3D.tick", () =>
883
+ pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges),
884
+ );
885
+ } else {
886
+ game.input?.tick();
887
+ scheduler.tick(dt);
888
+ pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
889
+ }
890
+ for (const plugin of game.activePlugins) {
891
+ if (debug && plugin.beforeUpdate !== undefined)
892
+ measureDebug(
893
+ `beforeUpdate.${game.activePlugins.indexOf(plugin)}.${plugin.beforeUpdate.name || "anonymous"}`,
894
+ "update",
895
+ `plugins[${game.activePlugins.indexOf(plugin)}].${plugin.beforeUpdate.name || "beforeUpdate"}`,
896
+ () => plugin.beforeUpdate?.(ctx, dt),
897
+ );
898
+ else plugin.beforeUpdate?.(ctx, dt);
899
+ }
900
+ const scene = game.scene;
901
+ const frame = game.sceneFrame;
902
+ if (game.sceneEntered && frame !== undefined) {
903
+ if (debug)
904
+ measureDebug(
905
+ "sceneCallbacks",
906
+ "update",
907
+ `${scene?.constructor.name}.${frame.name || "frame"}`,
908
+ () => frame(ctx, dt),
909
+ );
910
+ else frame(ctx, dt);
911
+ startup.updates += 1;
912
+ }
913
+ // An async goto() installs the incoming scene before its load resolves; until enter()
914
+ // has run there is no gameplay to step and a game-overridden update() would run against
915
+ // a cleared graph.
916
+ else if (game.sceneEntered && scene !== undefined) {
917
+ if (debug)
918
+ measureDebug("sceneCallbacks", "update", `${scene.constructor.name}.update`, () =>
919
+ scene.update(ctx, dt),
920
+ );
921
+ else scene.update(ctx, dt);
922
+ startup.updates += 1;
923
+ }
924
+ if (game.scene !== scene || game.sceneFrame !== frame) return;
925
+ for (const plugin of game.activePlugins) {
926
+ if (debug && plugin.update !== undefined)
927
+ measureDebug(
928
+ `plugins.${game.activePlugins.indexOf(plugin)}.${plugin.update.name || "anonymous"}`,
929
+ "update",
930
+ `plugins[${game.activePlugins.indexOf(plugin)}].${plugin.update.name || "update"}`,
931
+ () => plugin.update?.(ctx, dt),
932
+ );
933
+ else plugin.update?.(ctx, dt);
934
+ }
935
+ if (debug) measureDebug("entities", "update", "Registry.sweep", () => game.entities?.sweep());
936
+ else game.entities?.sweep();
937
+ if (game.renderer !== undefined && game.sceneEntered) {
938
+ if (debug)
939
+ measureDebug(
940
+ "computeDriven",
941
+ "update",
942
+ "ComputeDriven.process",
943
+ () => game.renderer && game.computeDriven.process(game.renderer),
944
+ );
945
+ else game.computeDriven.process(game.renderer);
946
+ }
947
+ },
948
+ // A frame the renderer declined to draw (the Wasm engine's gate: two frames still on the GPU)
949
+ // is no frame at all for the readiness window. Counted, five cheap declined frames closed the
950
+ // window while the first world frame was still compiling on the GPU, so the cover lifted and
951
+ // the player saw a 0.9 s stall and then a first frame with unmetered exposure (Hop Garden, 4
952
+ // of 13 launches). Not a reset either: a GPU-bound world under the cover declines every other
953
+ // frame, and a reset held every Hop launch to the 10 s window bound.
954
+ onFrame: (frameMs) => {
955
+ const skips = rendererFrameGateSkips(renderer.raw);
956
+ const declined = skips !== undefined && skips > readinessGateSkips;
957
+ if (skips !== undefined) readinessGateSkips = skips;
958
+ if (!declined) startupReadiness.observe(frameMs);
959
+ // Bounded like every other startup wait: a renderer that retires no frame (hosted CI's
960
+ // SwiftShader declined 73 of 73 after readiness) would otherwise keep the HUD covered for
961
+ // the whole session. Past the window the cover lifts anyway, and says why.
962
+ const handOffWaitedMs = now() - (timeline.readyMs ?? now());
963
+ const handOffBounded = handOffWaitedMs >= STARTUP_STABLE_WINDOW_MS;
964
+ // A draw the gate accepted is only queued: the cover lifts once the GPU has finished the first world frame.
965
+ const worldOnDisplay = rendererWorldPresented(renderer.raw) !== false;
966
+ if (startup.stateHandOffFrames > 0 && ((!declined && worldOnDisplay) || handOffBounded)) {
967
+ if (handOffBounded) {
968
+ console.warn(
969
+ `TN_STARTUP_HANDOFF_BOUNDED:${JSON.stringify({
970
+ retiredFrames: STARTUP_HANDOFF_FRAMES - startup.stateHandOffFrames,
971
+ requiredFrames: STARTUP_HANDOFF_FRAMES,
972
+ waitedMs: Math.round(handOffWaitedMs),
973
+ reason:
974
+ "the GPU retired fewer frames than the hand-off needs; the cover lifted at the bound",
975
+ })}`,
976
+ );
977
+ startup.stateHandOffFrames = 0;
978
+ } else startup.stateHandOffFrames -= 1;
979
+ // The frame the held state publishes again is the frame the cover is gone.
980
+ if (startup.stateHandOffFrames === 0) {
981
+ game.uiRevealed = true;
982
+ if (game.uiBridge?.hasPeer()) game.postUiStartup();
983
+ }
984
+ }
985
+ },
986
+ step: game.config.step,
987
+ });
988
+ loopState.current = gameLoop;
989
+
990
+ return {
991
+ dispose: () => gameLoop.stop(),
992
+ geometryCapture,
993
+ loop: gameLoop,
994
+ };
995
+ }