@threenative/core 0.3.4 → 0.3.5
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-Bj8G1wmD.d.ts} +102 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12423 -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 +47 -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 +2390 -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 +564 -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 +839 -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/loop.ts
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
import type { FrameBudget, IFramePhaseSample } from "./frame-budget.js";
|
|
2
|
+
import type { PhysicsInterpolation } from "./interpolation.js";
|
|
3
|
+
import type { SpanRecorder } from "./profiling/Spans.js";
|
|
4
|
+
import type { FramePassKind, IRenderPassSample } from "./render-pass-budget.js";
|
|
5
|
+
|
|
6
|
+
export type AfterPhysicsCallback = (dt: number) => void;
|
|
7
|
+
|
|
8
|
+
export interface IAfterPhysicsContext {
|
|
9
|
+
readonly afterPhysics: (callback: AfterPhysicsCallback) => () => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface IAfterPhysicsPhase {
|
|
13
|
+
clear(): void;
|
|
14
|
+
register(callback: AfterPhysicsCallback): () => void;
|
|
15
|
+
run(dt: number): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createAfterPhysicsPhase(): IAfterPhysicsPhase {
|
|
19
|
+
const callbacks = new Set<AfterPhysicsCallback>();
|
|
20
|
+
// Snapshot storage reused across frames, with one array per nesting level so a dispatch
|
|
21
|
+
// started from inside a running callback cannot clobber its parent's snapshot.
|
|
22
|
+
const snapshots: AfterPhysicsCallback[][] = [];
|
|
23
|
+
let depth = 0;
|
|
24
|
+
return {
|
|
25
|
+
clear: () => callbacks.clear(),
|
|
26
|
+
register: (callback) => {
|
|
27
|
+
if (typeof callback !== "function")
|
|
28
|
+
throw new Error("afterPhysics requires a callback function.");
|
|
29
|
+
callbacks.add(callback);
|
|
30
|
+
return () => callbacks.delete(callback);
|
|
31
|
+
},
|
|
32
|
+
run: (dt) => {
|
|
33
|
+
if (!Number.isFinite(dt) || dt <= 0)
|
|
34
|
+
throw new Error(`afterPhysics requires a positive finite dt, received ${String(dt)}.`);
|
|
35
|
+
if (callbacks.size === 0) return;
|
|
36
|
+
let snapshot = snapshots[depth];
|
|
37
|
+
if (snapshot === undefined) {
|
|
38
|
+
snapshot = [];
|
|
39
|
+
snapshots[depth] = snapshot;
|
|
40
|
+
}
|
|
41
|
+
depth += 1;
|
|
42
|
+
snapshot.length = 0;
|
|
43
|
+
// Snapshot before running: a callback that registers or removes work affects the next
|
|
44
|
+
// dispatch, not this one, and one already snapshotted still runs after a later removal.
|
|
45
|
+
for (const callback of callbacks) snapshot.push(callback);
|
|
46
|
+
try {
|
|
47
|
+
for (let index = 0; index < snapshot.length; index += 1) snapshot[index]?.(dt);
|
|
48
|
+
} finally {
|
|
49
|
+
depth -= 1;
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Register work that reads transforms after every simulation step and before the frame renders. */
|
|
56
|
+
export function afterPhysics(
|
|
57
|
+
context: IAfterPhysicsContext,
|
|
58
|
+
callback: AfterPhysicsCallback,
|
|
59
|
+
): () => void {
|
|
60
|
+
if (typeof context?.afterPhysics !== "function")
|
|
61
|
+
throw new Error("afterPhysics requires a game context.");
|
|
62
|
+
return context.afterPhysics(callback);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface IFixedStepLoopOptions {
|
|
66
|
+
readonly interpolation?: PhysicsInterpolation;
|
|
67
|
+
readonly step?: number;
|
|
68
|
+
readonly maxSteps?: number;
|
|
69
|
+
/** Collect per-frame render samples for diagnostics consumers. Default false. */
|
|
70
|
+
readonly collectMetrics?: boolean;
|
|
71
|
+
/** Runs once per presented frame, before any fixed-step simulation dispatches. */
|
|
72
|
+
readonly onBeginFrame?: () => void;
|
|
73
|
+
readonly onUpdate: (dt: number) => void;
|
|
74
|
+
/** Runs after `onUpdate` has completed and before `onRender` starts. */
|
|
75
|
+
readonly onAfterPhysics?: (dt: number) => void;
|
|
76
|
+
readonly onRender?: (alpha: number) => undefined | IRenderPerformanceMetrics;
|
|
77
|
+
/** Actual wall time spent in one simulation+render callback, for startup gates and diagnostics. */
|
|
78
|
+
readonly onFrame?: (frameMs: number) => void;
|
|
79
|
+
readonly requestFrame?: (callback: (time: number) => void) => number;
|
|
80
|
+
readonly cancelFrame?: (handle: number) => void;
|
|
81
|
+
/**
|
|
82
|
+
* Per-frame cost attribution. The loop is the only place that knows where the simulation phase
|
|
83
|
+
* ends and the render phase begins, so it is the only honest place to measure them; a game
|
|
84
|
+
* wrapping `requestAnimationFrame` from outside has to guess that boundary.
|
|
85
|
+
*/
|
|
86
|
+
readonly budget?: FrameBudget;
|
|
87
|
+
/**
|
|
88
|
+
* The render-phase span tree, when `TN_FRAME_SPANS` asked for one.
|
|
89
|
+
*
|
|
90
|
+
* The loop is where the frame budget's own phase split becomes a number, so it is the only place
|
|
91
|
+
* that can close the span tree against the same render phase the meter charged. A tree closed
|
|
92
|
+
* anywhere else would be arithmetic against a second, slightly different interval.
|
|
93
|
+
*/
|
|
94
|
+
readonly spans?: SpanRecorder;
|
|
95
|
+
/** Monotonic clock for phase boundaries. Defaults to `performance.now`. */
|
|
96
|
+
readonly now?: () => number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface IRenderPerformanceMetrics {
|
|
100
|
+
readonly drawCalls?: number;
|
|
101
|
+
readonly passes?: readonly IRenderPassSample[];
|
|
102
|
+
readonly triangles?: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface IRenderPerformanceSample extends IRenderPerformanceMetrics {
|
|
106
|
+
readonly frameMs: number;
|
|
107
|
+
/** Successful render-callback completion ID; absolute across clears and retention. */
|
|
108
|
+
readonly sequence?: number;
|
|
109
|
+
/** Completion boundary from the monotonic phase clock, not the rAF timestamp or render-body cost. */
|
|
110
|
+
readonly completedAtMs?: number;
|
|
111
|
+
/** Where this frame's milliseconds went. Present whenever a frame budget is installed. */
|
|
112
|
+
readonly phases?: IFramePhaseSample;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const MAX_RENDER_PERFORMANCE_SAMPLES = 1_024;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* One entry per pass kind, summed, for a retained sample.
|
|
119
|
+
*
|
|
120
|
+
* `RenderPassBudget` records one entry per `render()` call, which is what the frame budget and the
|
|
121
|
+
* geometry capture need to attribute a submission to the innermost call. A retained sample does
|
|
122
|
+
* not: it is a 1,024-frame window shipped to the playtest bridge under a 1 MB payload ceiling, and
|
|
123
|
+
* a frame with 30 nested calls made that window ~1.4 MB, so `assert.performance` failed with
|
|
124
|
+
* TN_PLAYTEST_PAYLOAD_TOO_LARGE before frame 0. Consumers read per-kind values, and taking the
|
|
125
|
+
* first of N silently undercounted every lane past its first call.
|
|
126
|
+
*/
|
|
127
|
+
function aggregatePassesByKind(passes: readonly IRenderPassSample[]): IRenderPassSample[] {
|
|
128
|
+
const totals = new Map<FramePassKind, IRenderPassSample>();
|
|
129
|
+
for (const pass of passes) {
|
|
130
|
+
const total = totals.get(pass.kind);
|
|
131
|
+
totals.set(pass.kind, {
|
|
132
|
+
draws: (total?.draws ?? 0) + pass.draws,
|
|
133
|
+
kind: pass.kind,
|
|
134
|
+
triangles: (total?.triangles ?? 0) + pass.triangles,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return [...totals.values()];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* How many fixed steps a frozen clock runs once, before the run's first observation.
|
|
142
|
+
*
|
|
143
|
+
* This is the settling the boot used to do by accident, counted instead of measured. Live frames
|
|
144
|
+
* during the startup compile wait advanced the simulation at whatever rate the machine managed —
|
|
145
|
+
* 59 ticks before the first sample on a quiet one, thousands on a loaded one — and games leaned on
|
|
146
|
+
* that: the platformer character captures its visual-attachment baseline on its first grounded
|
|
147
|
+
* contact, so a run that started at tick 0 read `visualAttached: false` where a run that started at
|
|
148
|
+
* tick 59 read `true`, from the same build. A fixed count is the same settling with the machine out
|
|
149
|
+
* of it, and one second is what the quiet machine actually delivered. A run's own steps are
|
|
150
|
+
* unaffected: this happens once, before the runner takes its first tick, and `#tick` counts it, so
|
|
151
|
+
* the report says how old the simulation is.
|
|
152
|
+
*/
|
|
153
|
+
const FROZEN_SETTLE_STEPS = 60;
|
|
154
|
+
|
|
155
|
+
export class FixedStepLoop {
|
|
156
|
+
readonly step: number;
|
|
157
|
+
readonly maxSteps: number;
|
|
158
|
+
#onBeginFrame: (() => void) | undefined;
|
|
159
|
+
#onUpdate: (dt: number) => void;
|
|
160
|
+
#onAfterPhysics: (dt: number) => void;
|
|
161
|
+
#onRender: (alpha: number) => undefined | IRenderPerformanceMetrics;
|
|
162
|
+
#onFrame: (frameMs: number) => void;
|
|
163
|
+
#requestFrame: (callback: (time: number) => void) => number;
|
|
164
|
+
#cancelFrame: (handle: number) => void;
|
|
165
|
+
readonly #interpolation: PhysicsInterpolation | undefined;
|
|
166
|
+
#accumulator = 0;
|
|
167
|
+
#lastTime: number | undefined;
|
|
168
|
+
#frameTime = 0;
|
|
169
|
+
#frameHandle: number | undefined;
|
|
170
|
+
#running = false;
|
|
171
|
+
#held = false;
|
|
172
|
+
#clockFrozen = false;
|
|
173
|
+
#driven = false;
|
|
174
|
+
#primePending = false;
|
|
175
|
+
#settleSteps = FROZEN_SETTLE_STEPS;
|
|
176
|
+
#tick = 0;
|
|
177
|
+
#fps = 0;
|
|
178
|
+
#lastRenderTime: number | undefined;
|
|
179
|
+
#renderPerformanceSamples: IRenderPerformanceSample[] = [];
|
|
180
|
+
#renderCompletionSequence = 0;
|
|
181
|
+
#frameCallback: (time: number) => void;
|
|
182
|
+
#budget: FrameBudget | undefined;
|
|
183
|
+
#spans: SpanRecorder | undefined;
|
|
184
|
+
#now: () => number;
|
|
185
|
+
// Sample collection is opt-in because nothing outside a diagnostics consumer reads the series:
|
|
186
|
+
// collecting unconditionally spent allocations on every rendered frame of every game.
|
|
187
|
+
#collectMetrics: boolean;
|
|
188
|
+
|
|
189
|
+
constructor(options: IFixedStepLoopOptions) {
|
|
190
|
+
const step = options.step ?? 1 / 60;
|
|
191
|
+
if (!Number.isFinite(step) || step <= 0) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`FixedStepLoop step must be a finite number of seconds greater than zero, received ${String(options.step)}.`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
this.step = step;
|
|
197
|
+
this.#interpolation = options.interpolation;
|
|
198
|
+
// A maxSteps below one passed the while-loop bound `updates < maxSteps` zero
|
|
199
|
+
// times per frame: the game rendered but never simulated, silently.
|
|
200
|
+
const maxSteps = options.maxSteps ?? 5;
|
|
201
|
+
if (!Number.isInteger(maxSteps) || maxSteps < 1) {
|
|
202
|
+
throw new Error(
|
|
203
|
+
`FixedStepLoop maxSteps must be an integer of at least one, received ${String(options.maxSteps)}.`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
this.maxSteps = maxSteps;
|
|
207
|
+
this.#collectMetrics = options.collectMetrics ?? false;
|
|
208
|
+
this.#budget = options.budget;
|
|
209
|
+
this.#spans = options.spans;
|
|
210
|
+
this.#now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
|
|
211
|
+
this.#onBeginFrame = options.onBeginFrame;
|
|
212
|
+
this.#onUpdate = options.onUpdate;
|
|
213
|
+
this.#onAfterPhysics = options.onAfterPhysics ?? (() => undefined);
|
|
214
|
+
this.#onRender = options.onRender ?? (() => undefined);
|
|
215
|
+
this.#onFrame = options.onFrame ?? (() => undefined);
|
|
216
|
+
this.#requestFrame =
|
|
217
|
+
options.requestFrame ??
|
|
218
|
+
((callback) =>
|
|
219
|
+
typeof globalThis.requestAnimationFrame === "function"
|
|
220
|
+
? globalThis.requestAnimationFrame(callback)
|
|
221
|
+
: 0);
|
|
222
|
+
this.#cancelFrame =
|
|
223
|
+
options.cancelFrame ??
|
|
224
|
+
((handle) => {
|
|
225
|
+
if (typeof globalThis.cancelAnimationFrame === "function")
|
|
226
|
+
globalThis.cancelAnimationFrame(handle);
|
|
227
|
+
});
|
|
228
|
+
this.#frameCallback = (time) => this.#frame(time);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Frame callback timestamp in milliseconds. */
|
|
232
|
+
get frameTime(): number {
|
|
233
|
+
return this.#frameTime;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Fraction of the next fixed step accumulated for this presented frame. */
|
|
237
|
+
get alpha(): number {
|
|
238
|
+
return Math.max(0, Math.min(1 - Number.EPSILON, this.#accumulator / this.step));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
get running(): boolean {
|
|
242
|
+
return this.#running;
|
|
243
|
+
}
|
|
244
|
+
get fps(): number {
|
|
245
|
+
return this.#fps;
|
|
246
|
+
}
|
|
247
|
+
runtimeDiagnosticsSeries(): readonly IRenderPerformanceSample[] {
|
|
248
|
+
return this.#renderPerformanceSamples.map((sample) => ({ ...sample }));
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Forget the render samples taken so far. The game calls it once, when the world first draws:
|
|
252
|
+
* the frames before it are the boot — held behind the startup compile, drawing nothing — and a
|
|
253
|
+
* steady-state window that keeps them fails `maxDrawCalls` closed on frames that have no draw
|
|
254
|
+
* count and puts seconds of compile into the frame-time percentile.
|
|
255
|
+
*/
|
|
256
|
+
clearRuntimeDiagnostics(): void {
|
|
257
|
+
this.#renderPerformanceSamples = [];
|
|
258
|
+
}
|
|
259
|
+
/** The frame budget this loop feeds, when one is installed. */
|
|
260
|
+
get budget(): FrameBudget | undefined {
|
|
261
|
+
return this.#budget;
|
|
262
|
+
}
|
|
263
|
+
/** Turns sample collection on for the rest of the run; a diagnostics consumer asking for the series is the only caller. */
|
|
264
|
+
setCollectMetrics(enabled: boolean): void {
|
|
265
|
+
this.#collectMetrics = enabled;
|
|
266
|
+
}
|
|
267
|
+
/** True while the loop renders without simulating. */
|
|
268
|
+
get held(): boolean {
|
|
269
|
+
return this.#held;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Render without simulating.
|
|
273
|
+
*
|
|
274
|
+
* Boot needs frames on the screen before the start scene has finished loading: on native the
|
|
275
|
+
* render loop is the only thing that can draw, so a loop that starts after `load()` resolves
|
|
276
|
+
* leaves the screen black for the whole asset load and a loading screen never appears. A held
|
|
277
|
+
* loop draws and does nothing else -- `onUpdate` is never called, `tick()` still reads zero,
|
|
278
|
+
* and the hold banks no time, so the first tick after release gets one frame of `dt` rather
|
|
279
|
+
* than one covering the entire load.
|
|
280
|
+
*/
|
|
281
|
+
setHeld(held: boolean): void {
|
|
282
|
+
this.#held = held;
|
|
283
|
+
}
|
|
284
|
+
/** Reserved playtest seam: transition without banking elapsed wall time. */
|
|
285
|
+
_setClockMode(mode: "fixed-step" | "wall-clock"): void {
|
|
286
|
+
if (mode !== "fixed-step" && mode !== "wall-clock") throw new Error("Unknown clock mode.");
|
|
287
|
+
const frozen = mode === "fixed-step";
|
|
288
|
+
if (this.#clockFrozen === frozen) return;
|
|
289
|
+
this.#clockFrozen = frozen;
|
|
290
|
+
this.#primePending = false;
|
|
291
|
+
this.#accumulator = 0;
|
|
292
|
+
this.#lastTime = frozen ? Number.POSITIVE_INFINITY : undefined;
|
|
293
|
+
this.#lastRenderTime = undefined;
|
|
294
|
+
this.#driven = false;
|
|
295
|
+
this.clearRuntimeDiagnostics();
|
|
296
|
+
if (this.#running && this.#frameHandle === undefined)
|
|
297
|
+
this.#frameHandle = this.#requestFrame(this.#frameCallback);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Stop the live clock: from here a rendered frame draws and simulates nothing, and banks no
|
|
302
|
+
* time. `advance()` is then the only thing that moves the simulation.
|
|
303
|
+
*
|
|
304
|
+
* This is the whole-run form of the hold above, and it exists because the hold is undone by the
|
|
305
|
+
* first tick while the clock is not. A tick-counting playtest run banks real wall-clock seconds
|
|
306
|
+
* into the same simulation its ticks measure: the runner pumps live frames for the rAF warmup
|
|
307
|
+
* and then for the whole startup wait -- compile settlement is 30s+ on a software adapter and
|
|
308
|
+
* is itself a function of how loaded the machine is -- and every one of those frames advanced
|
|
309
|
+
* the game. Measured on the racing template's `racing-finish-behind-rival-is-dnf`: 164 ticks
|
|
310
|
+
* (2.73s of race time) elapsed before the scenario pressed a key on a fast machine with a real
|
|
311
|
+
* GPU, and that scenario's third lap lands at 47.0s against a 90s in-game race limit, so the
|
|
312
|
+
* 42.7s of headroom is spent by boot time rather than by the scenario. The same scenario then
|
|
313
|
+
* fails its `completedLaps` assertion on a loaded runner and passes on a quiet one, from the
|
|
314
|
+
* same build. Idempotent, and implied by `advance()`.
|
|
315
|
+
*
|
|
316
|
+
* Frozen stops *time*, not the frame function: the loop still settles the world with a fixed
|
|
317
|
+
* number of steps — see `#primeFrame`. A game lays out per-frame state in `update` (action-rpg's
|
|
318
|
+
* touch overlay places itself against the viewport there and is parented to the camera), and a
|
|
319
|
+
* run reads its first observation before it takes its first tick, so a freeze that skipped
|
|
320
|
+
* updates outright left that state at its constructed pose: the overlay sat on the camera's own
|
|
321
|
+
* origin and `point.project` divided by a zero w, which is `NaN` bounds in the entity observation
|
|
322
|
+
* and took the scenario down before it asserted anything.
|
|
323
|
+
*
|
|
324
|
+
* @param settleSteps Fixed steps to run once the loop is live. Defaults to one second; zero
|
|
325
|
+
* leaves the world exactly as the game built it.
|
|
326
|
+
*/
|
|
327
|
+
freezeClock(settleSteps = FROZEN_SETTLE_STEPS): void {
|
|
328
|
+
// Armed by the *transition* into frozen, so `advance()` — which implies the freeze — does not
|
|
329
|
+
// re-arm it and spend a settling pass after every tick-counted step the runner takes.
|
|
330
|
+
if (!Number.isInteger(settleSteps) || settleSteps < 0)
|
|
331
|
+
throw new Error("settleSteps must be a non-negative integer.");
|
|
332
|
+
if (!this.#clockFrozen) this.#primePending = true;
|
|
333
|
+
this.#clockFrozen = true;
|
|
334
|
+
this.#settleSteps = settleSteps;
|
|
335
|
+
this.#lastTime = Number.POSITIVE_INFINITY;
|
|
336
|
+
}
|
|
337
|
+
/** True once the live clock no longer drives the simulation. */
|
|
338
|
+
get clockFrozen(): boolean {
|
|
339
|
+
return this.#clockFrozen;
|
|
340
|
+
}
|
|
341
|
+
readonly tick = (): number => this.#tick;
|
|
342
|
+
start(now = globalThis.performance?.now() ?? 0): void {
|
|
343
|
+
if (this.#running) return;
|
|
344
|
+
this.#running = true;
|
|
345
|
+
this.#driven = false;
|
|
346
|
+
// A freeze asked for before the loop ran outranks the start timestamp, or a playtest bridge
|
|
347
|
+
// that installs first would be undone by the boot it is supposed to cover.
|
|
348
|
+
this.#lastTime = this.#clockFrozen ? Number.POSITIVE_INFINITY : now;
|
|
349
|
+
this.#lastRenderTime = undefined;
|
|
350
|
+
this.#tick = 0;
|
|
351
|
+
this.#fps = 0;
|
|
352
|
+
this.#renderPerformanceSamples = [];
|
|
353
|
+
this.#frameHandle = this.#requestFrame(this.#frameCallback);
|
|
354
|
+
}
|
|
355
|
+
stop(): void {
|
|
356
|
+
this.#running = false;
|
|
357
|
+
if (this.#frameHandle !== undefined) this.#cancelFrame(this.#frameHandle);
|
|
358
|
+
this.#frameHandle = undefined;
|
|
359
|
+
this.#lastTime = undefined;
|
|
360
|
+
this.#accumulator = 0;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
#advanceSimulation(now: number): number {
|
|
364
|
+
if (this.#held || this.#clockFrozen) {
|
|
365
|
+
// The whole accumulate-and-update block is skipped rather than just the callback: `#tick`
|
|
366
|
+
// advances inside that loop, and a held frame that moved the tick would break the
|
|
367
|
+
// determinism contract every playtest hold depends on. The clock still moves forward so
|
|
368
|
+
// the hold banks no time.
|
|
369
|
+
this.#lastTime = Math.max(this.#lastTime ?? now, now);
|
|
370
|
+
this.#primeFrame();
|
|
371
|
+
return 0;
|
|
372
|
+
}
|
|
373
|
+
const elapsed = Math.max(0, (now - (this.#lastTime ?? now)) / 1000);
|
|
374
|
+
this.#lastTime = Math.max(this.#lastTime ?? now, now);
|
|
375
|
+
this.#accumulator += elapsed;
|
|
376
|
+
let updates = 0;
|
|
377
|
+
while (this.#accumulator + Number.EPSILON >= this.step && updates < this.maxSteps) {
|
|
378
|
+
this.#interpolation?.beginTick();
|
|
379
|
+
this.#onUpdate(this.step);
|
|
380
|
+
this.#onAfterPhysics(this.step);
|
|
381
|
+
this.#interpolation?.endTick();
|
|
382
|
+
this.#tick += 1;
|
|
383
|
+
this.#accumulator -= this.step;
|
|
384
|
+
updates += 1;
|
|
385
|
+
}
|
|
386
|
+
if (updates === this.maxSteps && this.#accumulator >= this.step) this.#accumulator = 0;
|
|
387
|
+
return updates;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Settle the world once, on the first live frame after the clock froze.
|
|
392
|
+
*
|
|
393
|
+
* `freezeClock` means the wall clock stops moving the simulation, not that the game stops being
|
|
394
|
+
* called: a scene computes per-frame state in `update` — action-rpg's touch overlay measures the
|
|
395
|
+
* viewport and parents itself to the camera there — and a playtest run reads its first
|
|
396
|
+
* observation before it takes its first tick. Without this pass that state is still whatever its
|
|
397
|
+
* constructor left it, which for a camera-parented overlay is a 72-unit ring sitting on the
|
|
398
|
+
* camera's own origin: `point.project` divides by a zero `w`, and the observation the run reads
|
|
399
|
+
* carries `NaN` bounds, which takes the scenario down before it asserts anything.
|
|
400
|
+
*
|
|
401
|
+
* It is `advance()` over a fixed count, so it is a tick-counted settle rather than a timed one:
|
|
402
|
+
* what it costs is a constant no machine speed can change, and `#tick` moves with it, because the
|
|
403
|
+
* simulation really is that many steps old and the run's report should say so. `FROZEN_SETTLE_STEPS`
|
|
404
|
+
* is where the count comes from.
|
|
405
|
+
*
|
|
406
|
+
* A held boot frame cannot spend it: the scene has not entered yet, so there is nothing of the
|
|
407
|
+
* game's to settle, and the arm survives the hold to fire when the loop is genuinely live. Once,
|
|
408
|
+
* because a second pass would repeat input edge detection and per-frame bookkeeping for nothing.
|
|
409
|
+
*/
|
|
410
|
+
#primeFrame(): void {
|
|
411
|
+
if (!this.#primePending || this.#held) return;
|
|
412
|
+
this.#primePending = false;
|
|
413
|
+
if (this.#settleSteps > 0) this.advance(this.#settleSteps);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
#recordFrameTiming(now: number): number | undefined {
|
|
417
|
+
if (!Number.isFinite(now)) return undefined;
|
|
418
|
+
const frameMs = this.#lastRenderTime === undefined ? undefined : now - this.#lastRenderTime;
|
|
419
|
+
if (frameMs !== undefined && frameMs > 0) this.#fps += (1_000 / frameMs - this.#fps) * 0.1;
|
|
420
|
+
this.#lastRenderTime = now;
|
|
421
|
+
return frameMs;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
stepFrame(now: number, driven: boolean | "render-only" = false): number {
|
|
425
|
+
this.#frameTime = now;
|
|
426
|
+
const callbackStartedAt = this.#now();
|
|
427
|
+
const budget = this.#budget;
|
|
428
|
+
budget?.beginFrame(now, this.#now());
|
|
429
|
+
let updates = 0;
|
|
430
|
+
let frameMs: number | undefined;
|
|
431
|
+
let callbackMs: number | undefined;
|
|
432
|
+
let callbackFinishedAt = Number.NaN;
|
|
433
|
+
let metrics: IRenderPerformanceMetrics | undefined;
|
|
434
|
+
let phases: IFramePhaseSample | undefined;
|
|
435
|
+
try {
|
|
436
|
+
this.#onBeginFrame?.();
|
|
437
|
+
if (driven === true) {
|
|
438
|
+
this.#onUpdate(this.step);
|
|
439
|
+
this.#onAfterPhysics(this.step);
|
|
440
|
+
this.#tick += 1;
|
|
441
|
+
updates = 1;
|
|
442
|
+
} else if (driven !== "render-only") updates = this.#advanceSimulation(now);
|
|
443
|
+
budget?.markSimulationEnd(this.#now(), updates);
|
|
444
|
+
frameMs = this.#recordFrameTiming(now);
|
|
445
|
+
// onRender does the rendering itself; only its metrics return value is optional.
|
|
446
|
+
metrics = this.#onRender(this.alpha);
|
|
447
|
+
} finally {
|
|
448
|
+
// A renderer can throw before it returns (for example, when SwiftShader rejects a buffer).
|
|
449
|
+
// Close the budget before propagating that error so later frames report the real failure
|
|
450
|
+
// instead of flooding the console with beginFrame calls against a poisoned budget.
|
|
451
|
+
phases = budget?.endFrame(this.#now(), this.#collectMetrics);
|
|
452
|
+
// Closed against the meter's own render phase, so the tree's residual is arithmetic against
|
|
453
|
+
// the number the window reports rather than against a second measurement of the same work.
|
|
454
|
+
// A frame that threw keeps its half-open stack out of the window instead of contributing a
|
|
455
|
+
// fabricated zero.
|
|
456
|
+
const spans = this.#spans;
|
|
457
|
+
if (spans !== undefined) {
|
|
458
|
+
// From the meter's own reading, never from the optional phase sample: `endFrame` builds a
|
|
459
|
+
// sample only when a consumer asked for one, and shipping games do not, so closing the
|
|
460
|
+
// tree on `phases` abandoned every frame and the span window never appeared.
|
|
461
|
+
const renderMs = budget?.lastRenderMs;
|
|
462
|
+
if (renderMs !== undefined && spans.depth === 0) spans.endFrame(renderMs);
|
|
463
|
+
else spans.abandonFrame();
|
|
464
|
+
}
|
|
465
|
+
callbackFinishedAt = this.#now();
|
|
466
|
+
if (Number.isFinite(callbackStartedAt) && Number.isFinite(callbackFinishedAt)) {
|
|
467
|
+
callbackMs = Math.max(0, callbackFinishedAt - callbackStartedAt);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// Reached only after successful rendering; IDs also reveal gaps across disabled collection.
|
|
471
|
+
const sequence = ++this.#renderCompletionSequence;
|
|
472
|
+
if (callbackMs !== undefined) this.#onFrame(callbackMs);
|
|
473
|
+
if (this.#collectMetrics && frameMs !== undefined && frameMs > 0) {
|
|
474
|
+
const sample: IRenderPerformanceSample = {
|
|
475
|
+
frameMs,
|
|
476
|
+
sequence,
|
|
477
|
+
completedAtMs: callbackFinishedAt,
|
|
478
|
+
...(metrics === undefined || metrics.drawCalls === undefined
|
|
479
|
+
? {}
|
|
480
|
+
: { drawCalls: metrics.drawCalls }),
|
|
481
|
+
...(metrics?.passes === undefined || metrics.passes.length === 0
|
|
482
|
+
? {}
|
|
483
|
+
: { passes: aggregatePassesByKind(metrics.passes) }),
|
|
484
|
+
...(phases === undefined ? {} : { phases }),
|
|
485
|
+
...(metrics === undefined || metrics.triangles === undefined
|
|
486
|
+
? {}
|
|
487
|
+
: { triangles: metrics.triangles }),
|
|
488
|
+
};
|
|
489
|
+
this.#renderPerformanceSamples.push(sample);
|
|
490
|
+
if (this.#renderPerformanceSamples.length > MAX_RENDER_PERFORMANCE_SAMPLES)
|
|
491
|
+
this.#renderPerformanceSamples.shift();
|
|
492
|
+
}
|
|
493
|
+
return updates;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
advance(ticks: number, options?: { render?: boolean }): number {
|
|
497
|
+
if (!this.#running) throw new Error("Cannot advance a stopped loop.");
|
|
498
|
+
if (!Number.isInteger(ticks) || ticks <= 0)
|
|
499
|
+
throw new Error("advance ticks must be a positive integer.");
|
|
500
|
+
// Driving one tick is a statement that the run counts ticks, so it also stops the live clock
|
|
501
|
+
// racing it. `freezeClock()` exists for the frames *before* that statement, which is where a
|
|
502
|
+
// boot's wall clock used to reach the simulation. The prime is not armed from here: this line
|
|
503
|
+
// has just delivered a real update, so the game has had its pass, and arming it would spend
|
|
504
|
+
// one more zero-dt update after every step a run counts. For the same reason a settle still
|
|
505
|
+
// pending is spent: it would otherwise land inside a later counted step as extra ticks.
|
|
506
|
+
this.#primePending = false;
|
|
507
|
+
this.#clockFrozen = true;
|
|
508
|
+
this.#lastTime = Number.POSITIVE_INFINITY;
|
|
509
|
+
if (options?.render === true && !this.#held) {
|
|
510
|
+
// Held startup still needs automatic loading/warmup frames.
|
|
511
|
+
this.#driven = true;
|
|
512
|
+
if (this.#frameHandle !== undefined) this.#cancelFrame(this.#frameHandle);
|
|
513
|
+
this.#frameHandle = undefined;
|
|
514
|
+
for (let index = 0; index < ticks; index += 1) this.stepFrame(this.#now(), true);
|
|
515
|
+
return ticks;
|
|
516
|
+
}
|
|
517
|
+
// A counted batch is metered, because a tick-counted run — which is what a playtest run is — is
|
|
518
|
+
// simulated entirely by `advance()` and reported `update 0 ms`, `substeps 0` and one boot window
|
|
519
|
+
// followed by nothing but hitches, a blocking batch having pushed the next live timestamp past
|
|
520
|
+
// `hitchMs`. It is charged as simulation, not as a frame: it presents nothing, so counting it as
|
|
521
|
+
// one put zero-millisecond frames that drew nothing into half of every window's frame and render
|
|
522
|
+
// percentiles. `addSimulation` decides which it is from the frame it lands in, so an `advance()`
|
|
523
|
+
// from inside a live frame — the frozen prime's settle — is charged there exactly once.
|
|
524
|
+
const startedAt = this.#now();
|
|
525
|
+
for (let index = 0; index < ticks; index += 1) {
|
|
526
|
+
this.#interpolation?.beginTick();
|
|
527
|
+
this.#onUpdate(this.step);
|
|
528
|
+
this.#onAfterPhysics(this.step);
|
|
529
|
+
this.#interpolation?.endTick();
|
|
530
|
+
this.#tick += 1;
|
|
531
|
+
}
|
|
532
|
+
const finishedAt = this.#now();
|
|
533
|
+
const budget = this.#budget;
|
|
534
|
+
if (budget !== undefined && Number.isFinite(startedAt) && Number.isFinite(finishedAt))
|
|
535
|
+
budget.addSimulation(Math.max(0, finishedAt - startedAt), ticks);
|
|
536
|
+
return ticks;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Draw the world once without stepping it, for a native deterministic screenshot: the automatic
|
|
541
|
+
* frame pump is off between ticks, so nothing presents and a desktop capture would time out.
|
|
542
|
+
* `render-only` runs the render hooks but skips the frozen startup settle, so the copy is the
|
|
543
|
+
* standing world rather than a simulation change; a live clock fails closed.
|
|
544
|
+
*/
|
|
545
|
+
renderCurrentFrame(): number {
|
|
546
|
+
if (!this.#running) throw new Error("Cannot render a stopped loop.");
|
|
547
|
+
if (!this.#clockFrozen)
|
|
548
|
+
throw new Error(
|
|
549
|
+
"renderCurrentFrame requires a frozen clock; a live loop advances through its own frames.",
|
|
550
|
+
);
|
|
551
|
+
return this.stepFrame(this.#now(), "render-only");
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
#frame(time: number): void {
|
|
555
|
+
if (!this.#running || this.#driven) return;
|
|
556
|
+
try {
|
|
557
|
+
this.stepFrame(time);
|
|
558
|
+
} finally {
|
|
559
|
+
if (this.#running && !this.#driven) {
|
|
560
|
+
this.#frameHandle = this.#requestFrame(this.#frameCallback);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|