@threenative/core 0.3.11 → 0.3.13

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