@threenative/core 0.3.3 → 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.
Files changed (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -0,0 +1,1566 @@
1
+ /**
2
+ * A bounded observation of the pipelines a Three.js renderer actually asked the GPU device to make.
3
+ *
4
+ * This module deliberately knows the shape of Three's private render object, but not its cache-key
5
+ * algorithm. Three owns the identity; the collector only reads the object at the backend boundary
6
+ * where a cache miss becomes a real device creation. That keeps a material label from becoming a
7
+ * pipeline key and makes the same observation useful on browser WebGPU and the native binding.
8
+ *
9
+ * The backend boundary alone is not the whole device, and a census that claims otherwise is
10
+ * wrong by exactly the pipelines it cannot see: Three's texture pass utils build mipmap transfer
11
+ * pipelines straight on the device, which is why a Bayview native capture logged 94 device
12
+ * creations against 92 renderer events. So the device's own creation methods are observed too,
13
+ * with creations reached through the wrapped backend attributed to their backend event rather
14
+ * than counted twice, and a direct creation reported with the label the device was given, an
15
+ * explicitly unknown pass and unknown provenance rather than the render object that happened to
16
+ * be drawing when a texture uploaded.
17
+ */
18
+
19
+ import { CORE_VERSION } from "./version.js";
20
+
21
+ export const PIPELINE_CENSUS_VERSION = 1 as const;
22
+ export const PIPELINE_CENSUS_CAPABILITY = "runtime.pipelineCensus" as const;
23
+ export const DEFAULT_PIPELINE_CENSUS_LIMIT = 512;
24
+
25
+ export type PipelineCensusStatus = "created" | "failed" | "pending";
26
+ export type PipelineCensusMode = "sync" | "async";
27
+
28
+ export interface IPipelineShaderObservation {
29
+ readonly bytes: number;
30
+ readonly hash: string;
31
+ }
32
+
33
+ export interface IPipelineProvenance {
34
+ readonly material?: {
35
+ readonly id?: number;
36
+ readonly name?: string;
37
+ readonly type?: string;
38
+ };
39
+ readonly object?: {
40
+ readonly id?: number;
41
+ readonly name?: string;
42
+ readonly uuid?: string;
43
+ };
44
+ /** True when no stable material/object label was available at the creation boundary. */
45
+ readonly unknown: boolean;
46
+ }
47
+
48
+ export interface IPipelineCensusEvent {
49
+ /** Monotonic sequence, useful for detecting a dropped event in a merged native log. */
50
+ readonly sequence: number;
51
+ /** Three's program identity: the generated vertex/fragment source pair. */
52
+ readonly programIdentity: string;
53
+ /** Backend identity, separate from the program identity and from the material label. */
54
+ readonly pipelineIdentity: string;
55
+ readonly kind: "compute" | "render";
56
+ readonly pass: string;
57
+ readonly mode: PipelineCensusMode;
58
+ readonly status: PipelineCensusStatus;
59
+ readonly vertex?: IPipelineShaderObservation;
60
+ readonly fragment?: IPipelineShaderObservation;
61
+ readonly compute?: IPipelineShaderObservation;
62
+ readonly provenance: IPipelineProvenance;
63
+ /** The label the device was handed, when one was observed. A label is never read as a pass. */
64
+ readonly label?: string;
65
+ /** Structural inputs observed beside the generated shader, not a guessed reason. */
66
+ readonly reasons: readonly string[];
67
+ /** Host monotonic milliseconds relative to the capture origin. */
68
+ readonly startedMs: number;
69
+ readonly settledMs?: number;
70
+ /** Synchronous device-call wall time; absent for an async promise. */
71
+ readonly serviceMs?: number;
72
+ /** Promise latency is retained as latency, never labelled native compiler time. */
73
+ readonly promiseMs?: number;
74
+ readonly error?: string;
75
+ /** Number of distinct Three node-builder states first observed during this render-object call. */
76
+ readonly nodeBuilds?: number;
77
+ /** Whether this event settled before the first present boundary. */
78
+ readonly beforeFirstPresent?: boolean;
79
+ /** Whether this event settled before the explicit warm-up completion boundary. */
80
+ readonly beforeWarmUpSettled?: boolean;
81
+ /** The most recent streamed warm-up scope that preceded this event. */
82
+ readonly afterWarmUpScope?: string;
83
+ }
84
+
85
+ /** A node-builder state observed even when Three reused an existing GPU pipeline. */
86
+ export interface IPipelineNodeBuild {
87
+ readonly provenance: IPipelineProvenance;
88
+ readonly startedMs: number;
89
+ readonly beforeFirstPresent?: boolean;
90
+ readonly beforeWarmUpSettled?: boolean;
91
+ readonly afterWarmUpScope?: string;
92
+ }
93
+
94
+ export interface IPipelineCensusCounts {
95
+ readonly lookups: number;
96
+ readonly creations: number;
97
+ readonly failures: number;
98
+ readonly pending: number;
99
+ readonly uniquePrograms: number;
100
+ readonly uniquePipelines: number;
101
+ readonly recordedEvents: number;
102
+ readonly droppedEvents: number;
103
+ readonly nodeBuilds: number;
104
+ /**
105
+ * Every creation seen at the device, including those attributed to a backend event. Absent
106
+ * when the device could not be observed at all, so no reader mistakes silence for zero.
107
+ */
108
+ readonly deviceCreations?: number;
109
+ /** Creations seen only at the device, never reached through the wrapped backend methods. */
110
+ readonly directCreations?: number;
111
+ }
112
+
113
+ export interface IPipelineCensus {
114
+ readonly version: typeof PIPELINE_CENSUS_VERSION;
115
+ readonly complete: boolean;
116
+ readonly overflowed: boolean;
117
+ readonly unsupported: boolean;
118
+ readonly limit: number;
119
+ readonly clock: {
120
+ readonly originMs: number;
121
+ readonly source: "performance" | "date";
122
+ };
123
+ readonly build: {
124
+ readonly identity: string;
125
+ };
126
+ readonly adapter: {
127
+ readonly identity: string;
128
+ readonly thermal: string;
129
+ };
130
+ readonly backend: {
131
+ readonly kind: "webgpu" | "webgl2";
132
+ readonly identity: string;
133
+ };
134
+ readonly firstPresent?: {
135
+ readonly boundaryMs: number;
136
+ readonly eventsSettled: number;
137
+ };
138
+ readonly warmUpSettled?: {
139
+ readonly boundaryMs: number;
140
+ readonly eventsSettled: number;
141
+ readonly nodeBuilds: number;
142
+ readonly renderPipelineCreations: number;
143
+ };
144
+ readonly warmUpScopes?: readonly {
145
+ readonly label: string;
146
+ readonly boundaryMs: number;
147
+ readonly eventsSettled: number;
148
+ readonly nodeBuilds: number;
149
+ readonly renderPipelineCreations: number;
150
+ readonly firstDraw?: {
151
+ readonly nodeBuilds: number;
152
+ readonly renderPipelineCreations: number;
153
+ };
154
+ }[];
155
+ readonly counts: IPipelineCensusCounts;
156
+ readonly events: readonly IPipelineCensusEvent[];
157
+ readonly nodeBuilds?: readonly IPipelineNodeBuild[];
158
+ readonly incompleteReasons: readonly string[];
159
+ }
160
+
161
+ export interface IPipelineCensusOptions {
162
+ readonly adapterIdentity?: string;
163
+ readonly buildIdentity?: string;
164
+ readonly kind: "webgpu" | "webgl2";
165
+ readonly limit?: number;
166
+ readonly now?: () => number;
167
+ readonly backendIdentity?: string;
168
+ readonly thermalIdentity?: string;
169
+ }
170
+
171
+ interface IRenderObjectLike {
172
+ readonly object?: unknown;
173
+ readonly material?: unknown;
174
+ readonly pipeline?: unknown;
175
+ readonly context?: unknown;
176
+ readonly scene?: unknown;
177
+ readonly passId?: unknown;
178
+ }
179
+
180
+ interface IProgramLike {
181
+ readonly code?: unknown;
182
+ readonly id?: unknown;
183
+ readonly stage?: unknown;
184
+ }
185
+
186
+ interface IPipelineLike {
187
+ readonly cacheKey?: unknown;
188
+ readonly vertexProgram?: IProgramLike;
189
+ readonly fragmentProgram?: IProgramLike;
190
+ readonly computeProgram?: IProgramLike;
191
+ readonly isComputePipeline?: unknown;
192
+ }
193
+
194
+ interface IBackendLike {
195
+ createRenderPipeline?: (...args: unknown[]) => unknown;
196
+ createComputePipeline?: (...args: unknown[]) => unknown;
197
+ get?: (value: unknown) => unknown;
198
+ /** The GPU device the backend delegates to, absent until the backend has initialised. */
199
+ device?: unknown;
200
+ }
201
+
202
+ /** The device methods that turn a descriptor into a real GPU object. */
203
+ const DEVICE_PIPELINE_METHODS = [
204
+ ["createRenderPipeline", "render", "sync"],
205
+ ["createRenderPipelineAsync", "render", "async"],
206
+ ["createComputePipeline", "compute", "sync"],
207
+ ["createComputePipelineAsync", "compute", "async"],
208
+ ] as const satisfies readonly (readonly [string, "compute" | "render", PipelineCensusMode])[];
209
+
210
+ interface IInstalledDevice {
211
+ readonly backend: IBackendLike;
212
+ readonly device: Record<string, unknown>;
213
+ readonly restore: readonly (() => void)[];
214
+ }
215
+
216
+ interface IActiveRenderObject {
217
+ readonly clippingContext: unknown;
218
+ readonly object: unknown;
219
+ readonly material: unknown;
220
+ readonly scene: unknown;
221
+ readonly passId: unknown;
222
+ nodeBuilds: number;
223
+ }
224
+
225
+ interface IMutableCensusEvent {
226
+ sequence: number;
227
+ programIdentity: string;
228
+ pipelineIdentity: string;
229
+ kind: "compute" | "render";
230
+ pass: string;
231
+ mode: PipelineCensusMode;
232
+ status: PipelineCensusStatus;
233
+ vertex?: IPipelineShaderObservation;
234
+ fragment?: IPipelineShaderObservation;
235
+ /** Whether the render descriptor carried a fragment stage, even when it was not observed. */
236
+ fragmentStagePresent?: boolean;
237
+ compute?: IPipelineShaderObservation;
238
+ provenance: IPipelineProvenance;
239
+ label?: string;
240
+ reasons: readonly string[];
241
+ startedMs: number;
242
+ settledMs?: number;
243
+ serviceMs?: number;
244
+ promiseMs?: number;
245
+ error?: string;
246
+ nodeBuilds?: number;
247
+ beforeFirstPresent?: boolean;
248
+ beforeWarmUpSettled?: boolean;
249
+ afterWarmUpScope?: string;
250
+ /** Three's logical pipeline object, retained privately for backend data lookup. */
251
+ backendPipeline?: unknown;
252
+ /** Observed at the device rather than through a backend method, so it carries its own handle. */
253
+ direct?: boolean;
254
+ deviceHandle?: unknown;
255
+ /** Whether this event still owns one of the pending counts, so settling releases exactly one. */
256
+ pending?: boolean;
257
+ }
258
+
259
+ interface IInstalledBackend {
260
+ readonly backend: IBackendLike;
261
+ render?: (...args: unknown[]) => unknown;
262
+ renderWrapper?: (...args: unknown[]) => unknown;
263
+ compute?: (...args: unknown[]) => unknown;
264
+ computeWrapper?: (...args: unknown[]) => unknown;
265
+ }
266
+
267
+ interface IRendererHookTarget {
268
+ backend?: unknown;
269
+ /** Three's renderer-owned node manager; absent on the WebGL2 renderer. */
270
+ _nodes?: unknown;
271
+ renderObject?: (...args: unknown[]) => unknown;
272
+ }
273
+
274
+ interface INodeBuilderObservation {
275
+ readonly state: object;
276
+ builds: number;
277
+ reported: boolean;
278
+ }
279
+
280
+ interface IMutableWarmUpScope {
281
+ label: string;
282
+ boundaryMs: number;
283
+ eventsSettled: number;
284
+ nodeBuilds: number;
285
+ renderPipelineCreations: number;
286
+ firstDraw?: {
287
+ nodeBuilds: number;
288
+ renderPipelineCreations: number;
289
+ };
290
+ frameObserved: boolean;
291
+ frameNodeBuilds: number;
292
+ frameRenderPipelineCreations: number;
293
+ }
294
+
295
+ /**
296
+ * Create and install a bounded census. The returned object is intentionally small: renderers own
297
+ * lifecycle and callers only need `snapshot()`, `withRenderObject()`, and the two lifecycle
298
+ * boundaries.
299
+ */
300
+ export function createPipelineCensus(options: IPipelineCensusOptions): PipelineCensus {
301
+ return new PipelineCensus(options);
302
+ }
303
+
304
+ export class PipelineCensus {
305
+ readonly #kind: "webgpu" | "webgl2";
306
+ readonly #limit: number;
307
+ readonly #now: () => number;
308
+ readonly #origin: number;
309
+ readonly #clockSource: "performance" | "date";
310
+ readonly #backendIdentity: string;
311
+ readonly #buildIdentity: string;
312
+ readonly #adapterIdentity: string;
313
+ readonly #thermalIdentity: string;
314
+ readonly #events: IMutableCensusEvent[] = [];
315
+ readonly #nodeBuildEvents: IPipelineNodeBuild[] = [];
316
+ readonly #programs = new Set<string>();
317
+ readonly #pipelines = new Set<string>();
318
+ readonly #installed: IInstalledBackend[] = [];
319
+ readonly #devices: IInstalledDevice[] = [];
320
+ readonly #pipelineIds = new WeakMap<object, string>();
321
+ readonly #backendPipelineIds = new WeakMap<object, string>();
322
+ /**
323
+ * Shader identity by the object that owns the source: Three's programmable stage on the backend
324
+ * path, the shader module on the device path. Keying by object rather than by text means one
325
+ * hash per source instead of one per pipeline, and no capture ever retains a shader.
326
+ */
327
+ readonly #observations = new WeakMap<object, IPipelineShaderObservation>();
328
+ /** Distinct node-builder states, so a repeated render-object lookup is not a graph rebuild. */
329
+ readonly #nodeBuilderStates = new WeakSet<object>();
330
+ /** Pending state-build counts keyed by Three's internal RenderObject for async compilation. */
331
+ readonly #nodeBuilderObservations = new WeakMap<object, INodeBuilderObservation>();
332
+ /** Device methods that exist but refused their hook, so their creations were never seen. */
333
+ readonly #deviceRefusals = new Set<string>();
334
+ #activeRenderObject: IActiveRenderObject | undefined;
335
+ #nextSequence = 1;
336
+ #nextBackendPipelineIdentity = 1;
337
+ #nextLogicalPipelineIdentity = 1;
338
+ #nextDevicePipelineIdentity = 1;
339
+ #lookups = 0;
340
+ #creations = 0;
341
+ #failures = 0;
342
+ #pending = 0;
343
+ #dropped = 0;
344
+ #droppedNodeBuilds = 0;
345
+ #deviceCreations = 0;
346
+ #directCreations = 0;
347
+ #nodeBuilds = 0;
348
+ #nestedDeviceCreations = 0;
349
+ #backendDepth = 0;
350
+ #backendDeviceCalls = 0;
351
+ #deviceObserved = false;
352
+ #overflowed = false;
353
+ #unsupported = false;
354
+ #firstPresentMs: number | undefined;
355
+ #eventsSettledAtFirstPresent = 0;
356
+ #warmUpSettledMs: number | undefined;
357
+ #eventsSettledAtWarmUpSettled = 0;
358
+ #nodeBuildsAtWarmUpSettled = 0;
359
+ #renderPipelineCreationsAtWarmUpSettled = 0;
360
+ readonly #warmUpScopes: IMutableWarmUpScope[] = [];
361
+ /** Scope lists keyed weakly by streamed root, so an evicted chunk graph is not kept alive here. */
362
+ readonly #warmUpTargets = new WeakMap<object, IMutableWarmUpScope[]>();
363
+ /** Scopes a draw touched in the open world frame; only these reset when it closes. */
364
+ #frameWarmUpScopes: IMutableWarmUpScope[] = [];
365
+ #activeWarmUpScope: { label: string; boundaryMs: number } | undefined;
366
+ #activeWorldFrame: { root: object } | undefined;
367
+ #nodeBuilderObservationUnavailable = false;
368
+ #cleanup: (() => void) | undefined;
369
+
370
+ constructor(options: IPipelineCensusOptions) {
371
+ if (!Number.isInteger(options.limit) || (options.limit ?? DEFAULT_PIPELINE_CENSUS_LIMIT) <= 0) {
372
+ if (options.limit !== undefined)
373
+ throw new Error(`TN_PIPELINE_CENSUS_LIMIT_INVALID: ${String(options.limit)}`);
374
+ }
375
+ this.#kind = options.kind;
376
+ this.#limit = options.limit ?? DEFAULT_PIPELINE_CENSUS_LIMIT;
377
+ this.#now = options.now ?? defaultNow;
378
+ this.#origin = this.#now();
379
+ this.#clockSource = typeof globalThis.performance?.now === "function" ? "performance" : "date";
380
+ this.#backendIdentity = options.backendIdentity ?? `${options.kind}:renderer`;
381
+ this.#buildIdentity = options.buildIdentity ?? `@threenative/core@${CORE_VERSION}`;
382
+ this.#adapterIdentity = options.adapterIdentity ?? this.#backendIdentity;
383
+ this.#thermalIdentity = options.thermalIdentity ?? "unavailable";
384
+ }
385
+
386
+ /** Install the backend creation hooks and the render-object context wrapper once. */
387
+ install(backendValue: unknown): () => void {
388
+ if (!isObject(backendValue)) {
389
+ this.#unsupported = true;
390
+ return () => undefined;
391
+ }
392
+ const backend = backendValue as IBackendLike;
393
+ if (this.#installed.some((entry) => entry.backend === backend)) return () => undefined;
394
+ const installed: IInstalledBackend = { backend };
395
+ let changed = false;
396
+ if (typeof backend.createRenderPipeline === "function") {
397
+ const original = backend.createRenderPipeline;
398
+ const wrapper = (...args: unknown[]): unknown =>
399
+ this.#observeRenderCreation(backend, original, args);
400
+ backend.createRenderPipeline = wrapper;
401
+ installed.render = original;
402
+ installed.renderWrapper = wrapper;
403
+ changed = true;
404
+ }
405
+ if (typeof backend.createComputePipeline === "function") {
406
+ const original = backend.createComputePipeline;
407
+ const wrapper = (...args: unknown[]): unknown =>
408
+ this.#observeComputeCreation(backend, original, args);
409
+ backend.createComputePipeline = wrapper;
410
+ installed.compute = original;
411
+ installed.computeWrapper = wrapper;
412
+ changed = true;
413
+ }
414
+ if (!changed) this.#unsupported = true;
415
+ else this.#installed.push(installed);
416
+ this.#ensureDevice(backend);
417
+ return () => {
418
+ this.#restoreDevices(backend);
419
+ if (
420
+ installed.render !== undefined &&
421
+ backend.createRenderPipeline === installed.renderWrapper
422
+ ) {
423
+ backend.createRenderPipeline = installed.render;
424
+ }
425
+ if (
426
+ installed.compute !== undefined &&
427
+ backend.createComputePipeline === installed.computeWrapper
428
+ ) {
429
+ backend.createComputePipeline = installed.compute;
430
+ }
431
+ const index = this.#installed.indexOf(installed);
432
+ if (index !== -1) this.#installed.splice(index, 1);
433
+ };
434
+ }
435
+
436
+ /**
437
+ * Install the device hooks for a backend that has one, once per device. The backend is asked
438
+ * again on every creation because the device arrives with `init()` and is replaced on a device
439
+ * loss; a census that only looked at install time would stop observing the moment either
440
+ * happened. A device whose methods cannot be replaced is left alone and reported unobserved.
441
+ *
442
+ * Every method the device actually has must accept its hook. One accepted hook is not the
443
+ * device: a host that binds `createRenderPipeline` as a non-writable property while leaving
444
+ * `createComputePipeline` writable would otherwise report a complete census that never saw a
445
+ * single render creation. A method the device does not have issues no work and is not missing.
446
+ */
447
+ #ensureDevice(backend: IBackendLike): void {
448
+ if (this.#kind !== "webgpu" || !isObject(backend.device)) return;
449
+ const device = backend.device;
450
+ if (this.#devices.some((entry) => entry.device === device)) return;
451
+ const restore: (() => void)[] = [];
452
+ const refused: string[] = [];
453
+ this.#patchIfPresent(
454
+ device,
455
+ "createShaderModule",
456
+ (original) =>
457
+ (...args: unknown[]) =>
458
+ this.#observeShaderModule(device, original, args),
459
+ restore,
460
+ refused,
461
+ );
462
+ let observed = 0;
463
+ for (const [name, kind, mode] of DEVICE_PIPELINE_METHODS) {
464
+ if (
465
+ this.#patchIfPresent(
466
+ device,
467
+ name,
468
+ (original) =>
469
+ (...args: unknown[]) =>
470
+ this.#observeDeviceCreation(device, original, args, kind, mode),
471
+ restore,
472
+ refused,
473
+ )
474
+ )
475
+ observed += 1;
476
+ }
477
+ // Nothing observable here: leave the device exactly as found and let it be reported
478
+ // unobserved rather than partially, so a later retry can still take it.
479
+ if (observed === 0) {
480
+ for (const undo of restore) undo();
481
+ return;
482
+ }
483
+ for (const name of refused) this.#deviceRefusals.add(name);
484
+ this.#devices.push({ backend, device, restore });
485
+ this.#deviceObserved = true;
486
+ }
487
+
488
+ /** Patch a method the device has, recording a refusal that must invalidate completeness. */
489
+ #patchIfPresent(
490
+ device: Record<string, unknown>,
491
+ name: string,
492
+ build: (original: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown,
493
+ restore: (() => void)[],
494
+ refused: string[],
495
+ ): boolean {
496
+ if (typeof device[name] !== "function") return false;
497
+ if (this.#patchMethod(device, name, build, restore)) return true;
498
+ refused.push(name);
499
+ return false;
500
+ }
501
+
502
+ #patchMethod(
503
+ target: Record<string, unknown>,
504
+ name: string,
505
+ build: (original: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown,
506
+ restore: (() => void)[],
507
+ ): boolean {
508
+ const original = target[name];
509
+ if (typeof original !== "function") return false;
510
+ const previous = original as (...args: unknown[]) => unknown;
511
+ // A browser device carries these on its prototype and a host binds them to the object itself.
512
+ // Remember which, so teardown leaves the device exactly as it was found rather than pinning an
513
+ // own copy of a prototype method.
514
+ const owned = Object.hasOwn(target, name);
515
+ const wrapper = build(previous);
516
+ try {
517
+ target[name] = wrapper;
518
+ } catch {
519
+ return false;
520
+ }
521
+ // A host may expose its bindings as non-writable properties; in that case the assignment is
522
+ // silently or loudly refused and the census must report an unobserved device, not a green one.
523
+ if (target[name] !== wrapper) return false;
524
+ restore.push(() => {
525
+ if (target[name] !== wrapper) return;
526
+ if (owned) target[name] = previous;
527
+ else delete target[name];
528
+ });
529
+ return true;
530
+ }
531
+
532
+ #restoreDevices(backend: IBackendLike): void {
533
+ for (let index = this.#devices.length - 1; index >= 0; index -= 1) {
534
+ const entry = this.#devices[index];
535
+ if (entry === undefined || entry.backend !== backend) continue;
536
+ for (const undo of entry.restore) undo();
537
+ this.#devices.splice(index, 1);
538
+ }
539
+ }
540
+
541
+ /** Install every renderer-side hook owned by this capture. */
542
+ installRenderer(renderer: IRendererHookTarget): void {
543
+ if (this.#cleanup !== undefined) return;
544
+ const restoreBackend = this.install(renderer.backend);
545
+ const restoreNodeBuilder = this.#installNodeBuilderObservation(renderer);
546
+ const originalRenderObject = renderer.renderObject;
547
+ let wrappedRenderObject: ((...args: unknown[]) => unknown) | undefined;
548
+ if (originalRenderObject !== undefined) {
549
+ const census = this;
550
+ wrappedRenderObject = function (this: unknown, ...args: unknown[]): unknown {
551
+ return census.withRenderObject(args, () => originalRenderObject.apply(this, args));
552
+ };
553
+ renderer.renderObject = wrappedRenderObject;
554
+ }
555
+ this.#cleanup = () => {
556
+ restoreNodeBuilder();
557
+ if (wrappedRenderObject !== undefined && renderer.renderObject === wrappedRenderObject)
558
+ renderer.renderObject = originalRenderObject;
559
+ restoreBackend();
560
+ this.#cleanup = undefined;
561
+ };
562
+ }
563
+
564
+ /** Restore private hooks while retaining the immutable capture already recorded. */
565
+ dispose(): void {
566
+ this.#cleanup?.();
567
+ }
568
+
569
+ /** Wrap Three's public render-object method so compileAsync retains the authored pass id. */
570
+ withRenderObject<T>(args: readonly unknown[], callback: () => T): T {
571
+ const previous = this.#activeRenderObject;
572
+ const active: IActiveRenderObject = {
573
+ clippingContext: args[7],
574
+ object: args[0],
575
+ material: args[4],
576
+ scene: args[1],
577
+ passId: args[8],
578
+ nodeBuilds: 0,
579
+ };
580
+ this.#activeRenderObject = active;
581
+ this.#observeWarmUpScopes(this.#matchingWarmUpScopes());
582
+ try {
583
+ return callback();
584
+ } finally {
585
+ this.#activeRenderObject = previous;
586
+ }
587
+ }
588
+
589
+ #matchingWarmUpScopes(active = this.#activeRenderObject): readonly IMutableWarmUpScope[] {
590
+ const activeObject = active?.object;
591
+ if (
592
+ active === undefined ||
593
+ this.#activeWorldFrame?.root !== active.scene ||
594
+ !isObject(activeObject) ||
595
+ !isMainWorldPass(active.passId)
596
+ )
597
+ return NO_WARM_UP_SCOPES;
598
+ return warmUpScopesOf(this.#warmUpTargets, activeObject);
599
+ }
600
+
601
+ #observeWarmUpScopes(scopes: readonly IMutableWarmUpScope[]): void {
602
+ for (const scope of scopes) {
603
+ if (scope.frameObserved) continue;
604
+ scope.frameObserved = true;
605
+ this.#frameWarmUpScopes.push(scope);
606
+ }
607
+ }
608
+
609
+ /** Begin the outer world render that can close target-bound streamed warm-up scopes. */
610
+ beginWorldFrame(root: object): void {
611
+ this.#activeWorldFrame = { root };
612
+ }
613
+
614
+ /** Close target-bound scopes only after the complete visible world frame has returned. */
615
+ endWorldFrame(root: object, completed: boolean): void {
616
+ const frame = this.#activeWorldFrame;
617
+ this.#activeWorldFrame = undefined;
618
+ const matches = completed && frame !== undefined && frame.root === root;
619
+ for (const scope of this.#frameWarmUpScopes) {
620
+ if (matches && scope.firstDraw === undefined)
621
+ scope.firstDraw = {
622
+ nodeBuilds: scope.frameNodeBuilds,
623
+ renderPipelineCreations: scope.frameRenderPipelineCreations,
624
+ };
625
+ scope.frameObserved = false;
626
+ scope.frameNodeBuilds = 0;
627
+ scope.frameRenderPipelineCreations = 0;
628
+ }
629
+ this.#frameWarmUpScopes = [];
630
+ }
631
+
632
+ /** Observe state creation at Three's renderer-owned NodeManager seam, never on the game Mesh. */
633
+ #installNodeBuilderObservation(renderer: IRendererHookTarget): () => void {
634
+ if (this.#kind !== "webgpu" || renderer.renderObject === undefined) return () => undefined;
635
+ if (!isObject(renderer._nodes)) {
636
+ this.#nodeBuilderObservationUnavailable = true;
637
+ return () => undefined;
638
+ }
639
+ const nodes = renderer._nodes;
640
+ const original = nodes.getForRender;
641
+ if (typeof original !== "function") {
642
+ this.#nodeBuilderObservationUnavailable = true;
643
+ return () => undefined;
644
+ }
645
+ const census = this;
646
+ const restore: (() => void)[] = [];
647
+ const installed = this.#patchMethod(
648
+ nodes,
649
+ "getForRender",
650
+ (method) =>
651
+ function (this: unknown, ...args: unknown[]): unknown {
652
+ const result = method.apply(this, args);
653
+ return census.#observeNodeBuilderResult(args[0], result);
654
+ },
655
+ restore,
656
+ );
657
+ if (!installed) {
658
+ this.#nodeBuilderObservationUnavailable = true;
659
+ return () => undefined;
660
+ }
661
+ return () => {
662
+ for (const undo of restore.splice(0).reverse()) undo();
663
+ };
664
+ }
665
+
666
+ #observeNodeBuilderResult(renderObjectValue: unknown, result: unknown): unknown {
667
+ if (isPromiseLike(result)) {
668
+ return result.then((state: unknown) => {
669
+ this.#recordNodeBuilderState(renderObjectValue, state);
670
+ return state;
671
+ });
672
+ }
673
+ this.#recordNodeBuilderState(renderObjectValue, result);
674
+ return result;
675
+ }
676
+
677
+ #recordNodeBuilderState(renderObjectValue: unknown, state: unknown): void {
678
+ if (!isObject(renderObjectValue) || !isObject(state)) {
679
+ this.#nodeBuilderObservationUnavailable = true;
680
+ return;
681
+ }
682
+ if (this.#nodeBuilderStates.has(state)) return;
683
+ this.#nodeBuilderStates.add(state);
684
+ this.#nodeBuilds += 1;
685
+ const previous = this.#nodeBuilderObservations.get(renderObjectValue);
686
+ const observation: INodeBuilderObservation =
687
+ previous === undefined || previous.state !== state
688
+ ? {
689
+ state,
690
+ builds: (previous?.builds ?? 0) + 1,
691
+ reported: false,
692
+ }
693
+ : previous;
694
+ this.#nodeBuilderObservations.set(renderObjectValue, observation);
695
+ if (this.#activeRenderObject !== undefined) this.#activeRenderObject.nodeBuilds += 1;
696
+ const startedMs = this.#clock();
697
+ const matching = this.#matchingWarmUpScopes();
698
+ this.#observeWarmUpScopes(matching);
699
+ for (const scope of matching) scope.frameNodeBuilds += 1;
700
+ const legacyScope =
701
+ this.#activeWarmUpScope !== undefined && startedMs > this.#activeWarmUpScope.boundaryMs
702
+ ? this.#activeWarmUpScope.label
703
+ : undefined;
704
+ const scopedLabel = matching.length === 1 ? matching[0]?.label : legacyScope;
705
+ const record: IPipelineNodeBuild = {
706
+ provenance: provenance(
707
+ { object: this.#activeRenderObject?.object, material: this.#activeRenderObject?.material },
708
+ this.#activeRenderObject,
709
+ ),
710
+ startedMs,
711
+ beforeFirstPresent: this.#firstPresentMs === undefined || startedMs <= this.#firstPresentMs,
712
+ ...(this.#warmUpSettledMs === undefined
713
+ ? {}
714
+ : { beforeWarmUpSettled: startedMs <= this.#warmUpSettledMs }),
715
+ ...(scopedLabel === undefined ? {} : { afterWarmUpScope: scopedLabel }),
716
+ };
717
+ if (this.#nodeBuildEvents.length < this.#limit) this.#nodeBuildEvents.push(record);
718
+ else this.#droppedNodeBuilds += 1;
719
+ }
720
+
721
+ #nodeBuildsFor(renderObjectValue: IRenderObjectLike | undefined): number {
722
+ if (!isObject(renderObjectValue)) return this.#activeRenderObject?.nodeBuilds ?? 0;
723
+ const observation = this.#nodeBuilderObservations.get(renderObjectValue);
724
+ if (observation === undefined || observation.reported) return 0;
725
+ observation.reported = true;
726
+ return observation.builds;
727
+ }
728
+
729
+ /** Mark the first renderer render call as the first-present boundary. */
730
+ firstPresent(): void {
731
+ if (this.#firstPresentMs !== undefined) return;
732
+ const boundaryMs = this.#clock();
733
+ this.#firstPresentMs = boundaryMs;
734
+ this.#eventsSettledAtFirstPresent = this.#events.filter(
735
+ (event) => event.settledMs !== undefined && event.settledMs <= boundaryMs,
736
+ ).length;
737
+ }
738
+
739
+ /** Mark the explicit shader warm-up as settled before the first measured world pass. */
740
+ warmUpSettled(): void {
741
+ if (this.#warmUpSettledMs !== undefined) return;
742
+ const boundaryMs = this.#clock();
743
+ this.#warmUpSettledMs = boundaryMs;
744
+ this.#eventsSettledAtWarmUpSettled = this.#events.filter(
745
+ (event) => event.settledMs !== undefined && event.settledMs <= boundaryMs,
746
+ ).length;
747
+ this.#nodeBuildsAtWarmUpSettled = this.#nodeBuilds;
748
+ this.#renderPipelineCreationsAtWarmUpSettled = this.#events.filter(
749
+ (event) =>
750
+ event.kind === "render" &&
751
+ event.status === "created" &&
752
+ event.settledMs !== undefined &&
753
+ event.settledMs <= boundaryMs,
754
+ ).length;
755
+ for (const event of this.#events) {
756
+ if (event.settledMs !== undefined) event.beforeWarmUpSettled = event.settledMs <= boundaryMs;
757
+ }
758
+ for (const nodeBuild of this.#nodeBuildEvents)
759
+ Object.assign(nodeBuild, { beforeWarmUpSettled: nodeBuild.startedMs <= boundaryMs });
760
+ }
761
+
762
+ /** Mark one repeatable streamed warm-up boundary; target-bound scopes close on their first world frame. */
763
+ warmUpScopeSettled(label: string, target?: object): void {
764
+ if (label.trim() === "") throw new Error("TN_PIPELINE_CENSUS_SCOPE_INVALID: empty label");
765
+ const boundaryMs = this.#clock();
766
+ const scope: IMutableWarmUpScope = {
767
+ label,
768
+ boundaryMs,
769
+ eventsSettled: this.#events.filter(
770
+ (event) => event.settledMs !== undefined && event.settledMs <= boundaryMs,
771
+ ).length,
772
+ nodeBuilds: this.#nodeBuilds,
773
+ renderPipelineCreations: this.#events.filter(
774
+ (event) =>
775
+ event.kind === "render" &&
776
+ event.status === "created" &&
777
+ event.settledMs !== undefined &&
778
+ event.settledMs <= boundaryMs,
779
+ ).length,
780
+ frameObserved: false,
781
+ frameNodeBuilds: 0,
782
+ frameRenderPipelineCreations: 0,
783
+ };
784
+ this.#warmUpScopes.push(scope);
785
+ if (target !== undefined) {
786
+ const scopes = this.#warmUpTargets.get(target);
787
+ if (scopes === undefined) this.#warmUpTargets.set(target, [scope]);
788
+ else scopes.push(scope);
789
+ }
790
+ if (target === undefined) this.#activeWarmUpScope = { label, boundaryMs };
791
+ }
792
+
793
+ snapshot(): IPipelineCensus {
794
+ const incompleteReasons: string[] = [];
795
+ if (this.#unsupported) incompleteReasons.push("backend creation observation unavailable");
796
+ if (this.#nodeBuilderObservationUnavailable)
797
+ incompleteReasons.push("node builder observation unavailable");
798
+ incompleteReasons.push(...this.#deviceReasons());
799
+ if (this.#adapterIdentity === "unavailable")
800
+ incompleteReasons.push("adapter identity unavailable");
801
+ if (this.#overflowed) incompleteReasons.push("bounded event buffer overflowed");
802
+ if (this.#droppedNodeBuilds > 0) incompleteReasons.push("bounded node-build buffer overflowed");
803
+ if (this.#pending > 0) incompleteReasons.push(`${this.#pending} pipeline event(s) are pending`);
804
+ if (this.#failures > 0) incompleteReasons.push(`${this.#failures} pipeline creation(s) failed`);
805
+ if (this.#creations === 0) incompleteReasons.push("no pipeline creations observed");
806
+ for (const event of this.#events) {
807
+ if (event.kind === "render" && event.vertex === undefined)
808
+ incompleteReasons.push("a render pipeline is missing its vertex shader observation");
809
+ if (
810
+ event.kind === "render" &&
811
+ event.fragmentStagePresent === true &&
812
+ event.fragment === undefined
813
+ )
814
+ incompleteReasons.push("a render pipeline is missing its fragment shader observation");
815
+ if (event.kind === "compute" && event.compute === undefined)
816
+ incompleteReasons.push("a compute pipeline is missing its shader observation");
817
+ }
818
+ if (this.#creations !== this.#events.length + this.#dropped)
819
+ incompleteReasons.push("observed creation count does not reconcile with recorded events");
820
+ const events = this.#events.map((event) => freezeEvent(event));
821
+ return {
822
+ version: PIPELINE_CENSUS_VERSION,
823
+ complete: incompleteReasons.length === 0 && this.#creations > 0,
824
+ overflowed: this.#overflowed,
825
+ unsupported: this.#unsupported,
826
+ limit: this.#limit,
827
+ clock: { originMs: this.#origin, source: this.#clockSource },
828
+ backend: { kind: this.#kind, identity: this.#backendIdentity },
829
+ build: { identity: this.#buildIdentity },
830
+ adapter: { identity: this.#adapterIdentity, thermal: this.#thermalIdentity },
831
+ ...(this.#firstPresentMs === undefined
832
+ ? {}
833
+ : {
834
+ firstPresent: {
835
+ boundaryMs: this.#firstPresentMs,
836
+ eventsSettled: this.#eventsSettledAtFirstPresent,
837
+ },
838
+ }),
839
+ ...(this.#warmUpSettledMs === undefined
840
+ ? {}
841
+ : {
842
+ warmUpSettled: {
843
+ boundaryMs: this.#warmUpSettledMs,
844
+ eventsSettled: this.#eventsSettledAtWarmUpSettled,
845
+ nodeBuilds: this.#nodeBuildsAtWarmUpSettled,
846
+ renderPipelineCreations: this.#renderPipelineCreationsAtWarmUpSettled,
847
+ },
848
+ }),
849
+ ...(this.#warmUpScopes.length === 0
850
+ ? {}
851
+ : {
852
+ warmUpScopes: this.#warmUpScopes.map((scope) => ({
853
+ label: scope.label,
854
+ boundaryMs: scope.boundaryMs,
855
+ eventsSettled: scope.eventsSettled,
856
+ nodeBuilds: scope.nodeBuilds,
857
+ renderPipelineCreations: scope.renderPipelineCreations,
858
+ ...(scope.firstDraw === undefined ? {} : { firstDraw: { ...scope.firstDraw } }),
859
+ })),
860
+ }),
861
+ counts: {
862
+ lookups: this.#lookups,
863
+ creations: this.#creations,
864
+ failures: this.#failures,
865
+ pending: this.#pending,
866
+ uniquePrograms: this.#programs.size,
867
+ uniquePipelines: this.#pipelines.size,
868
+ recordedEvents: this.#events.length,
869
+ droppedEvents: this.#dropped,
870
+ nodeBuilds: this.#nodeBuilds,
871
+ ...this.#deviceCounts(),
872
+ },
873
+ events,
874
+ ...(this.#nodeBuildEvents.length === 0 && this.#nodeBuilds === 0
875
+ ? {}
876
+ : { nodeBuilds: this.#nodeBuildEvents.map((entry) => freezeNodeBuild(entry)) }),
877
+ incompleteReasons,
878
+ };
879
+ }
880
+
881
+ #clock(): number {
882
+ return Math.max(0, this.#now() - this.#origin);
883
+ }
884
+
885
+ /**
886
+ * Three creates pipelines the backend never sees, so a capture that never reached the device
887
+ * cannot claim it counted them, however many backend events it holds. A creation nested inside
888
+ * a backend creation is attributed to that backend event, and is reported here so the extra
889
+ * device call is never quietly dropped from the total. A device observed through some of its
890
+ * methods is short by whatever went through the rest, and says which method it was.
891
+ */
892
+ #deviceReasons(): string[] {
893
+ const reasons: string[] = [];
894
+ if (this.#kind === "webgpu" && !this.#deviceObserved)
895
+ reasons.push("device creation observation unavailable");
896
+ for (const name of [...this.#deviceRefusals].sort())
897
+ reasons.push(`device method ${name} could not be observed`);
898
+ if (this.#nestedDeviceCreations > 0)
899
+ reasons.push(
900
+ `${this.#nestedDeviceCreations} device pipeline creation(s) were nested inside a backend creation`,
901
+ );
902
+ return reasons;
903
+ }
904
+
905
+ #deviceCounts(): { deviceCreations?: number; directCreations?: number } {
906
+ if (!this.#deviceObserved) return {};
907
+ return { deviceCreations: this.#deviceCreations, directCreations: this.#directCreations };
908
+ }
909
+
910
+ #observeRenderCreation(
911
+ backend: IBackendLike,
912
+ original: (...args: unknown[]) => unknown,
913
+ args: readonly unknown[],
914
+ ): unknown {
915
+ this.#ensureDevice(backend);
916
+ const renderObject = isObject(args[0]) ? (args[0] as IRenderObjectLike) : {};
917
+ const pipeline = isObject(renderObject.pipeline)
918
+ ? (renderObject.pipeline as IPipelineLike)
919
+ : undefined;
920
+ const vertex = this.#programObservation(backend, pipeline?.vertexProgram);
921
+ const fragment = this.#programObservation(backend, pipeline?.fragmentProgram);
922
+ const event = this.#beginEvent({
923
+ backend,
924
+ kind: "render",
925
+ pipeline,
926
+ vertex,
927
+ fragment,
928
+ ...(pipeline === undefined
929
+ ? {}
930
+ : {
931
+ fragmentStagePresent:
932
+ pipeline.fragmentProgram !== undefined && pipeline.fragmentProgram !== null,
933
+ }),
934
+ renderObject,
935
+ mode: args[1] === null ? "sync" : "async",
936
+ });
937
+ const started = this.#now();
938
+ try {
939
+ const result = this.#throughBackend(() => original.apply(backend, [...args]));
940
+ const promises = asyncPromises(args[1]);
941
+ if (promises.length > 0) {
942
+ event.mode = "async";
943
+ event.status = "pending";
944
+ event.pending = true;
945
+ this.#pending += 1;
946
+ void Promise.all(promises).then(
947
+ () => this.#settleEvent(backend, event, started, undefined),
948
+ (error: unknown) => this.#settleEvent(backend, event, started, error),
949
+ );
950
+ } else {
951
+ this.#settleEvent(backend, event, started, undefined);
952
+ }
953
+ return result;
954
+ } catch (error) {
955
+ this.#settleEvent(backend, event, started, error);
956
+ throw error;
957
+ }
958
+ }
959
+
960
+ #observeComputeCreation(
961
+ backend: IBackendLike,
962
+ original: (...args: unknown[]) => unknown,
963
+ args: readonly unknown[],
964
+ ): unknown {
965
+ this.#ensureDevice(backend);
966
+ const pipeline = isObject(args[0]) ? (args[0] as IPipelineLike) : undefined;
967
+ const compute = this.#programObservation(backend, pipeline?.computeProgram);
968
+ const event = this.#beginEvent({
969
+ backend,
970
+ kind: "compute",
971
+ pipeline,
972
+ compute,
973
+ renderObject: undefined,
974
+ mode: "sync",
975
+ });
976
+ const started = this.#now();
977
+ try {
978
+ const result = this.#throughBackend(() => original.apply(backend, [...args]));
979
+ this.#settleEvent(backend, event, started, undefined);
980
+ return result;
981
+ } catch (error) {
982
+ this.#settleEvent(backend, event, started, error);
983
+ throw error;
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Run a backend creation with its device calls attributed to it. Three reaches the device
989
+ * synchronously in both paths — `createRenderPipelineAsync` is called before the first `await`
990
+ * of the promise it hands back — so the depth is enough to tell a delegated creation from a
991
+ * direct one, and a second device call inside one backend creation is reported rather than lost.
992
+ */
993
+ #throughBackend<T>(callback: () => T): T {
994
+ const previousCalls = this.#backendDeviceCalls;
995
+ this.#backendDepth += 1;
996
+ this.#backendDeviceCalls = 0;
997
+ try {
998
+ return callback();
999
+ } finally {
1000
+ if (this.#backendDeviceCalls > 1) this.#nestedDeviceCreations += this.#backendDeviceCalls - 1;
1001
+ this.#backendDepth -= 1;
1002
+ this.#backendDeviceCalls = previousCalls;
1003
+ }
1004
+ }
1005
+
1006
+ #observeShaderModule(
1007
+ device: Record<string, unknown>,
1008
+ original: (...args: unknown[]) => unknown,
1009
+ args: readonly unknown[],
1010
+ ): unknown {
1011
+ const result = original.apply(device, [...args]);
1012
+ const descriptor = isObject(args[0]) ? args[0] : undefined;
1013
+ const code = typeof descriptor?.code === "string" ? descriptor.code : undefined;
1014
+ if (code !== undefined && isObject(result) && !this.#observations.has(result))
1015
+ this.#observations.set(result, { bytes: utf8Bytes(code), hash: hashText(code) });
1016
+ return result;
1017
+ }
1018
+
1019
+ #observeDeviceCreation(
1020
+ device: Record<string, unknown>,
1021
+ original: (...args: unknown[]) => unknown,
1022
+ args: readonly unknown[],
1023
+ kind: "compute" | "render",
1024
+ mode: PipelineCensusMode,
1025
+ ): unknown {
1026
+ this.#deviceCreations += 1;
1027
+ if (this.#backendDepth > 0) {
1028
+ this.#backendDeviceCalls += 1;
1029
+ return original.apply(device, [...args]);
1030
+ }
1031
+ const descriptor = isObject(args[0]) ? args[0] : {};
1032
+ const label = typeof descriptor.label === "string" ? descriptor.label : undefined;
1033
+ const event = this.#beginEvent({
1034
+ kind,
1035
+ pipeline: undefined,
1036
+ ...(kind === "compute"
1037
+ ? { compute: this.#stageObservation(descriptor.compute) }
1038
+ : {
1039
+ vertex: this.#stageObservation(descriptor.vertex),
1040
+ fragment: this.#stageObservation(descriptor.fragment),
1041
+ fragmentStagePresent: descriptor.fragment !== undefined && descriptor.fragment !== null,
1042
+ }),
1043
+ renderObject: undefined,
1044
+ // The mode describes what the call did, not which method was named: an async method that
1045
+ // returns no promise settled synchronously and is timed as the device call it was.
1046
+ mode: "sync",
1047
+ direct: true,
1048
+ ...(label === undefined || label.length === 0 ? {} : { label }),
1049
+ });
1050
+ this.#directCreations += 1;
1051
+ const started = this.#now();
1052
+ try {
1053
+ const result = original.apply(device, [...args]);
1054
+ const promise = mode === "async" && isPromiseLike(result) ? result : undefined;
1055
+ if (promise !== undefined) {
1056
+ event.mode = "async";
1057
+ event.status = "pending";
1058
+ event.pending = true;
1059
+ this.#pending += 1;
1060
+ void promise.then(
1061
+ (handle: unknown) => {
1062
+ event.deviceHandle = handle;
1063
+ this.#settleEvent(undefined, event, started, undefined);
1064
+ },
1065
+ (error: unknown) => this.#settleEvent(undefined, event, started, error),
1066
+ );
1067
+ return result;
1068
+ }
1069
+ event.deviceHandle = result;
1070
+ this.#settleEvent(undefined, event, started, undefined);
1071
+ return result;
1072
+ } catch (error) {
1073
+ this.#settleEvent(undefined, event, started, error);
1074
+ throw error;
1075
+ }
1076
+ }
1077
+
1078
+ #beginEvent(input: {
1079
+ readonly backend?: IBackendLike;
1080
+ readonly kind: "compute" | "render";
1081
+ readonly pipeline: IPipelineLike | undefined;
1082
+ readonly vertex?: IPipelineShaderObservation;
1083
+ readonly fragment?: IPipelineShaderObservation;
1084
+ readonly fragmentStagePresent?: boolean;
1085
+ readonly compute?: IPipelineShaderObservation;
1086
+ readonly renderObject: IRenderObjectLike | undefined;
1087
+ readonly mode: PipelineCensusMode;
1088
+ readonly direct?: boolean;
1089
+ readonly label?: string;
1090
+ }): IMutableCensusEvent {
1091
+ this.#creations += 1;
1092
+ const matching =
1093
+ input.kind === "render" && input.direct !== true ? this.#matchingWarmUpScopes() : [];
1094
+ this.#observeWarmUpScopes(matching);
1095
+ for (const scope of matching) scope.frameRenderPipelineCreations += 1;
1096
+ // A direct creation has no logical Three pipeline to be identified by, and one shared
1097
+ // placeholder would make two of them look like one. Each takes its own until its handle lands.
1098
+ const pipelineIdentity =
1099
+ input.direct === true
1100
+ ? `device-pipeline-${this.#nextDevicePipelineIdentity++}`
1101
+ : this.#logicalIdentity(input.pipeline);
1102
+ const programIdentity =
1103
+ input.kind === "compute"
1104
+ ? (input.compute?.hash ?? "unknown")
1105
+ : `${input.vertex?.hash ?? "unknown"}/${input.fragment?.hash ?? "unknown"}`;
1106
+ this.#programs.add(programIdentity);
1107
+ this.#pipelines.add(pipelineIdentity);
1108
+ const event: IMutableCensusEvent = {
1109
+ sequence: this.#nextSequence++,
1110
+ programIdentity,
1111
+ pipelineIdentity,
1112
+ kind: input.kind,
1113
+ ...this.#attribution(input.kind, input.direct === true, input.renderObject),
1114
+ mode: input.mode,
1115
+ status: input.mode === "async" ? "pending" : "created",
1116
+ ...(input.vertex === undefined ? {} : { vertex: input.vertex }),
1117
+ ...(input.fragment === undefined ? {} : { fragment: input.fragment }),
1118
+ ...(input.fragmentStagePresent === undefined
1119
+ ? {}
1120
+ : { fragmentStagePresent: input.fragmentStagePresent }),
1121
+ ...(input.compute === undefined ? {} : { compute: input.compute }),
1122
+ ...(input.label === undefined ? {} : { label: input.label }),
1123
+ ...(input.kind === "render" && input.direct !== true
1124
+ ? { nodeBuilds: this.#nodeBuildsFor(input.renderObject) }
1125
+ : {}),
1126
+ ...(matching.length === 1 && matching[0] !== undefined
1127
+ ? { afterWarmUpScope: matching[0].label }
1128
+ : {}),
1129
+ startedMs: this.#clock(),
1130
+ backendPipeline: input.pipeline,
1131
+ ...(input.direct === true ? { direct: true } : {}),
1132
+ };
1133
+ if (this.#events.length < this.#limit) this.#events.push(event);
1134
+ else {
1135
+ this.#overflowed = true;
1136
+ this.#dropped += 1;
1137
+ }
1138
+ return event;
1139
+ }
1140
+
1141
+ /**
1142
+ * Who a creation belongs to. A texture can upload while a mesh is drawing, so the render object
1143
+ * in flight is not a direct creation's author: it reports what it knows — the device label it
1144
+ * already carries — and says the rest is unknown rather than borrowing a pass and a material it
1145
+ * never had.
1146
+ */
1147
+ #attribution(
1148
+ kind: "compute" | "render",
1149
+ direct: boolean,
1150
+ renderObject: IRenderObjectLike | undefined,
1151
+ ): { pass: string; provenance: IPipelineProvenance; reasons: readonly string[] } {
1152
+ if (direct)
1153
+ return {
1154
+ pass: kind === "compute" ? "compute" : "unknown",
1155
+ provenance: { unknown: true },
1156
+ reasons: ["device-direct-creation"],
1157
+ };
1158
+ return {
1159
+ pass:
1160
+ kind === "compute"
1161
+ ? "compute"
1162
+ : resolvePass(
1163
+ this.#activeRenderObject?.passId,
1164
+ this.#activeRenderObject?.material,
1165
+ this.#activeRenderObject?.clippingContext,
1166
+ renderObject?.material,
1167
+ ),
1168
+ provenance: provenance(renderObject, this.#activeRenderObject),
1169
+ reasons: structuralReasons(renderObject?.object, renderObject?.material),
1170
+ };
1171
+ }
1172
+
1173
+ #settleEvent(
1174
+ backend: IBackendLike | undefined,
1175
+ event: IMutableCensusEvent,
1176
+ started: number,
1177
+ error: unknown,
1178
+ ): void {
1179
+ const settledAt = this.#clock();
1180
+ event.settledMs = settledAt;
1181
+ event.beforeFirstPresent =
1182
+ this.#firstPresentMs === undefined || settledAt <= this.#firstPresentMs;
1183
+ if (this.#warmUpSettledMs !== undefined)
1184
+ event.beforeWarmUpSettled = settledAt <= this.#warmUpSettledMs;
1185
+ if (
1186
+ event.afterWarmUpScope === undefined &&
1187
+ this.#activeWarmUpScope !== undefined &&
1188
+ settledAt > this.#activeWarmUpScope.boundaryMs
1189
+ )
1190
+ event.afterWarmUpScope = this.#activeWarmUpScope.label;
1191
+ if (event.pending === true) {
1192
+ event.pending = false;
1193
+ this.#pending = Math.max(0, this.#pending - 1);
1194
+ }
1195
+ if (event.mode === "async") event.promiseMs = Math.max(0, this.#now() - started);
1196
+ else event.serviceMs = Math.max(0, this.#now() - started);
1197
+ if (error !== undefined) {
1198
+ event.status = "failed";
1199
+ event.error = error instanceof Error ? error.message : String(error);
1200
+ this.#failures += 1;
1201
+ return;
1202
+ }
1203
+ // A direct creation carries the handle the device returned; a backend one has to be read back
1204
+ // out of Three's data map, where async data is installed before its promise resolves. Either
1205
+ // way a missing handle means nothing usable was created; do not report green.
1206
+ const pipeline =
1207
+ event.direct === true
1208
+ ? event.deviceHandle
1209
+ : this.#backendPipeline(backend, event.backendPipeline);
1210
+ if (pipeline === undefined && this.#kind === "webgpu") {
1211
+ event.status = "failed";
1212
+ event.error =
1213
+ event.direct === true
1214
+ ? `device did not return a created ${event.kind} pipeline`
1215
+ : `backend did not expose a created ${event.kind} pipeline`;
1216
+ this.#failures += 1;
1217
+ return;
1218
+ }
1219
+ if (pipeline !== undefined && this.#kind === "webgpu") {
1220
+ this.#replacePipelineIdentity(event, this.#backendPipelineIdentity(pipeline, event.kind));
1221
+ }
1222
+ // The identity is recorded, so let the GPU pipeline go; a census must not be why one stays alive.
1223
+ event.deviceHandle = undefined;
1224
+ event.status = "created";
1225
+ }
1226
+
1227
+ /**
1228
+ * Shader identity for a Three programmable stage, hashed once per stage rather than per use.
1229
+ *
1230
+ * The module was already hashed when the device made it, and Three keeps that same object at
1231
+ * `backend.get(stage).module.module` — the seam `WebGPUPipelineUtils` reads to build the
1232
+ * pipeline descriptor. Reuse it and the source is never hashed twice. A backend that exposes
1233
+ * no module for the stage (WebGL2, or a device hooked after its modules were built) falls back
1234
+ * to hashing the stage source, still once, cached on the stage object rather than by its text.
1235
+ */
1236
+ #programObservation(
1237
+ backend: IBackendLike | undefined,
1238
+ program: IProgramLike | undefined,
1239
+ ): IPipelineShaderObservation | undefined {
1240
+ if (!isObject(program)) return undefined;
1241
+ const cached = this.#observations.get(program);
1242
+ if (cached !== undefined) return cached;
1243
+ const shared = this.#moduleObservation(backend, program);
1244
+ const observed = shared ?? shaderObservation(program as IProgramLike);
1245
+ if (observed !== undefined) this.#observations.set(program, observed);
1246
+ return observed;
1247
+ }
1248
+
1249
+ /** The observation of the shader module Three built for a stage, when the hooks recorded one. */
1250
+ #moduleObservation(
1251
+ backend: IBackendLike | undefined,
1252
+ program: object,
1253
+ ): IPipelineShaderObservation | undefined {
1254
+ if (typeof backend?.get !== "function") return undefined;
1255
+ let stage: unknown;
1256
+ try {
1257
+ const data = backend.get(program);
1258
+ stage = isObject(data) ? data.module : undefined;
1259
+ } catch {
1260
+ return undefined;
1261
+ }
1262
+ if (!isObject(stage)) return undefined;
1263
+ // Three wraps the module as `{ module, entryPoint }`; tolerate a backend that stores it bare.
1264
+ return this.#observations.get(isObject(stage.module) ? stage.module : stage);
1265
+ }
1266
+
1267
+ /** Shader identity for a device stage descriptor, absent when its module predates the hooks. */
1268
+ #stageObservation(stage: unknown): IPipelineShaderObservation | undefined {
1269
+ const module = isObject(stage) ? stage.module : undefined;
1270
+ return isObject(module) ? this.#observations.get(module) : undefined;
1271
+ }
1272
+
1273
+ #backendPipeline(backend: IBackendLike | undefined, pipeline: unknown): unknown {
1274
+ // The event's identity is the logical Three pipeline, while WebGPU's DataMap carries the
1275
+ // opaque device handle. Read that data only after creation; a missing handle is a failed
1276
+ // creation, not a guessed success. WebGL's fallback has a different backend data shape and is
1277
+ // explicitly marked unsupported by the census, so it does not pretend to reconcile GPU keys.
1278
+ if (this.#kind !== "webgpu") return pipeline === undefined ? undefined : pipeline;
1279
+ if (typeof backend?.get !== "function" || pipeline === undefined) return undefined;
1280
+ this.#lookups += 1;
1281
+ try {
1282
+ const data = backend.get(pipeline);
1283
+ return isObject(data) && data.pipeline !== undefined && data.pipeline !== null
1284
+ ? data.pipeline
1285
+ : undefined;
1286
+ } catch {
1287
+ return undefined;
1288
+ }
1289
+ }
1290
+
1291
+ #logicalIdentity(pipeline: IPipelineLike | undefined): string {
1292
+ const candidate = pipeline as unknown;
1293
+ if (isObject(candidate)) {
1294
+ const existing = this.#pipelineIds.get(candidate);
1295
+ if (existing !== undefined) return existing;
1296
+ const identity = `logical-pipeline-${this.#nextLogicalPipelineIdentity++}`;
1297
+ this.#pipelineIds.set(candidate, identity);
1298
+ return identity;
1299
+ }
1300
+ const cacheKey = typeof pipeline?.cacheKey === "string" ? pipeline.cacheKey : undefined;
1301
+ if (cacheKey !== undefined) return `cache-${hashText(cacheKey)}`;
1302
+ return "logical-pipeline-unknown";
1303
+ }
1304
+
1305
+ #backendPipelineIdentity(pipeline: unknown, kind: "render" | "compute"): string {
1306
+ if (!isObject(pipeline)) return "backend-pipeline-unknown";
1307
+ // Native wrappers expose the same handle that their compile events report. Preserve it so
1308
+ // diagnostic tools can join exact creations, including state variants of the same program.
1309
+ const nativeId = pipeline._pipelineId;
1310
+ if (typeof nativeId === "number" && Number.isSafeInteger(nativeId) && nativeId > 0) {
1311
+ return `native-${kind}-${nativeId}`;
1312
+ }
1313
+ const existing = this.#backendPipelineIds.get(pipeline);
1314
+ if (existing !== undefined) return existing;
1315
+ const identity = `backend-pipeline-${this.#nextBackendPipelineIdentity++}`;
1316
+ this.#backendPipelineIds.set(pipeline, identity);
1317
+ return identity;
1318
+ }
1319
+
1320
+ #replacePipelineIdentity(event: IMutableCensusEvent, identity: string): void {
1321
+ if (event.pipelineIdentity === identity) return;
1322
+ this.#pipelines.delete(event.pipelineIdentity);
1323
+ event.pipelineIdentity = identity;
1324
+ this.#pipelines.add(identity);
1325
+ }
1326
+ }
1327
+
1328
+ function defaultNow(): number {
1329
+ return typeof globalThis.performance?.now === "function"
1330
+ ? globalThis.performance.now()
1331
+ : Date.now();
1332
+ }
1333
+
1334
+ function isObject(value: unknown): value is Record<string, unknown> {
1335
+ return typeof value === "object" && value !== null;
1336
+ }
1337
+
1338
+ function shaderObservation(
1339
+ program: IProgramLike | undefined,
1340
+ ): IPipelineShaderObservation | undefined {
1341
+ const code = program?.code;
1342
+ if (typeof code !== "string") return undefined;
1343
+ return { bytes: utf8Bytes(code), hash: hashText(code) };
1344
+ }
1345
+
1346
+ function utf8Bytes(value: string): number {
1347
+ if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(value).byteLength;
1348
+ return unescape(encodeURIComponent(value)).length;
1349
+ }
1350
+
1351
+ /** Stable non-cryptographic identity; the full shader is intentionally never retained. */
1352
+ function hashText(value: string): string {
1353
+ let hash = 0xcbf29ce484222325n;
1354
+ const bytes =
1355
+ typeof TextEncoder !== "undefined"
1356
+ ? new TextEncoder().encode(value)
1357
+ : [...unescape(encodeURIComponent(value))].map((character) => character.charCodeAt(0));
1358
+ for (const byte of bytes) {
1359
+ hash ^= BigInt(byte);
1360
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
1361
+ }
1362
+ return hash.toString(16).padStart(16, "0");
1363
+ }
1364
+
1365
+ function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
1366
+ return isObject(value) && typeof value.then === "function";
1367
+ }
1368
+
1369
+ function isMainWorldPass(passId: unknown): boolean {
1370
+ return passId === undefined || passId === null || passId === "main";
1371
+ }
1372
+
1373
+ const NO_WARM_UP_SCOPES: readonly IMutableWarmUpScope[] = [];
1374
+
1375
+ /** Scopes bound to the value, its `tnChunkRoot`, or any ancestor: O(depth) lookups per draw. */
1376
+ function warmUpScopesOf(
1377
+ targets: WeakMap<object, IMutableWarmUpScope[]>,
1378
+ value: object,
1379
+ ): readonly IMutableWarmUpScope[] {
1380
+ const userData = (value as { userData?: unknown }).userData;
1381
+ const chunkRoot = isObject(userData) ? userData.tnChunkRoot : undefined;
1382
+ let found = addWarmUpScopes(undefined, targets.get(value));
1383
+ if (isObject(chunkRoot)) found = addWarmUpScopes(found, targets.get(chunkRoot));
1384
+ for (
1385
+ let current = (value as { parent?: unknown }).parent;
1386
+ isObject(current);
1387
+ current = (current as { parent?: unknown }).parent
1388
+ )
1389
+ found = addWarmUpScopes(found, targets.get(current));
1390
+ return found ?? NO_WARM_UP_SCOPES;
1391
+ }
1392
+
1393
+ function addWarmUpScopes(
1394
+ found: IMutableWarmUpScope[] | undefined,
1395
+ scopes: readonly IMutableWarmUpScope[] | undefined,
1396
+ ): IMutableWarmUpScope[] | undefined {
1397
+ if (scopes === undefined) return found;
1398
+ const next = found ?? [];
1399
+ for (const scope of scopes) if (!next.includes(scope)) next.push(scope);
1400
+ return next;
1401
+ }
1402
+
1403
+ function asyncPromises(value: unknown): Promise<unknown>[] {
1404
+ if (!Array.isArray(value)) return [];
1405
+ return value
1406
+ .slice()
1407
+ .filter(
1408
+ (candidate): candidate is Promise<unknown> =>
1409
+ isObject(candidate) && typeof (candidate as { then?: unknown }).then === "function",
1410
+ );
1411
+ }
1412
+
1413
+ function resolvePass(
1414
+ passId: unknown,
1415
+ material: unknown,
1416
+ clippingContext?: unknown,
1417
+ secondaryMaterial?: unknown,
1418
+ ): string {
1419
+ if (typeof passId === "string" && passId.length > 0) return passId;
1420
+ const clippingRecord = isObject(clippingContext) ? clippingContext : undefined;
1421
+ if (clippingRecord?.shadowPass === true) return "shadow";
1422
+ for (const candidate of [secondaryMaterial, material]) {
1423
+ const materialRecord = isObject(candidate) ? candidate : undefined;
1424
+ if (
1425
+ materialRecord !== undefined &&
1426
+ (materialRecord.isShadowPassMaterial === true || isShadowMaterial(materialRecord))
1427
+ )
1428
+ return "shadow";
1429
+ const name = typeof materialRecord?.name === "string" ? materialRecord.name : "";
1430
+ if (/^PMREM_/u.test(name)) return "pmrem";
1431
+ if (name === "outputColorTransform" || name === "RenderPipeline") return "output";
1432
+ }
1433
+ if (clippingContext !== undefined && clippingContext !== null) return "main-clipped";
1434
+ return "main";
1435
+ }
1436
+
1437
+ function isShadowMaterial(material: Record<string, unknown>): boolean {
1438
+ const type = typeof material.type === "string" ? material.type : "";
1439
+ const name = typeof material.name === "string" ? material.name : "";
1440
+ return /shadow|depth/u.test(`${type} ${name}`);
1441
+ }
1442
+
1443
+ function provenance(
1444
+ renderObject: IRenderObjectLike | undefined,
1445
+ active: IActiveRenderObject | undefined,
1446
+ ): IPipelineProvenance {
1447
+ const material = active?.material ?? renderObject?.material;
1448
+ const object = active?.object ?? renderObject?.object;
1449
+ const materialRecord = isObject(material) ? material : undefined;
1450
+ const objectRecord = isObject(object) ? object : undefined;
1451
+ const materialValue =
1452
+ materialRecord === undefined
1453
+ ? undefined
1454
+ : {
1455
+ ...(finiteNumber(materialRecord.id) ? { id: materialRecord.id } : {}),
1456
+ ...(typeof materialRecord.name === "string" && materialRecord.name.length > 0
1457
+ ? { name: materialRecord.name }
1458
+ : {}),
1459
+ ...(typeof materialRecord.type === "string" ? { type: materialRecord.type } : {}),
1460
+ };
1461
+ const objectValue =
1462
+ objectRecord === undefined
1463
+ ? undefined
1464
+ : {
1465
+ ...(finiteNumber(objectRecord.id) ? { id: objectRecord.id } : {}),
1466
+ ...(typeof objectRecord.name === "string" && objectRecord.name.length > 0
1467
+ ? { name: objectRecord.name }
1468
+ : {}),
1469
+ ...(typeof objectRecord.uuid === "string" ? { uuid: objectRecord.uuid } : {}),
1470
+ };
1471
+ return {
1472
+ ...(materialValue === undefined ? {} : { material: materialValue }),
1473
+ ...(objectValue === undefined ? {} : { object: objectValue }),
1474
+ unknown: materialValue === undefined && objectValue === undefined,
1475
+ };
1476
+ }
1477
+
1478
+ function structuralReasons(object: unknown, material: unknown): string[] {
1479
+ const reasons: string[] = [];
1480
+ const objectRecord = isObject(object) ? object : undefined;
1481
+ const materialRecord = isObject(material) ? material : undefined;
1482
+ if (objectRecord?.isSkinnedMesh === true || materialRecord?.skinning === true)
1483
+ reasons.push("skinning");
1484
+ if (objectRecord?.isInstancedMesh === true) reasons.push("instancing");
1485
+ if (materialRecord !== undefined) {
1486
+ for (const [key, label] of [
1487
+ ["map", "map"],
1488
+ ["normalMap", "normal-map"],
1489
+ ["roughnessMap", "roughness-map"],
1490
+ ["metalnessMap", "metalness-map"],
1491
+ ["alphaMap", "alpha-map"],
1492
+ ["envMap", "environment-map"],
1493
+ ["clipping", "clipping"],
1494
+ ] as const) {
1495
+ if (
1496
+ materialRecord[key] !== undefined &&
1497
+ materialRecord[key] !== null &&
1498
+ materialRecord[key] !== false
1499
+ )
1500
+ reasons.push(label);
1501
+ }
1502
+ }
1503
+ if (reasons.length === 0) reasons.push("unknown-structural-difference");
1504
+ return reasons;
1505
+ }
1506
+
1507
+ function finiteNumber(value: unknown): value is number {
1508
+ return typeof value === "number" && Number.isFinite(value);
1509
+ }
1510
+
1511
+ function freezeEvent(event: IMutableCensusEvent): IPipelineCensusEvent {
1512
+ return {
1513
+ sequence: event.sequence,
1514
+ programIdentity: event.programIdentity,
1515
+ pipelineIdentity: event.pipelineIdentity,
1516
+ kind: event.kind,
1517
+ pass: event.pass,
1518
+ mode: event.mode,
1519
+ status: event.status,
1520
+ ...(event.vertex === undefined ? {} : { vertex: { ...event.vertex } }),
1521
+ ...(event.fragment === undefined ? {} : { fragment: { ...event.fragment } }),
1522
+ ...(event.compute === undefined ? {} : { compute: { ...event.compute } }),
1523
+ provenance: {
1524
+ ...(event.provenance.material === undefined
1525
+ ? {}
1526
+ : { material: { ...event.provenance.material } }),
1527
+ ...(event.provenance.object === undefined ? {} : { object: { ...event.provenance.object } }),
1528
+ unknown: event.provenance.unknown,
1529
+ },
1530
+ ...(event.label === undefined ? {} : { label: event.label }),
1531
+ reasons: [...event.reasons],
1532
+ startedMs: event.startedMs,
1533
+ ...(event.settledMs === undefined ? {} : { settledMs: event.settledMs }),
1534
+ ...(event.serviceMs === undefined ? {} : { serviceMs: event.serviceMs }),
1535
+ ...(event.promiseMs === undefined ? {} : { promiseMs: event.promiseMs }),
1536
+ ...(event.error === undefined ? {} : { error: event.error }),
1537
+ ...(event.nodeBuilds === undefined ? {} : { nodeBuilds: event.nodeBuilds }),
1538
+ ...(event.beforeFirstPresent === undefined
1539
+ ? {}
1540
+ : { beforeFirstPresent: event.beforeFirstPresent }),
1541
+ ...(event.beforeWarmUpSettled === undefined
1542
+ ? {}
1543
+ : { beforeWarmUpSettled: event.beforeWarmUpSettled }),
1544
+ ...(event.afterWarmUpScope === undefined ? {} : { afterWarmUpScope: event.afterWarmUpScope }),
1545
+ };
1546
+ }
1547
+
1548
+ function freezeNodeBuild(entry: IPipelineNodeBuild): IPipelineNodeBuild {
1549
+ return {
1550
+ provenance: {
1551
+ ...(entry.provenance.material === undefined
1552
+ ? {}
1553
+ : { material: { ...entry.provenance.material } }),
1554
+ ...(entry.provenance.object === undefined ? {} : { object: { ...entry.provenance.object } }),
1555
+ unknown: entry.provenance.unknown,
1556
+ },
1557
+ startedMs: entry.startedMs,
1558
+ ...(entry.beforeFirstPresent === undefined
1559
+ ? {}
1560
+ : { beforeFirstPresent: entry.beforeFirstPresent }),
1561
+ ...(entry.beforeWarmUpSettled === undefined
1562
+ ? {}
1563
+ : { beforeWarmUpSettled: entry.beforeWarmUpSettled }),
1564
+ ...(entry.afterWarmUpScope === undefined ? {} : { afterWarmUpScope: entry.afterWarmUpScope }),
1565
+ };
1566
+ }