@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.
Files changed (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,548 @@
1
+ /**
2
+ * Nested cost spans across the render phase, default-off.
3
+ *
4
+ * The frame budget names six phases and one of them — `render` — is 16.1 ms of a 20.2 ms frame
5
+ * while every engine-owned thing inside it sums to under 1.5 ms. A phase that big with nothing
6
+ * inside it is not a measurement, it is a question, and four ranked optimisation options were
7
+ * priced against four different answers to it. This is the instrument that answers it: a span tree
8
+ * whose leaves are the parts of the render phase, with the leftover computed rather than assumed.
9
+ *
10
+ * Three properties make it trustworthy enough to price work against:
11
+ *
12
+ * - **The residual is arithmetic, not a category.** Every non-leaf reports its own duration minus
13
+ * the durations of the spans it contains, so an unmeasured part shows up as a number instead of
14
+ * being quietly filed under "other". A child that outlives its parent reports a negative
15
+ * residual rather than being clamped to zero, because a negative residual means the nesting is
16
+ * wrong and a clamped one means nothing at all.
17
+ * - **It is default-off and costs one guarded return when off.** `TN_FRAME_SPANS=1` installs it;
18
+ * unset, every call site is `if (recorder === undefined) return;` with no clock read.
19
+ * - **Nothing here decides anything.** It measures the path that exists. It does not select a
20
+ * renderer, a traversal strategy or a pass order, and no number it produces is evidence for
21
+ * owning the renderer.
22
+ *
23
+ * The ids are integers on the hot path — a span call must not allocate a string to be cheap enough
24
+ * to put around a per-draw call — and the names exist only in the report.
25
+ */
26
+
27
+ /** Marker printed once per report window when spans are installed. */
28
+ export const SPANS_MARKER = "TN_FRAME_SPANS";
29
+
30
+ /**
31
+ * The launch flag that installs the spans. Off by default: this is a diagnostic that adds work to
32
+ * the frame it measures, so a game must ask for it.
33
+ */
34
+ export const SPANS_FLAG = "TN_FRAME_SPANS";
35
+
36
+ /**
37
+ * Every span, in the order the report prints them. Integers, because `beginSpan` runs per draw.
38
+ *
39
+ * `pass` and its nested kinds are one id per render call three makes, not one per camera: three
40
+ * renders the main camera first and the shadow and reflection cameras from inside that call, so
41
+ * the nesting is the renderer's own and a flat list of passes would have to invent a relationship
42
+ * the measurement already has.
43
+ */
44
+ export const SPANS = {
45
+ /** Compute-driven render work dispatched by the engine before the world render. */
46
+ compute: 0,
47
+ /** The engine's own `beforeRender` seam, where a game prepares the scene it is about to draw. */
48
+ beforeRender: 1,
49
+ /** The scene-graph matrix walk. */
50
+ sceneUpdate: 2,
51
+ /** The projection's reconcile, when one is installed. */
52
+ reconcile: 3,
53
+ /** Virtual-geometry clustered mesh update. */
54
+ clustered: 4,
55
+ /** Automatic discrete LOD selection. */
56
+ lod: 5,
57
+ /** The projected-size cull, apply and restore together. */
58
+ cull: 6,
59
+ /** The main camera's render call. */
60
+ mainPass: 7,
61
+ /** A nested render call three names as a shadow map. */
62
+ shadowPass: 8,
63
+ /** A nested render call three names as a reflector. */
64
+ reflectionPass: 9,
65
+ /** Any other nested render call. */
66
+ nestedPass: 10,
67
+ /** Render-list construction inside a render call. */
68
+ projectObject: 11,
69
+ /** Render-list sort inside a render call. */
70
+ sort: 12,
71
+ /** Per-draw submission inside a render call, accumulated across the draws of one pass. */
72
+ draw: 13,
73
+ /** Terrain block rebuild and merged-attribute swap on the calling thread. */
74
+ terrainBlock: 14,
75
+ /** Terrain seam reconciliation and bridge-attribute swap on the calling thread. */
76
+ terrainSeam: 15,
77
+ } as const;
78
+
79
+ export type SpanId = (typeof SPANS)[keyof typeof SPANS];
80
+
81
+ /**
82
+ * Native game-JS spans use the player's monotonic clock, independent of the simulation clock. They
83
+ * follow {@link SPANS} in one id space (`__tnGameSpan` takes either), so a new render span moves
84
+ * every id here; the engine player's name table (`run.cpp` `kGameSpanNames`) is pinned to these
85
+ * numbers by `native-engine-game-spans.spec.ts`. `hostUpdate`, `hostFrame`, `gc` and `view` are
86
+ * opened by the host itself and have no id here.
87
+ */
88
+ 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,
114
+ } as const;
115
+
116
+ /** Names, indexed by id. The only place a span name is a string. */
117
+ export const SPAN_NAMES: readonly string[] = [
118
+ "compute",
119
+ "beforeRender",
120
+ "sceneUpdate",
121
+ "reconcile",
122
+ "clustered",
123
+ "lod",
124
+ "cull",
125
+ "mainPass",
126
+ "shadowPass",
127
+ "reflectionPass",
128
+ "nestedPass",
129
+ "projectObject",
130
+ "sort",
131
+ "draw",
132
+ "terrainBlock",
133
+ "terrainSeam",
134
+ ];
135
+
136
+ export const SPAN_COUNT = SPAN_NAMES.length;
137
+
138
+ /** Deepest nesting the recorder accepts. Exceeding it is reported, never silently dropped. */
139
+ const MAX_DEPTH = 64;
140
+
141
+ /** Per-frame samples kept for the window percentiles. Matches the frame budget's own ring. */
142
+ const DEFAULT_CAPACITY = 1_024;
143
+
144
+ /** One span's cost across a reported window. */
145
+ export interface ISpanSummary {
146
+ /** Frames in the window that entered this span at least once. */
147
+ readonly frames: number;
148
+ /** Entries per frame, mean over the frames that entered it. */
149
+ readonly perFrame: number;
150
+ readonly mean: number;
151
+ readonly p50: number;
152
+ readonly p95: number;
153
+ readonly max: number;
154
+ /**
155
+ * This span's own time minus the time of the spans inside it, at p50.
156
+ *
157
+ * Negative when a child outlived its parent, which means the nesting is wrong. Never clamped: a
158
+ * clamped residual reads as a complete attribution, and this is the number that says whether the
159
+ * attribution is complete.
160
+ */
161
+ readonly residualP50: number;
162
+ }
163
+
164
+ /**
165
+ * One reported window of the span tree.
166
+ *
167
+ * `residual` is the render phase's own cost with every top-level span subtracted — the number this
168
+ * instrument exists to shrink. `coverage` is its complement as a fraction of the phase, and a
169
+ * reader that sees 0.68 is being told that a third of the phase is still unmeasured.
170
+ */
171
+ export interface ISpanWindow {
172
+ readonly window: number;
173
+ readonly frames: number;
174
+ /** The render phase as the frame budget charged it, at p50. */
175
+ readonly renderMs: number;
176
+ readonly residualMs: number;
177
+ readonly coverage: number;
178
+ /** Frames whose span nesting exceeded `MAX_DEPTH`, whose residual is therefore incomplete. */
179
+ readonly overflowed: number;
180
+ readonly spans: Readonly<Record<string, ISpanSummary>>;
181
+ }
182
+
183
+ function round(value: number): number {
184
+ return Math.round(value * 100) / 100;
185
+ }
186
+
187
+ /** A fixed-capacity ring of samples. Never allocates after construction. */
188
+ class Ring {
189
+ readonly #buffer: Float64Array;
190
+ #count = 0;
191
+ #cursor = 0;
192
+
193
+ constructor(capacity: number) {
194
+ this.#buffer = new Float64Array(capacity);
195
+ }
196
+
197
+ push(value: number): void {
198
+ const capacity = this.#buffer.length;
199
+ this.#buffer[this.#cursor % capacity] = value;
200
+ this.#cursor += 1;
201
+ if (this.#count < capacity) this.#count += 1;
202
+ }
203
+
204
+ reset(): void {
205
+ this.#count = 0;
206
+ this.#cursor = 0;
207
+ }
208
+
209
+ get count(): number {
210
+ return this.#count;
211
+ }
212
+
213
+ summarize(scratch: Float64Array): { mean: number; p50: number; p95: number; max: number } {
214
+ const count = this.#count;
215
+ if (count === 0) return { max: 0, mean: 0, p50: 0, p95: 0 };
216
+ let total = 0;
217
+ for (let index = 0; index < count; index += 1) {
218
+ const value = this.#buffer[index] ?? 0;
219
+ scratch[index] = value;
220
+ total += value;
221
+ }
222
+ const view = scratch.subarray(0, count);
223
+ view.sort();
224
+ const rank = (fraction: number): number =>
225
+ round(view[Math.min(count - 1, Math.ceil(fraction * count) - 1)] ?? 0);
226
+ return {
227
+ max: round(view[count - 1] ?? 0),
228
+ mean: round(total / count),
229
+ p50: rank(0.5),
230
+ p95: rank(0.95),
231
+ };
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Accumulates a nested span tree, one frame at a time, and reports it windowed.
237
+ *
238
+ * The owner brackets a frame with `beginFrame` and `endFrame`; the render phase's own duration is
239
+ * handed in at the close rather than measured here, so the root residual is arithmetic against the
240
+ * number the frame budget already reports and cannot drift from it.
241
+ *
242
+ * Nesting is strict: `end(id)` must name the span `begin(id)` opened. A mismatch throws, because a
243
+ * tree whose parentage is wrong produces a residual that is confidently wrong, and that is worse
244
+ * than a loud failure in a mode a game opted into.
245
+ */
246
+ export class SpanRecorder {
247
+ readonly capacity: number;
248
+ readonly #stackId = new Int32Array(MAX_DEPTH);
249
+ readonly #stackStart = new Float64Array(MAX_DEPTH);
250
+ readonly #own = new Float64Array(SPAN_COUNT);
251
+ readonly #child = new Float64Array(SPAN_COUNT);
252
+ readonly #entries = new Uint32Array(SPAN_COUNT);
253
+ readonly #entryTotals = new Float64Array(SPAN_COUNT);
254
+ readonly #ownSeries: Ring[] = [];
255
+ readonly #residualSeries: Ring[] = [];
256
+ readonly #renderSeries: Ring;
257
+ readonly #topLevelSeries: Ring;
258
+ readonly #scratch = new Float64Array(DEFAULT_CAPACITY);
259
+ #depth = 0;
260
+ #topLevelMs = 0;
261
+ #frames = 0;
262
+ #overflowed = 0;
263
+ #window = 0;
264
+
265
+ constructor(capacity: number = DEFAULT_CAPACITY) {
266
+ if (!Number.isInteger(capacity) || capacity < 1)
267
+ throw new Error(
268
+ `Span recorder capacity must be an integer of at least one, got ${String(capacity)}.`,
269
+ );
270
+ this.capacity = capacity;
271
+ for (let id = 0; id < SPAN_COUNT; id += 1) {
272
+ this.#ownSeries.push(new Ring(capacity));
273
+ this.#residualSeries.push(new Ring(capacity));
274
+ }
275
+ this.#renderSeries = new Ring(capacity);
276
+ this.#topLevelSeries = new Ring(capacity);
277
+ }
278
+
279
+ /** Opens a span. Returns false when the tree is already at `MAX_DEPTH` and the span is dropped. */
280
+ begin(id: SpanId, now: number): boolean {
281
+ if (this.#depth >= MAX_DEPTH) {
282
+ this.#overflowed += 1;
283
+ return false;
284
+ }
285
+ this.#stackId[this.#depth] = id;
286
+ this.#stackStart[this.#depth] = now;
287
+ this.#depth += 1;
288
+ this.#entries[id] = (this.#entries[id] ?? 0) + 1;
289
+ return true;
290
+ }
291
+
292
+ /** Closes the span `begin` opened. Throws when it names a different span. */
293
+ end(id: SpanId, now: number): void {
294
+ if (this.#depth === 0)
295
+ throw new Error(`Span ${SPAN_NAMES[id] ?? String(id)} ended with no span open.`);
296
+ const depth = this.#depth - 1;
297
+ const open = this.#stackId[depth] ?? -1;
298
+ if (open !== id)
299
+ throw new Error(
300
+ `Span ${SPAN_NAMES[id] ?? String(id)} ended while ${SPAN_NAMES[open] ?? String(open)} was open.`,
301
+ );
302
+ this.#depth = depth;
303
+ const ms = now - (this.#stackStart[depth] ?? now);
304
+ this.#own[id] = (this.#own[id] ?? 0) + ms;
305
+ this.#attribute(ms);
306
+ }
307
+
308
+ /**
309
+ * Adds `ms` to a span that is entered many times per frame — a per-draw call, or a call site that
310
+ * cannot be bracketed. Counts as one entry and attributes to the enclosing span exactly as a
311
+ * bracketed one would.
312
+ */
313
+ add(id: SpanId, ms: number): void {
314
+ this.#own[id] = (this.#own[id] ?? 0) + ms;
315
+ this.#entries[id] = (this.#entries[id] ?? 0) + 1;
316
+ this.#attribute(ms);
317
+ }
318
+
319
+ #attribute(ms: number): void {
320
+ if (this.#depth === 0) {
321
+ this.#topLevelMs += ms;
322
+ return;
323
+ }
324
+ const parent = this.#stackId[this.#depth - 1] ?? -1;
325
+ if (parent >= 0) this.#child[parent] = (this.#child[parent] ?? 0) + ms;
326
+ }
327
+
328
+ /** How many spans are currently open. Zero outside a frame's own work. */
329
+ get depth(): number {
330
+ return this.#depth;
331
+ }
332
+
333
+ /**
334
+ * Throws a half-open frame away without recording it.
335
+ *
336
+ * A frame that failed mid-render has a span stack that cannot be closed honestly, and recording
337
+ * it would put a fabricated zero in the window. The loop abandons it instead, so the window only
338
+ * ever reports frames whose spans all closed.
339
+ */
340
+ abandonFrame(): void {
341
+ this.#depth = 0;
342
+ for (let id = 0; id < SPAN_COUNT; id += 1) {
343
+ this.#own[id] = 0;
344
+ this.#child[id] = 0;
345
+ this.#entries[id] = 0;
346
+ }
347
+ this.#topLevelMs = 0;
348
+ }
349
+
350
+ /** Records the frame's totals against the render phase the frame budget charged. */
351
+ endFrame(renderPhaseMs: number): void {
352
+ if (this.#depth !== 0) {
353
+ const open = this.#stackId[this.#depth - 1] ?? -1;
354
+ this.#depth = 0;
355
+ throw new Error(
356
+ `Span ${SPAN_NAMES[open] ?? String(open)} was still open at the end of a frame.`,
357
+ );
358
+ }
359
+ if (!Number.isFinite(renderPhaseMs))
360
+ throw new Error(
361
+ `Span recorder received a non-finite render phase: ${String(renderPhaseMs)}.`,
362
+ );
363
+ for (let id = 0; id < SPAN_COUNT; id += 1) {
364
+ this.#ownSeries[id]?.push(this.#own[id] ?? 0);
365
+ this.#residualSeries[id]?.push((this.#own[id] ?? 0) - (this.#child[id] ?? 0));
366
+ this.#entryTotals[id] = (this.#entryTotals[id] ?? 0) + (this.#entries[id] ?? 0);
367
+ this.#own[id] = 0;
368
+ this.#child[id] = 0;
369
+ this.#entries[id] = 0;
370
+ }
371
+ this.#renderSeries.push(renderPhaseMs);
372
+ this.#topLevelSeries.push(this.#topLevelMs);
373
+ this.#topLevelMs = 0;
374
+ this.#frames += 1;
375
+ }
376
+
377
+ /** The window just closed, or `undefined` when no frame was recorded in it. */
378
+ window(): ISpanWindow | undefined {
379
+ const frames = this.#frames;
380
+ if (frames === 0) return undefined;
381
+ this.#window += 1;
382
+ const render = this.#renderSeries.summarize(this.#scratch);
383
+ // The spans that were open when nothing else was, at the same percentile as the phase itself.
384
+ // Summing every span instead would count each child twice — once inside its parent, once on its
385
+ // own — and report a residual that is too small by exactly the nesting depth.
386
+ const topLevel = this.#topLevelSeries.summarize(this.#scratch).p50;
387
+ const residualMs = round(render.p50 - topLevel);
388
+ const spans: Record<string, ISpanSummary> = {};
389
+ for (let id = 0; id < SPAN_COUNT; id += 1) {
390
+ const own = this.#ownSeries[id];
391
+ if (own === undefined || own.count === 0) continue;
392
+ const summary = own.summarize(this.#scratch);
393
+ const residual = this.#residualSeries[id]?.summarize(this.#scratch) ?? {
394
+ max: 0,
395
+ mean: 0,
396
+ p50: 0,
397
+ p95: 0,
398
+ };
399
+ const entries = this.#entryMean(id, frames);
400
+ // A span that was entered and cost almost nothing is a *measurement*, and dropping it
401
+ // because it rounds to zero is the same "absent means zero" confusion the rest of this file
402
+ // refuses. Measured on the reference game in a browser: the world render call costs about
403
+ // 0.07 ms there, and dropping it left a window with no `mainPass` row at all — which reads
404
+ // as "the render never happened" rather than "the render was cheap". Only a span nothing
405
+ // ever entered is omitted.
406
+ if (entries === 0) continue;
407
+ spans[SPAN_NAMES[id] ?? String(id)] = {
408
+ frames,
409
+ mean: summary.mean,
410
+ max: summary.max,
411
+ p50: summary.p50,
412
+ p95: summary.p95,
413
+ perFrame: entries,
414
+ residualP50: residual.p50,
415
+ };
416
+ }
417
+ const window: ISpanWindow = {
418
+ coverage: render.p50 > 0 ? round(1 - residualMs / render.p50) : 0,
419
+ frames,
420
+ overflowed: this.#overflowed,
421
+ renderMs: render.p50,
422
+ residualMs,
423
+ spans,
424
+ window: this.#window,
425
+ };
426
+ this.#resetWindow();
427
+ return window;
428
+ }
429
+
430
+ /** Mean entries per frame for one span, from the window's own totals. */
431
+ #entryMean(id: number, frames: number): number {
432
+ const total = this.#entryTotals[id] ?? 0;
433
+ return round(total / frames);
434
+ }
435
+
436
+ #resetWindow(): void {
437
+ for (let id = 0; id < SPAN_COUNT; id += 1) {
438
+ this.#ownSeries[id]?.reset();
439
+ this.#residualSeries[id]?.reset();
440
+ this.#entryTotals[id] = 0;
441
+ }
442
+ this.#renderSeries.reset();
443
+ this.#topLevelSeries.reset();
444
+ this.#frames = 0;
445
+ this.#overflowed = 0;
446
+ }
447
+ }
448
+
449
+ /**
450
+ * The installed recorder, or `undefined` when spans are off.
451
+ *
452
+ * `Symbol.for` on `globalThis` rather than module state, because core is built once per entry: a
453
+ * game that imports `@threenative/core/world` gets a second copy of this module, and a recorder
454
+ * installed by the main entry is invisible to it. The world's own spans (terrain block rebuild and
455
+ * seam swap) recorded nothing in a browser walk for exactly that reason — two copies, two states.
456
+ * The global symbol is one slot every copy reads, and a parameter would still put a recorder on the
457
+ * hot path for a diagnostic that is off in every shipped build.
458
+ */
459
+ const RECORDER_SLOT = Symbol.for("threenative.frameSpans.recorder");
460
+
461
+ type RecorderHost = { [key: symbol]: SpanRecorder | undefined };
462
+
463
+ function recorderHost(): RecorderHost {
464
+ // quality-allow: the recorder lives on globalThis under a private symbol, which no lib type names.
465
+ return globalThis as unknown as RecorderHost;
466
+ }
467
+
468
+ /** Installs or removes the recorder every `beginSpan`/`endSpan` routes to, in every entry copy. */
469
+ export function setSpanRecorder(next: SpanRecorder | undefined): void {
470
+ recorderHost()[RECORDER_SLOT] = next;
471
+ }
472
+
473
+ export function spanRecorder(): SpanRecorder | undefined {
474
+ return recorderHost()[RECORDER_SLOT];
475
+ }
476
+
477
+ /** The one clock the spans and the frame budget share, so their numbers are comparable. */
478
+ export function spanNow(): number {
479
+ return globalThis.performance?.now() ?? Date.now();
480
+ }
481
+
482
+ /** Player sink only; does not alter the render recorder. No clock read or allocation when off. */
483
+ export function nativeSpan(id: number, action: number): void {
484
+ (globalThis as { __tnGameSpan?: (id: number, action: number) => number }).__tnGameSpan?.(
485
+ id,
486
+ action,
487
+ );
488
+ }
489
+
490
+ /**
491
+ * Opens a span. One guarded return when spans are off — no clock read, no allocation, no branch on
492
+ * anything but the recorder's own presence. The opt-in native wall-time sink sees it first.
493
+ */
494
+ export function beginSpan(id: SpanId): void {
495
+ nativeSpan(id, 0);
496
+ const active = spanRecorder();
497
+ if (active === undefined) return;
498
+ active.begin(id, spanNow());
499
+ }
500
+
501
+ export function endSpan(id: SpanId): void {
502
+ nativeSpan(id, 1);
503
+ const active = spanRecorder();
504
+ if (active === undefined) return;
505
+ active.end(id, spanNow());
506
+ }
507
+
508
+ /** Adds an already-measured duration to a span entered many times per frame. */
509
+ export function addSpan(id: SpanId, ms: number): void {
510
+ const active = spanRecorder();
511
+ if (active === undefined) return;
512
+ active.add(id, ms);
513
+ }
514
+
515
+ /**
516
+ * Whether `TN_FRAME_SPANS` asks for spans on this launch.
517
+ *
518
+ * Three ways in, because the three launches have three different seams and none of them is
519
+ * `import.meta.env` (Vite replaces that at build time, and a measurement flag must be settable
520
+ * without rebuilding the game): a native host forwards `TN_FRAME_SPANS` through `process.env`, a
521
+ * browser page carries `?tnFrameSpans=1` in its URL, and any harness can set
522
+ * `globalThis.__tnFrameSpans` before the game boots.
523
+ */
524
+ export function spansRequested(): boolean {
525
+ const host = globalThis as {
526
+ process?: { env?: Record<string, unknown> };
527
+ __tnFrameSpans?: unknown;
528
+ };
529
+ const fromEnv = host.process?.env?.[SPANS_FLAG];
530
+ if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
531
+ return true;
532
+ const query = globalThis.location?.search;
533
+ if (typeof query === "string" && /[?&]tnFrameSpans=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
534
+ return true;
535
+ const fromGlobal = host.__tnFrameSpans;
536
+ return (
537
+ fromGlobal === true ||
538
+ (typeof fromGlobal === "string" &&
539
+ fromGlobal !== "" &&
540
+ fromGlobal !== "0" &&
541
+ fromGlobal !== "false")
542
+ );
543
+ }
544
+
545
+ /** The window as the marker line prints it. */
546
+ export function formatSpansWindow(window: ISpanWindow): string {
547
+ return `${SPANS_MARKER}:${JSON.stringify(window)}`;
548
+ }
@@ -0,0 +1,21 @@
1
+ import type { Object3D } from "three";
2
+ import { materialExamples, opacityIgnoredMaterials } from "./render-trap-audit.js";
3
+
4
+ /** Marker for the opacity convention turning transparency on for an authored opacity below 1. */
5
+ export const OPACITY_TRANSPARENT_MARKER = "TN_OPACITY_TRANSPARENT";
6
+
7
+ /**
8
+ * Convention: authored opacity takes effect. three draws a material with opacity < 1 opaque unless
9
+ * it is transparent or alpha-hashed, so this turns transparency on for each drawn one and returns
10
+ * the warning line that says so, or undefined when nothing changed. The opacity stays the game's.
11
+ * Override on the same material: `alphaHash: true`, or `opacity: 1` for an opaque surface.
12
+ */
13
+ export function applyOpacityConvention(scene: Object3D): string | undefined {
14
+ const materials = opacityIgnoredMaterials(scene);
15
+ if (materials.size === 0) return undefined;
16
+ for (const material of materials) {
17
+ material.transparent = true;
18
+ (material as { needsUpdate?: boolean }).needsUpdate = true;
19
+ }
20
+ return `${OPACITY_TRANSPARENT_MARKER}:${JSON.stringify({ materials: materials.size, examples: materialExamples(materials) })} opacity < 1 now draws transparent; set alphaHash: true or opacity: 1 on the material to override`;
21
+ }