@threenative/core 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -25,6 +25,8 @@
25
25
  */
26
26
 
27
27
  /** Marker printed once per report window when spans are installed. */
28
+ import { countDebug, debugRequested } from "./debug-telemetry.js";
29
+
28
30
  export const SPANS_MARKER = "TN_FRAME_SPANS";
29
31
 
30
32
  /**
@@ -74,6 +76,10 @@ export const SPANS = {
74
76
  terrainBlock: 14,
75
77
  /** Terrain seam reconciliation and bridge-attribute swap on the calling thread. */
76
78
  terrainSeam: 15,
79
+ /** One actual AnimationPlayer.update call, measured by the crowd fixture. */
80
+ animationUpdate: 16,
81
+ /** One actual SkinnedBatch.write call, including its guard and any skeleton/palette work. */
82
+ skinnedWrite: 17,
77
83
  } as const;
78
84
 
79
85
  export type SpanId = (typeof SPANS)[keyof typeof SPANS];
@@ -86,31 +92,31 @@ export type SpanId = (typeof SPANS)[keyof typeof SPANS];
86
92
  * opened by the host itself and have no id here.
87
93
  */
88
94
  export const GAME_SPANS = {
89
- input: 16,
90
- scheduler: 17,
91
- plugins: 18,
92
- sceneCallbacks: 19,
93
- entities: 20,
94
- afterPhysics: 21,
95
- mixer: 22,
96
- stride: 23,
97
- blend: 24,
98
- transport: 25,
99
- publish: 26,
100
- playtest: 27,
101
- ui: 30,
102
- loop: 33,
103
- state: 34,
104
- contacts: 35,
105
- transitions: 36,
106
- objectGraph: 37,
107
- physicsStep: 38,
108
- physicsRead: 39,
109
- physicsApply: 40,
110
- characterMove: 41,
111
- animationPlay: 42,
112
- inputVector: 43,
113
- graphVisit: 44,
95
+ input: 18,
96
+ scheduler: 19,
97
+ plugins: 20,
98
+ sceneCallbacks: 21,
99
+ entities: 22,
100
+ afterPhysics: 23,
101
+ mixer: 24,
102
+ stride: 25,
103
+ blend: 26,
104
+ transport: 27,
105
+ publish: 28,
106
+ playtest: 29,
107
+ ui: 32,
108
+ loop: 35,
109
+ state: 36,
110
+ contacts: 37,
111
+ transitions: 38,
112
+ objectGraph: 39,
113
+ physicsStep: 40,
114
+ physicsRead: 41,
115
+ physicsApply: 42,
116
+ characterMove: 43,
117
+ animationPlay: 44,
118
+ inputVector: 45,
119
+ graphVisit: 46,
114
120
  } as const;
115
121
 
116
122
  /** Names, indexed by id. The only place a span name is a string. */
@@ -131,6 +137,8 @@ export const SPAN_NAMES: readonly string[] = [
131
137
  "draw",
132
138
  "terrainBlock",
133
139
  "terrainSeam",
140
+ "animationUpdate",
141
+ "skinnedWrite",
134
142
  ];
135
143
 
136
144
  export const SPAN_COUNT = SPAN_NAMES.length;
@@ -244,6 +252,7 @@ class Ring {
244
252
  * than a loud failure in a mode a game opted into.
245
253
  */
246
254
  export class SpanRecorder {
255
+ readonly #debug = debugRequested();
247
256
  readonly capacity: number;
248
257
  readonly #stackId = new Int32Array(MAX_DEPTH);
249
258
  readonly #stackStart = new Float64Array(MAX_DEPTH);
@@ -301,6 +310,8 @@ export class SpanRecorder {
301
310
  );
302
311
  this.#depth = depth;
303
312
  const ms = now - (this.#stackStart[depth] ?? now);
313
+ if (this.#debug)
314
+ countDebug(`span.${SPAN_NAMES[id]}Ms`, ms, "renderer", `Spans.${SPAN_NAMES[id]}`, "ms");
304
315
  this.#own[id] = (this.#own[id] ?? 0) + ms;
305
316
  this.#attribute(ms);
306
317
  }
@@ -311,6 +322,8 @@ export class SpanRecorder {
311
322
  * bracketed one would.
312
323
  */
313
324
  add(id: SpanId, ms: number): void {
325
+ if (this.#debug)
326
+ countDebug(`span.${SPAN_NAMES[id]}Ms`, ms, "renderer", `Spans.${SPAN_NAMES[id]}`, "ms");
314
327
  this.#own[id] = (this.#own[id] ?? 0) + ms;
315
328
  this.#entries[id] = (this.#entries[id] ?? 0) + 1;
316
329
  this.#attribute(ms);
@@ -522,6 +535,7 @@ export function addSpan(id: SpanId, ms: number): void {
522
535
  * `globalThis.__tnFrameSpans` before the game boots.
523
536
  */
524
537
  export function spansRequested(): boolean {
538
+ if (debugRequested()) return true;
525
539
  const host = globalThis as {
526
540
  process?: { env?: Record<string, unknown> };
527
541
  __tnFrameSpans?: unknown;
@@ -0,0 +1,312 @@
1
+ import type { IFrameBudgetWindow } from "../frame-budget.js";
2
+
3
+ export interface IDebugSource {
4
+ readonly area: string;
5
+ readonly caller: string;
6
+ readonly lever?: string;
7
+ readonly unit?: string;
8
+ }
9
+
10
+ interface IDebugHost {
11
+ process?: { env?: Record<string, unknown> };
12
+ __tnEngineCost?: Record<string, number>;
13
+ __tnDebugSources?: Record<string, IDebugSource>;
14
+ /** The web back end's running totals by name, the same bag `createEngineCounterReader` differences. */
15
+ __tnEngineCounters?: () => Readonly<Record<string, number>>;
16
+ }
17
+
18
+ /** The biggest content-scaled names one report lists; a series for each would never stop growing. */
19
+ const CONTENT_SCALED_LIMIT = 10;
20
+
21
+ /**
22
+ * Counters whose name multiplies with the content: one per asset URL (`assetDispatch.<url>Ms`,
23
+ * `textureDecode.<url>WallMs`, `assetLoad.<url>WallMs`) and one per bridged property
24
+ * (`bridge:get DirectionalLight.intensity`). A scene with 500 textures makes 500 names, so a
25
+ * per-frame series for each is an unbounded map; the reader skips them and the report ranks the
26
+ * largest {@link CONTENT_SCALED_LIMIT} of the run instead.
27
+ */
28
+ export function isContentScaled(name: string): boolean {
29
+ return name.startsWith("bridge:") || /^(?:assetDispatch|assetLoad|textureDecode)\./u.test(name);
30
+ }
31
+
32
+ /** Read at installation, using the same launch seams as spansRequested(). */
33
+ /** The public launch flag shared with native and worker hosts; a string key keeps its spelling out of the naming lint. */
34
+ const DEBUG_GLOBAL = "__THREENATIVE_DEBUG__";
35
+
36
+ export function debugRequested(): boolean {
37
+ const host = globalThis as IDebugHost;
38
+ return (
39
+ host.process?.env?.TN_DEBUG === "1" ||
40
+ (globalThis as Record<string, unknown>)[DEBUG_GLOBAL] === true ||
41
+ /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "")
42
+ );
43
+ }
44
+
45
+ /** Debug-only producers call this; the existing engine-cost reader owns the per-frame difference. */
46
+ export function countDebug(
47
+ name: string,
48
+ value: number,
49
+ area: string,
50
+ caller: string,
51
+ unit = "count",
52
+ ): void {
53
+ if (!Number.isFinite(value) || value < 0)
54
+ throw new Error(`TN_DEBUG: invalid ${name} observation.`);
55
+ const host = globalThis as IDebugHost;
56
+ host.__tnEngineCost ??= {};
57
+ host.__tnDebugSources ??= {};
58
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + value;
59
+ host.__tnDebugSources[name] ??= { area, caller, unit };
60
+ }
61
+
62
+ /** Call only from an installed debug branch; preserves thrown errors and records their cost. */
63
+ export function measureDebug<T>(name: string, area: string, caller: string, run: () => T): T {
64
+ const start = performance.now();
65
+ try {
66
+ return run();
67
+ } finally {
68
+ countDebug(`${name}Ms`, performance.now() - start, area, caller, "ms");
69
+ countDebug(`${name}Calls`, 1, area, caller);
70
+ }
71
+ }
72
+
73
+ /** GC entries are optional platform observations, and the observer exists only during a debug game. */
74
+ export function observeDebugGc(): (() => void) | undefined {
75
+ if (!globalThis.PerformanceObserver?.supportedEntryTypes?.includes("gc")) return undefined;
76
+ const observer = new PerformanceObserver((list) => {
77
+ for (const entry of list.getEntries()) {
78
+ countDebug("gcPauses", 1, "memory", "PerformanceObserver.gc");
79
+ countDebug("gcPauseMs", entry.duration, "memory", "PerformanceObserver.gc", "ms");
80
+ }
81
+ });
82
+ observer.observe({ type: "gc" });
83
+ return () => observer.disconnect();
84
+ }
85
+
86
+ function sourceOf(name: string): IDebugSource {
87
+ const source = (globalThis as IDebugHost).__tnDebugSources?.[name];
88
+ if (source !== undefined)
89
+ return { ...source, unit: source.unit ?? (name.endsWith("Ms") ? "ms" : "count") };
90
+ const areas: readonly (readonly [RegExp, string])[] = [
91
+ [/bridge|children|wrapper|share|scratch|widen|overflow/iu, "bridge"],
92
+ [/velocity|temporal|history|rejected|clamped/iu, "temporal"],
93
+ [
94
+ /heap|memory|live|released|allocated|gc|CreatedBytes|FreedBytes|handleCreates|handleReleases/iu,
95
+ "memory",
96
+ ],
97
+ [/gpu|map|timestamp|gate|submit|completion/iu, "gpu"],
98
+ [/matrix|travers|transform|hierarchy|walk/iu, "scene"],
99
+ ];
100
+ const area = areas.find(([pattern]) => pattern.test(name))?.[1] ?? "renderer";
101
+ const nativeCallers: readonly (readonly [RegExp, string])[] = [
102
+ [/^gate/u, "renderer/frame_gate.h:FrameGate::decline"],
103
+ [/^(pipeline|bindGroups)/u, "renderer/pipeline_cache.cpp"],
104
+ [/^(buffer|texture|queue|readback)/u, "renderer/gpu_resources.cpp"],
105
+ [/^handle/u, "foundation/handles.cpp"],
106
+ [
107
+ /^(velocity|temporal|timestamp|gpuTimestamp|render|shadow|aux|uniform|attribute)/u,
108
+ "renderer/renderer.cpp",
109
+ ],
110
+ [/^cull/u, "scene/projected_cull.cpp"],
111
+ [/scene|matrix|hierarchy/iu, "scene/object3d.cpp"],
112
+ ];
113
+ const site = nativeCallers.find(([pattern]) => pattern.test(name))?.[1];
114
+ const async = /queueCallback|queueDelivery/iu.test(name);
115
+ return {
116
+ area,
117
+ caller: /^gc/u.test(name)
118
+ ? `packages/runtime-native/src/adapters/v8/adapter.cpp (${name})`
119
+ : site === undefined
120
+ ? `engine counter: ${name}`
121
+ : `packages/runtime-native/src/engine/${site} (${name})`,
122
+ unit: async ? "async-ms" : name.endsWith("Ms") ? "ms" : "count",
123
+ };
124
+ }
125
+
126
+ function leverOf(area: string): string | undefined {
127
+ const anchor: Record<string, string> = {
128
+ bridge:
129
+ "2026-10-27--web-engine-bridge-keep-what-game-code-reads-again-three-native-back-end--keep",
130
+ renderer:
131
+ "2026-10-27--wasted-work-on-the-shooter-counted-by-class--diagnostic-2-of-6-classes-have-a-fix-in-another-lane",
132
+ scene:
133
+ "2026-10-27--a-scratch-objects-death-leaves-the-hierarchy-counter-alone-native-engine--keep",
134
+ ui: "2026-10-14--publishuistate-serializes-a-changed-hud-frame-once-instead-of-three-times--keep",
135
+ update:
136
+ "2026-10-27--rapier-step-grew-from-21-to-34-66-ms-a-frame-in-profiler-round-2--not-a-cause-host-load",
137
+ host: "method-lessons",
138
+ };
139
+ return anchor[area] === undefined ? undefined : `PERFORMANCE-LEARNINGS.md#${anchor[area]}`;
140
+ }
141
+
142
+ /** One report from the budget's own completed window; counts remain counts, including unknown cost. */
143
+ export function formatDebugReport(window: IFrameBudgetWindow): string {
144
+ const interval =
145
+ window.presented.samples > 0 && window.presented.mean > 0 ? window.presented.mean : undefined;
146
+ const engine = window.counters?.engine ?? {};
147
+ const durationMs = window.durationMs;
148
+ const observations = Object.fromEntries(
149
+ Object.entries(engine).map(([name, series]) => {
150
+ if (!Number.isFinite(series.mean) || series.mean < 0)
151
+ throw new Error(`TN_DEBUG: invalid ${name} series.`);
152
+ const source = sourceOf(name);
153
+ const rate = source.unit === "count" || source.unit?.endsWith("bytes");
154
+ return [
155
+ name,
156
+ {
157
+ ...series,
158
+ ...source,
159
+ ...(rate
160
+ ? {
161
+ perSecond:
162
+ durationMs !== undefined && durationMs > 0 && series.samples === window.frames
163
+ ? (series.mean * series.samples * 1000) / durationMs
164
+ : null,
165
+ }
166
+ : {}),
167
+ },
168
+ ];
169
+ }),
170
+ );
171
+ const offenders: Array<{
172
+ name: string;
173
+ area: string;
174
+ caller: string;
175
+ ms: number;
176
+ share: number | null;
177
+ basis: string;
178
+ lever?: string;
179
+ }> = [];
180
+ const add = (name: string, ms: number, source: IDebugSource, basis: string): void => {
181
+ if (ms <= 0) return;
182
+ const lever = source.lever ?? leverOf(source.area);
183
+ offenders.push({
184
+ name,
185
+ ms,
186
+ area: source.area,
187
+ caller: source.caller,
188
+ share: interval === undefined ? null : ms / interval,
189
+ basis,
190
+ ...(lever === undefined ? {} : { lever }),
191
+ });
192
+ };
193
+ for (const [name, series] of Object.entries(engine)) {
194
+ const source = sourceOf(name);
195
+ if (source.unit === "ms" || source.unit === "estimated-ms")
196
+ add(
197
+ name,
198
+ series.mean,
199
+ source,
200
+ source.unit === "estimated-ms" ? "estimated-getter-equivalent" : "measured",
201
+ );
202
+ }
203
+ for (const [name, series] of Object.entries(window.phases))
204
+ add(
205
+ `phase.${name}`,
206
+ series.mean,
207
+ { area: name === "hostGap" ? "host" : name, caller: "FixedStepLoop", unit: "ms" },
208
+ "measured-parent",
209
+ );
210
+ for (const [name, ms] of [
211
+ ["main", window.gpuMain],
212
+ ["shadow", window.gpuShadow],
213
+ ["other", window.gpuOther],
214
+ ["compute", window.gpuCompute],
215
+ ] as const)
216
+ if (ms !== undefined)
217
+ add(
218
+ `gpu.${name}`,
219
+ ms,
220
+ { area: "gpu", caller: "GPU timestamp query", unit: "ms" },
221
+ "gpu-execution",
222
+ );
223
+ // Async wall times are observations. They overlap the frame and are not CPU work.
224
+ offenders.sort((a, b) => (b.share ?? -1) - (a.share ?? -1) || a.name.localeCompare(b.name));
225
+ const findings: Array<{
226
+ code: string;
227
+ ratio?: number;
228
+ perFrame?: number;
229
+ share: number | null;
230
+ caller: string;
231
+ lever?: string;
232
+ }> = [];
233
+ const total = (name: string): number | undefined => {
234
+ const series = engine[name];
235
+ return series === undefined ? undefined : series.mean * series.samples;
236
+ };
237
+ const ratio = (code: string, numerator: string, denominator: string, limit: number): void => {
238
+ const n = total(numerator);
239
+ const d = total(denominator);
240
+ if (n === undefined || d === undefined || d <= 0 || n / d <= limit) return;
241
+ const source = sourceOf(numerator);
242
+ const timing = engine[`${numerator}Ms`];
243
+ const lever = source.lever ?? leverOf(source.area);
244
+ findings.push({
245
+ code,
246
+ ratio: n / d,
247
+ share: timing === undefined || interval === undefined ? null : timing.mean / interval,
248
+ caller: source.caller,
249
+ ...(lever === undefined ? {} : { lever }),
250
+ });
251
+ };
252
+ ratio("temporal-missing-velocity", "velocitySkipped", "velocityCandidates", 0);
253
+ ratio("temporal-history-unavailable", "temporalInvalidFrames", "temporalActiveFrames", 0);
254
+ const activity = (code: string, counter: string): void => {
255
+ const value = engine[counter]?.mean;
256
+ if (value === undefined || value <= 0) return;
257
+ const source = sourceOf(counter);
258
+ const lever = source.lever ?? leverOf(source.area);
259
+ findings.push({
260
+ code,
261
+ perFrame: value,
262
+ share: null,
263
+ caller: source.caller,
264
+ ...(lever === undefined ? {} : { lever }),
265
+ });
266
+ };
267
+ activity("timestamp-oversampling", "gpuTimestampUnrequestedSamples");
268
+ activity("bridge-arena-overflow", "bridgeOverflowAllocations");
269
+ activity("gate-capacity-decline", "gateDeclinedCapacity");
270
+ activity("gate-completion-age-decline", "gateDeclinedAge");
271
+ ratio("bridge-typed-array-widening", "bridgeTypedEncodedBytes", "bridgeTypedSourceBytes", 1);
272
+ // Memory/population changes are observations until measured cost or a lifetime invariant fails.
273
+ // One name per asset URL and per bridged property cannot be a series, so the run's own totals are
274
+ // ranked here: a slow decode or a hot crossing is named without a per-frame map growing with them.
275
+ const host = globalThis as IDebugHost;
276
+ const contentScaled = Object.entries({ ...host.__tnEngineCounters?.(), ...host.__tnEngineCost })
277
+ .filter(([name, total]) => {
278
+ if (!isContentScaled(name)) return false;
279
+ if (!Number.isFinite(total) || total < 0)
280
+ throw new Error(`TN_DEBUG: invalid ${name} counter.`);
281
+ return total > 0;
282
+ })
283
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
284
+ .slice(0, CONTENT_SCALED_LIMIT)
285
+ .map(([name, total]) => ({ name, total, ...sourceOf(name) }));
286
+ return `TN_DEBUG_REPORT:${JSON.stringify({ window: window.window, frames: window.frames, durationMs: durationMs ?? null, intervalMs: interval ?? null, offenders, findings, observations, contentScaled: { basis: "run-total", top: contentScaled }, longTasks: window.longTasks, gpu: window.gpu, passes: window.passes })}`;
287
+ }
288
+
289
+ /** A single slow named callback exceeds the interval the loop actually observed. Debug-only. */
290
+ export function debugHotCalls(window: IFrameBudgetWindow): string | undefined {
291
+ const interval = window.presented.mean;
292
+ if (!(interval > 0)) return undefined;
293
+ const calls = Object.entries(window.counters?.engine ?? {})
294
+ .flatMap(([name, series]) => {
295
+ const source = sourceOf(name);
296
+ return source.area === "update" && source.unit === "ms" && series.p95 > interval
297
+ ? [
298
+ {
299
+ name,
300
+ caller: source.caller,
301
+ ms: series.p95,
302
+ share: series.p95 / interval,
303
+ lever: source.lever ?? leverOf(source.area),
304
+ },
305
+ ]
306
+ : [];
307
+ })
308
+ .sort((a, b) => b.share - a.share);
309
+ return calls.length === 0
310
+ ? undefined
311
+ : `TN_HOT_CALL:${JSON.stringify({ window: window.window, intervalMs: interval, calls })}`;
312
+ }
@@ -10,8 +10,9 @@
10
10
  * **The rule is derived, never a constant an author is told to revisit.** It fires when
11
11
  *
12
12
  * - the GPU used less than a third of the frame — the device is not the constraint, and
13
- * - the JS render phase alone is longer than the display's own period — so the scene cannot make
14
- * the display's rate even if everything else in the frame were free.
13
+ * - the JS render phase alone, in the typical (median) frame, is longer than the display's own
14
+ * period — so the scene cannot make the display's rate even if everything else in the frame
15
+ * were free.
15
16
  *
16
17
  * Both numbers come from the frame meter. The display's period comes from the host's own
17
18
  * presentation cap where there is one, and otherwise from the frame rate the game itself declared;
@@ -56,7 +57,7 @@ export interface ISceneWarning {
56
57
  readonly window: number;
57
58
  /** The GPU's share of the frame, as a fraction. */
58
59
  readonly gpuShare: number;
59
- /** The JS render phase's mean, in milliseconds. */
60
+ /** The JS render phase's median, in milliseconds. */
60
61
  readonly renderMs: number;
61
62
  /** The period the display works at, in milliseconds, and where that number came from. */
62
63
  readonly displayPeriodMs: number;
@@ -103,13 +104,17 @@ export function displayPeriodMs(
103
104
  * Fails closed in both directions: a window whose GPU was never measured gets no verdict, because
104
105
  * "the GPU is idle" is a claim and an absent reading is not evidence for it; and a window with no
105
106
  * shape to report gets none either, because a warning that cannot say what to change is noise.
107
+ * A software adapter gets none: its rasteriser runs inside the CPU's submit, so the render phase
108
+ * carries the GPU's work and "the GPU is idle" is false (a 3-draw UI frame read 54 ms on
109
+ * `Microsoft Basic Render Driver`).
106
110
  */
107
111
  export function sceneWarning(
108
112
  window: IFrameBudgetWindow,
109
113
  shape: ISceneShape | undefined,
110
114
  declaredTargetFps: number | undefined,
115
+ gpuClass?: string,
111
116
  ): ISceneWarning | undefined {
112
- if (shape === undefined) return undefined;
117
+ if (shape === undefined || gpuClass === "software") return undefined;
113
118
  const gpuMs = window.gpu?.mean;
114
119
  const frameMs = window.presented.mean;
115
120
  if (gpuMs === undefined || !(frameMs > 0)) return undefined;
@@ -117,7 +122,10 @@ export function sceneWarning(
117
122
  if (gpuShare >= GPU_IDLE_SHARE) return undefined;
118
123
  const period = displayPeriodMs(declaredTargetFps);
119
124
  if (period === undefined) return undefined;
120
- const renderMs = window.phases.render.mean;
125
+ // The median, not the mean: this verdict is about the scene's shape, which every frame pays. A
126
+ // single first-use compile in a short window lifts the mean past the period and says nothing about
127
+ // the scene (TN_FRAME_HITCH and the frame bounds report that stall).
128
+ const renderMs = window.phases.render.p50;
121
129
  if (renderMs <= period.ms) return undefined;
122
130
 
123
131
  // The terms are the things the CPU describes once per frame. They are counts, not milliseconds,
@@ -178,10 +186,38 @@ export function describeSceneShape(
178
186
  };
179
187
  }
180
188
 
189
+ /**
190
+ * The count a dominant term names, in that term's own unit, or `undefined` for a term this build
191
+ * does not measure. The ranking compares these same terms, so a missing pass reads zero here too;
192
+ * an unknown term is refused rather than answered with a number measured for something else.
193
+ */
194
+ function dominantCount(warning: ISceneWarning): { count: number; unit: string } | undefined {
195
+ switch (warning.dominantTerm) {
196
+ case "objectsConsidered":
197
+ return { count: warning.shape.objectsConsidered, unit: "objects" };
198
+ case "mainDraws":
199
+ return { count: warning.shape.draws.main ?? 0, unit: "draws" };
200
+ case "shadowDraws":
201
+ return { count: warning.shape.draws.shadow ?? 0, unit: "draws" };
202
+ case "reflectionDraws":
203
+ return { count: warning.shape.draws.reflection ?? 0, unit: "draws" };
204
+ default:
205
+ return undefined;
206
+ }
207
+ }
208
+
181
209
  /** The one-line summary a reader sees without opening a log viewer. */
182
210
  export function describeSceneWarning(warning: ISceneWarning): string {
183
211
  const gpuPercent = Math.round(warning.gpuShare * 100);
184
- return `the GPU used ${gpuPercent}% of the frame while the render phase took ${warning.renderMs} ms against a ${warning.displayPeriodMs} ms display period; ${warning.dominantTerm} is the largest term at ${warning.shape.trianglesPerDraw} triangles per draw`;
212
+ const dominant = dominantCount(warning);
213
+ // The dominant term is compared as a count, so it is printed as one: the triangles per draw
214
+ // beside it describe a different quantity and reading it as the object count overstates a scene
215
+ // by a factor of thirty.
216
+ const largest =
217
+ dominant === undefined
218
+ ? `${warning.dominantTerm} is the largest count: count unavailable`
219
+ : `${warning.dominantTerm} is the largest count: ${dominant.count} ${dominant.unit}`;
220
+ return `the GPU used ${gpuPercent}% of the frame while the render phase took ${warning.renderMs} ms against a ${warning.displayPeriodMs} ms display period; ${largest}; ${warning.shape.trianglesPerDraw} triangles per draw across passes`;
185
221
  }
186
222
 
187
223
  /** The marker line. */
@@ -32,6 +32,7 @@ import type {
32
32
  } from "./projection-plan.js";
33
33
  import { SkinnedBatch, isSimilarityTransform } from "./projection-skinned.js";
34
34
  import { baseColorOf, uniformUnchanged } from "./projection-uniform.js";
35
+ import { observeAnimationRates } from "./render-camera-cull.js";
35
36
  import {
36
37
  disposeBatchedMeshVelocity,
37
38
  ensureBatchedMeshVelocity,
@@ -114,7 +115,8 @@ const MATERIAL_CHECKS_PER_FRAME = 512;
114
115
  interface IBatch {
115
116
  readonly mesh: InstancedMesh;
116
117
  readonly group: IProjectionBatchGroup;
117
- readonly geometry: BufferGeometry;
118
+ /** The group's geometry: one member's, drawn for every member whose geometry has equal bytes. */
119
+ geometry: BufferGeometry;
118
120
  readonly material: Material;
119
121
  /**
120
122
  * True when the members' materials differ only in base colour: `material` is then a clone this
@@ -1077,6 +1079,11 @@ export class ProjectionMirror {
1077
1079
  */
1078
1080
  #ensureBatch(group: IProjectionBatchGroup): IBatch | undefined {
1079
1081
  const existing = this.#batches.get(group);
1082
+ // The member it drew from left the group or the scene; any member that stayed draws the same bytes.
1083
+ if (existing !== undefined && existing.geometry !== group.geometry) {
1084
+ existing.geometry = group.geometry;
1085
+ existing.mesh.geometry = group.geometry;
1086
+ }
1080
1087
  if (existing !== undefined && existing.capacity >= group.memberCount) return existing;
1081
1088
  const capacity = Math.max(BATCH_MIN_SLOTS, Math.ceil(group.memberCount * BATCH_GROWTH));
1082
1089
  const first = group.members[0] as Mesh;
@@ -1097,7 +1104,7 @@ export class ProjectionMirror {
1097
1104
  : (first.material as Material);
1098
1105
  let mesh: InstancedMesh;
1099
1106
  try {
1100
- mesh = new InstancedMesh(first.geometry, material, capacity);
1107
+ mesh = new InstancedMesh(group.geometry, material, capacity);
1101
1108
  } catch {
1102
1109
  return undefined;
1103
1110
  }
@@ -1121,7 +1128,7 @@ export class ProjectionMirror {
1121
1128
  const batch: IBatch = {
1122
1129
  mesh,
1123
1130
  group,
1124
- geometry: first.geometry,
1131
+ geometry: group.geometry,
1125
1132
  material,
1126
1133
  uniform,
1127
1134
  instances: new Map(),
@@ -1335,6 +1342,7 @@ export class ProjectionMirror {
1335
1342
  proxy.matrixAutoUpdate = false;
1336
1343
  this.#proxies.set(object, proxy);
1337
1344
  fresh = true;
1345
+ observeAnimationRates(proxy, new Map([[object, 0]]));
1338
1346
  // An `LOD` picks one of its levels by distance every frame, and it does that on itself. Its
1339
1347
  // levels therefore have to hang off the stand-in, or nothing selects one and the mirror
1340
1348
  // draws whichever rung happened to be visible when it was built.