@threenative/core 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12437 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +57 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2408 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +574 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +850 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
package/src/game.ts
ADDED
|
@@ -0,0 +1,2408 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Camera,
|
|
3
|
+
type Object3D,
|
|
4
|
+
OrthographicCamera,
|
|
5
|
+
PerspectiveCamera,
|
|
6
|
+
Scene as ThreeScene,
|
|
7
|
+
Vector2,
|
|
8
|
+
} from "three";
|
|
9
|
+
import { type IAssetLoaderOptions, createAssetLoader } from "./assets.js";
|
|
10
|
+
import { CanvasLayer } from "./canvas-layer.js";
|
|
11
|
+
import { updateClusteredMeshes } from "./clustered-mesh.js";
|
|
12
|
+
import { ComputeDrivenRegistry, isComputeDriven } from "./compute-driven.js";
|
|
13
|
+
import type { IThreeNativeConfig } from "./config.js";
|
|
14
|
+
import { type EntitySnapshot, Registry } from "./entities.js";
|
|
15
|
+
import { FrameBudget, type IFrameBudgetOptions, type IFrameBudgetWindow } from "./frame-budget.js";
|
|
16
|
+
import {
|
|
17
|
+
GeometryCapture,
|
|
18
|
+
type IGeometryCaptureReport,
|
|
19
|
+
type IGeometryCaptureRequest,
|
|
20
|
+
rendererBackendIdentity,
|
|
21
|
+
} from "./geometry-capture.js";
|
|
22
|
+
import { type ContextMenuPolicy, type InputBindings, InputMap } from "./input.js";
|
|
23
|
+
import { PhysicsInterpolation } from "./interpolation.js";
|
|
24
|
+
import { reportLaunchFailure, watchDeviceLoss, watchStartupStall } from "./launch-diagnostics.js";
|
|
25
|
+
import {
|
|
26
|
+
FixedStepLoop,
|
|
27
|
+
type IAfterPhysicsPhase,
|
|
28
|
+
type IRenderPerformanceMetrics,
|
|
29
|
+
type IRenderPerformanceSample,
|
|
30
|
+
createAfterPhysicsPhase,
|
|
31
|
+
} from "./loop.js";
|
|
32
|
+
import { MatrixWorldPass } from "./matrix-world.js";
|
|
33
|
+
import { updateModelLods } from "./model-lod.js";
|
|
34
|
+
import { ScenePicker } from "./picking.js";
|
|
35
|
+
import type { IPipelineCensus } from "./pipeline-census.js";
|
|
36
|
+
import { getPlatform } from "./platform.js";
|
|
37
|
+
import { PointerEvents3D } from "./pointer-events.js";
|
|
38
|
+
import { FrameCounters, counterDeviceOf } from "./profiling/FrameCounters.js";
|
|
39
|
+
import {
|
|
40
|
+
SPANS,
|
|
41
|
+
SpanRecorder,
|
|
42
|
+
addSpan,
|
|
43
|
+
beginSpan,
|
|
44
|
+
endSpan,
|
|
45
|
+
formatSpansWindow,
|
|
46
|
+
setSpanRecorder,
|
|
47
|
+
spanNow,
|
|
48
|
+
spansRequested,
|
|
49
|
+
} from "./profiling/Spans.js";
|
|
50
|
+
import { applyOpacityConvention } from "./profiling/opacity-convention.js";
|
|
51
|
+
import {
|
|
52
|
+
RenderListValidator,
|
|
53
|
+
formatValidationReport,
|
|
54
|
+
renderListValidationRequested,
|
|
55
|
+
} from "./profiling/render-list-validate.js";
|
|
56
|
+
import { renderTrapAudit } from "./profiling/render-trap-audit.js";
|
|
57
|
+
import {
|
|
58
|
+
describeSceneShape,
|
|
59
|
+
describeSceneWarning,
|
|
60
|
+
formatSceneWarning,
|
|
61
|
+
sceneWarning,
|
|
62
|
+
} from "./profiling/scene-warning.js";
|
|
63
|
+
import { installSpanProbes } from "./profiling/span-probes.js";
|
|
64
|
+
import {
|
|
65
|
+
UNLIT_FOLIAGE_FIX,
|
|
66
|
+
formatUnlitFoliageWarning,
|
|
67
|
+
unlitFoliageWarning,
|
|
68
|
+
} from "./profiling/unlit-foliage-warning.js";
|
|
69
|
+
import { formatProjectionWindow } from "./projection-marker.js";
|
|
70
|
+
import { type IRandom, createRandom } from "./random.js";
|
|
71
|
+
import { RenderCameraCull } from "./render-camera-cull.js";
|
|
72
|
+
import { RenderPassBudget } from "./render-pass-budget.js";
|
|
73
|
+
import { SceneRenderProjection } from "./renderProjection.js";
|
|
74
|
+
import {
|
|
75
|
+
resolveMatrixWorldMode,
|
|
76
|
+
resolvePlatformResolutionFloor,
|
|
77
|
+
resolveRendererAlphaAntialiasing,
|
|
78
|
+
resolveRendererAntialias,
|
|
79
|
+
resolveRendererScaleSetting,
|
|
80
|
+
} from "./renderer-config.js";
|
|
81
|
+
import {
|
|
82
|
+
type IRendererLike,
|
|
83
|
+
type IRendererOptions,
|
|
84
|
+
type RendererKind,
|
|
85
|
+
createRenderer,
|
|
86
|
+
} from "./renderer.js";
|
|
87
|
+
import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
|
|
88
|
+
import type {
|
|
89
|
+
ICtx,
|
|
90
|
+
IStartupStatus,
|
|
91
|
+
IStartupTimeline,
|
|
92
|
+
Scene,
|
|
93
|
+
SceneConstructor,
|
|
94
|
+
SceneFrame,
|
|
95
|
+
} from "./scene.js";
|
|
96
|
+
import { Scheduler } from "./schedule.js";
|
|
97
|
+
import {
|
|
98
|
+
STARTUP_COMPILE_BUDGET_MS,
|
|
99
|
+
STARTUP_STALL_MS,
|
|
100
|
+
type StartupCompile,
|
|
101
|
+
StartupReadiness,
|
|
102
|
+
} from "./startup-readiness.js";
|
|
103
|
+
import { type GameStore, createGameStore } from "./state.js";
|
|
104
|
+
import {
|
|
105
|
+
STATIC_TRANSFORM_MARKER,
|
|
106
|
+
refreshStaticTransforms,
|
|
107
|
+
staticRoots,
|
|
108
|
+
staticTransformCensus,
|
|
109
|
+
} from "./static-transform.js";
|
|
110
|
+
import { resolveTargetFps } from "./target-fps.js";
|
|
111
|
+
import {
|
|
112
|
+
type IUiBridge,
|
|
113
|
+
UI_DEV_METRICS_MESSAGE,
|
|
114
|
+
UI_READY_INTENT,
|
|
115
|
+
connectUiBridge,
|
|
116
|
+
} from "./ui-bridge.js";
|
|
117
|
+
import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
|
|
118
|
+
import { type IViewportOptions, Viewport } from "./viewport.js";
|
|
119
|
+
import {
|
|
120
|
+
type IWarmUpOptions,
|
|
121
|
+
type IWarmUpReport,
|
|
122
|
+
warmUpComputeNodes,
|
|
123
|
+
warmUpScene,
|
|
124
|
+
} from "./warmup.js";
|
|
125
|
+
|
|
126
|
+
export type PluginCleanup = () => void;
|
|
127
|
+
|
|
128
|
+
export interface IGameObservationSampleRequest {
|
|
129
|
+
readonly entities?: readonly string[];
|
|
130
|
+
/** Asks for one armed per-object geometry capture. Absent means no capture is collected. */
|
|
131
|
+
readonly geometry?: IGeometryCaptureRequest;
|
|
132
|
+
readonly include?: readonly string[];
|
|
133
|
+
readonly label?: string;
|
|
134
|
+
readonly resources?: readonly string[];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface IGameObservationContribution {
|
|
138
|
+
readonly capabilities: readonly string[];
|
|
139
|
+
/**
|
|
140
|
+
* May answer a promise: an observation that has to wait for the renderer — a geometry capture
|
|
141
|
+
* waits for one presented world frame — cannot be produced inside the request that asked for it.
|
|
142
|
+
*/
|
|
143
|
+
readonly sample: (
|
|
144
|
+
request: IGameObservationSampleRequest,
|
|
145
|
+
) => Readonly<Record<string, unknown>> | Promise<Readonly<Record<string, unknown>>>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface IGameRuntimeObservations {
|
|
149
|
+
contribute(contribution: IGameObservationContribution): PluginCleanup;
|
|
150
|
+
contributions(): readonly IGameObservationContribution[];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface IGamePluginRuntime {
|
|
154
|
+
/**
|
|
155
|
+
* Runs `ticks` fixed steps and returns how many ran. Fewer than asked when a `goto()` began
|
|
156
|
+
* inside the batch: the ticks after it belong to the destination scene, which does not exist
|
|
157
|
+
* until `sceneTransition()` settles.
|
|
158
|
+
*/
|
|
159
|
+
readonly fixedStep: (ticks: number, options?: { render?: boolean }) => number;
|
|
160
|
+
/**
|
|
161
|
+
* The `goto()` in flight, or undefined when no scene is loading. Settles once the destination
|
|
162
|
+
* scene has loaded and entered, and never rejects: a failed load is reported as a launch
|
|
163
|
+
* failure. A runner that counts ticks awaits it before spending more, exactly as it awaits
|
|
164
|
+
* `holdStart` at boot, so a restart cannot be outrun by the ticks that follow it.
|
|
165
|
+
*/
|
|
166
|
+
readonly sceneTransition?: () => Promise<void> | undefined;
|
|
167
|
+
/** Completed scene updates and primary world render requests, independent of budget windows. */
|
|
168
|
+
readonly frameCounts?: () => { updates: number; renders: number };
|
|
169
|
+
/**
|
|
170
|
+
* Announces that a diagnostics consumer is going to read render metrics, turning per-frame
|
|
171
|
+
* sample collection on for the rest of the run. Optional: a runtime without collection
|
|
172
|
+
* support just never enables. Games collect nothing until this fires — the samples exist for
|
|
173
|
+
* assertions, not for every frame of every game.
|
|
174
|
+
*/
|
|
175
|
+
readonly enableRuntimeDiagnostics?: () => void;
|
|
176
|
+
/** The frame's cost attribution so far, or undefined when the game turned the budget off. */
|
|
177
|
+
readonly frameBudgetWindow?: () => IFrameBudgetWindow | undefined;
|
|
178
|
+
/**
|
|
179
|
+
* Stop the live clock, so a rendered frame simulates nothing and banks no wall-clock time.
|
|
180
|
+
*
|
|
181
|
+
* A run that counts fixed-step ticks must not also accumulate real seconds into the same
|
|
182
|
+
* simulation, and the frames before its first `advance()` are exactly where a boot's seconds
|
|
183
|
+
* used to land. Optional: a runtime without a clock just never freezes one.
|
|
184
|
+
*/
|
|
185
|
+
readonly freezeClock?: () => void;
|
|
186
|
+
/**
|
|
187
|
+
* Draw the current world once without advancing it, for a screenshot taken while the loop is
|
|
188
|
+
* driven by `fixedStep` and presents nothing between ticks. Optional: a runtime without a frozen
|
|
189
|
+
* render loop just never draws a standing frame. The runner asks for it only when the bridge
|
|
190
|
+
* advertises it and the capture cannot otherwise see a present.
|
|
191
|
+
*/
|
|
192
|
+
readonly renderCurrent?: () => number;
|
|
193
|
+
/**
|
|
194
|
+
* Hold start-scene entry until `gate` settles.
|
|
195
|
+
*
|
|
196
|
+
* The returned promise settles after the scene that owns the world has entered: the start scene
|
|
197
|
+
* unless it navigated out of its own `enter()`, in which case it is the scene it navigated to,
|
|
198
|
+
* loaded and entered. A runner can therefore release the gate after applying pre-entry setup,
|
|
199
|
+
* then await the returned promise before describing entity-derived capabilities — the entities
|
|
200
|
+
* they read are the ones the world actually has. The frame loop remains held throughout.
|
|
201
|
+
*/
|
|
202
|
+
readonly holdStart?: (gate: Promise<void>) => Promise<void>;
|
|
203
|
+
readonly observations: IGameRuntimeObservations;
|
|
204
|
+
readonly tick: () => number;
|
|
205
|
+
readonly runtimeDiagnosticsSeries?: () => readonly IRenderPerformanceSample[];
|
|
206
|
+
readonly random?: Pick<IRandom, "state">;
|
|
207
|
+
rapier?: string | null;
|
|
208
|
+
readonly seed: number | null;
|
|
209
|
+
/**
|
|
210
|
+
* Whether first-use compilation has settled, separately from full readiness.
|
|
211
|
+
*
|
|
212
|
+
* Readiness also requires a sustained in-budget frame window, which is a player-experience
|
|
213
|
+
* gate — a CPU rasteriser never meets it and resolves on the window's own timeout instead. A
|
|
214
|
+
* harness that has been told the machine has no GPU needs the earlier, cheaper signal, and it
|
|
215
|
+
* must be reported rather than inferred from a phase that cannot distinguish the two.
|
|
216
|
+
*/
|
|
217
|
+
readonly startupCompileSettled?: () => boolean;
|
|
218
|
+
/** When the startup milestones happened, for the playtest bridge's startup observation. */
|
|
219
|
+
readonly startupTimeline?: () => IStartupTimeline;
|
|
220
|
+
/** The renderer-owned bounded pipeline capture, when the renderer has not been opted out. */
|
|
221
|
+
readonly pipelineCensus?: () => IPipelineCensus;
|
|
222
|
+
/**
|
|
223
|
+
* Arms one per-object geometry capture and answers its report after the next presented world
|
|
224
|
+
* frame. Absent on a runtime with no render loop to arm.
|
|
225
|
+
*/
|
|
226
|
+
readonly geometryCapture?: (request?: IGeometryCaptureRequest) => Promise<IGeometryCaptureReport>;
|
|
227
|
+
readonly step: number;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
interface IDevTools {
|
|
231
|
+
snapshot(): EntitySnapshot;
|
|
232
|
+
/**
|
|
233
|
+
* Arms one per-object geometry capture for a development overlay. Absent until the game has a
|
|
234
|
+
* render loop; the overlay treats that as "not ready", never as an empty scene.
|
|
235
|
+
*/
|
|
236
|
+
geometry?(request?: IGeometryCaptureRequest): Promise<IGeometryCaptureReport>;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
type DevToolsHost = Record<string, unknown> & Partial<Record<"__THREENATIVE__", IDevTools>>;
|
|
240
|
+
|
|
241
|
+
export interface IGamePlatformSource {
|
|
242
|
+
readonly devToolsHost?: Record<string, unknown>;
|
|
243
|
+
readonly input: NonNullable<ConstructorParameters<typeof InputMap>[3]>;
|
|
244
|
+
readonly inputTarget?: EventTarget;
|
|
245
|
+
readonly renderer: NonNullable<IRendererOptions["source"]>;
|
|
246
|
+
readonly viewport: NonNullable<IViewportOptions["source"]>;
|
|
247
|
+
mountCanvas(canvas: HTMLCanvasElement, container?: HTMLElement): void;
|
|
248
|
+
unmountCanvas(canvas: HTMLCanvasElement): void;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Whether this launch is a development one.
|
|
253
|
+
*
|
|
254
|
+
* A web build answers through Vite's own flag. A native build has no bundler flag at launch, so the
|
|
255
|
+
* host publishes `DEV_MODE` on `process.env` — the one place a game can read how it was started —
|
|
256
|
+
* and this reads it. Both routes answer the same question: should the dev surfaces exist.
|
|
257
|
+
*/
|
|
258
|
+
/**
|
|
259
|
+
* The bundler's dev flag.
|
|
260
|
+
*
|
|
261
|
+
* The `import.meta.env` access must stay written out exactly here. Vite replaces that member
|
|
262
|
+
* expression at build time; any indirection — a variable holding `import.meta`, or a helper that
|
|
263
|
+
* takes it as an argument — survives into the bundle, where the game is compiled as a script and
|
|
264
|
+
* not a module, and the whole bundle then fails to parse with "Cannot use 'import.meta' outside a
|
|
265
|
+
* module". That is a game that never starts, so the literal access is load-bearing, not style.
|
|
266
|
+
*/
|
|
267
|
+
function bundlerDevFlag(): boolean {
|
|
268
|
+
// quality-allow: DEV is the bundler's own name for the flag, so the name rule cannot apply.
|
|
269
|
+
// biome-ignore lint/style/useNamingConvention: the bundler's own flag name.
|
|
270
|
+
return (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function isDevLaunch(): boolean {
|
|
274
|
+
// `process.env` exists only where a host installed one: the native runtime does, a browser
|
|
275
|
+
// bundle does not. Narrowed rather than asserted, so a host that installs something else
|
|
276
|
+
// answers "not dev" instead of reading a field that is not there.
|
|
277
|
+
const scope: unknown = globalThis;
|
|
278
|
+
if (typeof scope === "object" && scope !== null && "process" in scope) {
|
|
279
|
+
const hostProcess: unknown = scope.process;
|
|
280
|
+
if (typeof hostProcess === "object" && hostProcess !== null && "env" in hostProcess) {
|
|
281
|
+
const env: unknown = hostProcess.env;
|
|
282
|
+
if (typeof env === "object" && env !== null && "DEV_MODE" in env) {
|
|
283
|
+
const flag: unknown = env.DEV_MODE;
|
|
284
|
+
if (typeof flag === "string" && flag !== "" && flag !== "0" && flag !== "false")
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return bundlerDevFlag();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function installDevTools(
|
|
293
|
+
entities: Registry,
|
|
294
|
+
host: DevToolsHost | undefined,
|
|
295
|
+
// Late-bound: the capture is constructed with the render loop, after this install runs.
|
|
296
|
+
geometry: () => GeometryCapture | undefined,
|
|
297
|
+
): PluginCleanup {
|
|
298
|
+
// Written out here, not through `isDevLaunch()`: the bundler must see the literal flag to strip
|
|
299
|
+
// this whole install from a production build, and a runtime `DEV_MODE` check cannot be stripped.
|
|
300
|
+
const isDev =
|
|
301
|
+
(import.meta as ImportMeta & { env?: Record<"DEV", boolean | undefined> }).env?.DEV === true;
|
|
302
|
+
if (!isDev || host === undefined) return () => undefined;
|
|
303
|
+
const devTools: IDevTools = {
|
|
304
|
+
...(host.__THREENATIVE__ as (IDevTools & Record<string, unknown>) | undefined),
|
|
305
|
+
geometry: async (request) => {
|
|
306
|
+
const capture = geometry();
|
|
307
|
+
if (capture === undefined) {
|
|
308
|
+
return {
|
|
309
|
+
reason: "TN_GEOMETRY_CAPTURE_NO_LOOP: the game has no running render loop to capture.",
|
|
310
|
+
status: "unavailable",
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
return capture.request(request);
|
|
314
|
+
},
|
|
315
|
+
snapshot: () => entities.snapshot(),
|
|
316
|
+
};
|
|
317
|
+
host.__THREENATIVE__ = devTools;
|
|
318
|
+
return () => {
|
|
319
|
+
if (host.__THREENATIVE__ !== devTools) return;
|
|
320
|
+
const remaining = Object.fromEntries(
|
|
321
|
+
Object.entries(devTools).filter(([key]) => key !== "snapshot" && key !== "geometry"),
|
|
322
|
+
);
|
|
323
|
+
host.__THREENATIVE__ =
|
|
324
|
+
// quality-allow: what other dev tools left on the shared global after this game removed its own.
|
|
325
|
+
Object.keys(remaining).length === 0 ? undefined : (remaining as unknown as IDevTools);
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export type GamePluginFunction<
|
|
330
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
331
|
+
TPhysics = undefined,
|
|
332
|
+
> = (ctx: ICtx<TState, TPhysics>) => undefined | PluginCleanup;
|
|
333
|
+
|
|
334
|
+
export interface IGamePluginHooks<
|
|
335
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
336
|
+
TPhysics = undefined,
|
|
337
|
+
> {
|
|
338
|
+
setup?(
|
|
339
|
+
ctx: ICtx<TState, TPhysics>,
|
|
340
|
+
runtime?: IGamePluginRuntime,
|
|
341
|
+
): undefined | PluginCleanup | Promise<undefined | PluginCleanup>;
|
|
342
|
+
beforeUpdate?(ctx: ICtx<TState, TPhysics>, dt: number): void;
|
|
343
|
+
update?(ctx: ICtx<TState, TPhysics>, dt: number): void;
|
|
344
|
+
sceneExit?(ctx: ICtx<TState, TPhysics>): void;
|
|
345
|
+
dispose?(ctx: ICtx<TState, TPhysics>): void;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export type GamePlugin<
|
|
349
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
350
|
+
TPhysics = undefined,
|
|
351
|
+
> = GamePluginFunction<TState, TPhysics> | IGamePluginHooks<TState, TPhysics>;
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The global a native host reads to know the world is on screen. Named here rather than written
|
|
355
|
+
* inline so the host and the framework agree on one spelling.
|
|
356
|
+
*/
|
|
357
|
+
const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
|
|
358
|
+
|
|
359
|
+
export interface IGameConfig<
|
|
360
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
361
|
+
TPhysics = undefined,
|
|
362
|
+
> {
|
|
363
|
+
readonly assets?: IAssetLoaderOptions;
|
|
364
|
+
readonly camera?: CameraConfig;
|
|
365
|
+
readonly canvas?: HTMLCanvasElement;
|
|
366
|
+
readonly container?: HTMLElement;
|
|
367
|
+
readonly input?: InputBindings;
|
|
368
|
+
/**
|
|
369
|
+
* Browser context menu over the game surface. Defaults to `"suppress"`, which is what a game
|
|
370
|
+
* wants: right-click is a binding, not a menu. Set `"allow"` only if your game genuinely needs
|
|
371
|
+
* the browser menu over its canvas.
|
|
372
|
+
*/
|
|
373
|
+
readonly contextMenu?: ContextMenuPolicy;
|
|
374
|
+
/**
|
|
375
|
+
* Per-frame cost attribution, on by default. Every `reportEvery` presented frames the game
|
|
376
|
+
* prints one `TN_FRAME_BUDGET` line naming where the frame went — present wait, simulation,
|
|
377
|
+
* three.js render, overlay, the rest — which is what a device lane reads instead of guessing.
|
|
378
|
+
* Pass `false` to silence the marker; the same numbers still reach a playtest `performance`
|
|
379
|
+
* assertion, because turning a convention off must not turn its measurement off.
|
|
380
|
+
*/
|
|
381
|
+
readonly frameBudget?: IFrameBudgetOptions | false;
|
|
382
|
+
readonly initialState?: TState;
|
|
383
|
+
/**
|
|
384
|
+
* The **pre-start** shader warm-up. Off by default, and that is not the same as no warm-up.
|
|
385
|
+
*
|
|
386
|
+
* Every distinct pipeline is otherwise built the first time something using it is drawn, inside
|
|
387
|
+
* the first rendered frame of a fully built scene. On a Pixel 8 that frame lasted **12.0 s, of
|
|
388
|
+
* which 8.0 s was 105 pipeline compiles** — a launch the player reads as a hang, because the
|
|
389
|
+
* loop presents nothing for the whole span. Warming those pipelines while the loading screen is
|
|
390
|
+
* up is the obvious fix, and it is the one this option exists for.
|
|
391
|
+
*
|
|
392
|
+
* **A game with this unset still warms up.** `startupCompile` runs the same `warmUpScene` from
|
|
393
|
+
* inside the loading layer's bounded readiness gate, where the opaque layer is on screen and the
|
|
394
|
+
* loop is turning. This option only moves that work *earlier*, to before `start()` releases the
|
|
395
|
+
* loop, where nothing is presenting — which is a thing to choose deliberately, not a default.
|
|
396
|
+
*
|
|
397
|
+
* **What PRD-327 changed is the mechanism, not this default.** The native host used to answer
|
|
398
|
+
* `createRenderPipelineAsync` with the synchronous create wrapped in a resolved promise, so
|
|
399
|
+
* `compileAsync` compiled on the main loop and was abandoned by its own budget having finished
|
|
400
|
+
* nothing — `TN_WARMUP:{"compiled":0,"abandoned":1,"timedOut":true,"elapsedMs":15325}` — while
|
|
401
|
+
* the first frame compiled the identical pipelines in 8.0 s anyway. Both entries are native
|
|
402
|
+
* handlers now, handing the descriptor to a host compile pool and holding the main thread for
|
|
403
|
+
* 0.27 ms of a 70 ms compile (ratio 0.0038 against a pre-registered bar of 0.25, asserted by
|
|
404
|
+
* `threenative-async-pipeline-thread-test`). The default path started working without its
|
|
405
|
+
* default moving.
|
|
406
|
+
*
|
|
407
|
+
* Pass `{}` or an options object to opt in, or `false` to opt out of warm-up entirely. Either
|
|
408
|
+
* way `TN_WARMUP` and `TN_STARTUP_WARMUP` report what happened, because turning a convention off
|
|
409
|
+
* must not turn its measurement off.
|
|
410
|
+
*/
|
|
411
|
+
readonly warmUp?: IWarmUpOptions | false | true;
|
|
412
|
+
readonly inputTarget?: EventTarget;
|
|
413
|
+
/**
|
|
414
|
+
* Maximum simulation steps per rendered frame. Default 5. Caps the catch-up burst after a
|
|
415
|
+
* stall so a slow frame cannot cascade into a spiral of longer frames.
|
|
416
|
+
*/
|
|
417
|
+
/** Smooth physics objects and the camera between fixed ticks. Default true. */
|
|
418
|
+
readonly physicsInterpolation?: boolean;
|
|
419
|
+
readonly maxSteps?: number;
|
|
420
|
+
readonly platform?: IGamePlatformSource;
|
|
421
|
+
readonly plugins?: readonly GamePlugin<TState, TPhysics>[];
|
|
422
|
+
/**
|
|
423
|
+
* The project's `display` block, passed straight through from `threenative.config.ts`. The
|
|
424
|
+
* adaptive scale holds `maxFps` as its budget, so a game that does not pass this gets the
|
|
425
|
+
* 60 fps default rather than a scaler with no target.
|
|
426
|
+
*/
|
|
427
|
+
readonly display?: NonNullable<IThreeNativeConfig["display"]>;
|
|
428
|
+
readonly render?: NonNullable<IThreeNativeConfig["renderer"]>;
|
|
429
|
+
readonly renderer?: IRendererOptions;
|
|
430
|
+
readonly seed?: number;
|
|
431
|
+
readonly scenes: Record<string, SceneConstructor<TState, TPhysics>>;
|
|
432
|
+
/**
|
|
433
|
+
* Fixed simulation step in seconds, e.g. `1 / 60`. **This is the fixed-step knob a game
|
|
434
|
+
* wants**; every `update(ctx, dt)` receives exactly this `dt`, never a variable frame time,
|
|
435
|
+
* so gameplay and physics advance together and never see a stall.
|
|
436
|
+
*
|
|
437
|
+
* Do not write your own accumulator on top of this. Doing so runs the scene's update several
|
|
438
|
+
* times per already-fixed step and decouples gameplay from the simulation — a real build lost
|
|
439
|
+
* its largest wrong turn to exactly that, because this field carried no documentation.
|
|
440
|
+
*/
|
|
441
|
+
readonly step?: number;
|
|
442
|
+
readonly start: string;
|
|
443
|
+
/** Optional slower UI publication interval. Omitted publishes once per rendered frame. */
|
|
444
|
+
readonly stateFlushMs?: number;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export interface IPerspectiveCameraConfig {
|
|
448
|
+
readonly projection: "perspective";
|
|
449
|
+
readonly fov?: number;
|
|
450
|
+
readonly near?: number;
|
|
451
|
+
readonly far?: number;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export interface IOrthogonalCameraConfig {
|
|
455
|
+
readonly projection: "orthogonal";
|
|
456
|
+
readonly size: number;
|
|
457
|
+
readonly near?: number;
|
|
458
|
+
readonly far?: number;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export type CameraConfig = IPerspectiveCameraConfig | IOrthogonalCameraConfig;
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The game's end of the UI bridge.
|
|
465
|
+
*
|
|
466
|
+
* The UI renders through the platform's own browser-class renderer, which on every native
|
|
467
|
+
* target is a different realm from this one — so it holds a mirror of the game's published
|
|
468
|
+
* state and sends intents back rather than calling into the game. The web target uses the same
|
|
469
|
+
* two channels through an in-process broker, which is what keeps one `src/ui/` honest: a HUD
|
|
470
|
+
* that works here works on a phone.
|
|
471
|
+
*
|
|
472
|
+
* Publication is automatic at the rendered frame cadence (or the named stateFlushMs override), and it stops
|
|
473
|
+
* entirely when nothing is listening — a game whose `ui.renderer` is `native` pays nothing.
|
|
474
|
+
*/
|
|
475
|
+
export interface IGameUi {
|
|
476
|
+
/**
|
|
477
|
+
* Whether a UI layer has announced itself.
|
|
478
|
+
*
|
|
479
|
+
* Stricter than "a transport exists": the UI sends `tn:ready` once its tree has rendered and its
|
|
480
|
+
* interactive rectangles are published, and only then is this true. A transport with nothing on
|
|
481
|
+
* the other end and a UI that failed to render look the same to a game otherwise.
|
|
482
|
+
*/
|
|
483
|
+
readonly connected: boolean;
|
|
484
|
+
/** Handle an intent the UI sent — `restart`, `pause`, whatever the game defines. */
|
|
485
|
+
onIntent(listener: (intent: string, payload: unknown) => void): () => void;
|
|
486
|
+
/** Publish the current state now, whether or not it changed. */
|
|
487
|
+
publish(): void;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export interface IGotoOptions<TState extends Record<string, unknown>> {
|
|
491
|
+
readonly carry?: Partial<TState>;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export interface IGame<
|
|
495
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
496
|
+
TPhysics = undefined,
|
|
497
|
+
> {
|
|
498
|
+
readonly ctx: ICtx<TState, TPhysics> | undefined;
|
|
499
|
+
readonly scene: Scene<TState, TPhysics> | undefined;
|
|
500
|
+
/** The name of the entered scene, or undefined before `start()`. */
|
|
501
|
+
readonly sceneName: string | undefined;
|
|
502
|
+
readonly state: GameStore<TState>;
|
|
503
|
+
/** The seam between the game and its UI layer, on every target. @see IGameUi */
|
|
504
|
+
readonly ui: IGameUi;
|
|
505
|
+
/** Rebuilds the requested scene from its initial state, then merges an optional carry patch. */
|
|
506
|
+
goto(name: string, options?: IGotoOptions<TState>): Promise<void>;
|
|
507
|
+
/** Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path. */
|
|
508
|
+
resumeScene(name: string): void;
|
|
509
|
+
start(): Promise<void>;
|
|
510
|
+
pause(): void;
|
|
511
|
+
resume(): void;
|
|
512
|
+
stop(): void;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function positiveCameraValue(name: string, value: number): number {
|
|
516
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
517
|
+
throw new Error(`camera.${name} must be finite and positive.`);
|
|
518
|
+
return value;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function assertJsonSafe(value: unknown, path = "$", seen = new WeakSet<object>()): void {
|
|
522
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
523
|
+
if (typeof value === "number") {
|
|
524
|
+
if (Number.isFinite(value)) return;
|
|
525
|
+
throw new TypeError(`${path} must contain only finite JSON numbers.`);
|
|
526
|
+
}
|
|
527
|
+
if (typeof value === "object") {
|
|
528
|
+
if (seen.has(value)) throw new TypeError(`${path} must be JSON-safe and cannot be cyclic.`);
|
|
529
|
+
seen.add(value);
|
|
530
|
+
if (Array.isArray(value)) {
|
|
531
|
+
if (Object.getPrototypeOf(value) !== Array.prototype) {
|
|
532
|
+
throw new TypeError(`${path} must be a JSON-safe array.`);
|
|
533
|
+
}
|
|
534
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
535
|
+
assertJsonSafe(value[index], `${path}[${index}]`, seen);
|
|
536
|
+
}
|
|
537
|
+
seen.delete(value);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
const prototype = Object.getPrototypeOf(value);
|
|
541
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
542
|
+
throw new TypeError(`${path} must be a JSON-safe plain object.`);
|
|
543
|
+
}
|
|
544
|
+
for (const [key, item] of Object.entries(value)) assertJsonSafe(item, `${path}.${key}`, seen);
|
|
545
|
+
seen.delete(value);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
throw new TypeError(`${path} must be JSON-safe.`);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function assertCarry(value: unknown): asserts value is Record<string, unknown> {
|
|
552
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
553
|
+
throw new TypeError("goto carry must be a JSON object.");
|
|
554
|
+
}
|
|
555
|
+
assertJsonSafe(value, "$.carry");
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function validateCameraConfig(config: CameraConfig | undefined): void {
|
|
559
|
+
if (config === undefined) return;
|
|
560
|
+
const near = positiveCameraValue("near", config.near ?? 0.1);
|
|
561
|
+
const far = positiveCameraValue("far", config.far ?? 2_000);
|
|
562
|
+
if (far <= near) throw new Error("camera.far must be greater than camera.near.");
|
|
563
|
+
if (config.projection === "perspective") {
|
|
564
|
+
const fov = config.fov ?? 60;
|
|
565
|
+
if (!Number.isFinite(fov) || fov <= 0 || fov >= 180)
|
|
566
|
+
throw new Error("camera.fov must be finite and between 0 and 180 degrees.");
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
positiveCameraValue("size", config.size);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): void {
|
|
573
|
+
computeDriven.clear();
|
|
574
|
+
scene.clear();
|
|
575
|
+
scene.background = null;
|
|
576
|
+
scene.environment = null;
|
|
577
|
+
scene.fog = null;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** The measured draw count on its own, for the projection line that reads it every frame. */
|
|
581
|
+
function rendererDrawCallCount(raw: unknown): number | undefined {
|
|
582
|
+
if (typeof raw !== "object" || raw === null) return undefined;
|
|
583
|
+
const info = (raw as { info?: unknown }).info;
|
|
584
|
+
if (typeof info !== "object" || info === null) return undefined;
|
|
585
|
+
const render = (info as { render?: unknown }).render;
|
|
586
|
+
if (typeof render !== "object" || render === null) return undefined;
|
|
587
|
+
const drawCalls = (render as { drawCalls?: unknown }).drawCalls;
|
|
588
|
+
const calls = drawCalls ?? (render as { calls?: unknown }).calls;
|
|
589
|
+
return typeof calls === "number" && Number.isFinite(calls) && calls >= 0 ? calls : undefined;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Cumulative render() calls the renderer declined to draw (the Wasm web engine's frame gate), when it counts them. */
|
|
593
|
+
function rendererFrameGateSkips(raw: unknown): number | undefined {
|
|
594
|
+
const info = (raw as { info?: { engine?: { frameGateSkips?: unknown } } } | null)?.info;
|
|
595
|
+
const skips = info?.engine?.frameGateSkips;
|
|
596
|
+
return typeof skips === "number" && Number.isFinite(skips) ? skips : undefined;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function rendererPerformanceMetrics(raw: unknown): {
|
|
600
|
+
drawCalls?: number;
|
|
601
|
+
triangles?: number;
|
|
602
|
+
} {
|
|
603
|
+
if (typeof raw !== "object" || raw === null) return {};
|
|
604
|
+
const info = (raw as { info?: unknown }).info;
|
|
605
|
+
if (typeof info !== "object" || info === null) return {};
|
|
606
|
+
const render = (info as { render?: unknown }).render;
|
|
607
|
+
if (typeof render !== "object" || render === null) return {};
|
|
608
|
+
const triangles = (render as { triangles?: unknown }).triangles;
|
|
609
|
+
const drawCalls = rendererDrawCallCount(raw);
|
|
610
|
+
return {
|
|
611
|
+
...(drawCalls === undefined ? {} : { drawCalls }),
|
|
612
|
+
...(typeof triangles === "number" && Number.isFinite(triangles) && triangles >= 0
|
|
613
|
+
? { triangles }
|
|
614
|
+
: {}),
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function resetRendererPerformanceMetrics(raw: unknown): void {
|
|
619
|
+
if (typeof raw !== "object" || raw === null) return;
|
|
620
|
+
const info = (raw as { info?: unknown }).info;
|
|
621
|
+
if (typeof info !== "object" || info === null) return;
|
|
622
|
+
const reset = (info as { reset?: unknown }).reset;
|
|
623
|
+
if (typeof reset === "function") reset.call(info);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* One frame's two render calls, combined.
|
|
628
|
+
*
|
|
629
|
+
* The two renderers' `info` do not mean the same thing, and the old sum only ever held for one of
|
|
630
|
+
* them. `WebGLRenderer` ends every `render()` with `info.reset()`, so the world sample and the
|
|
631
|
+
* overlay sample are disjoint and add up. WebGPU never resets: the engine owns the
|
|
632
|
+
* requestAnimationFrame loop, so it calls `info.reset()` itself once per frame before the world
|
|
633
|
+
* draw (see the render block), which leaves the overlay sample *cumulative* — world plus overlay.
|
|
634
|
+
* Adding it to the world sample reported every world draw twice, and the packed racing scenario
|
|
635
|
+
* read 358 draw calls against a 330 ceiling on a frame that submits far fewer.
|
|
636
|
+
*
|
|
637
|
+
* The world pass split belongs to the world call in both renderers and rides the same sample, so
|
|
638
|
+
* it is carried across rather than summed — a summed split attributes the world's shadow and
|
|
639
|
+
* reflection passes to the overlay too.
|
|
640
|
+
*/
|
|
641
|
+
function combineRenderPerformanceMetrics(
|
|
642
|
+
kind: RendererKind,
|
|
643
|
+
world: IRenderPerformanceMetrics | undefined,
|
|
644
|
+
overlay: IRenderPerformanceMetrics,
|
|
645
|
+
): IRenderPerformanceMetrics {
|
|
646
|
+
const passes = world?.passes;
|
|
647
|
+
if (kind === "webgpu") {
|
|
648
|
+
return passes === undefined ? overlay : { ...overlay, passes };
|
|
649
|
+
}
|
|
650
|
+
if (world === undefined) return overlay;
|
|
651
|
+
return {
|
|
652
|
+
...(world.drawCalls === undefined || overlay.drawCalls === undefined
|
|
653
|
+
? {}
|
|
654
|
+
: { drawCalls: world.drawCalls + overlay.drawCalls }),
|
|
655
|
+
...(world.triangles === undefined || overlay.triangles === undefined
|
|
656
|
+
? {}
|
|
657
|
+
: { triangles: world.triangles + overlay.triangles }),
|
|
658
|
+
...(passes === undefined ? {} : { passes }),
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function createCamera(config: CameraConfig | undefined): Camera {
|
|
663
|
+
if (config === undefined) return new PerspectiveCamera(60, 1, 0.1, 2_000);
|
|
664
|
+
validateCameraConfig(config);
|
|
665
|
+
const near = config.near ?? 0.1;
|
|
666
|
+
const far = config.far ?? 2_000;
|
|
667
|
+
if (config.projection === "perspective")
|
|
668
|
+
return new PerspectiveCamera(config.fov ?? 60, 1, near, far);
|
|
669
|
+
const size = config.size;
|
|
670
|
+
return new OrthographicCamera(-size, size, size, -size, near, far);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
class GameImpl<TState extends Record<string, unknown>, TPhysics>
|
|
674
|
+
implements IGame<TState, TPhysics>
|
|
675
|
+
{
|
|
676
|
+
#config: IGameConfig<TState, TPhysics>;
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Whether the caller asked for the pre-start warm-up *by hand*.
|
|
680
|
+
*
|
|
681
|
+
* PRD-327 Phase 2 proposed flipping this default on for native. Executing it showed the
|
|
682
|
+
* prescription was wrong, and the reason is worth keeping: **the framework already warms up by
|
|
683
|
+
* default, in a better place.** `startupCompile` below calls the same `warmUpScene`, but from
|
|
684
|
+
* inside the loading layer's readiness gate — opaque layer on screen, loop turning — whereas the
|
|
685
|
+
* pre-start block runs before `start()` releases the loop, with nothing presenting.
|
|
686
|
+
*
|
|
687
|
+
* What was actually broken was the mechanism, not the default: `compileAsync` could not resolve
|
|
688
|
+
* on native because `createRenderPipelineAsync` was the synchronous create wrapped in a resolved
|
|
689
|
+
* promise, so the default path compiled nothing and reported
|
|
690
|
+
* `{"compiled":0,"abandoned":1,"timedOut":true}`. Phase 1 fixed that, and the default path
|
|
691
|
+
* started working without its default moving.
|
|
692
|
+
*
|
|
693
|
+
* Flipping it anyway cost two regressions CI caught and a local run did not: the loading screen
|
|
694
|
+
* stopped covering startup (`verify-desktop-loading.mjs`: `loadingVisible: false` at every
|
|
695
|
+
* startup sample, on macOS and Windows), and the scene then compiled twice — once before the
|
|
696
|
+
* loop and once inside the gate — which pushed `verify-desktop-physics.mjs` past its 180-frame
|
|
697
|
+
* budget on macOS. Both are gone with the default back where it was.
|
|
698
|
+
*/
|
|
699
|
+
#warmUpConfiguredExplicitly(): boolean {
|
|
700
|
+
return this.#config.warmUp !== undefined && this.#config.warmUp !== false;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** The warm-up options for the pre-start block, once an explicit opt-in has asked for it. */
|
|
704
|
+
#warmUpOptions(): IWarmUpOptions {
|
|
705
|
+
const configured = this.#config.warmUp;
|
|
706
|
+
return configured === undefined || configured === true || configured === false
|
|
707
|
+
? {}
|
|
708
|
+
: configured;
|
|
709
|
+
}
|
|
710
|
+
#ctx: ICtx<TState, TPhysics> | undefined;
|
|
711
|
+
#scene: Scene<TState, TPhysics> | undefined;
|
|
712
|
+
/** The name of the scene currently entered. Carried across a hot update so a reload resumes
|
|
713
|
+
* where the session was, instead of restoring the game's state into its start scene. */
|
|
714
|
+
#sceneName: string | undefined;
|
|
715
|
+
#resumeScene: string | undefined;
|
|
716
|
+
#sceneFrame: SceneFrame<TState, TPhysics> | undefined;
|
|
717
|
+
#renderer: IRendererLike | undefined;
|
|
718
|
+
#viewport: Viewport | undefined;
|
|
719
|
+
#input: InputMap | undefined;
|
|
720
|
+
#state: GameStore<TState>;
|
|
721
|
+
#initialState: TState;
|
|
722
|
+
#loop: FixedStepLoop | undefined;
|
|
723
|
+
#interpolation: PhysicsInterpolation | undefined;
|
|
724
|
+
#projection: SceneRenderProjection | undefined;
|
|
725
|
+
#cameraCull: RenderCameraCull | undefined;
|
|
726
|
+
#matrixWorld: MatrixWorldPass | undefined;
|
|
727
|
+
#cleanup: Array<() => void> = [];
|
|
728
|
+
#computeDriven = new ComputeDrivenRegistry();
|
|
729
|
+
#entities: Registry | undefined;
|
|
730
|
+
#picker: ScenePicker | undefined;
|
|
731
|
+
#pointerEvents: PointerEvents3D | undefined;
|
|
732
|
+
#scheduler: Scheduler | undefined;
|
|
733
|
+
#afterPhysicsPhase: IAfterPhysicsPhase | undefined;
|
|
734
|
+
// Unlike afterPhysics, this seam's frame boundary is the world-render block below, so it is a
|
|
735
|
+
// plain scene-owned set rather than a phase on the loop.
|
|
736
|
+
#beforeRenderCallbacks = new Set<() => void>();
|
|
737
|
+
// Reused snapshot buffers, one per nesting depth, so a steady frame allocates no callback array.
|
|
738
|
+
#beforeRenderSnapshots: Array<Array<() => void>> = [];
|
|
739
|
+
#beforeRenderDepth = 0;
|
|
740
|
+
#frameBudget: FrameBudget | undefined;
|
|
741
|
+
#geometryCapture: GeometryCapture | undefined;
|
|
742
|
+
/** Bumped on every scene change, so a row id is stable exactly as long as the scene is. */
|
|
743
|
+
#sceneGeneration = 0;
|
|
744
|
+
#activePlugins: Array<IGamePluginHooks<TState, TPhysics>> = [];
|
|
745
|
+
#disposedPlugins = new Set<IGamePluginHooks<TState, TPhysics>>();
|
|
746
|
+
#pendingStart: Promise<void> | undefined;
|
|
747
|
+
#aborted = false;
|
|
748
|
+
#sceneEntered = false;
|
|
749
|
+
/**
|
|
750
|
+
* The scene a `goto()` is loading right now, or undefined when none is.
|
|
751
|
+
*
|
|
752
|
+
* Between a `goto()` and its `enter()` the registry is cleared and nothing owns the world, so a
|
|
753
|
+
* reader that needs the world's entities has to wait for this rather than for the scene it
|
|
754
|
+
* navigated from. The playtest handshake reads exactly that.
|
|
755
|
+
*/
|
|
756
|
+
#pendingSceneEnter: Promise<void> | undefined;
|
|
757
|
+
#paused = false;
|
|
758
|
+
#started = false;
|
|
759
|
+
#uiBridge: IUiBridge | undefined;
|
|
760
|
+
#uiPublisher: IUiStatePublisher | undefined;
|
|
761
|
+
#uiReady = false;
|
|
762
|
+
// Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics().
|
|
763
|
+
#renderMetricsEnabled = false;
|
|
764
|
+
// Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
|
|
765
|
+
// historical after-render hook so an atmosphere-free game has the same render path as HEAD.
|
|
766
|
+
#hasDepthCoupledOutput = false;
|
|
767
|
+
|
|
768
|
+
constructor(config: IGameConfig<TState, TPhysics>) {
|
|
769
|
+
this.#config = config;
|
|
770
|
+
validateCameraConfig(config.camera);
|
|
771
|
+
const startScene = this.#config.scenes[this.#config.start];
|
|
772
|
+
if (startScene === undefined) throw new Error(`Unknown start scene '${this.#config.start}'.`);
|
|
773
|
+
const initialState =
|
|
774
|
+
this.#config.initialState ??
|
|
775
|
+
(startScene as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState;
|
|
776
|
+
if (initialState === undefined) {
|
|
777
|
+
throw new Error(
|
|
778
|
+
`Scene '${this.#config.start}' must declare static initialState or provide config.initialState.`,
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
this.#state = createGameStore(initialState, this.#config.stateFlushMs);
|
|
782
|
+
this.#initialState = { ...initialState };
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
get ctx(): ICtx<TState, TPhysics> | undefined {
|
|
786
|
+
return this.#ctx;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
get scene(): Scene<TState, TPhysics> | undefined {
|
|
790
|
+
return this.#scene;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** The name of the entered scene, or undefined before `start()`. */
|
|
794
|
+
get sceneName(): string | undefined {
|
|
795
|
+
return this.#sceneName;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* Boot into `name` instead of `config.start` on the next `start()`.
|
|
800
|
+
*
|
|
801
|
+
* Hot reload's restore path is the only caller. `acceptHotUpdate` carries the state store across
|
|
802
|
+
* a module update and hands it back before the game runs — and without this the game rebuilt
|
|
803
|
+
* itself at `config.start`, so a session that was playing came back holding its own state on the
|
|
804
|
+
* main menu, with every entity and its physics world gone. Calling `goto()` instead is not
|
|
805
|
+
* available here: it throws before `start()`, and it resets state to the destination's
|
|
806
|
+
* `initialState`, which would discard the very state being restored.
|
|
807
|
+
*/
|
|
808
|
+
resumeScene(name: string): void {
|
|
809
|
+
if (this.#config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
|
|
810
|
+
this.#resumeScene = name;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
get state(): GameStore<TState> {
|
|
814
|
+
return this.#state;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* The UI seam. Startup connects it even for a read-only HUD; accessing it before startup
|
|
819
|
+
* connects early so the game can register intents. No state is serialized without a UI peer.
|
|
820
|
+
*/
|
|
821
|
+
get ui(): IGameUi {
|
|
822
|
+
const bridge = this.#connectUi();
|
|
823
|
+
const ready = () => this.#uiReady;
|
|
824
|
+
return {
|
|
825
|
+
get connected() {
|
|
826
|
+
return bridge.hasPeer() && ready();
|
|
827
|
+
},
|
|
828
|
+
onIntent: (listener) => onUiIntent(bridge, listener),
|
|
829
|
+
publish: () => this.#uiPublisher?.publish(),
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
#connectUi(): IUiBridge {
|
|
834
|
+
if (this.#uiBridge !== undefined) return this.#uiBridge;
|
|
835
|
+
const bridge = connectUiBridge({ end: "game" });
|
|
836
|
+
this.#uiBridge = bridge;
|
|
837
|
+
// The store already coalesces writes at flush. Deferring this again waits for the native
|
|
838
|
+
// host's next microtask pump, after that frame's WebView event pump has already passed.
|
|
839
|
+
this.#uiPublisher = publishUiState(bridge, this.#state, { schedule: (flush) => flush() });
|
|
840
|
+
onUiIntent(bridge, (intent) => {
|
|
841
|
+
if (intent !== UI_READY_INTENT) return;
|
|
842
|
+
this.#uiReady = true;
|
|
843
|
+
// Publish immediately: the UI has just rendered against nothing, and waiting for the store's
|
|
844
|
+
// next change would leave a HUD showing its initial values for up to a tick.
|
|
845
|
+
this.#uiPublisher?.publish();
|
|
846
|
+
});
|
|
847
|
+
return bridge;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
#disconnectUi(): void {
|
|
851
|
+
this.#uiPublisher?.stop();
|
|
852
|
+
this.#uiPublisher = undefined;
|
|
853
|
+
this.#uiReady = false;
|
|
854
|
+
this.#uiBridge?.close();
|
|
855
|
+
this.#uiBridge = undefined;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
goto(name: string, options?: IGotoOptions<TState>): Promise<void> {
|
|
859
|
+
if (this.#ctx === undefined) throw new Error("Cannot call game.goto() before start().");
|
|
860
|
+
// Validate before the reset: a typo'd scene name must not wipe the live session's state on
|
|
861
|
+
// its way to throwing.
|
|
862
|
+
const SceneType = this.#config.scenes[name];
|
|
863
|
+
if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
|
|
864
|
+
const carry = options?.carry;
|
|
865
|
+
if (carry !== undefined) assertCarry(carry);
|
|
866
|
+
const destinationInitialState =
|
|
867
|
+
(SceneType as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState ??
|
|
868
|
+
this.#initialState;
|
|
869
|
+
this.#state.stop();
|
|
870
|
+
this.#state.setState({ ...destinationInitialState, ...(carry as Partial<TState> | undefined) });
|
|
871
|
+
this.#state.start();
|
|
872
|
+
return this.#goto(name, this.#ctx);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
#goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void> {
|
|
876
|
+
const SceneType = this.#config.scenes[name];
|
|
877
|
+
if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
|
|
878
|
+
|
|
879
|
+
this.#hasDepthCoupledOutput = false;
|
|
880
|
+
this.#sceneGeneration += 1;
|
|
881
|
+
// The objects a pending capture armed are leaving the graph; a report about them would be
|
|
882
|
+
// about a scene that no longer exists.
|
|
883
|
+
this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_SCENE_EXIT: the scene changed mid-capture.");
|
|
884
|
+
this.#sceneFrame = undefined;
|
|
885
|
+
this.#afterPhysicsPhase?.clear();
|
|
886
|
+
this.#beforeRenderCallbacks.clear();
|
|
887
|
+
this.#interpolation?.clear();
|
|
888
|
+
this.#interpolation?.track(ctx.camera);
|
|
889
|
+
this.#scene?.exit(ctx);
|
|
890
|
+
this.#pointerEvents?.clear();
|
|
891
|
+
this.#sceneEntered = false;
|
|
892
|
+
this.#scheduler?.clear();
|
|
893
|
+
this.#entities?.clear();
|
|
894
|
+
for (const plugin of this.#config.plugins ?? []) {
|
|
895
|
+
if (typeof plugin !== "function") plugin.sceneExit?.(ctx);
|
|
896
|
+
}
|
|
897
|
+
// The projection holds batches built from the outgoing scene's geometry. Released before the
|
|
898
|
+
// scene is cleared, so a scene change cannot leave the next level drawing the last one's
|
|
899
|
+
// props — and released rather than rebuilt, because every source it referenced is about to go.
|
|
900
|
+
this.#projection?.dispose();
|
|
901
|
+
// Put back anything the cull hid before the outgoing scene is cleared, so a scene change never
|
|
902
|
+
// leaves an object invisible if the game keeps a reference to it.
|
|
903
|
+
this.#cameraCull?.restore();
|
|
904
|
+
clearScene(ctx.scene, this.#computeDriven);
|
|
905
|
+
const scene = new SceneType();
|
|
906
|
+
this.#scene = scene;
|
|
907
|
+
this.#sceneName = name;
|
|
908
|
+
const loaded = scene.load(ctx);
|
|
909
|
+
const transition =
|
|
910
|
+
loaded === undefined
|
|
911
|
+
? this.#enterTransitionScene(scene, ctx)
|
|
912
|
+
: Promise.resolve(loaded).then(() => this.#enterTransitionScene(scene, ctx));
|
|
913
|
+
const settled = (): void => {
|
|
914
|
+
if (this.#pendingSceneEnter === transition) this.#pendingSceneEnter = undefined;
|
|
915
|
+
};
|
|
916
|
+
// Handled here as well as by the caller: a start scene that navigates inside `enter()` throws
|
|
917
|
+
// its transition away, and the gate below still has to learn that no world arrived. The failure
|
|
918
|
+
// is reported by name: a swallowed rejection left the loading screen up as a "stall" with
|
|
919
|
+
// nothing outstanding (midway-open-pacific on the Wasm engine).
|
|
920
|
+
void transition.then(settled, (error: unknown) => {
|
|
921
|
+
settled();
|
|
922
|
+
reportLaunchFailure({
|
|
923
|
+
kind: "scene-load-failed",
|
|
924
|
+
message: `Scene '${name}' failed to load: ${error instanceof Error ? error.message : String(error)}`,
|
|
925
|
+
});
|
|
926
|
+
});
|
|
927
|
+
this.#pendingSceneEnter = transition;
|
|
928
|
+
return transition;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
#enterScene(scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean {
|
|
932
|
+
const frame = scene.enter(ctx);
|
|
933
|
+
if (frame !== undefined && typeof frame !== "function") {
|
|
934
|
+
throw new Error("Scene.enter() must return a frame function or undefined.");
|
|
935
|
+
}
|
|
936
|
+
// A boot scene may navigate synchronously; do not replace the frame installed by #goto().
|
|
937
|
+
if (this.#scene !== scene) return false;
|
|
938
|
+
this.#sceneFrame = typeof frame === "function" ? frame : undefined;
|
|
939
|
+
this.#sceneEntered = true;
|
|
940
|
+
// Before the audit, so an opacity the convention made take effect is reported as a warning.
|
|
941
|
+
const opacity = applyOpacityConvention(ctx.scene);
|
|
942
|
+
if (opacity !== undefined) console.warn(opacity);
|
|
943
|
+
for (const line of renderTrapAudit(ctx.scene)) console.error(line);
|
|
944
|
+
// Cutout PBR with no image-based light renders as cardboard, and the compensating tint the
|
|
945
|
+
// author reaches for is invisible in a screenshot review. Once per scene entry, right after
|
|
946
|
+
// `enter()`: `load()` and `enter()` are where the game builds its meshes and sets its own
|
|
947
|
+
// environment, so an earlier read would be a census of an empty scene and a later one would be
|
|
948
|
+
// a census of a scene the author already fixed.
|
|
949
|
+
const unlit = unlitFoliageWarning(ctx.scene);
|
|
950
|
+
if (unlit !== undefined)
|
|
951
|
+
console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
|
|
952
|
+
return true;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
async #enterTransitionScene(
|
|
956
|
+
scene: Scene<TState, TPhysics>,
|
|
957
|
+
ctx: ICtx<TState, TPhysics>,
|
|
958
|
+
): Promise<void> {
|
|
959
|
+
if (!this.#enterScene(scene, ctx)) return;
|
|
960
|
+
const renderer = this.#renderer;
|
|
961
|
+
const nodes = this.#computeDriven.warmupNodes;
|
|
962
|
+
if (renderer === undefined || nodes.length === 0) return;
|
|
963
|
+
this.#sceneEntered = false;
|
|
964
|
+
let report: Awaited<ReturnType<typeof warmUpComputeNodes>> | undefined;
|
|
965
|
+
let failure: string | undefined;
|
|
966
|
+
try {
|
|
967
|
+
report = await warmUpComputeNodes(renderer, nodes, this.#warmUpOptions());
|
|
968
|
+
} catch (error) {
|
|
969
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
970
|
+
}
|
|
971
|
+
console.log(
|
|
972
|
+
`TN_TRANSITION_COMPUTE_WARMUP:${JSON.stringify(
|
|
973
|
+
report === undefined
|
|
974
|
+
? { failed: failure ?? "unknown" }
|
|
975
|
+
: {
|
|
976
|
+
compiled: report.compiled,
|
|
977
|
+
abandoned: report.abandoned,
|
|
978
|
+
unsupported: report.unsupported,
|
|
979
|
+
timedOut: report.timedOut,
|
|
980
|
+
},
|
|
981
|
+
)}`,
|
|
982
|
+
);
|
|
983
|
+
if (!this.#aborted && this.#scene === scene) this.#sceneEntered = true;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
start(): Promise<void> {
|
|
987
|
+
if (this.#started) return Promise.resolve();
|
|
988
|
+
if (this.#pendingStart !== undefined) return this.#pendingStart;
|
|
989
|
+
this.#aborted = false;
|
|
990
|
+
const pendingStart = this.#boot().catch((error: unknown) => {
|
|
991
|
+
this.#disconnectUi();
|
|
992
|
+
throw error;
|
|
993
|
+
});
|
|
994
|
+
this.#pendingStart = pendingStart;
|
|
995
|
+
void pendingStart.then(
|
|
996
|
+
() => {
|
|
997
|
+
if (this.#pendingStart === pendingStart) this.#pendingStart = undefined;
|
|
998
|
+
},
|
|
999
|
+
(error: unknown) => {
|
|
1000
|
+
if (this.#pendingStart === pendingStart) this.#pendingStart = undefined;
|
|
1001
|
+
// Reported by name: a game that writes `void game.start()` otherwise keeps its loading
|
|
1002
|
+
// screen up until the stall watcher says "no asset is outstanding".
|
|
1003
|
+
reportLaunchFailure({
|
|
1004
|
+
kind: "start-failed",
|
|
1005
|
+
message: `The game failed to start: ${error instanceof Error ? error.message : String(error)}`,
|
|
1006
|
+
});
|
|
1007
|
+
},
|
|
1008
|
+
);
|
|
1009
|
+
return pendingStart;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
async #boot(): Promise<void> {
|
|
1013
|
+
const bootSceneName = this.#resumeScene ?? this.#config.start;
|
|
1014
|
+
this.#resumeScene = undefined;
|
|
1015
|
+
const SceneType = this.#config.scenes[bootSceneName];
|
|
1016
|
+
if (SceneType === undefined) throw new Error(`Unknown start scene '${bootSceneName}'.`);
|
|
1017
|
+
this.#connectUi();
|
|
1018
|
+
|
|
1019
|
+
const renderer = await createRenderer({
|
|
1020
|
+
...this.#config.renderer,
|
|
1021
|
+
canvas: this.#config.canvas ?? this.#config.renderer?.canvas,
|
|
1022
|
+
preferWebGPU: this.#config.render?.preferWebGPU ?? this.#config.renderer?.preferWebGPU,
|
|
1023
|
+
// One rule on both runtimes, decided 2026-09-01 after a HiDPI desktop browser upscaled a
|
|
1024
|
+
// DPR-1 web buffer into visible pixelation: the device's real density, with an explicit
|
|
1025
|
+
// `renderer.pixelRatio` winning over it (the old branch silently clobbered that value).
|
|
1026
|
+
// Headless capture lanes run at DPR 1 and are unaffected; the resolution scaler composes
|
|
1027
|
+
// on top, so a density the GPU cannot afford is trimmed by rungs, not by the developer.
|
|
1028
|
+
pixelRatio: this.#config.renderer?.pixelRatio ?? globalThis.devicePixelRatio ?? 1,
|
|
1029
|
+
antialias: resolveRendererAntialias(
|
|
1030
|
+
this.#config.render,
|
|
1031
|
+
this.#config.renderer?.antialias,
|
|
1032
|
+
getPlatform().os,
|
|
1033
|
+
),
|
|
1034
|
+
alphaAntialiasing: resolveRendererAlphaAntialiasing(
|
|
1035
|
+
this.#config.render,
|
|
1036
|
+
this.#config.renderer?.alphaAntialiasing,
|
|
1037
|
+
getPlatform().os,
|
|
1038
|
+
),
|
|
1039
|
+
...resolveRendererScaleSetting(
|
|
1040
|
+
this.#config.render,
|
|
1041
|
+
this.#config.renderer?.resolutionScale,
|
|
1042
|
+
getPlatform().os,
|
|
1043
|
+
),
|
|
1044
|
+
source: this.#config.renderer?.source ?? this.#config.platform?.renderer,
|
|
1045
|
+
});
|
|
1046
|
+
if (this.#aborted) {
|
|
1047
|
+
renderer.dispose();
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
this.#renderer = renderer;
|
|
1051
|
+
const canvas = renderer.domElement;
|
|
1052
|
+
const platform = this.#config.platform;
|
|
1053
|
+
if (platform !== undefined) platform.mountCanvas(canvas, this.#config.container);
|
|
1054
|
+
else if (
|
|
1055
|
+
this.#config.container !== undefined &&
|
|
1056
|
+
canvas.parentElement !== this.#config.container
|
|
1057
|
+
)
|
|
1058
|
+
this.#config.container.append(canvas);
|
|
1059
|
+
else if (canvas.parentElement === null && typeof document !== "undefined")
|
|
1060
|
+
document.body.append(canvas);
|
|
1061
|
+
|
|
1062
|
+
const inputTarget =
|
|
1063
|
+
this.#config.inputTarget ??
|
|
1064
|
+
(platform === undefined
|
|
1065
|
+
? typeof window === "undefined"
|
|
1066
|
+
? canvas
|
|
1067
|
+
: window
|
|
1068
|
+
: (platform.inputTarget ?? canvas));
|
|
1069
|
+
this.#input = new InputMap(
|
|
1070
|
+
this.#config.input,
|
|
1071
|
+
inputTarget,
|
|
1072
|
+
canvas,
|
|
1073
|
+
platform?.input,
|
|
1074
|
+
this.#config.contextMenu,
|
|
1075
|
+
);
|
|
1076
|
+
this.#state.start();
|
|
1077
|
+
const threeScene = new ThreeScene();
|
|
1078
|
+
const camera = createCamera(this.#config.camera);
|
|
1079
|
+
const interpolation = new PhysicsInterpolation(this.#config.physicsInterpolation);
|
|
1080
|
+
this.#interpolation = interpolation;
|
|
1081
|
+
interpolation.track(camera);
|
|
1082
|
+
const viewport = new Viewport({ camera, renderer: this.#renderer, source: platform?.viewport });
|
|
1083
|
+
const canvasLayer = new CanvasLayer(viewport);
|
|
1084
|
+
this.#viewport = viewport;
|
|
1085
|
+
// The renderer goes to the asset loader so compiled KTX2 textures detect transcoding
|
|
1086
|
+
// support against the real backend; a target that supports none fails right here.
|
|
1087
|
+
const assets = createAssetLoader({ ...this.#config.assets, renderer: renderer.raw });
|
|
1088
|
+
if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
|
|
1089
|
+
const entities = new Registry();
|
|
1090
|
+
const random = createRandom(this.#config.seed);
|
|
1091
|
+
const scheduler = new Scheduler();
|
|
1092
|
+
const afterPhysicsPhase = createAfterPhysicsPhase();
|
|
1093
|
+
const input = this.#input;
|
|
1094
|
+
const picker = new ScenePicker({
|
|
1095
|
+
camera,
|
|
1096
|
+
// Input reports window-relative client coordinates; the picker's NDC math is
|
|
1097
|
+
// canvas-relative. Subtract the canvas page offset like replay.ts does for recorded
|
|
1098
|
+
// pointers, or every pick lands displaced by wherever the canvas sits in the layout.
|
|
1099
|
+
pointer: () => {
|
|
1100
|
+
const position = input.raw.pointer.position;
|
|
1101
|
+
const rect = (
|
|
1102
|
+
canvas as { getBoundingClientRect?: () => DOMRect }
|
|
1103
|
+
).getBoundingClientRect?.();
|
|
1104
|
+
return rect === undefined
|
|
1105
|
+
? position
|
|
1106
|
+
: new Vector2(position.x - rect.left, position.y - rect.top);
|
|
1107
|
+
},
|
|
1108
|
+
scene: threeScene,
|
|
1109
|
+
viewport,
|
|
1110
|
+
});
|
|
1111
|
+
this.#picker = picker;
|
|
1112
|
+
const pointerEvents = new PointerEvents3D({
|
|
1113
|
+
screen: (position, target) => {
|
|
1114
|
+
const rect = (
|
|
1115
|
+
canvas as { getBoundingClientRect?: () => DOMRect }
|
|
1116
|
+
).getBoundingClientRect?.();
|
|
1117
|
+
return rect === undefined
|
|
1118
|
+
? target.copy(position)
|
|
1119
|
+
: target.set(position.x - rect.left, position.y - rect.top);
|
|
1120
|
+
},
|
|
1121
|
+
});
|
|
1122
|
+
this.#pointerEvents = pointerEvents;
|
|
1123
|
+
const loopState: { current?: FixedStepLoop } = {};
|
|
1124
|
+
// The engine owns the world-matrix walk, not three's renderer: on by default it does not recurse
|
|
1125
|
+
// into a hidden subtree, and `renderer.matrixWorld: "all"` restores the every-node walk. The
|
|
1126
|
+
// authored scene is marked once, here, so three never walks it a second time; the mirror scene
|
|
1127
|
+
// is marked at the render site, where whichever root is drawn this frame is known.
|
|
1128
|
+
const matrixWorldPass = new MatrixWorldPass({
|
|
1129
|
+
mode: resolveMatrixWorldMode(this.#config.render),
|
|
1130
|
+
});
|
|
1131
|
+
this.#matrixWorld = matrixWorldPass;
|
|
1132
|
+
threeScene.matrixWorldAutoUpdate = false;
|
|
1133
|
+
// Built before the context because `ctx.startup` reads it: a game asks what the framework's
|
|
1134
|
+
// startup is doing, and the answer is this pass.
|
|
1135
|
+
const projection = new SceneRenderProjection(threeScene, {
|
|
1136
|
+
// The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
|
|
1137
|
+
// names the material check beside accepting it, and the projection owns both readings.
|
|
1138
|
+
projection: this.#config.render?.projection,
|
|
1139
|
+
velocity: () => renderer.renderChainUsesPerObjectVelocity?.() ?? false,
|
|
1140
|
+
matrixWorld: matrixWorldPass,
|
|
1141
|
+
});
|
|
1142
|
+
this.#projection = projection;
|
|
1143
|
+
// Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
|
|
1144
|
+
// and measured whether or not the game narrows or declines it. Its decision is per camera, so
|
|
1145
|
+
// a shadow caster and anything attached to the camera are never dropped on the main view alone.
|
|
1146
|
+
const cameraCull = new RenderCameraCull({
|
|
1147
|
+
minimumPixels: this.#config.render?.minimumProjectedPixels,
|
|
1148
|
+
});
|
|
1149
|
+
this.#cameraCull = cameraCull;
|
|
1150
|
+
let projectionSettled = false;
|
|
1151
|
+
/**
|
|
1152
|
+
* Progress is a high-water mark over the measured load state, never a value that can fall.
|
|
1153
|
+
*
|
|
1154
|
+
* The ratio's denominator grows: a request registered after an earlier one settled shrinks
|
|
1155
|
+
* `settled / requested`, and the file-count and byte branches can disagree across the switch
|
|
1156
|
+
* the first weighed manifest entry triggers. Both make the bar jump backwards, which a player
|
|
1157
|
+
* reads as the load restarting. Measured: a second texture requested after the first settled
|
|
1158
|
+
* took the reported value from 0.7 to 0.35.
|
|
1159
|
+
*/
|
|
1160
|
+
let reportedProgress = 0;
|
|
1161
|
+
/** What the load state says right now. This may fall; `startup.progress` is what never does. */
|
|
1162
|
+
const measuredProgress = (): number => {
|
|
1163
|
+
if (projectionSettled) return 1;
|
|
1164
|
+
// A registered hold owns the last tenth. Without this the bar sat at 0.9 for the whole
|
|
1165
|
+
// of the game's own tier and then jumped, which is the reading a player calls frozen.
|
|
1166
|
+
if (startupReadiness.frameworkReady) {
|
|
1167
|
+
const held = startupReadiness.holdReport.length;
|
|
1168
|
+
if (held === 0) return 0.9;
|
|
1169
|
+
const settled = held - startupReadiness.pendingHolds.length;
|
|
1170
|
+
return 0.9 + 0.1 * (settled / held);
|
|
1171
|
+
}
|
|
1172
|
+
if (startupReadiness.compileSettled) return 0.9;
|
|
1173
|
+
if (timeline.enteredMs !== undefined) return 0.8;
|
|
1174
|
+
const { requested, requestedBytes, settled, settledBytes } = assets.progress;
|
|
1175
|
+
// Bytes when the manifest knows them, files when it does not. A file count spends the
|
|
1176
|
+
// same travel on a 4 KB icon as on a 710 MB model, which is how a bar reaches 92% and
|
|
1177
|
+
// then stands still for the rest of the download.
|
|
1178
|
+
if (requestedBytes > 0) return 0.7 * Math.min(1, settledBytes / requestedBytes);
|
|
1179
|
+
return requested === 0 ? 0 : 0.7 * Math.min(1, settled / requested);
|
|
1180
|
+
};
|
|
1181
|
+
let worldRendered = false;
|
|
1182
|
+
let loadingFramePresented = false;
|
|
1183
|
+
let markProjectionSettled: () => void = () => undefined;
|
|
1184
|
+
const projectionReady = new Promise<void>((resolve) => {
|
|
1185
|
+
markProjectionSettled = resolve;
|
|
1186
|
+
});
|
|
1187
|
+
const startupReadiness = new StartupReadiness({
|
|
1188
|
+
/**
|
|
1189
|
+
* The second warm-up: everything a game attached while it held startup.
|
|
1190
|
+
*
|
|
1191
|
+
* The first pass runs at framework readiness, which for a streaming game is before most of
|
|
1192
|
+
* the world exists. Without this, `hold()` buys a complete *picture* and leaves a scene whose
|
|
1193
|
+
* every material still compiles on first sight — which is worse than the pop-in it replaced,
|
|
1194
|
+
* because a compile stall lands while the player is walking rather than while they are
|
|
1195
|
+
* waiting. Measured on a 46,190-instance forest: 8 pipelines warmed, then 28 main-thread
|
|
1196
|
+
* tasks over 40 ms in a minute of play, the worst 267 ms.
|
|
1197
|
+
*
|
|
1198
|
+
* A third of the compile budget, not the whole of it, because this one is spent with the
|
|
1199
|
+
* player already waiting behind a curtain that has been up for seconds. Whatever does not
|
|
1200
|
+
* fit still compiles lazily — the same as before — so the ceiling on the wait is bounded and
|
|
1201
|
+
* the worst case is the behaviour we already had.
|
|
1202
|
+
*/
|
|
1203
|
+
afterHolds: async () => {
|
|
1204
|
+
await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
|
|
1205
|
+
},
|
|
1206
|
+
});
|
|
1207
|
+
// Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
|
|
1208
|
+
// script ran, not that a pixel reached the screen, so waiting on it never closed the race it
|
|
1209
|
+
// was added for — it only made the losing side lose later, after up to 45 s of held frames.
|
|
1210
|
+
// The race no longer exists: the native UI is now composited into the game's own frame, so the
|
|
1211
|
+
// cover and the world share one swapchain and there is no second surface left to arrive late.
|
|
1212
|
+
// The held loop starts before an explicit warm-up so the loading surface can animate. A native
|
|
1213
|
+
// frame may therefore arrive while that pass is still awaiting a compile promise; keep first-use
|
|
1214
|
+
// rendering and compute behind the same held boundary until the explicit pass has settled.
|
|
1215
|
+
let explicitWarmUpSettled = !this.#warmUpConfiguredExplicitly();
|
|
1216
|
+
// A web UI is the loading surface on native and on the web. Its bridge must be both attached
|
|
1217
|
+
// and announced ready: an attached but unrendered web view is not a cover the player can see.
|
|
1218
|
+
// Keep this predicate tied to an actually attached and rendered web UI. The render path still
|
|
1219
|
+
// lets a settled world render behind either kind of cover; only the unresolved first-use work
|
|
1220
|
+
// is held, so a persistent HUD cannot stop the world pass after loading.
|
|
1221
|
+
const startupCoverActive = (): boolean =>
|
|
1222
|
+
!startupReadiness.ready &&
|
|
1223
|
+
(canvasLayer.opaque || (this.#uiReady && this.#uiBridge?.hasPeer() === true));
|
|
1224
|
+
const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
|
|
1225
|
+
let warmUpStatus: IStartupStatus["warmup"];
|
|
1226
|
+
const now = (): number => globalThis.performance?.now() ?? Date.now();
|
|
1227
|
+
/**
|
|
1228
|
+
* A launch that stops making progress says so, on the page, instead of leaving a loading
|
|
1229
|
+
* screen up forever. Measured on `midway-open-pacific`: a 104 s launch and then a lost GPU
|
|
1230
|
+
* device, with the only account of either on a terminal the player does not have.
|
|
1231
|
+
*/
|
|
1232
|
+
const stopStallWatch = watchStartupStall({
|
|
1233
|
+
pending: () => [...assets.progress.pending, ...startupReadiness.pendingHolds],
|
|
1234
|
+
progress: () => this.#ctx?.startup.progress ?? 0,
|
|
1235
|
+
workProgress: () => assets.progress.settled + startupReadiness.workProgress,
|
|
1236
|
+
stallMs: STARTUP_STALL_MS,
|
|
1237
|
+
});
|
|
1238
|
+
watchDeviceLoss(
|
|
1239
|
+
(
|
|
1240
|
+
renderer.raw as {
|
|
1241
|
+
backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
|
|
1242
|
+
}
|
|
1243
|
+
).backend?.device,
|
|
1244
|
+
);
|
|
1245
|
+
// Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
|
|
1246
|
+
// registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
|
|
1247
|
+
// framework cost" and "what the player waited for", and collapsing them is how a valley that
|
|
1248
|
+
// took 8.8 s to appear reported 1.5 s.
|
|
1249
|
+
void startupReadiness.whenFrameworkReady().then(() => {
|
|
1250
|
+
timeline.compileSettledMs ??= now();
|
|
1251
|
+
timeline.frameworkReadyMs ??= now();
|
|
1252
|
+
});
|
|
1253
|
+
void startupReadiness.whenReady().then(() => {
|
|
1254
|
+
stopStallWatch();
|
|
1255
|
+
// A renderer without first-use compilation settles without running the compile closure
|
|
1256
|
+
// below, so the settle stamp is guaranteed here at the latest.
|
|
1257
|
+
timeline.compileSettledMs ??= now();
|
|
1258
|
+
timeline.frameworkReadyMs ??= now();
|
|
1259
|
+
timeline.readyMs ??= now();
|
|
1260
|
+
projectionSettled = true;
|
|
1261
|
+
markProjectionSettled();
|
|
1262
|
+
// A host capturing a frame has no other way to know the world is on screen. Counting frames
|
|
1263
|
+
// cannot express it: on a software rasteriser the gate resolves on its bounded window rather
|
|
1264
|
+
// than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
|
|
1265
|
+
// and captures the loading state. The native screenshot path waits on this flag.
|
|
1266
|
+
(globalThis as Record<string, unknown>)[STARTUP_READY_GLOBAL] = true;
|
|
1267
|
+
// Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
|
|
1268
|
+
const unlit = unlitFoliageWarning(threeScene);
|
|
1269
|
+
if (unlit !== undefined)
|
|
1270
|
+
console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
|
|
1271
|
+
});
|
|
1272
|
+
const warmUp = async (marker: string, budgetMs: number, stamp: boolean): Promise<void> => {
|
|
1273
|
+
if (this.#aborted || this.#renderer === undefined) return;
|
|
1274
|
+
let report: IWarmUpReport | undefined;
|
|
1275
|
+
let failure: string | undefined;
|
|
1276
|
+
try {
|
|
1277
|
+
projection.reconcile();
|
|
1278
|
+
// The frame loop's own walk, run here too because the warm-up draws before that loop does.
|
|
1279
|
+
// Three is told not to walk the scene (`matrixWorldAutoUpdate = false`), and a declined
|
|
1280
|
+
// projection returns from `reconcile()` without walking it, so without this the warm render
|
|
1281
|
+
// compiles every pipeline against stale world matrices and the real frames then build the
|
|
1282
|
+
// rest synchronously -- tens of seconds each on a software adapter, which loses the device.
|
|
1283
|
+
this.#matrixWorld?.apply(projection.root);
|
|
1284
|
+
report = await warmUpScene(renderer, projection.root, camera, {
|
|
1285
|
+
budgetMs,
|
|
1286
|
+
computeNodes: this.#computeDriven.warmupNodes,
|
|
1287
|
+
renderPasses: this.#warmUpOptions().renderPasses,
|
|
1288
|
+
includeHidden: this.#warmUpOptions().includeHidden,
|
|
1289
|
+
});
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
1292
|
+
}
|
|
1293
|
+
// With an explicit warm-up, this held pass is only the first half of startup. Stamp after
|
|
1294
|
+
// the explicit pass so its own pipelines remain inside the settled boundary; without one,
|
|
1295
|
+
// this is the only warm-up completion.
|
|
1296
|
+
if (stamp || !this.#warmUpConfiguredExplicitly()) renderer.warmUpSettled?.();
|
|
1297
|
+
warmUpStatus =
|
|
1298
|
+
report === undefined
|
|
1299
|
+
? { status: "unavailable" }
|
|
1300
|
+
: {
|
|
1301
|
+
attempted: report.attempted,
|
|
1302
|
+
candidates: report.candidates,
|
|
1303
|
+
observed: report.observed,
|
|
1304
|
+
status: report.observed.status,
|
|
1305
|
+
};
|
|
1306
|
+
if (stamp) timeline.compileSettledMs ??= now();
|
|
1307
|
+
console.log(
|
|
1308
|
+
`${marker}:${JSON.stringify(
|
|
1309
|
+
report === undefined
|
|
1310
|
+
? { failed: failure ?? "unknown" }
|
|
1311
|
+
: {
|
|
1312
|
+
compiled: report.compiled,
|
|
1313
|
+
pipelines: report.pipelines,
|
|
1314
|
+
candidates: report.candidates,
|
|
1315
|
+
attempted: report.attempted,
|
|
1316
|
+
observed: report.observed,
|
|
1317
|
+
slices: report.slices,
|
|
1318
|
+
elapsedMs: Math.round(report.elapsedMs),
|
|
1319
|
+
unsupported: report.unsupported,
|
|
1320
|
+
abandoned: report.abandoned,
|
|
1321
|
+
timedOut: report.timedOut,
|
|
1322
|
+
computeCompiled: report.computeCompiled,
|
|
1323
|
+
computeAbandoned: report.computeAbandoned,
|
|
1324
|
+
computeUnsupported: report.computeUnsupported,
|
|
1325
|
+
computeTimedOut: report.computeTimedOut,
|
|
1326
|
+
passes: report.passes,
|
|
1327
|
+
passPipelines: report.passPipelines,
|
|
1328
|
+
cullingForced: report.cullingForced,
|
|
1329
|
+
visibilityForced: report.visibilityForced,
|
|
1330
|
+
cache: report.cache,
|
|
1331
|
+
},
|
|
1332
|
+
)}`,
|
|
1333
|
+
);
|
|
1334
|
+
};
|
|
1335
|
+
const startupCompile: StartupCompile = async (): Promise<void> => {
|
|
1336
|
+
await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
|
|
1337
|
+
};
|
|
1338
|
+
// The GPU-selected main-pass tally, registered by whichever streamed world is added to the
|
|
1339
|
+
// scene. The frame budget reads it once per window; a world with no sample reports undefined, so
|
|
1340
|
+
// the window carries nothing rather than a zero no frame selected.
|
|
1341
|
+
let gpuTallyProvider:
|
|
1342
|
+
| (() => { readonly instances: number; readonly triangles: number } | undefined)
|
|
1343
|
+
| undefined;
|
|
1344
|
+
const ctx: ICtx<TState, TPhysics> = {
|
|
1345
|
+
get frameTime() {
|
|
1346
|
+
return loopState.current?.frameTime ?? 0;
|
|
1347
|
+
},
|
|
1348
|
+
get alpha() {
|
|
1349
|
+
return loopState.current?.alpha ?? 0;
|
|
1350
|
+
},
|
|
1351
|
+
interpolate: (object) => interpolation.track(object),
|
|
1352
|
+
resetInterpolation: (object) => interpolation.reset(object),
|
|
1353
|
+
add: (object) => {
|
|
1354
|
+
// Narrowed through a plain `Object3D` rather than the type parameter: a type guard applied
|
|
1355
|
+
// to `T` yields `T & IComputeDriven`, which TypeScript will not carry to the registry's
|
|
1356
|
+
// `Object3D & IComputeDriven` without a cast. The local keeps the guard honest and the
|
|
1357
|
+
// return keeps the caller's own type, so a game never casts back what it just built.
|
|
1358
|
+
const node: Object3D = object;
|
|
1359
|
+
threeScene.add(node);
|
|
1360
|
+
if (typeof (node as { aerialPerspective?: unknown }).aerialPerspective === "function") {
|
|
1361
|
+
this.#hasDepthCoupledOutput = true;
|
|
1362
|
+
}
|
|
1363
|
+
if (isComputeDriven(node)) {
|
|
1364
|
+
const activeRenderer = this.#renderer;
|
|
1365
|
+
if (activeRenderer === undefined)
|
|
1366
|
+
throw new Error("Cannot add a compute-driven object before the game starts.");
|
|
1367
|
+
this.#computeDriven.add(node, activeRenderer);
|
|
1368
|
+
}
|
|
1369
|
+
// A streamed world that can say what the GPU selected, so `TN_FRAME_BUDGET` reports the
|
|
1370
|
+
// GPU-selected main-pass count beside its pass record. The tally is asked for only when the
|
|
1371
|
+
// frame budget is on: with it off and no validation, the world adds no readback at all.
|
|
1372
|
+
const tallySource = node as {
|
|
1373
|
+
enableGpuSceneTally?: () => void;
|
|
1374
|
+
gpuSceneTally?: () =>
|
|
1375
|
+
| { readonly instances: number; readonly triangles: number }
|
|
1376
|
+
| undefined;
|
|
1377
|
+
};
|
|
1378
|
+
if (typeof tallySource.gpuSceneTally === "function") {
|
|
1379
|
+
gpuTallyProvider = tallySource.gpuSceneTally.bind(node);
|
|
1380
|
+
if (this.#config.frameBudget !== false) tallySource.enableGpuSceneTally?.();
|
|
1381
|
+
}
|
|
1382
|
+
return object;
|
|
1383
|
+
},
|
|
1384
|
+
assets,
|
|
1385
|
+
after: (delay, callback) => scheduler.after(delay, callback),
|
|
1386
|
+
afterPhysics: (callback) => afterPhysicsPhase.register(callback),
|
|
1387
|
+
beforeRender: (callback) => {
|
|
1388
|
+
if (typeof callback !== "function")
|
|
1389
|
+
throw new Error("beforeRender requires a callback function.");
|
|
1390
|
+
this.#beforeRenderCallbacks.add(callback);
|
|
1391
|
+
return () => this.#beforeRenderCallbacks.delete(callback);
|
|
1392
|
+
},
|
|
1393
|
+
camera,
|
|
1394
|
+
canvasLayer,
|
|
1395
|
+
entities,
|
|
1396
|
+
every: (callback) => scheduler.every(callback),
|
|
1397
|
+
get fps() {
|
|
1398
|
+
return loopState.current?.fps ?? 0;
|
|
1399
|
+
},
|
|
1400
|
+
goto: (name) => this.#goto(name, ctx),
|
|
1401
|
+
input: this.#input,
|
|
1402
|
+
pointer: pointerEvents,
|
|
1403
|
+
physics: undefined as TPhysics,
|
|
1404
|
+
random,
|
|
1405
|
+
raycast: (options) => picker.raycast(options),
|
|
1406
|
+
raycastAll: (options, target) => picker.raycastAll(options, target),
|
|
1407
|
+
startup: {
|
|
1408
|
+
get warmup() {
|
|
1409
|
+
return warmUpStatus;
|
|
1410
|
+
},
|
|
1411
|
+
get phase() {
|
|
1412
|
+
// The projection is reconciled before the first world draw, but readiness is not reported
|
|
1413
|
+
// until first-use work and a sustained in-budget window have completed. An opaque loading
|
|
1414
|
+
// layer cannot turn `whenReady()` into a first-present signal while work is still waiting
|
|
1415
|
+
// behind it.
|
|
1416
|
+
if (projectionSettled) return "ready" as const;
|
|
1417
|
+
return "collapsing" as const;
|
|
1418
|
+
},
|
|
1419
|
+
// True once first-use compilation has settled, which is earlier than `phase === "ready"`
|
|
1420
|
+
// and is the signal a game wants when it must not act during the launch. `phase` cannot
|
|
1421
|
+
// express it: it is binary, and readiness additionally requires a sustained in-budget
|
|
1422
|
+
// frame window that a software rasteriser can only ever let expire. A game gated on
|
|
1423
|
+
// `phase` alone therefore does nothing for ~25s on such a lane — measured as a chase route
|
|
1424
|
+
// of length 0.000000 where 6 was required, because the scenario ended first.
|
|
1425
|
+
get compileSettled() {
|
|
1426
|
+
return startupReadiness.compileSettled;
|
|
1427
|
+
},
|
|
1428
|
+
// Honest and monotonic: the asset ratio carries the first 70% while the start scene
|
|
1429
|
+
// loads, entering the world is 80%, compile settling 90%, and only readiness is 1.
|
|
1430
|
+
// Monotonicity is enforced rather than assumed — see the high-water mark above.
|
|
1431
|
+
get progress() {
|
|
1432
|
+
reportedProgress = Math.max(reportedProgress, measuredProgress());
|
|
1433
|
+
return reportedProgress;
|
|
1434
|
+
},
|
|
1435
|
+
hold: (label, work, budgetMs, progress) => {
|
|
1436
|
+
startupReadiness.hold(label, work, budgetMs, progress);
|
|
1437
|
+
},
|
|
1438
|
+
get timeline() {
|
|
1439
|
+
return { ...timeline };
|
|
1440
|
+
},
|
|
1441
|
+
whenReady: () => projectionReady,
|
|
1442
|
+
whenFrameworkReady: () => startupReadiness.whenFrameworkReady(),
|
|
1443
|
+
},
|
|
1444
|
+
renderer: this.#renderer,
|
|
1445
|
+
viewport,
|
|
1446
|
+
scene: threeScene,
|
|
1447
|
+
state: this.#state,
|
|
1448
|
+
tween: (target, properties, duration, options) =>
|
|
1449
|
+
scheduler.tween(target, properties, duration, options),
|
|
1450
|
+
};
|
|
1451
|
+
this.#ctx = ctx;
|
|
1452
|
+
this.#entities = entities;
|
|
1453
|
+
this.#scheduler = scheduler;
|
|
1454
|
+
this.#afterPhysicsPhase = afterPhysicsPhase;
|
|
1455
|
+
const devToolsHost =
|
|
1456
|
+
platform === undefined
|
|
1457
|
+
? typeof window === "undefined"
|
|
1458
|
+
? undefined
|
|
1459
|
+
: window
|
|
1460
|
+
: platform.devToolsHost;
|
|
1461
|
+
this.#cleanup.push(
|
|
1462
|
+
installDevTools(
|
|
1463
|
+
entities,
|
|
1464
|
+
devToolsHost as DevToolsHost | undefined,
|
|
1465
|
+
() => this.#geometryCapture,
|
|
1466
|
+
),
|
|
1467
|
+
);
|
|
1468
|
+
this.#scene = new SceneType();
|
|
1469
|
+
this.#sceneName = bootSceneName;
|
|
1470
|
+
// The scaler exists whenever the scale is automatic, which now includes a game that said
|
|
1471
|
+
// nothing about it. A pinned number leaves this undefined, which is what makes "pinned" a
|
|
1472
|
+
// guarantee rather than a preference the loop may overrule. `maxFps: 0` removes the ceiling,
|
|
1473
|
+
// and a scaler with no budget is not a scaler with a loose one, so an uncapped game simply
|
|
1474
|
+
// does not get adaptive scaling.
|
|
1475
|
+
const initialTarget = resolveTargetFps(this.#config, getPlatform());
|
|
1476
|
+
let heldTargetFps = initialTarget.targetFps;
|
|
1477
|
+
// Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
|
|
1478
|
+
renderer.noteTargetFps?.(initialTarget.targetFps);
|
|
1479
|
+
const scaler =
|
|
1480
|
+
renderer.surface().scaleSource === "auto" && initialTarget.targetFps > 0
|
|
1481
|
+
? new ResolutionScaler({
|
|
1482
|
+
// Phones keep the device ladder; a desktop stops before its bottom, where a picture
|
|
1483
|
+
// with nothing reconstructing it stops being a faster frame and becomes a blur.
|
|
1484
|
+
minScale: resolvePlatformResolutionFloor(getPlatform().os),
|
|
1485
|
+
// The adapter family picks the first rung; the first eligible window still decides.
|
|
1486
|
+
start:
|
|
1487
|
+
renderer.gpuClass === undefined
|
|
1488
|
+
? undefined
|
|
1489
|
+
: RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class],
|
|
1490
|
+
targetFps: initialTarget.targetFps,
|
|
1491
|
+
// No floor lift from motion data: consuming velocity is not upscaling. Three's TRAA
|
|
1492
|
+
// accumulates at the canvas's own size, so lifting the floor for it let a forest frame
|
|
1493
|
+
// fall to 0.23 (442x248 on a 1920x1080 canvas). Only a stage that reconstructs a
|
|
1494
|
+
// display-resolution frame may pass `temporalUpscale`, and none ships today.
|
|
1495
|
+
})
|
|
1496
|
+
: undefined;
|
|
1497
|
+
// A class that starts below the ceiling must draw there from the first frame; the scaler only
|
|
1498
|
+
// reports a scale, and nothing else would apply it until a window steps.
|
|
1499
|
+
if (scaler !== undefined && scaler.scale !== 1)
|
|
1500
|
+
renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
|
|
1501
|
+
// The panel's own rate, once a window of presented frames can say it. The native host's
|
|
1502
|
+
// present counter is the only series there that counts displays rather than loop iterations;
|
|
1503
|
+
// on the web one rAF callback is one vblank, so the median presented interval is the period.
|
|
1504
|
+
let measuredRefreshHz: number | undefined;
|
|
1505
|
+
// The world pass's own draw-call count, kept from the last frame of the window so the
|
|
1506
|
+
// projection line can report what the renderer was handed beside what the plan predicted.
|
|
1507
|
+
// A plan and a measurement that disagree is the finding; one number pretending to be both
|
|
1508
|
+
// is how an optimizer reports a win it did not deliver.
|
|
1509
|
+
let lastWorldDrawCalls: number | undefined;
|
|
1510
|
+
// Completion on the last frame must not make an otherwise compiling window look clean.
|
|
1511
|
+
let compilingInWindow = false;
|
|
1512
|
+
let lastCompileCount = renderer.compileCount;
|
|
1513
|
+
const observeCompilation = (): void => {
|
|
1514
|
+
const count = renderer.compileCount;
|
|
1515
|
+
compilingInWindow ||= renderer.compiling === true || count !== lastCompileCount;
|
|
1516
|
+
lastCompileCount = count;
|
|
1517
|
+
};
|
|
1518
|
+
// Built here rather than inside the loop so `frameBudget: false` is a single decision with a
|
|
1519
|
+
// single owner, and so the render phases below feed the same instrument the loop feeds.
|
|
1520
|
+
const frameBudget =
|
|
1521
|
+
this.#config.frameBudget === false
|
|
1522
|
+
? undefined
|
|
1523
|
+
: new FrameBudget({
|
|
1524
|
+
...this.#config.frameBudget,
|
|
1525
|
+
simulation: {
|
|
1526
|
+
tick: () => gameLoop.tick(),
|
|
1527
|
+
get step() {
|
|
1528
|
+
return gameLoop.step;
|
|
1529
|
+
},
|
|
1530
|
+
},
|
|
1531
|
+
// The scaler reads the same windows the marker reports, so what it acted on and what
|
|
1532
|
+
// the record shows are the same measurement rather than two sampling paths.
|
|
1533
|
+
onWindow: (reported) => {
|
|
1534
|
+
const sink =
|
|
1535
|
+
this.#config.frameBudget === false ? undefined : this.#config.frameBudget?.report;
|
|
1536
|
+
const reportInfo = sink ?? console.info;
|
|
1537
|
+
const reportWarning = sink ?? console.warn;
|
|
1538
|
+
observeCompilation();
|
|
1539
|
+
const compileObserved = compilingInWindow;
|
|
1540
|
+
compilingInWindow = false;
|
|
1541
|
+
// The display's own rate, read once per window from the cadence the loop already
|
|
1542
|
+
// measured: the host's present counter where there is one, else the median presented
|
|
1543
|
+
// interval, which on the web is the vblank period because rAF is the presentation.
|
|
1544
|
+
measuredRefreshHz =
|
|
1545
|
+
reported.presentedFps ??
|
|
1546
|
+
(reported.presented.p50 > 0 ? 1_000 / reported.presented.p50 : undefined);
|
|
1547
|
+
const target = resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz);
|
|
1548
|
+
renderer.noteTargetFps?.(target.targetFps);
|
|
1549
|
+
if (
|
|
1550
|
+
scaler !== undefined &&
|
|
1551
|
+
target.targetFps > 0 &&
|
|
1552
|
+
target.targetFps !== heldTargetFps
|
|
1553
|
+
) {
|
|
1554
|
+
heldTargetFps = target.targetFps;
|
|
1555
|
+
scaler.retarget(heldTargetFps);
|
|
1556
|
+
}
|
|
1557
|
+
renderer.observeRenderChainBudget?.(reported);
|
|
1558
|
+
this.#computeDriven.observeBudget(reported);
|
|
1559
|
+
const projection = this.#projection;
|
|
1560
|
+
// Printed every window, projecting or declined. `TN_RENDER_PROJECTION` says once
|
|
1561
|
+
// whether the optimizer engaged; this says, repeatedly, what it is still leaving on
|
|
1562
|
+
// the exact lane and whether the renderer agrees with the plan.
|
|
1563
|
+
if (projection !== undefined) {
|
|
1564
|
+
reportInfo(
|
|
1565
|
+
formatProjectionWindow(
|
|
1566
|
+
projection.report,
|
|
1567
|
+
reported.window,
|
|
1568
|
+
lastWorldDrawCalls,
|
|
1569
|
+
this.#cameraCull?.report,
|
|
1570
|
+
this.#matrixWorld?.report,
|
|
1571
|
+
),
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
1574
|
+
if (this.#config.frameBudget !== false)
|
|
1575
|
+
this.#config.frameBudget?.onWindow?.(reported);
|
|
1576
|
+
// The span tree closes on the same window, so the two lines in a log describe the
|
|
1577
|
+
// same frames and a reader can subtract one from the other without a second clock.
|
|
1578
|
+
const spanWindow = spans?.window();
|
|
1579
|
+
if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
|
|
1580
|
+
// The scene-shape verdict, on by default, from the census the frame already took.
|
|
1581
|
+
// An agent building a scene of the wrong shape reads it in the log before a human
|
|
1582
|
+
// ever plays the game and calls it slow.
|
|
1583
|
+
const staticCensus = staticTransformCensus();
|
|
1584
|
+
if (staticCensus.roots > 0)
|
|
1585
|
+
reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
|
|
1586
|
+
const validation = renderListValidator?.report();
|
|
1587
|
+
if (validation !== undefined) reportInfo(formatValidationReport(validation));
|
|
1588
|
+
const warning = sceneWarning(
|
|
1589
|
+
reported,
|
|
1590
|
+
describeSceneShape(reported, this.#cameraCull?.report),
|
|
1591
|
+
target.targetFps,
|
|
1592
|
+
);
|
|
1593
|
+
if (warning !== undefined) reportWarning(formatSceneWarning(warning));
|
|
1594
|
+
// The same sentence goes to the UI on a dev launch, so a human watching the window
|
|
1595
|
+
// and an agent reading the log are told the same thing at the same time. No frame
|
|
1596
|
+
// rate rides it: the loop's own rAF rate reads throttled under a compositor or a
|
|
1597
|
+
// virtual display, so a number drawn from it lies in exactly the sessions where
|
|
1598
|
+
// somebody is trying to measure.
|
|
1599
|
+
if (
|
|
1600
|
+
devMetricsEnabled &&
|
|
1601
|
+
warning !== undefined &&
|
|
1602
|
+
this.#uiBridge?.hasPeer() === true
|
|
1603
|
+
) {
|
|
1604
|
+
const verdict = describeSceneWarning(warning);
|
|
1605
|
+
if (verdict !== postedVerdict) {
|
|
1606
|
+
postedVerdict = verdict;
|
|
1607
|
+
this.#uiBridge.post({ type: UI_DEV_METRICS_MESSAGE, sceneWarning: verdict });
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
if (scaler === undefined) return;
|
|
1611
|
+
// **Not while the world is still arriving.** The scaler judges the game by closed
|
|
1612
|
+
// frame-budget windows, and the windows that close during a launch are not the game:
|
|
1613
|
+
// they are asset decode, scene construction and first-use compilation. Measured on
|
|
1614
|
+
// sandbox/wildwood, a 46,190-instance forest, the first two windows reported 18.8
|
|
1615
|
+
// and 27.3 fps against a 60 fps budget — a deficit large enough that `#rungsToDrop`
|
|
1616
|
+
// crossed three rungs at once and the buffer went from 1600x900 to 976x549 before
|
|
1617
|
+
// the player had control. It then settled at 0.72, which is 52% of the pixels, and
|
|
1618
|
+
// re-probed 0.85 every thirty seconds, missed, and fell back — so the picture went
|
|
1619
|
+
// soft a few seconds in and never fully recovered. The owner's report was "after a
|
|
1620
|
+
// while everything becomes blurry, and keeps getting worse".
|
|
1621
|
+
//
|
|
1622
|
+
// Readiness is the right gate rather than a frame count or a timer: it is the moment
|
|
1623
|
+
// the framework already defines as "the world is safe to show", it now includes
|
|
1624
|
+
// anything the game held startup for, and a host that never reaches it still gets
|
|
1625
|
+
// there on the bounded fallbacks inside `StartupReadiness`.
|
|
1626
|
+
if (!startupReadiness.ready || compileObserved) return;
|
|
1627
|
+
const stepped = scaler.observe(reported);
|
|
1628
|
+
if (stepped !== undefined) renderer.setResolutionScale(stepped, scaler.scaleSource);
|
|
1629
|
+
},
|
|
1630
|
+
// Last, so the engine's own renderer answers this and a game cannot report a
|
|
1631
|
+
// resolution it is not drawing at. The window carries it in both pinned and auto
|
|
1632
|
+
// modes: turning the convention off does not turn its measurement off.
|
|
1633
|
+
readGpuAgeFrames: () => renderer.gpuFrameAge?.(),
|
|
1634
|
+
// The world's own count of what the GPU selected, not `info.render.triangles`' upper
|
|
1635
|
+
// bound over mesh capacity. Absent until the world's first tally lands.
|
|
1636
|
+
readGpuTally: () => gpuTallyProvider?.(),
|
|
1637
|
+
// The resolved budget rides the window rather than a marker of its own, so a harness
|
|
1638
|
+
// reads the target and the frames it was judged against out of one line. It lags the
|
|
1639
|
+
// window by one, because the window is built before this callback runs.
|
|
1640
|
+
readTarget: () => resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz),
|
|
1641
|
+
readSurface: () => {
|
|
1642
|
+
observeCompilation();
|
|
1643
|
+
return {
|
|
1644
|
+
...renderer.surface(),
|
|
1645
|
+
...(scaler === undefined ? {} : { atFloor: scaler.atFloor }),
|
|
1646
|
+
compiling: compilingInWindow,
|
|
1647
|
+
};
|
|
1648
|
+
},
|
|
1649
|
+
});
|
|
1650
|
+
this.#frameBudget = frameBudget;
|
|
1651
|
+
// Per-pass draws and triangles ride the frame budget's window by default. The same property
|
|
1652
|
+
// that makes `info.render` an aggregate — one reset per frame before the world render, and
|
|
1653
|
+
// nested shadow/reflection renders sharing that counter — is what this recorder unwinds.
|
|
1654
|
+
const renderPassBudget =
|
|
1655
|
+
frameBudget === undefined
|
|
1656
|
+
? undefined
|
|
1657
|
+
: RenderPassBudget.install(renderer.raw as Parameters<typeof RenderPassBudget.install>[0]);
|
|
1658
|
+
// Spans are a diagnostic, never a convention: nothing installs them unless `TN_FRAME_SPANS`
|
|
1659
|
+
// asks for them, and every call site below is one guarded return when it does not. They wrap
|
|
1660
|
+
// three's own render path rather than reimplementing it, so what they measure is the path that
|
|
1661
|
+
// ships, and they are removed with the game.
|
|
1662
|
+
const spans = spansRequested() ? new SpanRecorder() : undefined;
|
|
1663
|
+
if (spans !== undefined) setSpanRecorder(spans);
|
|
1664
|
+
const removeSpanProbes =
|
|
1665
|
+
spans === undefined
|
|
1666
|
+
? undefined
|
|
1667
|
+
: installSpanProbes(renderer.raw as Parameters<typeof installSpanProbes>[0], threeScene);
|
|
1668
|
+
// The boundary counts ride the same flag: they wrap every WebGPU command of the frame, which is
|
|
1669
|
+
// work a shipped build must not pay for a diagnostic it did not ask for.
|
|
1670
|
+
const frameCounters =
|
|
1671
|
+
spans === undefined ? undefined : FrameCounters.install(counterDeviceOf(renderer.raw));
|
|
1672
|
+
// The parity oracle for the static freeze. Off by default and expensive on purpose: it
|
|
1673
|
+
// recomputes every world matrix the long way and throws on the first that disagrees with what
|
|
1674
|
+
// the frame is about to draw.
|
|
1675
|
+
const renderListValidator = renderListValidationRequested()
|
|
1676
|
+
? new RenderListValidator()
|
|
1677
|
+
: undefined;
|
|
1678
|
+
if (removeSpanProbes !== undefined) {
|
|
1679
|
+
this.#cleanup.push(() => {
|
|
1680
|
+
removeSpanProbes();
|
|
1681
|
+
setSpanRecorder(undefined);
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
if (frameCounters !== undefined) this.#cleanup.push(() => frameCounters.uninstall());
|
|
1685
|
+
// Holds no hook and does no work between requests, so an idle game pays nothing for it.
|
|
1686
|
+
const geometryCapture = new GeometryCapture();
|
|
1687
|
+
this.#geometryCapture = geometryCapture;
|
|
1688
|
+
const budgetNow = (): number => globalThis.performance?.now() ?? Date.now();
|
|
1689
|
+
// The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
|
|
1690
|
+
// a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
|
|
1691
|
+
// say nothing new.
|
|
1692
|
+
const devMetricsEnabled = isDevLaunch();
|
|
1693
|
+
let postedVerdict: string | undefined;
|
|
1694
|
+
let updates = 0;
|
|
1695
|
+
let renders = 0;
|
|
1696
|
+
let lastGateSkips = 0;
|
|
1697
|
+
const gameLoop: FixedStepLoop = new FixedStepLoop({
|
|
1698
|
+
interpolation,
|
|
1699
|
+
...(frameBudget === undefined ? {} : { budget: frameBudget }),
|
|
1700
|
+
...(spans === undefined ? {} : { spans }),
|
|
1701
|
+
maxSteps: this.#config.maxSteps,
|
|
1702
|
+
onBeginFrame: () => {
|
|
1703
|
+
// The engine owns this requestAnimationFrame loop instead of delegating to Three's
|
|
1704
|
+
// setAnimationLoop(). Three's renderer therefore cannot reset its frame counters for us;
|
|
1705
|
+
// a concurrent internal renderer callback can otherwise leave stale work in the first
|
|
1706
|
+
// sample after a held playtest start.
|
|
1707
|
+
resetRendererPerformanceMetrics(renderer.raw);
|
|
1708
|
+
renderer.beginFrame?.();
|
|
1709
|
+
},
|
|
1710
|
+
onRender: (alpha) => {
|
|
1711
|
+
observeCompilation();
|
|
1712
|
+
renderPassBudget?.beginFrame();
|
|
1713
|
+
// Runs on web as well as native, so the two stay one behaviour rather than diverging into
|
|
1714
|
+
// a fast path nobody tests. When the world is drawn, reconciliation happens immediately
|
|
1715
|
+
// before the render, inside the same frame, so a change the game made this tick reaches
|
|
1716
|
+
// the screen this tick instead of the next one. Scenes under its mesh floor get their own
|
|
1717
|
+
// graph back and pay nothing.
|
|
1718
|
+
// A goto clears the graph before its destination enters, and the projection has to drop
|
|
1719
|
+
// those objects on the very next frame. During the first-use hold, however, reconciling a
|
|
1720
|
+
// large scene would be more work before the loader has even presented. Present one
|
|
1721
|
+
// loader-only frame and keep reconciling skipped until first-use work settles; then the
|
|
1722
|
+
// world pass and projection start together behind the still-opaque layer.
|
|
1723
|
+
let worldMetrics: IRenderPerformanceMetrics | undefined;
|
|
1724
|
+
const firstWorldPass = !worldRendered && this.#sceneEntered;
|
|
1725
|
+
const explicitWarmUpPending = this.#warmUpConfiguredExplicitly() && !explicitWarmUpSettled;
|
|
1726
|
+
const loaderHasPixels = canvasLayer.scene.children.length > 0;
|
|
1727
|
+
const mustPresentLoader =
|
|
1728
|
+
firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
|
|
1729
|
+
if (firstWorldPass && !explicitWarmUpPending) {
|
|
1730
|
+
// `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
|
|
1731
|
+
// is on it has already happened behind the loading screen, so running it again here
|
|
1732
|
+
// would pay the same cost twice.
|
|
1733
|
+
startupReadiness.start(
|
|
1734
|
+
startupCoverActive() && !this.#warmUpConfiguredExplicitly()
|
|
1735
|
+
? startupCompile
|
|
1736
|
+
: undefined,
|
|
1737
|
+
);
|
|
1738
|
+
}
|
|
1739
|
+
// Ordinary render compute waits for startup readiness. Streaming explicitly opts in
|
|
1740
|
+
// after compilation so a spawn hold can finish behind the curtain. Present the loader
|
|
1741
|
+
// first; charge this admission to the same render phase as normal render compute.
|
|
1742
|
+
if (
|
|
1743
|
+
this.#renderer !== undefined &&
|
|
1744
|
+
this.#sceneEntered &&
|
|
1745
|
+
!explicitWarmUpPending &&
|
|
1746
|
+
!mustPresentLoader &&
|
|
1747
|
+
(!startupCoverActive() || startupReadiness.compileSettled)
|
|
1748
|
+
) {
|
|
1749
|
+
const computeStart = frameBudget === undefined ? 0 : budgetNow();
|
|
1750
|
+
beginSpan(SPANS.compute);
|
|
1751
|
+
try {
|
|
1752
|
+
// The render camera comes with it, because a render-cadence consumer that culls by the
|
|
1753
|
+
// view — a streamed world's main batches — has to be driven from here and not from a draw
|
|
1754
|
+
// three skips for a mesh that is hidden because it has nothing to draw.
|
|
1755
|
+
this.#computeDriven.processRender(
|
|
1756
|
+
this.#renderer,
|
|
1757
|
+
camera,
|
|
1758
|
+
startupCoverActive() && !startupReadiness.ready,
|
|
1759
|
+
gameLoop,
|
|
1760
|
+
);
|
|
1761
|
+
} finally {
|
|
1762
|
+
endSpan(SPANS.compute);
|
|
1763
|
+
}
|
|
1764
|
+
frameBudget?.addRender(budgetNow() - computeStart);
|
|
1765
|
+
}
|
|
1766
|
+
const waitingForFirstUse =
|
|
1767
|
+
firstWorldPass &&
|
|
1768
|
+
(explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
|
|
1769
|
+
let worldPasses: ReturnType<RenderPassBudget["passes"]> | undefined;
|
|
1770
|
+
if (
|
|
1771
|
+
!mustPresentLoader &&
|
|
1772
|
+
!waitingForFirstUse &&
|
|
1773
|
+
(!canvasLayer.opaque ||
|
|
1774
|
+
(!startupReadiness.ready && canvasLayer.renderWorldDuringStartup) ||
|
|
1775
|
+
canvasLayer.keepWorldRendering)
|
|
1776
|
+
) {
|
|
1777
|
+
// The projection's own scene when it is faithful, the game's when it is not. Nothing
|
|
1778
|
+
// here branches on which: `root` is the single render input either way, so there is no
|
|
1779
|
+
// second optional render path to leave untested.
|
|
1780
|
+
// The reconcile is bracketed with the render it feeds: its walk, grouping and matrix
|
|
1781
|
+
// sync are render-path work, and a frame budget that hid it in `residual` made the
|
|
1782
|
+
// optimizer's own cost unmeasurable exactly where the optimizer is engaged.
|
|
1783
|
+
const renderStart = frameBudget === undefined ? 0 : budgetNow();
|
|
1784
|
+
// Before anything walks: a frozen subtree whose author moved its root thaws here, so the
|
|
1785
|
+
// walk that follows sees a transform nobody had to remember to announce.
|
|
1786
|
+
refreshStaticTransforms();
|
|
1787
|
+
// Scene prep that must read the frame's last solved state before the projection packs and
|
|
1788
|
+
// the renderer draws. Inside the world-render block it cannot land on a held loader frame.
|
|
1789
|
+
if (this.#beforeRenderCallbacks.size > 0) {
|
|
1790
|
+
let snapshot = this.#beforeRenderSnapshots[this.#beforeRenderDepth];
|
|
1791
|
+
if (snapshot === undefined) {
|
|
1792
|
+
snapshot = [];
|
|
1793
|
+
this.#beforeRenderSnapshots[this.#beforeRenderDepth] = snapshot;
|
|
1794
|
+
}
|
|
1795
|
+
this.#beforeRenderDepth += 1;
|
|
1796
|
+
snapshot.length = 0;
|
|
1797
|
+
for (const callback of this.#beforeRenderCallbacks) snapshot.push(callback);
|
|
1798
|
+
beginSpan(SPANS.beforeRender);
|
|
1799
|
+
try {
|
|
1800
|
+
for (const callback of snapshot) callback();
|
|
1801
|
+
} finally {
|
|
1802
|
+
endSpan(SPANS.beforeRender);
|
|
1803
|
+
this.#beforeRenderDepth -= 1;
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
interpolation.render(gameLoop.clockFrozen || this.#paused ? 1 : alpha, () => {
|
|
1807
|
+
// Let a depth-coupled scene update its output node while the scene pass is still the
|
|
1808
|
+
// next render. Ordinary scenes keep the historical hook order and timing.
|
|
1809
|
+
const depthCoupledOutput = this.#hasDepthCoupledOutput;
|
|
1810
|
+
if (depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
|
|
1811
|
+
// The engine's own walk owns the frame's world matrices, so the count starts here and
|
|
1812
|
+
// covers both applications below: the authored scene the projection reconciles from and
|
|
1813
|
+
// the root the renderer is actually handed.
|
|
1814
|
+
this.#matrixWorld?.beginFrame();
|
|
1815
|
+
if (this.#projection !== undefined) {
|
|
1816
|
+
beginSpan(SPANS.reconcile);
|
|
1817
|
+
try {
|
|
1818
|
+
this.#projection.reconcile();
|
|
1819
|
+
} finally {
|
|
1820
|
+
endSpan(SPANS.reconcile);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
// Virtual geometry ships on by default, so the engine takes the cut rather than waiting
|
|
1824
|
+
// for a game to know it should. It runs here, before the render and after the reconcile,
|
|
1825
|
+
// because an empty cut has to skip its draw rather than submit a zero-count one — and a
|
|
1826
|
+
// scene holding no clustered mesh pays no traversal at all, only the tracked set.
|
|
1827
|
+
beginSpan(SPANS.clustered);
|
|
1828
|
+
try {
|
|
1829
|
+
updateClusteredMeshes(
|
|
1830
|
+
this.#projection?.root ?? threeScene,
|
|
1831
|
+
camera,
|
|
1832
|
+
renderer.surfaceDrawingBufferHeight?.() ?? renderer.surface().drawingBufferHeight,
|
|
1833
|
+
);
|
|
1834
|
+
} finally {
|
|
1835
|
+
endSpan(SPANS.clustered);
|
|
1836
|
+
}
|
|
1837
|
+
// Automatic discrete LOD ships on with the pipeline, so the engine takes the selection
|
|
1838
|
+
// too. It shares the render root and the same drawing-buffer height, and a scene with no
|
|
1839
|
+
// managed mesh pays only the tracked-set walk.
|
|
1840
|
+
beginSpan(SPANS.lod);
|
|
1841
|
+
try {
|
|
1842
|
+
updateModelLods(
|
|
1843
|
+
this.#projection?.root ?? threeScene,
|
|
1844
|
+
camera,
|
|
1845
|
+
renderer.surface().drawingBufferHeight,
|
|
1846
|
+
);
|
|
1847
|
+
} finally {
|
|
1848
|
+
endSpan(SPANS.lod);
|
|
1849
|
+
}
|
|
1850
|
+
// Projected-size cull, per render camera, default on. It writes only `object.visible` —
|
|
1851
|
+
// the one per-frame flag the projection's batch key ignores — and restores what it hid
|
|
1852
|
+
// immediately after the draw, so the authored scene is untouched between frames. The
|
|
1853
|
+
// renderer walks the same root the projection is about to draw, so a declined projection
|
|
1854
|
+
// and an active one both get the gate.
|
|
1855
|
+
const drawingBufferHeight = renderer.surface().drawingBufferHeight;
|
|
1856
|
+
const cullApplyStart = spans === undefined ? 0 : spanNow();
|
|
1857
|
+
this.#cameraCull?.apply(
|
|
1858
|
+
this.#projection?.root ?? threeScene,
|
|
1859
|
+
camera,
|
|
1860
|
+
drawingBufferHeight,
|
|
1861
|
+
);
|
|
1862
|
+
// Added, not bracketed: the render call sits between the apply and the restore, and a
|
|
1863
|
+
// span that contained it would report the world pass as cull work.
|
|
1864
|
+
if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullApplyStart);
|
|
1865
|
+
const capturing = geometryCapture.armed();
|
|
1866
|
+
if (capturing) {
|
|
1867
|
+
// The mirror is what the renderer sees; arming the authored scene would attribute the
|
|
1868
|
+
// frame to objects that were never submitted.
|
|
1869
|
+
geometryCapture.beginFrame({
|
|
1870
|
+
camera,
|
|
1871
|
+
generation: this.#sceneGeneration,
|
|
1872
|
+
root: this.#projection?.root ?? threeScene,
|
|
1873
|
+
tick: gameLoop.tick(),
|
|
1874
|
+
viewportHeight: renderer.surface().drawingBufferHeight,
|
|
1875
|
+
viewportWidth: renderer.surface().drawingBufferWidth,
|
|
1876
|
+
...(renderPassBudget === undefined
|
|
1877
|
+
? {}
|
|
1878
|
+
: { activePassKind: () => renderPassBudget.activeKind() }),
|
|
1879
|
+
...(this.#projection === undefined
|
|
1880
|
+
? {}
|
|
1881
|
+
: { ownership: this.#projection.describeOwnership() }),
|
|
1882
|
+
...(rendererBackendIdentity(renderer.raw) === undefined
|
|
1883
|
+
? {}
|
|
1884
|
+
: { backend: rendererBackendIdentity(renderer.raw) as string }),
|
|
1885
|
+
});
|
|
1886
|
+
}
|
|
1887
|
+
const renderRoot = this.#projection?.root ?? threeScene;
|
|
1888
|
+
// three's renderer walks whatever scene it is handed, so it is told not to: the pass above
|
|
1889
|
+
// is the walk. Handing it the mirror sets the mirror scene's flag; the authored scene was
|
|
1890
|
+
// marked at construction.
|
|
1891
|
+
renderRoot.matrixWorldAutoUpdate = false;
|
|
1892
|
+
this.#matrixWorld?.apply(renderRoot);
|
|
1893
|
+
renderer.render(renderRoot, camera);
|
|
1894
|
+
renders += 1;
|
|
1895
|
+
// Count declined frames without treating them as drawn-frame render cost.
|
|
1896
|
+
const gateSkips = rendererFrameGateSkips(renderer.raw);
|
|
1897
|
+
if (gateSkips !== undefined) {
|
|
1898
|
+
if (gateSkips > lastGateSkips) frameBudget?.addRenderSkip();
|
|
1899
|
+
lastGateSkips = gateSkips;
|
|
1900
|
+
}
|
|
1901
|
+
// *After* the render, because that is where the draw happened. The matrices read here are
|
|
1902
|
+
// the ones drawn: the walk above refreshed them and `render()` did not touch them. The
|
|
1903
|
+
// frozen roots are passed because the draw root is the projection's mirror when the
|
|
1904
|
+
// engine is collapsing, and validating only that reassured about a scene it never
|
|
1905
|
+
// looked at. `?.` short-circuits before the spread, so `staticRoots()` is not called
|
|
1906
|
+
// at all on a frame without the flag — verified, a million optional calls evaluate the
|
|
1907
|
+
// argument zero times — and this stays a single undefined check in a shipped game.
|
|
1908
|
+
renderListValidator?.frame(renderRoot, ...staticRoots());
|
|
1909
|
+
const cullRestoreStart = spans === undefined ? 0 : spanNow();
|
|
1910
|
+
this.#cameraCull?.restore();
|
|
1911
|
+
if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
|
|
1912
|
+
this.#projection?.commit();
|
|
1913
|
+
renderer.observeRenderChainFrame?.();
|
|
1914
|
+
frameBudget?.addRender(budgetNow() - renderStart);
|
|
1915
|
+
// Read the split before the overlay renders: the overlay is its own draw, not part of the
|
|
1916
|
+
// world pass, and the budget window already accounts for it in its own phase.
|
|
1917
|
+
worldPasses = renderPassBudget?.passes();
|
|
1918
|
+
if (worldPasses !== undefined && worldPasses.length > 0)
|
|
1919
|
+
frameBudget?.addRenderPasses(worldPasses);
|
|
1920
|
+
// After the passes are read, so the rows reconcile against this frame's own totals.
|
|
1921
|
+
if (capturing) geometryCapture.finishFrame(worldPasses ?? []);
|
|
1922
|
+
// Resolve the GPU timestamps every frame, not once per reported window.
|
|
1923
|
+
//
|
|
1924
|
+
// `trackTimestamp` spends two queries per render pass, and three's pool holds 2048.
|
|
1925
|
+
// A scene with a post-processing chain runs tens of passes per frame — a cathedral
|
|
1926
|
+
// with SSGI, denoise, godrays, SSR and bloom measured 27 — so the pool fills in
|
|
1927
|
+
// 2048 / (2 x 27) = 38 frames. The resolve used to be wired to the frame-budget
|
|
1928
|
+
// window boundary, 300 frames by default, which is eight times too slow: three
|
|
1929
|
+
// warned `Maximum number of queries exceeded`, stopped recording, and every window
|
|
1930
|
+
// after the first reported `gpuMs: undefined`. The one instrument that exists so the
|
|
1931
|
+
// GPU record is not wall-clock algebra was reading nothing.
|
|
1932
|
+
//
|
|
1933
|
+
// This does not put the GPU on the frame path. `resolveTimestampsAsync` is
|
|
1934
|
+
// fire-and-forget and already catch-guarded, which was the original cadence's only
|
|
1935
|
+
// stated concern.
|
|
1936
|
+
// Deliberately unspanned. The resolve runs *after* `addRender` closed the render phase,
|
|
1937
|
+
// so its milliseconds are in the frame's `residual`, not in `render`. A span for it was
|
|
1938
|
+
// measured on the native smoke game at 0.18 ms and showed up as exactly that much
|
|
1939
|
+
// negative residual — the tree reporting, correctly, that it had been handed a term from
|
|
1940
|
+
// outside the phase it is dividing up. The frame budget already carries this cost.
|
|
1941
|
+
renderer.resolveGpuFrame();
|
|
1942
|
+
frameBudget?.addGpuPyramidMs(renderer.gpuPyramidMs?.());
|
|
1943
|
+
// The budget's GPU series is fed every frame, not read once per reported window. A
|
|
1944
|
+
// single window-close read is one instantaneous, lagged `info.render.timestamp` — the
|
|
1945
|
+
// sample that made a 17.6 ms frame read as 2.98–10.40 ms. The sample carries the
|
|
1946
|
+
// resolved frame id so a resolve still in flight is counted stale, not measured twice.
|
|
1947
|
+
//
|
|
1948
|
+
// The reading is the frame's own passes out of three's per-pass map, handed out one
|
|
1949
|
+
// resolved frame per presented frame. Three's resolve answers with one number for the
|
|
1950
|
+
// batch — the last frame in it — so reading that instead dropped every frame a batch
|
|
1951
|
+
// caught up on, and because the resolve is asked for on the same 1-in-8 stride the
|
|
1952
|
+
// sampler uses, how many frames a batch caught up on was a function of frame rate.
|
|
1953
|
+
// The pass recorder is what reads three's per-pass map back into per-frame numbers; a
|
|
1954
|
+
// renderer it cannot instrument falls back to the batch's own single number, which is the
|
|
1955
|
+
// reading there was before — one sample per resolve rather than one per sampled frame.
|
|
1956
|
+
const gpuFrame = renderPassBudget?.nextGpuFrame();
|
|
1957
|
+
const gpuSample = gpuFrame === undefined ? renderer.gpuFrameSample?.() : undefined;
|
|
1958
|
+
frameBudget?.addGpuMs(
|
|
1959
|
+
gpuFrame?.total ?? gpuSample?.ms,
|
|
1960
|
+
gpuFrame?.frame ?? gpuSample?.frame,
|
|
1961
|
+
);
|
|
1962
|
+
// Where one resolved frame's GPU time went: main and shadow come from the pass
|
|
1963
|
+
// recorder's per-uid query results, and everything else in that pool (post chain,
|
|
1964
|
+
// reflections, HUD) is the remainder. Compute is its own pool.
|
|
1965
|
+
if (gpuFrame !== undefined) {
|
|
1966
|
+
const computeMs = renderer.gpuComputeMs?.();
|
|
1967
|
+
// The recorder hands out a frame only when every pass it recorded resolved, so `total`
|
|
1968
|
+
// is the whole frame and never a partial sum; `main` and `shadow` are whole or zero.
|
|
1969
|
+
// `other` is the remainder of the frame (post chain, reflection, HUD). `shadowPasses`
|
|
1970
|
+
// rides along so a consumer can tell a frame that rendered a shadow from one that drew
|
|
1971
|
+
// none, since a real render can resolve to 0 ms.
|
|
1972
|
+
frameBudget?.addGpuBucketMs({
|
|
1973
|
+
main: gpuFrame.main,
|
|
1974
|
+
shadow: gpuFrame.shadow,
|
|
1975
|
+
shadowPasses: gpuFrame.shadowPasses,
|
|
1976
|
+
other: Math.max(0, gpuFrame.total - gpuFrame.main - gpuFrame.shadow),
|
|
1977
|
+
...(computeMs === undefined ? {} : { compute: computeMs }),
|
|
1978
|
+
});
|
|
1979
|
+
// The main pass's own GPU series, for the adaptive LOD control loop: the frame
|
|
1980
|
+
// budget's `gpuMain` bucket is the record, and this is the same number smoothed on the
|
|
1981
|
+
// renderer so a world holding only the renderer can read it. Fed per delivered frame,
|
|
1982
|
+
// fresh or not.
|
|
1983
|
+
renderer.noteGpuMainMs?.(gpuFrame.main, gpuFrame.frame);
|
|
1984
|
+
} else {
|
|
1985
|
+
renderer.noteGpuMainMs?.(undefined);
|
|
1986
|
+
}
|
|
1987
|
+
if (!depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
|
|
1988
|
+
if (this.#sceneEntered) {
|
|
1989
|
+
if (!worldRendered) gameLoop.clearRuntimeDiagnostics();
|
|
1990
|
+
worldRendered = true;
|
|
1991
|
+
}
|
|
1992
|
+
if (this.#renderMetricsEnabled) {
|
|
1993
|
+
const metrics = rendererPerformanceMetrics(renderer.raw);
|
|
1994
|
+
worldMetrics =
|
|
1995
|
+
worldPasses === undefined || worldPasses.length === 0
|
|
1996
|
+
? metrics
|
|
1997
|
+
: { ...metrics, passes: worldPasses.map((pass) => ({ ...pass })) };
|
|
1998
|
+
}
|
|
1999
|
+
// Read whether or not the game asked for render metrics: the projection line reports
|
|
2000
|
+
// the measured draw count, and a convention's measurement does not switch off with the
|
|
2001
|
+
// convention that happens to sit beside it.
|
|
2002
|
+
lastWorldDrawCalls = rendererDrawCallCount(renderer.raw);
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
if (mustPresentLoader) loadingFramePresented = true;
|
|
2006
|
+
// Include state written by beforeRender and Scene.render in this frame's UI snapshot.
|
|
2007
|
+
if (this.#config.stateFlushMs === undefined) this.#state.flush();
|
|
2008
|
+
// Every frame, including one whose canvas layer is empty: the native UI is composited into
|
|
2009
|
+
// the game's own frame whether or not the game draws a HUD of its own, so a frame that
|
|
2010
|
+
// skipped this would report work it did pay as `residual`. The host reports what the
|
|
2011
|
+
// *previous* frame's composite cost — the only reading that exists when a frame begins —
|
|
2012
|
+
// so this charges the phase to the frame that paid it, one frame late rather than never.
|
|
2013
|
+
// Absent on the web target and on any host with no overlay, where the work is zero rather
|
|
2014
|
+
// than unknown, so an absent global must read as zero and not as a missing measurement.
|
|
2015
|
+
// The boundary counts ride the span flag, but the simulation tick does not need them: it is
|
|
2016
|
+
// fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
|
|
2017
|
+
// without `TN_FRAME_SPANS`. `addCounters` keeps the last tick a caller did provide.
|
|
2018
|
+
frameBudget?.addCounters({
|
|
2019
|
+
...(frameCounters?.read() ?? {}),
|
|
2020
|
+
simulationTick: gameLoop.tick(),
|
|
2021
|
+
});
|
|
2022
|
+
const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
|
|
2023
|
+
frameBudget?.addUi(
|
|
2024
|
+
typeof uiHost.__tnUiCompositeMs === "function" ? (uiHost.__tnUiCompositeMs() ?? 0) : 0,
|
|
2025
|
+
);
|
|
2026
|
+
if (canvasLayer.scene.children.length > 0) {
|
|
2027
|
+
const overlayStart = frameBudget === undefined ? 0 : budgetNow();
|
|
2028
|
+
// The overlay is its own render call and its own frame-budget phase. The span probes sit
|
|
2029
|
+
// on `render`, so without this they would charge the HUD's draw to the render phase the
|
|
2030
|
+
// spans are explaining — measured on the native smoke game as `coverage 1.03` and a
|
|
2031
|
+
// residual of −0.37 ms, two render calls per frame where the phase paid for one. The
|
|
2032
|
+
// recorder is unhooked rather than flagged, so every probe takes the same guarded return
|
|
2033
|
+
// it takes in a shipped build and the span stack cannot be left half-open.
|
|
2034
|
+
if (spans !== undefined) setSpanRecorder(undefined);
|
|
2035
|
+
try {
|
|
2036
|
+
renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
|
|
2037
|
+
} finally {
|
|
2038
|
+
if (spans !== undefined) setSpanRecorder(spans);
|
|
2039
|
+
}
|
|
2040
|
+
frameBudget?.addOverlay(budgetNow() - overlayStart);
|
|
2041
|
+
if (!this.#renderMetricsEnabled) return undefined;
|
|
2042
|
+
const overlayMetrics = rendererPerformanceMetrics(renderer.raw);
|
|
2043
|
+
return combineRenderPerformanceMetrics(renderer.kind, worldMetrics, overlayMetrics);
|
|
2044
|
+
}
|
|
2045
|
+
return this.#renderMetricsEnabled ? worldMetrics : undefined;
|
|
2046
|
+
},
|
|
2047
|
+
onAfterPhysics: (dt) => {
|
|
2048
|
+
if (this.#paused) return;
|
|
2049
|
+
afterPhysicsPhase.run(dt);
|
|
2050
|
+
},
|
|
2051
|
+
onUpdate: (dt) => {
|
|
2052
|
+
if (this.#paused) return;
|
|
2053
|
+
this.#input?.tick();
|
|
2054
|
+
scheduler.tick(dt);
|
|
2055
|
+
pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
|
|
2056
|
+
for (const plugin of this.#activePlugins) plugin.beforeUpdate?.(ctx, dt);
|
|
2057
|
+
const scene = this.#scene;
|
|
2058
|
+
const frame = this.#sceneFrame;
|
|
2059
|
+
if (frame !== undefined) {
|
|
2060
|
+
frame(ctx, dt);
|
|
2061
|
+
updates += 1;
|
|
2062
|
+
}
|
|
2063
|
+
// An async goto() installs the incoming scene before its load resolves; until enter()
|
|
2064
|
+
// has run there is no gameplay to step and a game-overridden update() would run against
|
|
2065
|
+
// a cleared graph.
|
|
2066
|
+
else if (this.#sceneEntered && scene !== undefined) {
|
|
2067
|
+
scene.update(ctx, dt);
|
|
2068
|
+
updates += 1;
|
|
2069
|
+
}
|
|
2070
|
+
if (this.#scene !== scene || this.#sceneFrame !== frame) return;
|
|
2071
|
+
for (const plugin of this.#activePlugins) plugin.update?.(ctx, dt);
|
|
2072
|
+
this.#entities?.sweep();
|
|
2073
|
+
if (this.#renderer !== undefined && this.#sceneEntered)
|
|
2074
|
+
this.#computeDriven.process(this.#renderer);
|
|
2075
|
+
},
|
|
2076
|
+
onFrame: (frameMs) => startupReadiness.observe(frameMs),
|
|
2077
|
+
step: this.#config.step,
|
|
2078
|
+
});
|
|
2079
|
+
loopState.current = gameLoop;
|
|
2080
|
+
this.#loop = gameLoop;
|
|
2081
|
+
const startGates: Array<{
|
|
2082
|
+
readonly gate: Promise<void>;
|
|
2083
|
+
readonly rejectEntered: (error: unknown) => void;
|
|
2084
|
+
readonly resolveEntered: () => void;
|
|
2085
|
+
}> = [];
|
|
2086
|
+
const runtime: IGamePluginRuntime = {
|
|
2087
|
+
fixedStep: (ticks, options) =>
|
|
2088
|
+
gameLoop.advance(ticks, { ...options, until: () => this.#pendingSceneEnter !== undefined }),
|
|
2089
|
+
sceneTransition: () =>
|
|
2090
|
+
this.#pendingSceneEnter?.then(
|
|
2091
|
+
() => undefined,
|
|
2092
|
+
() => undefined,
|
|
2093
|
+
),
|
|
2094
|
+
frameCounts: () => ({ updates, renders }),
|
|
2095
|
+
frameBudgetWindow: () => this.#frameBudget?.window(),
|
|
2096
|
+
freezeClock: () => gameLoop.freezeClock(),
|
|
2097
|
+
renderCurrent: () => gameLoop.renderCurrentFrame(),
|
|
2098
|
+
enableRuntimeDiagnostics: () => {
|
|
2099
|
+
this.#renderMetricsEnabled = true;
|
|
2100
|
+
gameLoop.setCollectMetrics(true);
|
|
2101
|
+
},
|
|
2102
|
+
holdStart: (gate) => {
|
|
2103
|
+
let rejectEntered: (error: unknown) => void = () => undefined;
|
|
2104
|
+
let resolveEntered: () => void = () => undefined;
|
|
2105
|
+
const entered = new Promise<void>((resolve, reject) => {
|
|
2106
|
+
rejectEntered = reject;
|
|
2107
|
+
resolveEntered = resolve;
|
|
2108
|
+
});
|
|
2109
|
+
startGates.push({ gate, rejectEntered, resolveEntered });
|
|
2110
|
+
return entered;
|
|
2111
|
+
},
|
|
2112
|
+
geometryCapture: (request) => geometryCapture.request(request),
|
|
2113
|
+
observations: createRuntimeObservations(),
|
|
2114
|
+
...(renderer.pipelineCensus === undefined ? {} : { pipelineCensus: renderer.pipelineCensus }),
|
|
2115
|
+
tick: gameLoop.tick,
|
|
2116
|
+
random,
|
|
2117
|
+
rapier: null,
|
|
2118
|
+
seed: this.#config.seed ?? null,
|
|
2119
|
+
startupCompileSettled: () => startupReadiness.compileSettled,
|
|
2120
|
+
startupTimeline: () => ({ ...timeline }),
|
|
2121
|
+
step: gameLoop.step,
|
|
2122
|
+
runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
|
|
2123
|
+
};
|
|
2124
|
+
Object.assign(runtime, {
|
|
2125
|
+
_setClockMode: (mode: "fixed-step" | "wall-clock") => gameLoop._setClockMode(mode),
|
|
2126
|
+
});
|
|
2127
|
+
// A boot that throws must end exactly like an aborted boot: every cleanup attempted, every
|
|
2128
|
+
// resource released — and the original error rethrown, not a teardown error standing in
|
|
2129
|
+
// for it. The abort branches below stay outside these guards: they tear down themselves.
|
|
2130
|
+
for (const plugin of this.#config.plugins ?? []) {
|
|
2131
|
+
let cleanup: PluginCleanup | undefined;
|
|
2132
|
+
try {
|
|
2133
|
+
cleanup = typeof plugin === "function" ? plugin(ctx) : await plugin.setup?.(ctx, runtime);
|
|
2134
|
+
} catch (error) {
|
|
2135
|
+
this.#teardown(ctx);
|
|
2136
|
+
throw error;
|
|
2137
|
+
}
|
|
2138
|
+
if (typeof plugin !== "function") this.#activePlugins.push(plugin);
|
|
2139
|
+
if (this.#aborted) {
|
|
2140
|
+
if (cleanup !== undefined) this.#cleanup.push(cleanup);
|
|
2141
|
+
this.#teardown(ctx);
|
|
2142
|
+
return;
|
|
2143
|
+
}
|
|
2144
|
+
if (cleanup !== undefined) this.#cleanup.push(cleanup);
|
|
2145
|
+
}
|
|
2146
|
+
const scene = this.#scene;
|
|
2147
|
+
if (scene === undefined) {
|
|
2148
|
+
this.#teardown(ctx);
|
|
2149
|
+
return;
|
|
2150
|
+
}
|
|
2151
|
+
// Held: the loop renders every frame from here but steps nothing. On native the render loop
|
|
2152
|
+
// is the only thing that can put pixels on the screen, so an async load starts it before the
|
|
2153
|
+
// await; a synchronous load has already completed and starts it after the call. Holding rather
|
|
2154
|
+
// than simply starting keeps the determinism contract intact: no tick advances and no elapsed
|
|
2155
|
+
// time is banked before the release below.
|
|
2156
|
+
const startHeldLoop = (): void => {
|
|
2157
|
+
gameLoop.setHeld(true);
|
|
2158
|
+
gameLoop.start();
|
|
2159
|
+
};
|
|
2160
|
+
try {
|
|
2161
|
+
timeline.loadStartedMs ??= now();
|
|
2162
|
+
const loaded = scene.load(ctx);
|
|
2163
|
+
startHeldLoop();
|
|
2164
|
+
if (loaded !== undefined) await loaded;
|
|
2165
|
+
} catch (error) {
|
|
2166
|
+
this.#teardown(ctx);
|
|
2167
|
+
throw error;
|
|
2168
|
+
}
|
|
2169
|
+
if (this.#aborted) {
|
|
2170
|
+
this.#teardown(ctx);
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
// Plugins that need to mutate scene-load placeholders hold here. Setup must land before
|
|
2174
|
+
// Scene.enter() transfers those values into authoritative physics/gameplay state.
|
|
2175
|
+
if (startGates.length > 0) {
|
|
2176
|
+
try {
|
|
2177
|
+
await Promise.all(startGates.map(({ gate }) => gate));
|
|
2178
|
+
} catch (error) {
|
|
2179
|
+
for (const startGate of startGates) startGate.rejectEntered(error);
|
|
2180
|
+
this.#teardown(ctx);
|
|
2181
|
+
throw error;
|
|
2182
|
+
}
|
|
2183
|
+
if (this.#aborted) {
|
|
2184
|
+
const error = new Error("Game start was aborted before the start scene entered.");
|
|
2185
|
+
for (const startGate of startGates) startGate.rejectEntered(error);
|
|
2186
|
+
this.#teardown(ctx);
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
try {
|
|
2191
|
+
this.#enterScene(scene, ctx);
|
|
2192
|
+
timeline.enteredMs ??= now();
|
|
2193
|
+
// A start scene that navigates inside `enter()` — every `boot` template does — has handed the
|
|
2194
|
+
// run a world that is still in `load()`, and the entity registry is empty until it enters.
|
|
2195
|
+
// Releasing the gate there described a game that had not been built yet, so every
|
|
2196
|
+
// entity-derived capability was read off nothing. The gate follows the scene that entered.
|
|
2197
|
+
const worldEntered = this.#pendingSceneEnter;
|
|
2198
|
+
const entered = (): void => {
|
|
2199
|
+
for (const startGate of startGates) startGate.resolveEntered();
|
|
2200
|
+
};
|
|
2201
|
+
if (worldEntered === undefined) entered();
|
|
2202
|
+
else
|
|
2203
|
+
void worldEntered.then(entered, (error: unknown) => {
|
|
2204
|
+
for (const startGate of startGates) startGate.rejectEntered(error);
|
|
2205
|
+
});
|
|
2206
|
+
} catch (error) {
|
|
2207
|
+
for (const startGate of startGates) startGate.rejectEntered(error);
|
|
2208
|
+
this.#teardown(ctx);
|
|
2209
|
+
throw error;
|
|
2210
|
+
}
|
|
2211
|
+
if (this.#aborted) {
|
|
2212
|
+
this.#teardown(ctx);
|
|
2213
|
+
return;
|
|
2214
|
+
}
|
|
2215
|
+
// The scene is built and the loop is still held, which is the only window where compiling can
|
|
2216
|
+
// cost frames nobody is playing. Warming up here rather than letting the first real frame do
|
|
2217
|
+
// it is what keeps a launch from freezing inside one 24-second frame. PRD-218.
|
|
2218
|
+
if (this.#warmUpConfiguredExplicitly() && this.#renderer !== undefined) {
|
|
2219
|
+
// Never fatal, and never able to hang the launch. This block sits between "the scene is
|
|
2220
|
+
// built" and "the game may start", so anything it does wrong is something the player
|
|
2221
|
+
// experiences as the game not starting -- which is exactly what the first version did: a
|
|
2222
|
+
// `compileAsync` that never resolved on a Pixel 8 left this `await` pending forever, the
|
|
2223
|
+
// loop stayed held, the simulation never advanced, and the game sat on its loading screen
|
|
2224
|
+
// with no error anywhere. A warm-up that fails must cost the launch its speed, never its
|
|
2225
|
+
// start, so the failure is reported and boot carries on.
|
|
2226
|
+
let report: IWarmUpReport | undefined;
|
|
2227
|
+
let failure: string | undefined;
|
|
2228
|
+
try {
|
|
2229
|
+
projection.reconcile();
|
|
2230
|
+
// Same walk as the held warm-up above: the explicit warm-up also draws before the frame
|
|
2231
|
+
// loop's own matrix pass, and a declined projection left the scene un-walked.
|
|
2232
|
+
this.#matrixWorld?.apply(projection.root);
|
|
2233
|
+
const warmUpOptions: IWarmUpOptions = this.#warmUpOptions();
|
|
2234
|
+
report = await warmUpScene(this.#renderer, projection.root, camera, {
|
|
2235
|
+
...warmUpOptions,
|
|
2236
|
+
computeNodes: [...(warmUpOptions.computeNodes ?? []), ...this.#computeDriven.warmupNodes],
|
|
2237
|
+
});
|
|
2238
|
+
} catch (error) {
|
|
2239
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
2240
|
+
}
|
|
2241
|
+
this.#renderer.warmUpSettled?.();
|
|
2242
|
+
warmUpStatus =
|
|
2243
|
+
report === undefined
|
|
2244
|
+
? { status: "unavailable" }
|
|
2245
|
+
: {
|
|
2246
|
+
attempted: report.attempted,
|
|
2247
|
+
candidates: report.candidates,
|
|
2248
|
+
observed: report.observed,
|
|
2249
|
+
status: report.observed.status,
|
|
2250
|
+
};
|
|
2251
|
+
// One greppable line on every platform, so a device lane reads what the warm-up did without
|
|
2252
|
+
// instrumenting anything -- including the cases where it could do nothing, ran out of
|
|
2253
|
+
// budget, or threw.
|
|
2254
|
+
console.log(
|
|
2255
|
+
`TN_WARMUP:${JSON.stringify(
|
|
2256
|
+
report === undefined
|
|
2257
|
+
? { failed: failure ?? "unknown" }
|
|
2258
|
+
: {
|
|
2259
|
+
compiled: report.compiled,
|
|
2260
|
+
pipelines: report.pipelines,
|
|
2261
|
+
candidates: report.candidates,
|
|
2262
|
+
attempted: report.attempted,
|
|
2263
|
+
observed: report.observed,
|
|
2264
|
+
slices: report.slices,
|
|
2265
|
+
elapsedMs: Math.round(report.elapsedMs),
|
|
2266
|
+
unsupported: report.unsupported,
|
|
2267
|
+
abandoned: report.abandoned,
|
|
2268
|
+
timedOut: report.timedOut,
|
|
2269
|
+
computeCompiled: report.computeCompiled,
|
|
2270
|
+
computeAbandoned: report.computeAbandoned,
|
|
2271
|
+
computeUnsupported: report.computeUnsupported,
|
|
2272
|
+
computeTimedOut: report.computeTimedOut,
|
|
2273
|
+
passes: report.passes,
|
|
2274
|
+
passPipelines: report.passPipelines,
|
|
2275
|
+
cullingForced: report.cullingForced,
|
|
2276
|
+
visibilityForced: report.visibilityForced,
|
|
2277
|
+
cache: report.cache,
|
|
2278
|
+
},
|
|
2279
|
+
)}`,
|
|
2280
|
+
);
|
|
2281
|
+
explicitWarmUpSettled = true;
|
|
2282
|
+
if (this.#aborted) {
|
|
2283
|
+
this.#teardown(ctx);
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
this.#started = true;
|
|
2288
|
+
// Every gate has resolved and the scene has entered, so the simulation may move. The first
|
|
2289
|
+
// tick after this reads a single frame's dt, not one spanning the load.
|
|
2290
|
+
gameLoop.setHeld(false);
|
|
2291
|
+
gameLoop.start();
|
|
2292
|
+
}
|
|
2293
|
+
pause(): void {
|
|
2294
|
+
this.#paused = true;
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
resume(): void {
|
|
2298
|
+
this.#paused = false;
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
stop(): void {
|
|
2302
|
+
this.#aborted = true;
|
|
2303
|
+
this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.");
|
|
2304
|
+
this.#teardown();
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
#disposePlugin(plugin: IGamePluginHooks<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): void {
|
|
2308
|
+
if (this.#disposedPlugins.has(plugin)) return;
|
|
2309
|
+
this.#disposedPlugins.add(plugin);
|
|
2310
|
+
plugin.dispose?.(ctx);
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
#teardown(startingCtx?: ICtx<TState, TPhysics>): void {
|
|
2314
|
+
const ctx = this.#ctx ?? startingCtx;
|
|
2315
|
+
// Teardown is failure-atomic: one throwing release must not strand the resources after it.
|
|
2316
|
+
// Every attempt runs, errors are collected, and the first — the original cause — is thrown
|
|
2317
|
+
// once all attempts and the final leak check have completed.
|
|
2318
|
+
const failures: unknown[] = [];
|
|
2319
|
+
this.#disconnectUi();
|
|
2320
|
+
this.#loop?.stop();
|
|
2321
|
+
this.#frameBudget?.dispose();
|
|
2322
|
+
this.#afterPhysicsPhase?.clear();
|
|
2323
|
+
this.#beforeRenderCallbacks.clear();
|
|
2324
|
+
this.#interpolation?.clear();
|
|
2325
|
+
this.#interpolation = undefined;
|
|
2326
|
+
if (this.#sceneEntered && ctx !== undefined) {
|
|
2327
|
+
try {
|
|
2328
|
+
this.#scene?.exit(ctx);
|
|
2329
|
+
} catch (error) {
|
|
2330
|
+
failures.push(error);
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
this.#sceneFrame = undefined;
|
|
2334
|
+
this.#sceneEntered = false;
|
|
2335
|
+
this.#scheduler?.clear();
|
|
2336
|
+
this.#entities?.clear();
|
|
2337
|
+
this.#entities = undefined;
|
|
2338
|
+
if (ctx !== undefined)
|
|
2339
|
+
for (const plugin of this.#activePlugins) {
|
|
2340
|
+
try {
|
|
2341
|
+
this.#disposePlugin(plugin, ctx);
|
|
2342
|
+
} catch (error) {
|
|
2343
|
+
failures.push(error);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
this.#activePlugins = [];
|
|
2347
|
+
for (const cleanup of this.#cleanup.splice(0)) {
|
|
2348
|
+
try {
|
|
2349
|
+
cleanup();
|
|
2350
|
+
} catch (error) {
|
|
2351
|
+
failures.push(error);
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
if (ctx !== undefined) clearScene(ctx.scene, this.#computeDriven);
|
|
2355
|
+
this.#cameraCull?.dispose();
|
|
2356
|
+
this.#cameraCull = undefined;
|
|
2357
|
+
this.#matrixWorld?.dispose();
|
|
2358
|
+
this.#matrixWorld = undefined;
|
|
2359
|
+
this.#input?.dispose();
|
|
2360
|
+
this.#state.stop();
|
|
2361
|
+
ctx?.canvasLayer.dispose();
|
|
2362
|
+
this.#viewport?.dispose();
|
|
2363
|
+
const renderer = this.#renderer;
|
|
2364
|
+
renderer?.dispose();
|
|
2365
|
+
if (renderer !== undefined) {
|
|
2366
|
+
if (this.#config.platform === undefined) renderer.domElement.remove?.();
|
|
2367
|
+
else this.#config.platform.unmountCanvas(renderer.domElement);
|
|
2368
|
+
}
|
|
2369
|
+
this.#renderer = undefined;
|
|
2370
|
+
this.#viewport = undefined;
|
|
2371
|
+
this.#input = undefined;
|
|
2372
|
+
this.#scene = undefined;
|
|
2373
|
+
this.#ctx = undefined;
|
|
2374
|
+
this.#hasDepthCoupledOutput = false;
|
|
2375
|
+
this.#loop = undefined;
|
|
2376
|
+
this.#pointerEvents?.dispose();
|
|
2377
|
+
this.#pointerEvents = undefined;
|
|
2378
|
+
this.#picker?.dispose();
|
|
2379
|
+
this.#picker = undefined;
|
|
2380
|
+
this.#scheduler = undefined;
|
|
2381
|
+
this.#afterPhysicsPhase = undefined;
|
|
2382
|
+
this.#disposedPlugins.clear();
|
|
2383
|
+
this.#paused = false;
|
|
2384
|
+
this.#started = false;
|
|
2385
|
+
// Runs even when releases above failed; its verdict loses to a real cleanup error, which is
|
|
2386
|
+
// the more actionable diagnosis of what went wrong while stopping.
|
|
2387
|
+
if ((ctx?.scene.children.length ?? 0) > 0)
|
|
2388
|
+
failures.push(new Error("IGame teardown leaked scene objects."));
|
|
2389
|
+
if (failures.length > 0) throw failures[0];
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
function createRuntimeObservations(): IGameRuntimeObservations {
|
|
2394
|
+
const contributions = new Set<IGameObservationContribution>();
|
|
2395
|
+
return {
|
|
2396
|
+
contribute: (contribution) => {
|
|
2397
|
+
contributions.add(contribution);
|
|
2398
|
+
return () => contributions.delete(contribution);
|
|
2399
|
+
},
|
|
2400
|
+
contributions: () => [...contributions],
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
export function defineGame<TState extends Record<string, unknown>, TPhysics = undefined>(
|
|
2405
|
+
config: IGameConfig<TState, TPhysics>,
|
|
2406
|
+
): IGame<TState, TPhysics> {
|
|
2407
|
+
return new GameImpl<TState, TPhysics>(config);
|
|
2408
|
+
}
|