@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,2237 @@
1
+ import { debugRequested, countDebug, isContentScaled } from './chunk-GYUZJQ7U.js';
2
+ import { mrt, velocity, output, context } from 'three/tsl';
3
+ import { BatchedMesh, DataTexture } from 'three';
4
+
5
+ // src/version.ts
6
+ var CORE_VERSION = "0.3.13";
7
+ var THREE_NATIVE_BATCHED_VELOCITY_PATCH = "threeNativeBatchedVelocityPatch";
8
+ function isBatchedMeshVelocityPatched() {
9
+ return Reflect.get(BatchedMesh, THREE_NATIVE_BATCHED_VELOCITY_PATCH) === true;
10
+ }
11
+ function state(mesh) {
12
+ return mesh;
13
+ }
14
+ function ensureBatchedMeshVelocity(mesh) {
15
+ const current = state(mesh)._matricesTexture;
16
+ if (current === null) throw new Error("BatchedMesh has no current matrix texture.");
17
+ if (state(mesh)._previousMatricesTexture != null) return;
18
+ const image = matrixImage(current);
19
+ const previous = new DataTexture(
20
+ image.data.slice(),
21
+ image.width,
22
+ image.height,
23
+ current.format,
24
+ current.type
25
+ );
26
+ previous.minFilter = current.minFilter;
27
+ previous.magFilter = current.magFilter;
28
+ previous.wrapS = current.wrapS;
29
+ previous.wrapT = current.wrapT;
30
+ previous.flipY = current.flipY;
31
+ previous.unpackAlignment = current.unpackAlignment;
32
+ previous.colorSpace = current.colorSpace;
33
+ previous.needsUpdate = true;
34
+ state(mesh)._previousMatricesTexture = previous;
35
+ }
36
+ function setBatchedMeshMatrixWithVelocity(mesh, instanceId, current, previous) {
37
+ setBatchedMeshPreviousMatrix(mesh, instanceId, previous);
38
+ mesh.setMatrixAt(instanceId, current);
39
+ }
40
+ function setBatchedMeshPreviousMatrix(mesh, instanceId, previous) {
41
+ ensureBatchedMeshVelocity(mesh);
42
+ const previousTexture = state(mesh)._previousMatricesTexture;
43
+ previous.toArray(matrixImage(previousTexture).data, instanceId * 16);
44
+ previousTexture.needsUpdate = true;
45
+ }
46
+ function setBatchedMeshPreviousMatrices(mesh, previous) {
47
+ ensureBatchedMeshVelocity(mesh);
48
+ const previousTexture = state(mesh)._previousMatricesTexture;
49
+ const image = matrixImage(previousTexture);
50
+ if (previous.length !== image.data.length) {
51
+ throw new Error(
52
+ `BatchedMesh previous matrix length ${String(previous.length)} does not match ${String(image.data.length)}.`
53
+ );
54
+ }
55
+ image.data.set(previous);
56
+ previousTexture.needsUpdate = true;
57
+ }
58
+ function disposeBatchedMeshVelocity(mesh) {
59
+ const previous = state(mesh)._previousMatricesTexture;
60
+ previous?.dispose();
61
+ state(mesh)._previousMatricesTexture = null;
62
+ }
63
+ function matrixImage(texture) {
64
+ const image = texture.image;
65
+ if (!(image.data instanceof Float32Array) || !Number.isInteger(image.width) || !Number.isInteger(image.height)) {
66
+ throw new Error("BatchedMesh matrix texture must contain a Float32Array image.");
67
+ }
68
+ return image;
69
+ }
70
+
71
+ // src/render/velocity.ts
72
+ var VELOCITY_OUTPUT_NAME = "velocity";
73
+ var VELOCITY_PREVIOUS_INSTANCE_MATRICES = /* @__PURE__ */ Symbol.for(
74
+ "threenative.velocity.previousInstanceMatrices"
75
+ );
76
+ var VELOCITY_PREVIOUS_WORLD_MATRIX = /* @__PURE__ */ Symbol.for(
77
+ "threenative.velocity.previousWorldMatrix"
78
+ );
79
+ var VELOCITY_PREVIOUS_BONE_MATRICES = /* @__PURE__ */ Symbol.for(
80
+ "threenative.velocity.previousBoneMatrices"
81
+ );
82
+ var VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE = /* @__PURE__ */ Symbol.for(
83
+ "threenative.velocity.previousBindMatrixInverse"
84
+ );
85
+ function ensureVelocityOutput(pass) {
86
+ const current = pass.getMRT();
87
+ if (current?.has(VELOCITY_OUTPUT_NAME)) return current;
88
+ const added = mrt({ [VELOCITY_OUTPUT_NAME]: velocity });
89
+ const next = current === null ? mrt({ output, [VELOCITY_OUTPUT_NAME]: velocity }) : current.merge(added);
90
+ pass.setMRT(next);
91
+ return next;
92
+ }
93
+ function velocityTexture(pass) {
94
+ ensureVelocityOutput(pass);
95
+ const node = pass.getTextureNode(VELOCITY_OUTPUT_NAME);
96
+ const target = pass.renderTarget;
97
+ const texture = node.value;
98
+ if (target !== void 0 && texture?.isTexture === true && !target.textures.includes(texture))
99
+ target.textures.push(texture);
100
+ return node;
101
+ }
102
+ function withVelocityContext(node, source) {
103
+ if (!isNode(node)) return node;
104
+ return context(node, { velocity: source });
105
+ }
106
+ function mrtVelocity() {
107
+ return { texture: velocityTexture, attach: (node) => withVelocityContext(node, velocity) };
108
+ }
109
+ var VelocityTracker = class {
110
+ #originalFlags = /* @__PURE__ */ new Map();
111
+ #instanceSnapshots = /* @__PURE__ */ new Map();
112
+ #worldSnapshots = /* @__PURE__ */ new Map();
113
+ #bindInverseSnapshots = /* @__PURE__ */ new Map();
114
+ #boneSnapshots = /* @__PURE__ */ new Map();
115
+ // The previous frame's buffers, written at the next commit. The snapshot scheduled for the frame
116
+ // that just rendered stays untouched until `update` replaces it, and steady state allocates nothing.
117
+ #spareInstances = /* @__PURE__ */ new Map();
118
+ #spareWorlds = /* @__PURE__ */ new Map();
119
+ #spareBones = /* @__PURE__ */ new Map();
120
+ /** `instanceMatrix.version` at the last commit: an unchanged mesh's history already equals it. */
121
+ #instanceVersions = /* @__PURE__ */ new Map();
122
+ #ownedBatchedMeshes = /* @__PURE__ */ new Set();
123
+ #active = /* @__PURE__ */ new Set();
124
+ #updatedRoot;
125
+ /** Schedule the committed snapshot that the current colour and velocity frame must read. */
126
+ update(root) {
127
+ this.#updatedRoot = root;
128
+ root.updateMatrixWorld(true);
129
+ const seen = /* @__PURE__ */ new Set();
130
+ const seenSkeletons = /* @__PURE__ */ new Set();
131
+ root.traverse((object) => {
132
+ if (!isVelocityRenderable(object)) return;
133
+ seen.add(object);
134
+ this.enable(object);
135
+ this.captureWorld(object);
136
+ const skeleton = getSkeleton(object);
137
+ if (skeleton !== void 0) {
138
+ if (!seenSkeletons.has(skeleton)) {
139
+ skeleton.update();
140
+ seenSkeletons.add(skeleton);
141
+ }
142
+ this.captureBones(object, skeleton);
143
+ object[VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE] = this.#bindInverseSnapshots.get(object) ?? object.bindMatrixInverse.clone();
144
+ } else {
145
+ Reflect.deleteProperty(object, VELOCITY_PREVIOUS_BONE_MATRICES);
146
+ Reflect.deleteProperty(object, VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE);
147
+ this.#bindInverseSnapshots.delete(object);
148
+ }
149
+ this.captureInstance(object);
150
+ });
151
+ for (const object of this.#active) {
152
+ if (seen.has(object)) continue;
153
+ this.restore(object);
154
+ this.#active.delete(object);
155
+ }
156
+ for (const skeleton of this.#boneSnapshots.keys()) {
157
+ if (!seenSkeletons.has(skeleton)) {
158
+ this.#boneSnapshots.delete(skeleton);
159
+ this.#spareBones.delete(skeleton);
160
+ }
161
+ }
162
+ for (const object of seen) this.#active.add(object);
163
+ }
164
+ /** Commit transforms after the renderer has consumed the scheduled velocity frame. */
165
+ commit(root) {
166
+ if (this.#updatedRoot !== root) return;
167
+ root.updateMatrixWorld(true);
168
+ const seen = /* @__PURE__ */ new Set();
169
+ const seenSkeletons = /* @__PURE__ */ new Set();
170
+ root.traverse((object) => {
171
+ if (!this.#active.has(object) || !isVelocityRenderable(object)) return;
172
+ seen.add(object);
173
+ const spare = this.#spareWorlds.get(object);
174
+ const scheduled = this.#worldSnapshots.get(object);
175
+ if (scheduled) this.#spareWorlds.set(object, scheduled);
176
+ this.#worldSnapshots.set(
177
+ object,
178
+ spare ? spare.copy(object.matrixWorld) : object.matrixWorld.clone()
179
+ );
180
+ const skeleton = getSkeleton(object);
181
+ if (skeleton !== void 0) {
182
+ this.#bindInverseSnapshots.set(object, object.bindMatrixInverse.clone());
183
+ if (!seenSkeletons.has(skeleton)) {
184
+ skeleton.update();
185
+ seenSkeletons.add(skeleton);
186
+ rotate(this.#boneSnapshots, this.#spareBones, skeleton, skeleton.boneMatrices);
187
+ }
188
+ }
189
+ this.commitInstance(object);
190
+ });
191
+ for (const object of this.#active) {
192
+ if (seen.has(object)) continue;
193
+ this.restore(object);
194
+ this.#active.delete(object);
195
+ }
196
+ }
197
+ /** Restore caller-owned flags and release all retained frame snapshots. */
198
+ clear() {
199
+ for (const object of this.#active) this.restore(object);
200
+ this.#active.clear();
201
+ this.#originalFlags.clear();
202
+ this.#instanceSnapshots.clear();
203
+ this.#worldSnapshots.clear();
204
+ this.#bindInverseSnapshots.clear();
205
+ this.#boneSnapshots.clear();
206
+ this.#spareInstances.clear();
207
+ this.#instanceVersions.clear();
208
+ this.#spareWorlds.clear();
209
+ this.#spareBones.clear();
210
+ this.#updatedRoot = void 0;
211
+ }
212
+ enable(object) {
213
+ if (!this.#originalFlags.has(object)) {
214
+ this.#originalFlags.set(object, {
215
+ present: Object.hasOwn(object.userData, "useVelocity"),
216
+ value: object.userData.useVelocity
217
+ });
218
+ }
219
+ object.userData.useVelocity = true;
220
+ }
221
+ captureWorld(object) {
222
+ const previous = this.#worldSnapshots.get(object);
223
+ const scheduledPrevious = previous ?? object.matrixWorld.clone();
224
+ object[VELOCITY_PREVIOUS_WORLD_MATRIX] = scheduledPrevious;
225
+ }
226
+ captureBones(object, skeleton) {
227
+ const current = skeleton.boneMatrices;
228
+ const previous = this.#boneSnapshots.get(skeleton);
229
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
230
+ object[VELOCITY_PREVIOUS_BONE_MATRICES] = scheduledPrevious;
231
+ }
232
+ captureInstance(object) {
233
+ const batch = getBatchedMesh(object);
234
+ if (batch !== void 0) {
235
+ this.captureBatch(object, batch);
236
+ return;
237
+ }
238
+ if (object.isInstancedMesh !== true) return;
239
+ const source = object;
240
+ const current = source.instanceMatrix?.array;
241
+ if (current === void 0) return;
242
+ const previous = this.#instanceSnapshots.get(object);
243
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
244
+ object[VELOCITY_PREVIOUS_INSTANCE_MATRICES] = scheduledPrevious;
245
+ }
246
+ captureBatch(object, batch) {
247
+ const current = batchedMatrixData(batch);
248
+ if (current === void 0) return;
249
+ if (!hasBatchedPreviousMatrices(batch)) {
250
+ ensureBatchedMeshVelocity(batch);
251
+ this.#ownedBatchedMeshes.add(batch);
252
+ }
253
+ const previous = this.#instanceSnapshots.get(object);
254
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
255
+ object[VELOCITY_PREVIOUS_INSTANCE_MATRICES] = scheduledPrevious;
256
+ if (this.#ownedBatchedMeshes.has(batch))
257
+ setBatchedMeshPreviousMatrices(batch, scheduledPrevious);
258
+ }
259
+ commitInstance(object) {
260
+ const batch = getBatchedMesh(object);
261
+ const matrices = batch === void 0 ? object.instanceMatrix : void 0;
262
+ const current = batch === void 0 ? matrices?.array : batchedMatrixData(batch);
263
+ if (current === void 0) return;
264
+ const version = matrices?.version;
265
+ if (version !== void 0 && this.#instanceVersions.get(object) === version && this.#instanceSnapshots.get(object)?.length === current.length)
266
+ return;
267
+ rotate(this.#instanceSnapshots, this.#spareInstances, object, current);
268
+ if (version !== void 0) this.#instanceVersions.set(object, version);
269
+ else this.#instanceVersions.delete(object);
270
+ }
271
+ restore(object) {
272
+ const typed = object;
273
+ const original = this.#originalFlags.get(object);
274
+ if (original === void 0 || !original.present)
275
+ Reflect.deleteProperty(typed.userData, "useVelocity");
276
+ else typed.userData.useVelocity = original.value;
277
+ const batch = getBatchedMesh(object);
278
+ if (batch !== void 0 && this.#ownedBatchedMeshes.delete(batch))
279
+ disposeBatchedMeshVelocity(batch);
280
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_INSTANCE_MATRICES);
281
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_WORLD_MATRIX);
282
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_BONE_MATRICES);
283
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE);
284
+ this.#originalFlags.delete(object);
285
+ this.#instanceSnapshots.delete(object);
286
+ this.#worldSnapshots.delete(object);
287
+ this.#spareInstances.delete(object);
288
+ this.#instanceVersions.delete(object);
289
+ this.#spareWorlds.delete(object);
290
+ this.#bindInverseSnapshots.delete(object);
291
+ }
292
+ };
293
+ function readVelocityPreviousMatrices(object) {
294
+ return object[VELOCITY_PREVIOUS_INSTANCE_MATRICES];
295
+ }
296
+ function readVelocityPreviousWorldMatrix(object) {
297
+ return object[VELOCITY_PREVIOUS_WORLD_MATRIX];
298
+ }
299
+ function readVelocityPreviousBoneMatrices(object) {
300
+ return object[VELOCITY_PREVIOUS_BONE_MATRICES];
301
+ }
302
+ function isVelocityRenderable(object) {
303
+ return object.isMesh === true || object.isLine === true || object.isPoints === true || object.isSprite === true;
304
+ }
305
+ function getSkeleton(object) {
306
+ const candidate = object;
307
+ return candidate.isSkinnedMesh === true ? candidate.skeleton : void 0;
308
+ }
309
+ function getBatchedMesh(object) {
310
+ return object.isBatchedMesh === true ? object : void 0;
311
+ }
312
+ function batchedMatrixData(mesh) {
313
+ return mesh._matricesTexture?.image?.data;
314
+ }
315
+ function hasBatchedPreviousMatrices(mesh) {
316
+ return mesh._previousMatricesTexture != null;
317
+ }
318
+ function isNode(value) {
319
+ return typeof value === "object" && value !== null && value.isNode === true;
320
+ }
321
+ function copyArray(source) {
322
+ const copy = new Float32Array(source.length);
323
+ copy.set(source);
324
+ return copy;
325
+ }
326
+ function rotate(snapshots, spares, key, source) {
327
+ const scheduled = snapshots.get(key);
328
+ const next = copyInto(spares.get(key), source);
329
+ if (scheduled) spares.set(key, scheduled);
330
+ snapshots.set(key, next);
331
+ }
332
+ function copyInto(target, source) {
333
+ if (target === void 0 || target.length !== source.length) return copyArray(source);
334
+ target.set(source);
335
+ return target;
336
+ }
337
+
338
+ // src/pipeline-census.ts
339
+ var PIPELINE_CENSUS_VERSION = 1;
340
+ var PIPELINE_CENSUS_CAPABILITY = "runtime.pipelineCensus";
341
+ var DEFAULT_PIPELINE_CENSUS_LIMIT = 512;
342
+ var DEVICE_PIPELINE_METHODS = [
343
+ ["createRenderPipeline", "render", "sync"],
344
+ ["createRenderPipelineAsync", "render", "async"],
345
+ ["createComputePipeline", "compute", "sync"],
346
+ ["createComputePipelineAsync", "compute", "async"]
347
+ ];
348
+ function createPipelineCensus(options) {
349
+ return new PipelineCensus(options);
350
+ }
351
+ var PipelineCensus = class {
352
+ #kind;
353
+ #limit;
354
+ #now;
355
+ #origin;
356
+ #clockSource;
357
+ #backendIdentity;
358
+ #buildIdentity;
359
+ #adapterIdentity;
360
+ #thermalIdentity;
361
+ #events = [];
362
+ #nodeBuildEvents = [];
363
+ #programs = /* @__PURE__ */ new Set();
364
+ #pipelines = /* @__PURE__ */ new Set();
365
+ #installed = [];
366
+ #devices = [];
367
+ #pipelineIds = /* @__PURE__ */ new WeakMap();
368
+ #backendPipelineIds = /* @__PURE__ */ new WeakMap();
369
+ /**
370
+ * Shader identity by the object that owns the source: Three's programmable stage on the backend
371
+ * path, the shader module on the device path. Keying by object rather than by text means one
372
+ * hash per source instead of one per pipeline, and no capture ever retains a shader.
373
+ */
374
+ #observations = /* @__PURE__ */ new WeakMap();
375
+ /** Distinct node-builder states, so a repeated render-object lookup is not a graph rebuild. */
376
+ #nodeBuilderStates = /* @__PURE__ */ new WeakSet();
377
+ /** Pending state-build counts keyed by Three's internal RenderObject for async compilation. */
378
+ #nodeBuilderObservations = /* @__PURE__ */ new WeakMap();
379
+ /** Device methods that exist but refused their hook, so their creations were never seen. */
380
+ #deviceRefusals = /* @__PURE__ */ new Set();
381
+ #activeRenderObject;
382
+ #nextSequence = 1;
383
+ #nextBackendPipelineIdentity = 1;
384
+ #nextLogicalPipelineIdentity = 1;
385
+ #nextDevicePipelineIdentity = 1;
386
+ #lookups = 0;
387
+ #creations = 0;
388
+ #failures = 0;
389
+ #pending = 0;
390
+ #dropped = 0;
391
+ #droppedNodeBuilds = 0;
392
+ #deviceCreations = 0;
393
+ #directCreations = 0;
394
+ #nodeBuilds = 0;
395
+ #nestedDeviceCreations = 0;
396
+ #backendDepth = 0;
397
+ #backendDeviceCalls = 0;
398
+ #deviceObserved = false;
399
+ #overflowed = false;
400
+ #unsupported = false;
401
+ #firstPresentMs;
402
+ #eventsSettledAtFirstPresent = 0;
403
+ #warmUpSettledMs;
404
+ #eventsSettledAtWarmUpSettled = 0;
405
+ #nodeBuildsAtWarmUpSettled = 0;
406
+ #renderPipelineCreationsAtWarmUpSettled = 0;
407
+ #warmUpScopes = [];
408
+ /** Scope lists keyed weakly by streamed root, so an evicted chunk graph is not kept alive here. */
409
+ #warmUpTargets = /* @__PURE__ */ new WeakMap();
410
+ /** Scopes a draw touched in the open world frame; only these reset when it closes. */
411
+ #frameWarmUpScopes = [];
412
+ #activeWarmUpScope;
413
+ #activeWorldFrame;
414
+ #nodeBuilderObservationUnavailable = false;
415
+ #cleanup;
416
+ constructor(options) {
417
+ if (!Number.isInteger(options.limit) || (options.limit ?? DEFAULT_PIPELINE_CENSUS_LIMIT) <= 0) {
418
+ if (options.limit !== void 0)
419
+ throw new Error(`TN_PIPELINE_CENSUS_LIMIT_INVALID: ${String(options.limit)}`);
420
+ }
421
+ this.#kind = options.kind;
422
+ this.#limit = options.limit ?? DEFAULT_PIPELINE_CENSUS_LIMIT;
423
+ this.#now = options.now ?? defaultNow;
424
+ this.#origin = this.#now();
425
+ this.#clockSource = typeof globalThis.performance?.now === "function" ? "performance" : "date";
426
+ this.#backendIdentity = options.backendIdentity ?? `${options.kind}:renderer`;
427
+ this.#buildIdentity = options.buildIdentity ?? `@threenative/core@${CORE_VERSION}`;
428
+ this.#adapterIdentity = options.adapterIdentity ?? this.#backendIdentity;
429
+ this.#thermalIdentity = options.thermalIdentity ?? "unavailable";
430
+ }
431
+ /** Install the backend creation hooks and the render-object context wrapper once. */
432
+ install(backendValue) {
433
+ if (!isObject(backendValue)) {
434
+ this.#unsupported = true;
435
+ return () => void 0;
436
+ }
437
+ const backend = backendValue;
438
+ if (this.#installed.some((entry) => entry.backend === backend)) return () => void 0;
439
+ const installed = { backend };
440
+ let changed = false;
441
+ if (typeof backend.createRenderPipeline === "function") {
442
+ const original = backend.createRenderPipeline;
443
+ const wrapper = (...args) => this.#observeRenderCreation(backend, original, args);
444
+ backend.createRenderPipeline = wrapper;
445
+ installed.render = original;
446
+ installed.renderWrapper = wrapper;
447
+ changed = true;
448
+ }
449
+ if (typeof backend.createComputePipeline === "function") {
450
+ const original = backend.createComputePipeline;
451
+ const wrapper = (...args) => this.#observeComputeCreation(backend, original, args);
452
+ backend.createComputePipeline = wrapper;
453
+ installed.compute = original;
454
+ installed.computeWrapper = wrapper;
455
+ changed = true;
456
+ }
457
+ if (!changed) this.#unsupported = true;
458
+ else this.#installed.push(installed);
459
+ this.#ensureDevice(backend);
460
+ return () => {
461
+ this.#restoreDevices(backend);
462
+ if (installed.render !== void 0 && backend.createRenderPipeline === installed.renderWrapper) {
463
+ backend.createRenderPipeline = installed.render;
464
+ }
465
+ if (installed.compute !== void 0 && backend.createComputePipeline === installed.computeWrapper) {
466
+ backend.createComputePipeline = installed.compute;
467
+ }
468
+ const index = this.#installed.indexOf(installed);
469
+ if (index !== -1) this.#installed.splice(index, 1);
470
+ };
471
+ }
472
+ /**
473
+ * Install the device hooks for a backend that has one, once per device. The backend is asked
474
+ * again on every creation because the device arrives with `init()` and is replaced on a device
475
+ * loss; a census that only looked at install time would stop observing the moment either
476
+ * happened. A device whose methods cannot be replaced is left alone and reported unobserved.
477
+ *
478
+ * Every method the device actually has must accept its hook. One accepted hook is not the
479
+ * device: a host that binds `createRenderPipeline` as a non-writable property while leaving
480
+ * `createComputePipeline` writable would otherwise report a complete census that never saw a
481
+ * single render creation. A method the device does not have issues no work and is not missing.
482
+ */
483
+ #ensureDevice(backend) {
484
+ if (this.#kind !== "webgpu" || !isObject(backend.device)) return;
485
+ const device = backend.device;
486
+ if (this.#devices.some((entry) => entry.device === device)) return;
487
+ const restore = [];
488
+ const refused = [];
489
+ this.#patchIfPresent(
490
+ device,
491
+ "createShaderModule",
492
+ (original) => (...args) => this.#observeShaderModule(device, original, args),
493
+ restore,
494
+ refused
495
+ );
496
+ let observed = 0;
497
+ for (const [name, kind, mode] of DEVICE_PIPELINE_METHODS) {
498
+ if (this.#patchIfPresent(
499
+ device,
500
+ name,
501
+ (original) => (...args) => this.#observeDeviceCreation(device, original, args, kind, mode),
502
+ restore,
503
+ refused
504
+ ))
505
+ observed += 1;
506
+ }
507
+ if (observed === 0) {
508
+ for (const undo of restore) undo();
509
+ return;
510
+ }
511
+ for (const name of refused) this.#deviceRefusals.add(name);
512
+ this.#devices.push({ backend, device, restore });
513
+ this.#deviceObserved = true;
514
+ }
515
+ /** Patch a method the device has, recording a refusal that must invalidate completeness. */
516
+ #patchIfPresent(device, name, build, restore, refused) {
517
+ if (typeof device[name] !== "function") return false;
518
+ if (this.#patchMethod(device, name, build, restore)) return true;
519
+ refused.push(name);
520
+ return false;
521
+ }
522
+ #patchMethod(target, name, build, restore) {
523
+ const original = target[name];
524
+ if (typeof original !== "function") return false;
525
+ const previous = original;
526
+ const owned = Object.hasOwn(target, name);
527
+ const wrapper = build(previous);
528
+ try {
529
+ target[name] = wrapper;
530
+ } catch {
531
+ return false;
532
+ }
533
+ if (target[name] !== wrapper) return false;
534
+ restore.push(() => {
535
+ if (target[name] !== wrapper) return;
536
+ if (owned) target[name] = previous;
537
+ else delete target[name];
538
+ });
539
+ return true;
540
+ }
541
+ #restoreDevices(backend) {
542
+ for (let index = this.#devices.length - 1; index >= 0; index -= 1) {
543
+ const entry = this.#devices[index];
544
+ if (entry === void 0 || entry.backend !== backend) continue;
545
+ for (const undo of entry.restore) undo();
546
+ this.#devices.splice(index, 1);
547
+ }
548
+ }
549
+ /** Install every renderer-side hook owned by this capture. */
550
+ installRenderer(renderer) {
551
+ if (this.#cleanup !== void 0) return;
552
+ const restoreBackend = this.install(renderer.backend);
553
+ const restoreNodeBuilder = this.#installNodeBuilderObservation(renderer);
554
+ const originalRenderObject = renderer.renderObject;
555
+ let wrappedRenderObject;
556
+ if (originalRenderObject !== void 0) {
557
+ const census = this;
558
+ wrappedRenderObject = function(...args) {
559
+ return census.withRenderObject(args, () => originalRenderObject.apply(this, args));
560
+ };
561
+ renderer.renderObject = wrappedRenderObject;
562
+ }
563
+ this.#cleanup = () => {
564
+ restoreNodeBuilder();
565
+ if (wrappedRenderObject !== void 0 && renderer.renderObject === wrappedRenderObject)
566
+ renderer.renderObject = originalRenderObject;
567
+ restoreBackend();
568
+ this.#cleanup = void 0;
569
+ };
570
+ }
571
+ /** Restore private hooks while retaining the immutable capture already recorded. */
572
+ dispose() {
573
+ this.#cleanup?.();
574
+ }
575
+ /** Wrap Three's public render-object method so compileAsync retains the authored pass id. */
576
+ withRenderObject(args, callback) {
577
+ const previous = this.#activeRenderObject;
578
+ const active = {
579
+ clippingContext: args[7],
580
+ object: args[0],
581
+ material: args[4],
582
+ scene: args[1],
583
+ passId: args[8],
584
+ nodeBuilds: 0
585
+ };
586
+ this.#activeRenderObject = active;
587
+ this.#observeWarmUpScopes(this.#matchingWarmUpScopes());
588
+ try {
589
+ return callback();
590
+ } finally {
591
+ this.#activeRenderObject = previous;
592
+ }
593
+ }
594
+ #matchingWarmUpScopes(active = this.#activeRenderObject) {
595
+ const activeObject = active?.object;
596
+ if (active === void 0 || this.#activeWorldFrame?.root !== active.scene || !isObject(activeObject) || !isMainWorldPass(active.passId))
597
+ return NO_WARM_UP_SCOPES;
598
+ return warmUpScopesOf(this.#warmUpTargets, activeObject);
599
+ }
600
+ #observeWarmUpScopes(scopes) {
601
+ for (const scope of scopes) {
602
+ if (scope.frameObserved) continue;
603
+ scope.frameObserved = true;
604
+ this.#frameWarmUpScopes.push(scope);
605
+ }
606
+ }
607
+ /** Begin the outer world render that can close target-bound streamed warm-up scopes. */
608
+ beginWorldFrame(root) {
609
+ this.#activeWorldFrame = { root };
610
+ }
611
+ /** Close target-bound scopes only after the complete visible world frame has returned. */
612
+ endWorldFrame(root, completed) {
613
+ const frame = this.#activeWorldFrame;
614
+ this.#activeWorldFrame = void 0;
615
+ const matches = completed && frame !== void 0 && frame.root === root;
616
+ for (const scope of this.#frameWarmUpScopes) {
617
+ if (matches && scope.firstDraw === void 0)
618
+ scope.firstDraw = {
619
+ nodeBuilds: scope.frameNodeBuilds,
620
+ renderPipelineCreations: scope.frameRenderPipelineCreations
621
+ };
622
+ scope.frameObserved = false;
623
+ scope.frameNodeBuilds = 0;
624
+ scope.frameRenderPipelineCreations = 0;
625
+ }
626
+ this.#frameWarmUpScopes = [];
627
+ }
628
+ /** Observe state creation at Three's renderer-owned NodeManager seam, never on the game Mesh. */
629
+ #installNodeBuilderObservation(renderer) {
630
+ if (this.#kind !== "webgpu" || renderer.renderObject === void 0) return () => void 0;
631
+ if (!isObject(renderer._nodes)) {
632
+ this.#nodeBuilderObservationUnavailable = true;
633
+ return () => void 0;
634
+ }
635
+ const nodes = renderer._nodes;
636
+ const original = nodes.getForRender;
637
+ if (typeof original !== "function") {
638
+ this.#nodeBuilderObservationUnavailable = true;
639
+ return () => void 0;
640
+ }
641
+ const census = this;
642
+ const restore = [];
643
+ const installed = this.#patchMethod(
644
+ nodes,
645
+ "getForRender",
646
+ (method) => function(...args) {
647
+ const result = method.apply(this, args);
648
+ return census.#observeNodeBuilderResult(args[0], result);
649
+ },
650
+ restore
651
+ );
652
+ if (!installed) {
653
+ this.#nodeBuilderObservationUnavailable = true;
654
+ return () => void 0;
655
+ }
656
+ return () => {
657
+ for (const undo of restore.splice(0).reverse()) undo();
658
+ };
659
+ }
660
+ #observeNodeBuilderResult(renderObjectValue, result) {
661
+ if (isPromiseLike(result)) {
662
+ return result.then((state2) => {
663
+ this.#recordNodeBuilderState(renderObjectValue, state2);
664
+ return state2;
665
+ });
666
+ }
667
+ this.#recordNodeBuilderState(renderObjectValue, result);
668
+ return result;
669
+ }
670
+ #recordNodeBuilderState(renderObjectValue, state2) {
671
+ if (!isObject(renderObjectValue) || !isObject(state2)) {
672
+ this.#nodeBuilderObservationUnavailable = true;
673
+ return;
674
+ }
675
+ if (this.#nodeBuilderStates.has(state2)) return;
676
+ this.#nodeBuilderStates.add(state2);
677
+ this.#nodeBuilds += 1;
678
+ const previous = this.#nodeBuilderObservations.get(renderObjectValue);
679
+ const observation = previous === void 0 || previous.state !== state2 ? {
680
+ state: state2,
681
+ builds: (previous?.builds ?? 0) + 1,
682
+ reported: false
683
+ } : previous;
684
+ this.#nodeBuilderObservations.set(renderObjectValue, observation);
685
+ if (this.#activeRenderObject !== void 0) this.#activeRenderObject.nodeBuilds += 1;
686
+ const startedMs = this.#clock();
687
+ const matching = this.#matchingWarmUpScopes();
688
+ this.#observeWarmUpScopes(matching);
689
+ for (const scope of matching) scope.frameNodeBuilds += 1;
690
+ const legacyScope = this.#activeWarmUpScope !== void 0 && startedMs > this.#activeWarmUpScope.boundaryMs ? this.#activeWarmUpScope.label : void 0;
691
+ const scopedLabel = matching.length === 1 ? matching[0]?.label : legacyScope;
692
+ const record = {
693
+ provenance: provenance(
694
+ { object: this.#activeRenderObject?.object, material: this.#activeRenderObject?.material },
695
+ this.#activeRenderObject
696
+ ),
697
+ startedMs,
698
+ beforeFirstPresent: this.#firstPresentMs === void 0 || startedMs <= this.#firstPresentMs,
699
+ ...this.#warmUpSettledMs === void 0 ? {} : { beforeWarmUpSettled: startedMs <= this.#warmUpSettledMs },
700
+ ...scopedLabel === void 0 ? {} : { afterWarmUpScope: scopedLabel }
701
+ };
702
+ if (this.#nodeBuildEvents.length < this.#limit) this.#nodeBuildEvents.push(record);
703
+ else this.#droppedNodeBuilds += 1;
704
+ }
705
+ #nodeBuildsFor(renderObjectValue) {
706
+ if (!isObject(renderObjectValue)) return this.#activeRenderObject?.nodeBuilds ?? 0;
707
+ const observation = this.#nodeBuilderObservations.get(renderObjectValue);
708
+ if (observation === void 0 || observation.reported) return 0;
709
+ observation.reported = true;
710
+ return observation.builds;
711
+ }
712
+ /** Mark the first renderer render call as the first-present boundary. */
713
+ firstPresent() {
714
+ if (this.#firstPresentMs !== void 0) return;
715
+ const boundaryMs = this.#clock();
716
+ this.#firstPresentMs = boundaryMs;
717
+ this.#eventsSettledAtFirstPresent = this.#events.filter(
718
+ (event) => event.settledMs !== void 0 && event.settledMs <= boundaryMs
719
+ ).length;
720
+ }
721
+ /** Mark the explicit shader warm-up as settled before the first measured world pass. */
722
+ warmUpSettled() {
723
+ if (this.#warmUpSettledMs !== void 0) return;
724
+ const boundaryMs = this.#clock();
725
+ this.#warmUpSettledMs = boundaryMs;
726
+ this.#eventsSettledAtWarmUpSettled = this.#events.filter(
727
+ (event) => event.settledMs !== void 0 && event.settledMs <= boundaryMs
728
+ ).length;
729
+ this.#nodeBuildsAtWarmUpSettled = this.#nodeBuilds;
730
+ this.#renderPipelineCreationsAtWarmUpSettled = this.#events.filter(
731
+ (event) => event.kind === "render" && event.status === "created" && event.settledMs !== void 0 && event.settledMs <= boundaryMs
732
+ ).length;
733
+ for (const event of this.#events) {
734
+ if (event.settledMs !== void 0) event.beforeWarmUpSettled = event.settledMs <= boundaryMs;
735
+ }
736
+ for (const nodeBuild of this.#nodeBuildEvents)
737
+ Object.assign(nodeBuild, { beforeWarmUpSettled: nodeBuild.startedMs <= boundaryMs });
738
+ }
739
+ /** Mark one repeatable streamed warm-up boundary; target-bound scopes close on their first world frame. */
740
+ warmUpScopeSettled(label, target) {
741
+ if (label.trim() === "") throw new Error("TN_PIPELINE_CENSUS_SCOPE_INVALID: empty label");
742
+ const boundaryMs = this.#clock();
743
+ const scope = {
744
+ label,
745
+ boundaryMs,
746
+ eventsSettled: this.#events.filter(
747
+ (event) => event.settledMs !== void 0 && event.settledMs <= boundaryMs
748
+ ).length,
749
+ nodeBuilds: this.#nodeBuilds,
750
+ renderPipelineCreations: this.#events.filter(
751
+ (event) => event.kind === "render" && event.status === "created" && event.settledMs !== void 0 && event.settledMs <= boundaryMs
752
+ ).length,
753
+ frameObserved: false,
754
+ frameNodeBuilds: 0,
755
+ frameRenderPipelineCreations: 0
756
+ };
757
+ this.#warmUpScopes.push(scope);
758
+ if (target !== void 0) {
759
+ const scopes = this.#warmUpTargets.get(target);
760
+ if (scopes === void 0) this.#warmUpTargets.set(target, [scope]);
761
+ else scopes.push(scope);
762
+ }
763
+ if (target === void 0) this.#activeWarmUpScope = { label, boundaryMs };
764
+ }
765
+ snapshot() {
766
+ const incompleteReasons = [];
767
+ if (this.#unsupported) incompleteReasons.push("backend creation observation unavailable");
768
+ if (this.#nodeBuilderObservationUnavailable)
769
+ incompleteReasons.push("node builder observation unavailable");
770
+ incompleteReasons.push(...this.#deviceReasons());
771
+ if (this.#adapterIdentity === "unavailable")
772
+ incompleteReasons.push("adapter identity unavailable");
773
+ if (this.#overflowed) incompleteReasons.push("bounded event buffer overflowed");
774
+ if (this.#droppedNodeBuilds > 0) incompleteReasons.push("bounded node-build buffer overflowed");
775
+ if (this.#pending > 0) incompleteReasons.push(`${this.#pending} pipeline event(s) are pending`);
776
+ if (this.#failures > 0) incompleteReasons.push(`${this.#failures} pipeline creation(s) failed`);
777
+ if (this.#creations === 0) incompleteReasons.push("no pipeline creations observed");
778
+ for (const event of this.#events) {
779
+ if (event.kind === "render" && event.vertex === void 0)
780
+ incompleteReasons.push("a render pipeline is missing its vertex shader observation");
781
+ if (event.kind === "render" && event.fragmentStagePresent === true && event.fragment === void 0)
782
+ incompleteReasons.push("a render pipeline is missing its fragment shader observation");
783
+ if (event.kind === "compute" && event.compute === void 0)
784
+ incompleteReasons.push("a compute pipeline is missing its shader observation");
785
+ }
786
+ if (this.#creations !== this.#events.length + this.#dropped)
787
+ incompleteReasons.push("observed creation count does not reconcile with recorded events");
788
+ const events = this.#events.map((event) => freezeEvent(event));
789
+ return {
790
+ version: PIPELINE_CENSUS_VERSION,
791
+ complete: incompleteReasons.length === 0 && this.#creations > 0,
792
+ overflowed: this.#overflowed,
793
+ unsupported: this.#unsupported,
794
+ limit: this.#limit,
795
+ clock: { originMs: this.#origin, source: this.#clockSource },
796
+ backend: { kind: this.#kind, identity: this.#backendIdentity },
797
+ build: { identity: this.#buildIdentity },
798
+ adapter: { identity: this.#adapterIdentity, thermal: this.#thermalIdentity },
799
+ ...this.#firstPresentMs === void 0 ? {} : {
800
+ firstPresent: {
801
+ boundaryMs: this.#firstPresentMs,
802
+ eventsSettled: this.#eventsSettledAtFirstPresent
803
+ }
804
+ },
805
+ ...this.#warmUpSettledMs === void 0 ? {} : {
806
+ warmUpSettled: {
807
+ boundaryMs: this.#warmUpSettledMs,
808
+ eventsSettled: this.#eventsSettledAtWarmUpSettled,
809
+ nodeBuilds: this.#nodeBuildsAtWarmUpSettled,
810
+ renderPipelineCreations: this.#renderPipelineCreationsAtWarmUpSettled
811
+ }
812
+ },
813
+ ...this.#warmUpScopes.length === 0 ? {} : {
814
+ warmUpScopes: this.#warmUpScopes.map((scope) => ({
815
+ label: scope.label,
816
+ boundaryMs: scope.boundaryMs,
817
+ eventsSettled: scope.eventsSettled,
818
+ nodeBuilds: scope.nodeBuilds,
819
+ renderPipelineCreations: scope.renderPipelineCreations,
820
+ ...scope.firstDraw === void 0 ? {} : { firstDraw: { ...scope.firstDraw } }
821
+ }))
822
+ },
823
+ counts: {
824
+ lookups: this.#lookups,
825
+ creations: this.#creations,
826
+ failures: this.#failures,
827
+ pending: this.#pending,
828
+ uniquePrograms: this.#programs.size,
829
+ uniquePipelines: this.#pipelines.size,
830
+ recordedEvents: this.#events.length,
831
+ droppedEvents: this.#dropped,
832
+ nodeBuilds: this.#nodeBuilds,
833
+ ...this.#deviceCounts()
834
+ },
835
+ events,
836
+ ...this.#nodeBuildEvents.length === 0 && this.#nodeBuilds === 0 ? {} : { nodeBuilds: this.#nodeBuildEvents.map((entry) => freezeNodeBuild(entry)) },
837
+ incompleteReasons
838
+ };
839
+ }
840
+ #clock() {
841
+ return Math.max(0, this.#now() - this.#origin);
842
+ }
843
+ /**
844
+ * Three creates pipelines the backend never sees, so a capture that never reached the device
845
+ * cannot claim it counted them, however many backend events it holds. A creation nested inside
846
+ * a backend creation is attributed to that backend event, and is reported here so the extra
847
+ * device call is never quietly dropped from the total. A device observed through some of its
848
+ * methods is short by whatever went through the rest, and says which method it was.
849
+ */
850
+ #deviceReasons() {
851
+ const reasons = [];
852
+ if (this.#kind === "webgpu" && !this.#deviceObserved)
853
+ reasons.push("device creation observation unavailable");
854
+ for (const name of [...this.#deviceRefusals].sort())
855
+ reasons.push(`device method ${name} could not be observed`);
856
+ if (this.#nestedDeviceCreations > 0)
857
+ reasons.push(
858
+ `${this.#nestedDeviceCreations} device pipeline creation(s) were nested inside a backend creation`
859
+ );
860
+ return reasons;
861
+ }
862
+ #deviceCounts() {
863
+ if (!this.#deviceObserved) return {};
864
+ return { deviceCreations: this.#deviceCreations, directCreations: this.#directCreations };
865
+ }
866
+ #observeRenderCreation(backend, original, args) {
867
+ this.#ensureDevice(backend);
868
+ const renderObject = isObject(args[0]) ? args[0] : {};
869
+ const pipeline = isObject(renderObject.pipeline) ? renderObject.pipeline : void 0;
870
+ const vertex = this.#programObservation(backend, pipeline?.vertexProgram);
871
+ const fragment = this.#programObservation(backend, pipeline?.fragmentProgram);
872
+ const event = this.#beginEvent({
873
+ backend,
874
+ kind: "render",
875
+ pipeline,
876
+ vertex,
877
+ fragment,
878
+ ...pipeline === void 0 ? {} : {
879
+ fragmentStagePresent: pipeline.fragmentProgram !== void 0 && pipeline.fragmentProgram !== null
880
+ },
881
+ renderObject,
882
+ mode: args[1] === null ? "sync" : "async"
883
+ });
884
+ const started = this.#now();
885
+ try {
886
+ const result = this.#throughBackend(() => original.apply(backend, [...args]));
887
+ const promises = asyncPromises(args[1]);
888
+ if (promises.length > 0) {
889
+ event.mode = "async";
890
+ event.status = "pending";
891
+ event.pending = true;
892
+ this.#pending += 1;
893
+ void Promise.all(promises).then(
894
+ () => this.#settleEvent(backend, event, started, void 0),
895
+ (error) => this.#settleEvent(backend, event, started, error)
896
+ );
897
+ } else {
898
+ this.#settleEvent(backend, event, started, void 0);
899
+ }
900
+ return result;
901
+ } catch (error) {
902
+ this.#settleEvent(backend, event, started, error);
903
+ throw error;
904
+ }
905
+ }
906
+ #observeComputeCreation(backend, original, args) {
907
+ this.#ensureDevice(backend);
908
+ const pipeline = isObject(args[0]) ? args[0] : void 0;
909
+ const compute = this.#programObservation(backend, pipeline?.computeProgram);
910
+ const event = this.#beginEvent({
911
+ backend,
912
+ kind: "compute",
913
+ pipeline,
914
+ compute,
915
+ renderObject: void 0,
916
+ mode: asyncPromises(args[2]).length > 0 ? "async" : "sync"
917
+ });
918
+ const started = this.#now();
919
+ try {
920
+ const result = this.#throughBackend(() => original.apply(backend, [...args]));
921
+ const promises = asyncPromises(args[2]);
922
+ if (promises.length > 0) {
923
+ event.mode = "async";
924
+ event.status = "pending";
925
+ event.pending = true;
926
+ this.#pending += 1;
927
+ void Promise.all(promises).then(
928
+ () => this.#settleEvent(backend, event, started, void 0),
929
+ (error) => this.#settleEvent(backend, event, started, error)
930
+ );
931
+ } else {
932
+ this.#settleEvent(backend, event, started, void 0);
933
+ }
934
+ return result;
935
+ } catch (error) {
936
+ this.#settleEvent(backend, event, started, error);
937
+ throw error;
938
+ }
939
+ }
940
+ /**
941
+ * Run a backend creation with its device calls attributed to it. Three reaches the device
942
+ * synchronously in both paths — `createRenderPipelineAsync` is called before the first `await`
943
+ * of the promise it hands back — so the depth is enough to tell a delegated creation from a
944
+ * direct one, and a second device call inside one backend creation is reported rather than lost.
945
+ */
946
+ #throughBackend(callback) {
947
+ const previousCalls = this.#backendDeviceCalls;
948
+ this.#backendDepth += 1;
949
+ this.#backendDeviceCalls = 0;
950
+ try {
951
+ return callback();
952
+ } finally {
953
+ if (this.#backendDeviceCalls > 1) this.#nestedDeviceCreations += this.#backendDeviceCalls - 1;
954
+ this.#backendDepth -= 1;
955
+ this.#backendDeviceCalls = previousCalls;
956
+ }
957
+ }
958
+ #observeShaderModule(device, original, args) {
959
+ const result = original.apply(device, [...args]);
960
+ const descriptor = isObject(args[0]) ? args[0] : void 0;
961
+ const code = typeof descriptor?.code === "string" ? descriptor.code : void 0;
962
+ if (code !== void 0 && isObject(result) && !this.#observations.has(result))
963
+ this.#observations.set(result, { bytes: utf8Bytes(code), hash: hashText(code) });
964
+ return result;
965
+ }
966
+ #observeDeviceCreation(device, original, args, kind, mode) {
967
+ this.#deviceCreations += 1;
968
+ if (this.#backendDepth > 0) {
969
+ this.#backendDeviceCalls += 1;
970
+ return original.apply(device, [...args]);
971
+ }
972
+ const descriptor = isObject(args[0]) ? args[0] : {};
973
+ const label = typeof descriptor.label === "string" ? descriptor.label : void 0;
974
+ const event = this.#beginEvent({
975
+ kind,
976
+ pipeline: void 0,
977
+ ...kind === "compute" ? { compute: this.#stageObservation(descriptor.compute) } : {
978
+ vertex: this.#stageObservation(descriptor.vertex),
979
+ fragment: this.#stageObservation(descriptor.fragment),
980
+ fragmentStagePresent: descriptor.fragment !== void 0 && descriptor.fragment !== null
981
+ },
982
+ renderObject: void 0,
983
+ // The mode describes what the call did, not which method was named: an async method that
984
+ // returns no promise settled synchronously and is timed as the device call it was.
985
+ mode: "sync",
986
+ direct: true,
987
+ ...label === void 0 || label.length === 0 ? {} : { label }
988
+ });
989
+ this.#directCreations += 1;
990
+ const started = this.#now();
991
+ try {
992
+ const result = original.apply(device, [...args]);
993
+ const promise = mode === "async" && isPromiseLike(result) ? result : void 0;
994
+ if (promise !== void 0) {
995
+ event.mode = "async";
996
+ event.status = "pending";
997
+ event.pending = true;
998
+ this.#pending += 1;
999
+ void promise.then(
1000
+ (handle) => {
1001
+ event.deviceHandle = handle;
1002
+ this.#settleEvent(void 0, event, started, void 0);
1003
+ },
1004
+ (error) => this.#settleEvent(void 0, event, started, error)
1005
+ );
1006
+ return result;
1007
+ }
1008
+ event.deviceHandle = result;
1009
+ this.#settleEvent(void 0, event, started, void 0);
1010
+ return result;
1011
+ } catch (error) {
1012
+ this.#settleEvent(void 0, event, started, error);
1013
+ throw error;
1014
+ }
1015
+ }
1016
+ #beginEvent(input) {
1017
+ this.#creations += 1;
1018
+ const matching = input.kind === "render" && input.direct !== true ? this.#matchingWarmUpScopes() : [];
1019
+ this.#observeWarmUpScopes(matching);
1020
+ for (const scope of matching) scope.frameRenderPipelineCreations += 1;
1021
+ const pipelineIdentity = input.direct === true ? `device-pipeline-${this.#nextDevicePipelineIdentity++}` : this.#logicalIdentity(input.pipeline);
1022
+ const programIdentity = input.kind === "compute" ? input.compute?.hash ?? "unknown" : `${input.vertex?.hash ?? "unknown"}/${input.fragment?.hash ?? "unknown"}`;
1023
+ this.#programs.add(programIdentity);
1024
+ this.#pipelines.add(pipelineIdentity);
1025
+ const event = {
1026
+ sequence: this.#nextSequence++,
1027
+ programIdentity,
1028
+ pipelineIdentity,
1029
+ kind: input.kind,
1030
+ ...this.#attribution(input.kind, input.direct === true, input.renderObject),
1031
+ mode: input.mode,
1032
+ status: input.mode === "async" ? "pending" : "created",
1033
+ ...input.vertex === void 0 ? {} : { vertex: input.vertex },
1034
+ ...input.fragment === void 0 ? {} : { fragment: input.fragment },
1035
+ ...input.fragmentStagePresent === void 0 ? {} : { fragmentStagePresent: input.fragmentStagePresent },
1036
+ ...input.compute === void 0 ? {} : { compute: input.compute },
1037
+ ...input.label === void 0 ? {} : { label: input.label },
1038
+ ...input.kind === "render" && input.direct !== true ? { nodeBuilds: this.#nodeBuildsFor(input.renderObject) } : {},
1039
+ ...matching.length === 1 && matching[0] !== void 0 ? { afterWarmUpScope: matching[0].label } : {},
1040
+ startedMs: this.#clock(),
1041
+ backendPipeline: input.pipeline,
1042
+ ...input.direct === true ? { direct: true } : {}
1043
+ };
1044
+ if (this.#events.length < this.#limit) this.#events.push(event);
1045
+ else {
1046
+ this.#overflowed = true;
1047
+ this.#dropped += 1;
1048
+ }
1049
+ return event;
1050
+ }
1051
+ /**
1052
+ * Who a creation belongs to. A texture can upload while a mesh is drawing, so the render object
1053
+ * in flight is not a direct creation's author: it reports what it knows — the device label it
1054
+ * already carries — and says the rest is unknown rather than borrowing a pass and a material it
1055
+ * never had.
1056
+ */
1057
+ #attribution(kind, direct, renderObject) {
1058
+ if (direct)
1059
+ return {
1060
+ pass: kind === "compute" ? "compute" : "unknown",
1061
+ provenance: { unknown: true },
1062
+ reasons: ["device-direct-creation"]
1063
+ };
1064
+ return {
1065
+ pass: kind === "compute" ? "compute" : resolvePass(
1066
+ this.#activeRenderObject?.passId,
1067
+ this.#activeRenderObject?.material,
1068
+ this.#activeRenderObject?.clippingContext,
1069
+ renderObject?.material
1070
+ ),
1071
+ provenance: provenance(renderObject, this.#activeRenderObject),
1072
+ reasons: structuralReasons(renderObject?.object, renderObject?.material)
1073
+ };
1074
+ }
1075
+ #settleEvent(backend, event, started, error) {
1076
+ const settledAt = this.#clock();
1077
+ event.settledMs = settledAt;
1078
+ event.beforeFirstPresent = this.#firstPresentMs === void 0 || settledAt <= this.#firstPresentMs;
1079
+ if (this.#warmUpSettledMs !== void 0)
1080
+ event.beforeWarmUpSettled = settledAt <= this.#warmUpSettledMs;
1081
+ if (event.afterWarmUpScope === void 0 && this.#activeWarmUpScope !== void 0 && settledAt > this.#activeWarmUpScope.boundaryMs)
1082
+ event.afterWarmUpScope = this.#activeWarmUpScope.label;
1083
+ if (event.pending === true) {
1084
+ event.pending = false;
1085
+ this.#pending = Math.max(0, this.#pending - 1);
1086
+ }
1087
+ if (event.mode === "async") event.promiseMs = Math.max(0, this.#now() - started);
1088
+ else event.serviceMs = Math.max(0, this.#now() - started);
1089
+ if (error !== void 0) {
1090
+ event.status = "failed";
1091
+ event.error = error instanceof Error ? error.message : String(error);
1092
+ this.#failures += 1;
1093
+ return;
1094
+ }
1095
+ const pipeline = event.direct === true ? event.deviceHandle : this.#backendPipeline(backend, event.backendPipeline);
1096
+ if (pipeline === void 0 && this.#kind === "webgpu") {
1097
+ event.status = "failed";
1098
+ event.error = event.direct === true ? `device did not return a created ${event.kind} pipeline` : `backend did not expose a created ${event.kind} pipeline`;
1099
+ this.#failures += 1;
1100
+ return;
1101
+ }
1102
+ if (pipeline !== void 0 && this.#kind === "webgpu") {
1103
+ this.#replacePipelineIdentity(event, this.#backendPipelineIdentity(pipeline, event.kind));
1104
+ }
1105
+ event.deviceHandle = void 0;
1106
+ event.status = "created";
1107
+ }
1108
+ /**
1109
+ * Shader identity for a Three programmable stage, hashed once per stage rather than per use.
1110
+ *
1111
+ * The module was already hashed when the device made it, and Three keeps that same object at
1112
+ * `backend.get(stage).module.module` — the seam `WebGPUPipelineUtils` reads to build the
1113
+ * pipeline descriptor. Reuse it and the source is never hashed twice. A backend that exposes
1114
+ * no module for the stage (WebGL2, or a device hooked after its modules were built) falls back
1115
+ * to hashing the stage source, still once, cached on the stage object rather than by its text.
1116
+ */
1117
+ #programObservation(backend, program) {
1118
+ if (!isObject(program)) return void 0;
1119
+ const cached = this.#observations.get(program);
1120
+ if (cached !== void 0) return cached;
1121
+ const shared = this.#moduleObservation(backend, program);
1122
+ const observed = shared ?? shaderObservation(program);
1123
+ if (observed !== void 0) this.#observations.set(program, observed);
1124
+ return observed;
1125
+ }
1126
+ /** The observation of the shader module Three built for a stage, when the hooks recorded one. */
1127
+ #moduleObservation(backend, program) {
1128
+ if (typeof backend?.get !== "function") return void 0;
1129
+ let stage;
1130
+ try {
1131
+ const data = backend.get(program);
1132
+ stage = isObject(data) ? data.module : void 0;
1133
+ } catch {
1134
+ return void 0;
1135
+ }
1136
+ if (!isObject(stage)) return void 0;
1137
+ return this.#observations.get(isObject(stage.module) ? stage.module : stage);
1138
+ }
1139
+ /** Shader identity for a device stage descriptor, absent when its module predates the hooks. */
1140
+ #stageObservation(stage) {
1141
+ const module = isObject(stage) ? stage.module : void 0;
1142
+ return isObject(module) ? this.#observations.get(module) : void 0;
1143
+ }
1144
+ #backendPipeline(backend, pipeline) {
1145
+ if (this.#kind !== "webgpu") return pipeline === void 0 ? void 0 : pipeline;
1146
+ if (typeof backend?.get !== "function" || pipeline === void 0) return void 0;
1147
+ this.#lookups += 1;
1148
+ try {
1149
+ const data = backend.get(pipeline);
1150
+ return isObject(data) && data.pipeline !== void 0 && data.pipeline !== null ? data.pipeline : void 0;
1151
+ } catch {
1152
+ return void 0;
1153
+ }
1154
+ }
1155
+ #logicalIdentity(pipeline) {
1156
+ const candidate = pipeline;
1157
+ if (isObject(candidate)) {
1158
+ const existing = this.#pipelineIds.get(candidate);
1159
+ if (existing !== void 0) return existing;
1160
+ const identity = `logical-pipeline-${this.#nextLogicalPipelineIdentity++}`;
1161
+ this.#pipelineIds.set(candidate, identity);
1162
+ return identity;
1163
+ }
1164
+ const cacheKey = typeof pipeline?.cacheKey === "string" ? pipeline.cacheKey : void 0;
1165
+ if (cacheKey !== void 0) return `cache-${hashText(cacheKey)}`;
1166
+ return "logical-pipeline-unknown";
1167
+ }
1168
+ #backendPipelineIdentity(pipeline, kind) {
1169
+ if (!isObject(pipeline)) return "backend-pipeline-unknown";
1170
+ const nativeId = pipeline._pipelineId;
1171
+ if (typeof nativeId === "number" && Number.isSafeInteger(nativeId) && nativeId > 0) {
1172
+ return `native-${kind}-${nativeId}`;
1173
+ }
1174
+ const existing = this.#backendPipelineIds.get(pipeline);
1175
+ if (existing !== void 0) return existing;
1176
+ const identity = `backend-pipeline-${this.#nextBackendPipelineIdentity++}`;
1177
+ this.#backendPipelineIds.set(pipeline, identity);
1178
+ return identity;
1179
+ }
1180
+ #replacePipelineIdentity(event, identity) {
1181
+ if (event.pipelineIdentity === identity) return;
1182
+ this.#pipelines.delete(event.pipelineIdentity);
1183
+ event.pipelineIdentity = identity;
1184
+ this.#pipelines.add(identity);
1185
+ }
1186
+ };
1187
+ function defaultNow() {
1188
+ return typeof globalThis.performance?.now === "function" ? globalThis.performance.now() : Date.now();
1189
+ }
1190
+ function isObject(value) {
1191
+ return typeof value === "object" && value !== null;
1192
+ }
1193
+ function shaderObservation(program) {
1194
+ const code = program?.code;
1195
+ if (typeof code !== "string") return void 0;
1196
+ return { bytes: utf8Bytes(code), hash: hashText(code) };
1197
+ }
1198
+ function utf8Bytes(value) {
1199
+ if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(value).byteLength;
1200
+ return unescape(encodeURIComponent(value)).length;
1201
+ }
1202
+ function hashText(value) {
1203
+ let hash = 0xcbf29ce484222325n;
1204
+ const bytes = typeof TextEncoder !== "undefined" ? new TextEncoder().encode(value) : [...unescape(encodeURIComponent(value))].map((character) => character.charCodeAt(0));
1205
+ for (const byte of bytes) {
1206
+ hash ^= BigInt(byte);
1207
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
1208
+ }
1209
+ return hash.toString(16).padStart(16, "0");
1210
+ }
1211
+ function isPromiseLike(value) {
1212
+ return isObject(value) && typeof value.then === "function";
1213
+ }
1214
+ function isMainWorldPass(passId) {
1215
+ return passId === void 0 || passId === null || passId === "main";
1216
+ }
1217
+ var NO_WARM_UP_SCOPES = [];
1218
+ function warmUpScopesOf(targets, value) {
1219
+ const userData = value.userData;
1220
+ const chunkRoot = isObject(userData) ? userData.tnChunkRoot : void 0;
1221
+ let found = addWarmUpScopes(void 0, targets.get(value));
1222
+ if (isObject(chunkRoot)) found = addWarmUpScopes(found, targets.get(chunkRoot));
1223
+ for (let current = value.parent; isObject(current); current = current.parent)
1224
+ found = addWarmUpScopes(found, targets.get(current));
1225
+ return found ?? NO_WARM_UP_SCOPES;
1226
+ }
1227
+ function addWarmUpScopes(found, scopes) {
1228
+ if (scopes === void 0) return found;
1229
+ const next = found ?? [];
1230
+ for (const scope of scopes) if (!next.includes(scope)) next.push(scope);
1231
+ return next;
1232
+ }
1233
+ function asyncPromises(value) {
1234
+ if (!Array.isArray(value)) return [];
1235
+ return value.slice().filter(
1236
+ (candidate) => isObject(candidate) && typeof candidate.then === "function"
1237
+ );
1238
+ }
1239
+ function resolvePass(passId, material, clippingContext, secondaryMaterial) {
1240
+ if (typeof passId === "string" && passId.length > 0) return passId;
1241
+ const clippingRecord = isObject(clippingContext) ? clippingContext : void 0;
1242
+ if (clippingRecord?.shadowPass === true) return "shadow";
1243
+ for (const candidate of [secondaryMaterial, material]) {
1244
+ const materialRecord = isObject(candidate) ? candidate : void 0;
1245
+ if (materialRecord !== void 0 && (materialRecord.isShadowPassMaterial === true || isShadowMaterial(materialRecord)))
1246
+ return "shadow";
1247
+ const name = typeof materialRecord?.name === "string" ? materialRecord.name : "";
1248
+ if (/^PMREM_/u.test(name)) return "pmrem";
1249
+ if (name === "outputColorTransform" || name === "RenderPipeline") return "output";
1250
+ }
1251
+ if (clippingContext !== void 0 && clippingContext !== null) return "main-clipped";
1252
+ return "main";
1253
+ }
1254
+ function isShadowMaterial(material) {
1255
+ const type = typeof material.type === "string" ? material.type : "";
1256
+ const name = typeof material.name === "string" ? material.name : "";
1257
+ return /shadow|depth/u.test(`${type} ${name}`);
1258
+ }
1259
+ function provenance(renderObject, active) {
1260
+ const material = active?.material ?? renderObject?.material;
1261
+ const object = active?.object ?? renderObject?.object;
1262
+ const materialRecord = isObject(material) ? material : void 0;
1263
+ const objectRecord = isObject(object) ? object : void 0;
1264
+ const materialValue = materialRecord === void 0 ? void 0 : {
1265
+ ...finiteNumber(materialRecord.id) ? { id: materialRecord.id } : {},
1266
+ ...typeof materialRecord.name === "string" && materialRecord.name.length > 0 ? { name: materialRecord.name } : {},
1267
+ ...typeof materialRecord.type === "string" ? { type: materialRecord.type } : {}
1268
+ };
1269
+ const objectValue = objectRecord === void 0 ? void 0 : {
1270
+ ...finiteNumber(objectRecord.id) ? { id: objectRecord.id } : {},
1271
+ ...typeof objectRecord.name === "string" && objectRecord.name.length > 0 ? { name: objectRecord.name } : {},
1272
+ ...typeof objectRecord.uuid === "string" ? { uuid: objectRecord.uuid } : {}
1273
+ };
1274
+ return {
1275
+ ...materialValue === void 0 ? {} : { material: materialValue },
1276
+ ...objectValue === void 0 ? {} : { object: objectValue },
1277
+ unknown: materialValue === void 0 && objectValue === void 0
1278
+ };
1279
+ }
1280
+ function structuralReasons(object, material) {
1281
+ const reasons = [];
1282
+ const objectRecord = isObject(object) ? object : void 0;
1283
+ const materialRecord = isObject(material) ? material : void 0;
1284
+ if (objectRecord?.isSkinnedMesh === true || materialRecord?.skinning === true)
1285
+ reasons.push("skinning");
1286
+ if (objectRecord?.isInstancedMesh === true) reasons.push("instancing");
1287
+ if (materialRecord !== void 0) {
1288
+ for (const [key, label] of [
1289
+ ["map", "map"],
1290
+ ["normalMap", "normal-map"],
1291
+ ["roughnessMap", "roughness-map"],
1292
+ ["metalnessMap", "metalness-map"],
1293
+ ["alphaMap", "alpha-map"],
1294
+ ["envMap", "environment-map"],
1295
+ ["clipping", "clipping"]
1296
+ ]) {
1297
+ if (materialRecord[key] !== void 0 && materialRecord[key] !== null && materialRecord[key] !== false)
1298
+ reasons.push(label);
1299
+ }
1300
+ }
1301
+ if (reasons.length === 0) reasons.push("unknown-structural-difference");
1302
+ return reasons;
1303
+ }
1304
+ function finiteNumber(value) {
1305
+ return typeof value === "number" && Number.isFinite(value);
1306
+ }
1307
+ function freezeEvent(event) {
1308
+ return {
1309
+ sequence: event.sequence,
1310
+ programIdentity: event.programIdentity,
1311
+ pipelineIdentity: event.pipelineIdentity,
1312
+ kind: event.kind,
1313
+ pass: event.pass,
1314
+ mode: event.mode,
1315
+ status: event.status,
1316
+ ...event.vertex === void 0 ? {} : { vertex: { ...event.vertex } },
1317
+ ...event.fragment === void 0 ? {} : { fragment: { ...event.fragment } },
1318
+ ...event.compute === void 0 ? {} : { compute: { ...event.compute } },
1319
+ provenance: {
1320
+ ...event.provenance.material === void 0 ? {} : { material: { ...event.provenance.material } },
1321
+ ...event.provenance.object === void 0 ? {} : { object: { ...event.provenance.object } },
1322
+ unknown: event.provenance.unknown
1323
+ },
1324
+ ...event.label === void 0 ? {} : { label: event.label },
1325
+ reasons: [...event.reasons],
1326
+ startedMs: event.startedMs,
1327
+ ...event.settledMs === void 0 ? {} : { settledMs: event.settledMs },
1328
+ ...event.serviceMs === void 0 ? {} : { serviceMs: event.serviceMs },
1329
+ ...event.promiseMs === void 0 ? {} : { promiseMs: event.promiseMs },
1330
+ ...event.error === void 0 ? {} : { error: event.error },
1331
+ ...event.nodeBuilds === void 0 ? {} : { nodeBuilds: event.nodeBuilds },
1332
+ ...event.beforeFirstPresent === void 0 ? {} : { beforeFirstPresent: event.beforeFirstPresent },
1333
+ ...event.beforeWarmUpSettled === void 0 ? {} : { beforeWarmUpSettled: event.beforeWarmUpSettled },
1334
+ ...event.afterWarmUpScope === void 0 ? {} : { afterWarmUpScope: event.afterWarmUpScope }
1335
+ };
1336
+ }
1337
+ function freezeNodeBuild(entry) {
1338
+ return {
1339
+ provenance: {
1340
+ ...entry.provenance.material === void 0 ? {} : { material: { ...entry.provenance.material } },
1341
+ ...entry.provenance.object === void 0 ? {} : { object: { ...entry.provenance.object } },
1342
+ unknown: entry.provenance.unknown
1343
+ },
1344
+ startedMs: entry.startedMs,
1345
+ ...entry.beforeFirstPresent === void 0 ? {} : { beforeFirstPresent: entry.beforeFirstPresent },
1346
+ ...entry.beforeWarmUpSettled === void 0 ? {} : { beforeWarmUpSettled: entry.beforeWarmUpSettled },
1347
+ ...entry.afterWarmUpScope === void 0 ? {} : { afterWarmUpScope: entry.afterWarmUpScope }
1348
+ };
1349
+ }
1350
+
1351
+ // src/render/chain.ts
1352
+ var RENDER_CHAIN_MARKER = "TN_RENDER_CHAIN";
1353
+ var RENDER_CHAIN_STAGE_ORDER = [
1354
+ "probeVolume",
1355
+ "ambientOcclusion",
1356
+ "ssgi",
1357
+ "godRays",
1358
+ "ssr",
1359
+ "denoise",
1360
+ "temporalReproject",
1361
+ "taa",
1362
+ "traa",
1363
+ "motionBlur",
1364
+ "sharpen",
1365
+ "bloom",
1366
+ "vignette",
1367
+ "lensDistortion",
1368
+ "sparkle",
1369
+ "gradualBackground"
1370
+ ];
1371
+ var TIER_LEVEL = {
1372
+ high: 3,
1373
+ low: 1,
1374
+ medium: 2,
1375
+ off: 0
1376
+ };
1377
+ var RENDER_CHAIN_TIERS = {
1378
+ high: { denoiseIterations: 3, sliceCount: 3, ssrMaxSteps: 32, stepCount: 16 },
1379
+ low: { denoiseIterations: 1, sliceCount: 1, ssrMaxSteps: 8, stepCount: 12 },
1380
+ medium: { denoiseIterations: 2, sliceCount: 2, ssrMaxSteps: 16, stepCount: 8 },
1381
+ off: { denoiseIterations: 0, sliceCount: 0, ssrMaxSteps: 0, stepCount: 0 }
1382
+ };
1383
+ var VELOCITY_STAGES = /* @__PURE__ */ new Set([
1384
+ "motionBlur",
1385
+ "taa",
1386
+ "temporalReproject",
1387
+ "traa"
1388
+ ]);
1389
+ var REPORT_KEY = /* @__PURE__ */ Symbol.for("threenative.renderChain.report");
1390
+ function storedReport(target) {
1391
+ return target[REPORT_KEY];
1392
+ }
1393
+ function storeReport(target, marker) {
1394
+ Object.defineProperty(target, REPORT_KEY, {
1395
+ configurable: true,
1396
+ enumerable: false,
1397
+ value: marker,
1398
+ writable: true
1399
+ });
1400
+ }
1401
+ function readRenderChainReport(renderer) {
1402
+ if (!isObject2(renderer)) return void 0;
1403
+ const raw = readRawRenderer(renderer);
1404
+ return storedReport(renderer) ?? (isObject2(raw) ? storedReport(raw) : void 0);
1405
+ }
1406
+ function readRenderChainObservation(renderer) {
1407
+ return readRenderChainReport(renderer)?.applied;
1408
+ }
1409
+ function publishDirectRenderChainReport(renderer, tier, dropped, report = (line) => console.log(line)) {
1410
+ const marker = {
1411
+ applied: { ...emptyApplied([], tier, "pinned", false), dropped },
1412
+ marker: RENDER_CHAIN_MARKER
1413
+ };
1414
+ rememberReport(renderer, marker);
1415
+ report(`${RENDER_CHAIN_MARKER}:${JSON.stringify(marker)}`);
1416
+ return () => forgetReport(renderer);
1417
+ }
1418
+ var RenderChain = class {
1419
+ #renderer;
1420
+ #input;
1421
+ #worldPass;
1422
+ #resolutionSubrect;
1423
+ #report;
1424
+ #stageDefinitions;
1425
+ #requested;
1426
+ #requestVelocity;
1427
+ #automatic;
1428
+ #targetFps;
1429
+ #dwellWindows;
1430
+ #scene;
1431
+ #activeStageDefinitions = [];
1432
+ #tier;
1433
+ #source;
1434
+ #overBudgetWindows = 0;
1435
+ #lastMeasurementFrame;
1436
+ #reportedMeasurement = false;
1437
+ #velocityResultNode = void 0;
1438
+ #velocityResultReader = void 0;
1439
+ #ownedVelocityPass = void 0;
1440
+ #ownedVelocityMrt = void 0;
1441
+ #ownedVelocityTexture = void 0;
1442
+ #disposed = false;
1443
+ #installedNode;
1444
+ #installation;
1445
+ #applied;
1446
+ constructor(rendererOrOptions, suppliedOptions = {}) {
1447
+ const options = isRenderer(rendererOrOptions) ? { ...suppliedOptions, renderer: rendererOrOptions } : rendererOrOptions;
1448
+ this.#renderer = options.renderer;
1449
+ this.#input = options.input;
1450
+ this.#worldPass = options.worldPass;
1451
+ this.#resolutionSubrect = options.resolutionSubrect;
1452
+ this.#report = options.report ?? ((line) => console.log(line));
1453
+ this.#stageDefinitions = createStageDefinitions(options.stages ?? []);
1454
+ this.#requested = normalizeRequestedStages(
1455
+ options.request?.stages ?? [],
1456
+ this.#stageDefinitions
1457
+ );
1458
+ this.#requestVelocity = options.request?.velocity ?? {};
1459
+ this.#automatic = (options.request?.tier ?? "high") === "auto";
1460
+ this.#tier = this.#automatic ? "high" : validateTier(options.request?.tier ?? "high");
1461
+ this.#source = this.#automatic ? "auto" : "pinned";
1462
+ this.#targetFps = requirePositiveNumber(options.targetFps ?? 60, "targetFps");
1463
+ this.#dwellWindows = requirePositiveInteger(options.dwellWindows ?? 2, "dwellWindows");
1464
+ this.#scene = options.scene;
1465
+ this.#applied = emptyApplied(this.#requested, this.#tier, this.#source, false);
1466
+ this.apply();
1467
+ }
1468
+ get applied() {
1469
+ return this.#applied;
1470
+ }
1471
+ get disposed() {
1472
+ return this.#disposed;
1473
+ }
1474
+ /** Rebuild and install the current tier. */
1475
+ apply() {
1476
+ if (this.#disposed) throw new Error("RenderChain.apply called after dispose().");
1477
+ this.#disposeActiveStages();
1478
+ this.#restoreOwnedVelocityOutput();
1479
+ this.#velocityResultNode = void 0;
1480
+ this.#velocityResultReader = void 0;
1481
+ if (this.#requested.length === 0) {
1482
+ this.#applied = emptyApplied([], this.#tier, this.#source, false);
1483
+ this.#lastMeasurementFrame = void 0;
1484
+ this.#reportedMeasurement = false;
1485
+ this.#renderer.setRenderChainVelocityEnabled?.(false);
1486
+ forgetReport(this.#renderer);
1487
+ return this.#applied;
1488
+ }
1489
+ const requiredVelocity = this.#requested.some(
1490
+ (name) => requiresVelocityFor(this.#stageDefinitions.get(name), name)
1491
+ );
1492
+ const velocity2 = resolveVelocity(
1493
+ this.#renderer,
1494
+ this.#requestVelocity,
1495
+ this.#scene,
1496
+ requiredVelocity
1497
+ );
1498
+ let velocityNode;
1499
+ let attachVelocity;
1500
+ const originalMrt = this.#requestVelocity.pass?.getMRT();
1501
+ this.#lastMeasurementFrame = void 0;
1502
+ this.#reportedMeasurement = false;
1503
+ const dropped = [];
1504
+ const contributions = [];
1505
+ const stages = [];
1506
+ const builtStageDefinitions = [];
1507
+ let node = this.#input;
1508
+ for (const name of this.#requested) {
1509
+ if (this.#tier === "off") {
1510
+ dropped.push({ name, reason: "tier:off" });
1511
+ continue;
1512
+ }
1513
+ const definition = this.#stageDefinitions.get(name);
1514
+ if (definition === void 0) {
1515
+ dropped.push({ name, reason: "provider:missing" });
1516
+ continue;
1517
+ }
1518
+ if (this.#renderer.kind !== "webgpu") {
1519
+ dropped.push({ name, reason: `renderer:${this.#renderer.kind}` });
1520
+ continue;
1521
+ }
1522
+ if (definition.minimumTier !== void 0 && TIER_LEVEL[this.#tier] < TIER_LEVEL[definition.minimumTier]) {
1523
+ dropped.push({ name, reason: `tier:${this.#tier}` });
1524
+ continue;
1525
+ }
1526
+ const requiresVelocity = requiresVelocityFor(definition, name);
1527
+ if (requiresVelocity && !velocity2.provisioned) {
1528
+ dropped.push({ name, reason: "velocity:missing" });
1529
+ continue;
1530
+ }
1531
+ const context2 = stageContext(
1532
+ this.#tier,
1533
+ velocity2,
1534
+ velocityNode,
1535
+ this.#resolutionSubrect?.view
1536
+ );
1537
+ const availability = definition.available?.(context2);
1538
+ if (availability === false) {
1539
+ dropped.push({ name, reason: `unavailable:${this.#renderer.kind}` });
1540
+ continue;
1541
+ }
1542
+ if (typeof availability === "string") {
1543
+ dropped.push({ name, reason: availability });
1544
+ continue;
1545
+ }
1546
+ try {
1547
+ if (requiresVelocity && velocityNode === void 0 && velocity2.source === "mrt" && this.#requestVelocity.pass !== void 0) {
1548
+ const pass = this.#requestVelocity.pass;
1549
+ const priorTextures = [...pass.renderTarget?.textures ?? []];
1550
+ const provision = this.#requestVelocity.provision ?? mrtVelocity();
1551
+ velocityNode = provision.texture(pass);
1552
+ attachVelocity = provision.attach;
1553
+ this.#ownedVelocityPass = pass;
1554
+ this.#ownedVelocityMrt = originalMrt;
1555
+ if (originalMrt?.has(VELOCITY_OUTPUT_NAME) !== true)
1556
+ this.#ownedVelocityTexture = pass.renderTarget?.textures.find(
1557
+ (texture) => texture.name === VELOCITY_OUTPUT_NAME && !priorTextures.includes(texture)
1558
+ );
1559
+ }
1560
+ const buildContext = stageContext(
1561
+ this.#tier,
1562
+ velocity2,
1563
+ velocityNode,
1564
+ this.#resolutionSubrect?.view
1565
+ );
1566
+ const next = definition.build(node, buildContext);
1567
+ if (next === void 0 || next === null) throw new Error("stage returned no node");
1568
+ contributions.push({ graphOutputChanged: next !== node, name });
1569
+ node = next;
1570
+ stages.push(name);
1571
+ builtStageDefinitions.push(definition);
1572
+ if (requiresVelocity && definition.readVelocityResult !== void 0) {
1573
+ this.#velocityResultNode = next;
1574
+ this.#velocityResultReader = definition.readVelocityResult;
1575
+ }
1576
+ } catch (error) {
1577
+ definition.dispose?.();
1578
+ dropped.push({ name, reason: `build:${errorMessage(error)}` });
1579
+ }
1580
+ }
1581
+ const hasActiveVelocityStage = stages.some(
1582
+ (name) => requiresVelocityFor(this.#stageDefinitions.get(name), name)
1583
+ );
1584
+ if (velocityNode !== void 0 && attachVelocity !== void 0 && hasActiveVelocityStage)
1585
+ node = attachVelocity(node, velocityNode);
1586
+ if (stages.length > 0) {
1587
+ try {
1588
+ const outputOptions = builtStageDefinitions.some(
1589
+ (definition) => definition.afterOutputTransform === true
1590
+ ) ? [{ outputColorTransform: false }] : [];
1591
+ if (this.#resolutionSubrect !== void 0) {
1592
+ const refused = builtStageDefinitions.filter((stage) => stage.supportsResolutionSubrect !== true).map((stage) => stage.name);
1593
+ this.#report(
1594
+ `TN_RESOLUTION_SUBRECT ${JSON.stringify({ applied: refused.length === 0 ? stages : [], refused: refused.map((name) => ({ name, reason: "sampling support not declared" })) })}`
1595
+ );
1596
+ if (refused.length === 0) {
1597
+ if (outputOptions.length === 0)
1598
+ outputOptions.push({ resolutionSubrect: this.#resolutionSubrect });
1599
+ else
1600
+ outputOptions[0] = {
1601
+ ...outputOptions[0],
1602
+ resolutionSubrect: this.#resolutionSubrect
1603
+ };
1604
+ }
1605
+ }
1606
+ const installation = this.#renderer.setOutputNode(
1607
+ node,
1608
+ this.#worldPass ?? this.#requestVelocity.pass,
1609
+ ...outputOptions
1610
+ );
1611
+ this.#installation = installation && typeof installation.isCurrent === "function" && typeof installation.dispose === "function" ? installation : void 0;
1612
+ this.#installedNode = node;
1613
+ } catch (error) {
1614
+ const reason = `install:${errorMessage(error)}`;
1615
+ dropped.push(...stages.map((name) => ({ name, reason })));
1616
+ stages.length = 0;
1617
+ contributions.length = 0;
1618
+ for (const definition of builtStageDefinitions) definition.dispose?.();
1619
+ builtStageDefinitions.length = 0;
1620
+ this.#renderer.clearOutputNode?.(node);
1621
+ this.#clearOwnedOutput();
1622
+ }
1623
+ } else {
1624
+ this.#clearOwnedOutput();
1625
+ }
1626
+ const activeVelocity = stages.some(
1627
+ (name) => requiresVelocityFor(this.#stageDefinitions.get(name), name)
1628
+ );
1629
+ if (!activeVelocity) {
1630
+ this.#restoreOwnedVelocityOutput();
1631
+ this.#velocityResultNode = void 0;
1632
+ this.#velocityResultReader = void 0;
1633
+ }
1634
+ const appliedVelocity = activeVelocity ? velocity2 : { provisioned: false, required: velocity2.required, source: null };
1635
+ this.#applied = {
1636
+ contributions,
1637
+ dropped,
1638
+ requested: this.#requested,
1639
+ source: this.#source,
1640
+ stages,
1641
+ tier: this.#tier,
1642
+ velocity: appliedVelocity
1643
+ };
1644
+ this.#activeStageDefinitions = builtStageDefinitions;
1645
+ this.#renderer.setRenderChainVelocityEnabled?.(
1646
+ stages.some((name) => requiresVelocityFor(this.#stageDefinitions.get(name), name))
1647
+ );
1648
+ this.#publish(true);
1649
+ return this.#applied;
1650
+ }
1651
+ /** Samples the active temporal stage's completed velocity result after rendering. */
1652
+ observeFrame() {
1653
+ if (this.#disposed) throw new Error("RenderChain.observeFrame called after dispose().");
1654
+ if (this.#installation?.isCurrent() === false) return this.#applied;
1655
+ this.#observeStageSizes();
1656
+ const requiresMeasurement = this.#applied.stages.some(
1657
+ (name) => requiresVelocityFor(this.#stageDefinitions.get(name), name)
1658
+ );
1659
+ if (!requiresMeasurement) return this.#applied;
1660
+ const result = this.#velocityResultReader?.(this.#velocityResultNode);
1661
+ const measurement = result === void 0 ? validateCompatibilityMeasurement(
1662
+ this.#requestVelocity.rejectionMeasurement?.(),
1663
+ this.#lastMeasurementFrame
1664
+ ) : deriveVelocityMeasurement(result, this.#lastMeasurementFrame);
1665
+ if (measurement === void 0) {
1666
+ this.#setMeasurement(void 0, false);
1667
+ return this.#applied;
1668
+ }
1669
+ this.#lastMeasurementFrame = measurement.frame;
1670
+ this.#setMeasurement(measurement, !this.#reportedMeasurement || measurement.frame % 60 === 0);
1671
+ return this.#applied;
1672
+ }
1673
+ /** Feed the chain the same render-window evidence used by the frame budget. */
1674
+ observeFrameBudget(window) {
1675
+ if (this.#disposed) throw new Error("RenderChain.observeFrameBudget called after dispose().");
1676
+ if (!this.#automatic || this.#installation?.isCurrent() === false) return this.#tier;
1677
+ const renderP95 = window.phases.render?.p95;
1678
+ if (typeof renderP95 !== "number" || !Number.isFinite(renderP95) || renderP95 < 0) {
1679
+ throw new Error("RenderChain frame budget render.p95 must be a finite non-negative number.");
1680
+ }
1681
+ const compiling = window.surface?.compiling;
1682
+ if (compiling !== void 0 && typeof compiling !== "boolean") {
1683
+ throw new Error(
1684
+ "RenderChain frame budget surface.compiling must be a boolean when observed."
1685
+ );
1686
+ }
1687
+ if (compiling === true) {
1688
+ this.#overBudgetWindows = 0;
1689
+ return this.#tier;
1690
+ }
1691
+ const budgetMs = 1e3 / this.#targetFps;
1692
+ if (renderP95 > budgetMs) this.#overBudgetWindows += 1;
1693
+ else this.#overBudgetWindows = 0;
1694
+ if (this.#overBudgetWindows >= this.#dwellWindows) {
1695
+ this.#overBudgetWindows = 0;
1696
+ const next = nextLowerTier(this.#tier);
1697
+ if (next !== this.#tier) {
1698
+ this.#tier = next;
1699
+ this.#source = "auto";
1700
+ this.apply();
1701
+ }
1702
+ }
1703
+ return this.#tier;
1704
+ }
1705
+ dispose() {
1706
+ if (this.#disposed) return;
1707
+ this.#disposed = true;
1708
+ this.#disposeActiveStages();
1709
+ this.#restoreOwnedVelocityOutput();
1710
+ this.#renderer.setRenderChainVelocityEnabled?.(false);
1711
+ this.#clearOwnedOutput();
1712
+ forgetReport(this.#renderer);
1713
+ }
1714
+ #clearOwnedOutput() {
1715
+ if (this.#installation !== void 0) this.#installation.dispose();
1716
+ else if (this.#installedNode !== void 0)
1717
+ this.#renderer.clearOutputNode?.(this.#installedNode);
1718
+ this.#installation = void 0;
1719
+ this.#installedNode = void 0;
1720
+ }
1721
+ #observeStageSizes() {
1722
+ const raw = this.#renderer.raw;
1723
+ const engine = isObject2(raw) && isObject2(raw.info) ? raw.info.engine : void 0;
1724
+ const temporal = isObject2(engine) ? engine.temporal : void 0;
1725
+ const dimensions = isObject2(temporal) ? [temporal.inputWidth, temporal.inputHeight, temporal.outputWidth, temporal.outputHeight] : [];
1726
+ const sizes = this.#applied.stages.includes("traa") && isObject2(temporal) && temporal.active === true && dimensions.length === 4 && dimensions.every(
1727
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0
1728
+ ) ? dimensions : void 0;
1729
+ const old = this.#applied.stageSizes?.traa;
1730
+ if (sizes === void 0 && old === void 0) return;
1731
+ if (sizes !== void 0 && old !== void 0 && old.input[0] === sizes[0] && old.input[1] === sizes[1] && old.output[0] === sizes[2] && old.output[1] === sizes[3])
1732
+ return;
1733
+ const { stageSizes: _previousSizes, ...applied } = this.#applied;
1734
+ this.#applied = {
1735
+ ...applied,
1736
+ ...sizes === void 0 ? {} : {
1737
+ stageSizes: {
1738
+ traa: { input: [sizes[0], sizes[1]], output: [sizes[2], sizes[3]] }
1739
+ }
1740
+ }
1741
+ };
1742
+ this.#publish(true);
1743
+ }
1744
+ #setMeasurement(measurement, emit) {
1745
+ const { provisioned, required, source } = this.#applied.velocity;
1746
+ this.#applied = {
1747
+ ...this.#applied,
1748
+ velocity: {
1749
+ provisioned,
1750
+ required,
1751
+ source,
1752
+ ...measurement === void 0 ? {} : {
1753
+ measurementFrame: measurement.frame,
1754
+ rejectionFraction: measurement.rejectionFraction
1755
+ }
1756
+ }
1757
+ };
1758
+ if (measurement !== void 0) this.#reportedMeasurement = true;
1759
+ this.#publish(emit);
1760
+ }
1761
+ #publish(emit) {
1762
+ const marker = { applied: this.#applied, marker: RENDER_CHAIN_MARKER };
1763
+ rememberReport(this.#renderer, marker);
1764
+ if (emit) this.#report(`${RENDER_CHAIN_MARKER}:${JSON.stringify(marker)}`);
1765
+ }
1766
+ #restoreOwnedVelocityOutput() {
1767
+ if (this.#ownedVelocityPass !== void 0 && this.#ownedVelocityMrt !== void 0) {
1768
+ this.#ownedVelocityPass.setMRT(this.#ownedVelocityMrt);
1769
+ const target = this.#ownedVelocityPass.renderTarget;
1770
+ const texture = this.#ownedVelocityTexture;
1771
+ if (target !== void 0 && texture !== void 0) {
1772
+ const index = target.textures.indexOf(texture);
1773
+ if (index !== -1) {
1774
+ target.dispose();
1775
+ target.textures.splice(index, 1);
1776
+ }
1777
+ }
1778
+ }
1779
+ this.#ownedVelocityPass = void 0;
1780
+ this.#ownedVelocityMrt = void 0;
1781
+ this.#ownedVelocityTexture = void 0;
1782
+ }
1783
+ #disposeActiveStages() {
1784
+ for (const definition of this.#activeStageDefinitions) definition.dispose?.();
1785
+ this.#activeStageDefinitions = [];
1786
+ }
1787
+ };
1788
+ function createStageDefinitions(stages) {
1789
+ const definitions = /* @__PURE__ */ new Map();
1790
+ for (const stage of stages) {
1791
+ const name = requireStageId(stage.name, "render-chain stage");
1792
+ if (definitions.has(name)) throw new Error(`duplicate render-chain stage '${stage.name}'`);
1793
+ if (typeof stage.build !== "function")
1794
+ throw new Error(`render-chain stage '${name}' needs a build function`);
1795
+ const hasBefore = stage.before !== void 0;
1796
+ const hasAfter = stage.after !== void 0;
1797
+ if (stage.afterOutputTransform === true && (hasBefore || hasAfter)) {
1798
+ throw new Error(
1799
+ `render-chain stage '${name}' declares afterOutputTransform and an anchor; a stage that reads display-referred colour is last by construction, so an anchor is either ignored or wrong`
1800
+ );
1801
+ }
1802
+ if (isBuiltInStageId(name)) {
1803
+ if (hasBefore || hasAfter) {
1804
+ throw new Error(
1805
+ `built-in render-chain stage '${name}' cannot declare before or after; its canonical order is fixed`
1806
+ );
1807
+ }
1808
+ } else if (hasBefore === hasAfter && stage.afterOutputTransform !== true) {
1809
+ throw new Error(
1810
+ `authored render-chain stage '${name}' must declare exactly one of before or after`
1811
+ );
1812
+ }
1813
+ if (hasBefore) requireStageId(stage.before, `render-chain stage '${name}' before anchor`);
1814
+ if (hasAfter) requireStageId(stage.after, `render-chain stage '${name}' after anchor`);
1815
+ definitions.set(name, stage);
1816
+ }
1817
+ for (const [name, stage] of definitions) {
1818
+ const anchor = stage.before ?? stage.after;
1819
+ if (anchor !== void 0 && !isBuiltInStageId(anchor) && !definitions.has(anchor)) {
1820
+ throw new Error(`render-chain stage '${name}' anchor '${anchor}' is missing`);
1821
+ }
1822
+ }
1823
+ resolveStageOrder(definitions);
1824
+ return definitions;
1825
+ }
1826
+ function normalizeRequestedStages(stages, definitions) {
1827
+ const requested = /* @__PURE__ */ new Set();
1828
+ for (const name of stages) {
1829
+ const id = requireStageId(name, "requested render-chain stage");
1830
+ if (requested.has(id)) throw new Error(`duplicate requested render-chain stage '${id}'`);
1831
+ if (!isBuiltInStageId(id) && !definitions.has(id)) {
1832
+ throw new Error(`unknown render-chain stage '${id}': no supplied definition`);
1833
+ }
1834
+ requested.add(id);
1835
+ }
1836
+ return resolveStageOrder(definitions, requested).filter((name) => requested.has(name));
1837
+ }
1838
+ function resolveStageOrder(definitions, additionalIds = []) {
1839
+ const ranks = /* @__PURE__ */ new Map();
1840
+ const visiting = [];
1841
+ const step = 1 / (definitions.size + 1);
1842
+ const rank = (id) => {
1843
+ const builtInIndex = RENDER_CHAIN_STAGE_ORDER.indexOf(id);
1844
+ if (builtInIndex >= 0) return builtInIndex;
1845
+ const known = ranks.get(id);
1846
+ if (known !== void 0) return known;
1847
+ const cycleStart = visiting.indexOf(id);
1848
+ if (cycleStart >= 0) {
1849
+ const cycle = [...visiting.slice(cycleStart), id].join(" -> ");
1850
+ throw new Error(`render-chain stage anchor cycle: ${cycle}`);
1851
+ }
1852
+ const definition = definitions.get(id);
1853
+ if (definition === void 0) {
1854
+ throw new Error(`render-chain stage '${id}' has no supplied definition`);
1855
+ }
1856
+ if (definition.afterOutputTransform === true) {
1857
+ ranks.set(id, RENDER_CHAIN_STAGE_ORDER.length + 1);
1858
+ return ranks.get(id);
1859
+ }
1860
+ const anchor = definition.before ?? definition.after;
1861
+ if (anchor === void 0) {
1862
+ throw new Error(`authored render-chain stage '${id}' has no anchor`);
1863
+ }
1864
+ visiting.push(id);
1865
+ const anchorRank = rank(anchor);
1866
+ visiting.pop();
1867
+ const resolved = anchorRank + (definition.before === void 0 ? step : -step);
1868
+ ranks.set(id, resolved);
1869
+ return resolved;
1870
+ };
1871
+ const ordered = [.../* @__PURE__ */ new Set([...definitions.keys(), ...additionalIds])].map((id, index) => ({
1872
+ id,
1873
+ index,
1874
+ rank: rank(id)
1875
+ }));
1876
+ ordered.sort((left, right) => left.rank - right.rank || left.index - right.index);
1877
+ return ordered.map(({ id }) => id);
1878
+ }
1879
+ function requireStageId(value, label) {
1880
+ if (typeof value !== "string" || value.trim().length === 0) {
1881
+ throw new Error(`${label} id must be a non-blank string; received ${String(value)}`);
1882
+ }
1883
+ return value;
1884
+ }
1885
+ function isBuiltInStageId(value) {
1886
+ return RENDER_CHAIN_STAGE_ORDER.includes(value);
1887
+ }
1888
+ function requiresVelocityFor(definition, id) {
1889
+ return definition?.requiresVelocity ?? (isBuiltInStageId(id) && VELOCITY_STAGES.has(id));
1890
+ }
1891
+ function validateTier(value) {
1892
+ if (value === "high" || value === "medium" || value === "low" || value === "off") return value;
1893
+ throw new Error(
1894
+ `RenderChain tier must be high, medium, low, off, or auto; received ${String(value)}.`
1895
+ );
1896
+ }
1897
+ function resolveVelocity(renderer, request, scene, required) {
1898
+ if (!required) return { provisioned: false, required: false, source: null };
1899
+ const source = request.source ?? (request.pass !== void 0 || request.mrt === true || hasMrtVelocity(renderer.raw) ? "mrt" : void 0) ?? (request.objectFlags === true || request.perObject === true || hasObjectVelocityFlag(scene) ? "per-object" : null);
1900
+ return { provisioned: source !== null, required: true, source };
1901
+ }
1902
+ function hasMrtVelocity(raw) {
1903
+ if (!isObject2(raw)) return false;
1904
+ const getMrt = raw.getMRT;
1905
+ if (typeof getMrt === "function") {
1906
+ try {
1907
+ if (containsVelocity(getMrt.call(raw))) return true;
1908
+ } catch {
1909
+ return false;
1910
+ }
1911
+ }
1912
+ return containsVelocity(raw.mrt) || containsVelocity(raw.mrtOutputs);
1913
+ }
1914
+ function containsVelocity(value) {
1915
+ if (value instanceof Set || value instanceof Map) return value.has("velocity");
1916
+ if (Array.isArray(value)) return value.includes("velocity");
1917
+ return isObject2(value) && value.velocity === true;
1918
+ }
1919
+ function hasObjectVelocityFlag(scene) {
1920
+ if (scene === void 0) return false;
1921
+ let found = false;
1922
+ scene.traverse((object) => {
1923
+ if (object.userData?.useVelocity === true) found = true;
1924
+ });
1925
+ return found;
1926
+ }
1927
+ function stageContext(tier, velocity2, velocityNode, resolutionSubrect) {
1928
+ return {
1929
+ quality: RENDER_CHAIN_TIERS[tier],
1930
+ tier,
1931
+ velocity: velocity2,
1932
+ ...velocityNode === void 0 ? {} : { velocityNode },
1933
+ ...resolutionSubrect === void 0 ? {} : { resolutionSubrect }
1934
+ };
1935
+ }
1936
+ function deriveVelocityMeasurement(result, previousFrame) {
1937
+ if (!Number.isInteger(result.frame) || result.frame < 0) {
1938
+ throw new Error(
1939
+ `RenderChain velocity result frame must be a non-negative integer, received ${String(result.frame)}.`
1940
+ );
1941
+ }
1942
+ if (previousFrame !== void 0 && result.frame <= previousFrame) {
1943
+ throw new Error(
1944
+ `RenderChain velocity result frame must advance beyond ${String(previousFrame)}, received ${String(result.frame)}.`
1945
+ );
1946
+ }
1947
+ if (!Number.isInteger(result.rejectionMask.length) || result.rejectionMask.length <= 0) {
1948
+ throw new Error("RenderChain velocity result rejectionMask must contain at least one pixel.");
1949
+ }
1950
+ let rejected = 0;
1951
+ for (let index = 0; index < result.rejectionMask.length; index += 1) {
1952
+ const value = result.rejectionMask[index];
1953
+ if (value !== 0 && value !== 1) {
1954
+ throw new Error(
1955
+ `RenderChain velocity result rejectionMask[${String(index)}] must be 0 or 1, received ${String(value)}.`
1956
+ );
1957
+ }
1958
+ rejected += value;
1959
+ }
1960
+ return {
1961
+ frame: result.frame,
1962
+ rejectionFraction: rejected / result.rejectionMask.length
1963
+ };
1964
+ }
1965
+ function validateCompatibilityMeasurement(value, previousFrame) {
1966
+ if (value === void 0) return void 0;
1967
+ if (!isObject2(value))
1968
+ throw new Error("RenderChain rejectionMeasurement must return an object or undefined.");
1969
+ const frame = value.frame;
1970
+ const rejectionFraction = value.rejectionFraction;
1971
+ if (typeof frame !== "number" || !Number.isInteger(frame) || frame < 0) {
1972
+ throw new Error(
1973
+ `RenderChain rejectionMeasurement frame must be a non-negative integer, received ${String(frame)}.`
1974
+ );
1975
+ }
1976
+ if (previousFrame !== void 0 && frame <= previousFrame) {
1977
+ throw new Error(
1978
+ `RenderChain rejectionMeasurement frame must advance beyond ${String(previousFrame)}, received ${String(frame)}.`
1979
+ );
1980
+ }
1981
+ if (typeof rejectionFraction !== "number" || !Number.isFinite(rejectionFraction) || rejectionFraction < 0 || rejectionFraction > 1) {
1982
+ throw new Error(
1983
+ `RenderChain rejectionMeasurement rejectionFraction must be between 0 and 1, received ${String(rejectionFraction)}.`
1984
+ );
1985
+ }
1986
+ return { frame, rejectionFraction };
1987
+ }
1988
+ function emptyApplied(requested, tier, source, required) {
1989
+ return {
1990
+ contributions: [],
1991
+ dropped: [],
1992
+ requested,
1993
+ source,
1994
+ stages: [],
1995
+ tier,
1996
+ velocity: { provisioned: false, required, source: null }
1997
+ };
1998
+ }
1999
+ function nextLowerTier(tier) {
2000
+ if (tier === "high") return "medium";
2001
+ if (tier === "medium") return "low";
2002
+ if (tier === "low") return "off";
2003
+ return "off";
2004
+ }
2005
+ function rememberReport(renderer, marker) {
2006
+ if (isObject2(renderer)) storeReport(renderer, marker);
2007
+ if (isObject2(renderer.raw)) storeReport(renderer.raw, marker);
2008
+ }
2009
+ function forgetReport(renderer) {
2010
+ if (isObject2(renderer)) storeReport(renderer, void 0);
2011
+ if (isObject2(renderer.raw)) storeReport(renderer.raw, void 0);
2012
+ }
2013
+ function readRawRenderer(renderer) {
2014
+ return "raw" in renderer ? renderer.raw : renderer;
2015
+ }
2016
+ function isRenderer(value) {
2017
+ return isObject2(value) && "kind" in value && "setOutputNode" in value;
2018
+ }
2019
+ function isObject2(value) {
2020
+ return typeof value === "object" && value !== null;
2021
+ }
2022
+ function errorMessage(error) {
2023
+ return error instanceof Error ? error.message : String(error);
2024
+ }
2025
+ function requirePositiveInteger(value, name) {
2026
+ if (!Number.isInteger(value) || value <= 0)
2027
+ throw new Error(`RenderChain ${name} must be a positive integer.`);
2028
+ return value;
2029
+ }
2030
+ function requirePositiveNumber(value, name) {
2031
+ if (!Number.isFinite(value) || value <= 0)
2032
+ throw new Error(`RenderChain ${name} must be a finite positive number.`);
2033
+ return value;
2034
+ }
2035
+
2036
+ // src/profiling/FrameCounters.ts
2037
+ var SKIP = {
2038
+ addEventListener: true,
2039
+ destroy: true,
2040
+ dispatchEvent: true,
2041
+ onuncapturederror: true,
2042
+ removeEventListener: true
2043
+ };
2044
+ var GPU_COUNTERS = {
2045
+ createBuffer: "gpuBufferCreates",
2046
+ createTexture: "gpuTextureCreates",
2047
+ createBindGroup: "gpuBindGroupCreates",
2048
+ createRenderPipeline: "gpuPipelineCompiles",
2049
+ createRenderPipelineAsync: "gpuPipelineCompiles",
2050
+ mapAsync: "gpuReadbackMaps",
2051
+ submit: "gpuQueueSubmits",
2052
+ resolveQuerySet: "gpuQueryResolves",
2053
+ beginRenderPass: "gpuRenderPasses"
2054
+ };
2055
+ function methodNames(target) {
2056
+ const names = [];
2057
+ const seen = /* @__PURE__ */ new Set();
2058
+ let node = target;
2059
+ while (node !== null && node !== Object.prototype) {
2060
+ for (const name of Object.getOwnPropertyNames(node)) {
2061
+ if (name === "constructor" || seen.has(name) || SKIP[name] === true) continue;
2062
+ seen.add(name);
2063
+ const descriptor = Object.getOwnPropertyDescriptor(node, name);
2064
+ if (descriptor === void 0 || typeof descriptor.value !== "function") continue;
2065
+ names.push(name);
2066
+ }
2067
+ node = Object.getPrototypeOf(node);
2068
+ }
2069
+ return names;
2070
+ }
2071
+ function resolveMethod(owner, name) {
2072
+ let node = owner;
2073
+ while (node !== null) {
2074
+ const descriptor = Object.getOwnPropertyDescriptor(node, name);
2075
+ if (descriptor !== void 0)
2076
+ return typeof descriptor.value === "function" ? descriptor.value : void 0;
2077
+ node = Object.getPrototypeOf(node);
2078
+ }
2079
+ return void 0;
2080
+ }
2081
+ function counterDeviceOf(raw) {
2082
+ if (typeof raw !== "object" || raw === null || !("backend" in raw)) return void 0;
2083
+ const backend = raw.backend;
2084
+ if (typeof backend !== "object" || backend === null || !("device" in backend)) return void 0;
2085
+ return backend.device;
2086
+ }
2087
+ var FrameCounters = class _FrameCounters {
2088
+ #debug = debugRequested();
2089
+ #hostCalls = 0;
2090
+ #gpuBytes = 0;
2091
+ #lastHeapBytes;
2092
+ #restore = [];
2093
+ #wrappedEncoders = /* @__PURE__ */ new WeakSet();
2094
+ constructor(device) {
2095
+ this.#wrap(
2096
+ device,
2097
+ this.#debug ? methodNames(device) : ["createCommandEncoder", "createRenderBundleEncoder"],
2098
+ (name, result) => {
2099
+ if (typeof result !== "object" || result === null) return;
2100
+ if (name.endsWith("Encoder")) this.#wrapEncoder(result);
2101
+ if (this.#debug && name === "createBuffer") this.#wrap(result, ["mapAsync"], void 0);
2102
+ }
2103
+ );
2104
+ const queue = device.queue;
2105
+ if (typeof queue === "object" && queue !== null)
2106
+ this.#wrap(queue, methodNames(queue), void 0);
2107
+ }
2108
+ /** Installs the counters on a device, or answers `undefined` when it has nothing to count. */
2109
+ static install(device) {
2110
+ if (typeof device !== "object" || device === null) return void 0;
2111
+ const counterDevice = device;
2112
+ if (typeof counterDevice.queue !== "object" || counterDevice.queue === null) return void 0;
2113
+ return new _FrameCounters(counterDevice);
2114
+ }
2115
+ #wrapEncoder(encoder) {
2116
+ if (this.#wrappedEncoders.has(encoder)) return;
2117
+ this.#wrappedEncoders.add(encoder);
2118
+ this.#wrap(encoder, methodNames(encoder), void 0);
2119
+ }
2120
+ #wrap(owner, names, after) {
2121
+ const target = owner;
2122
+ for (const name of names) {
2123
+ const original = resolveMethod(owner, name);
2124
+ if (original === void 0) continue;
2125
+ const wrapped = (...args) => {
2126
+ this.#hostCalls += 1;
2127
+ const start = this.#debug ? performance.now() : void 0;
2128
+ if (name === "writeBuffer") {
2129
+ const data = args[2];
2130
+ const dataOffset = typeof args[3] === "number" ? args[3] : 0;
2131
+ const size = typeof args[4] === "number" ? args[4] : void 0;
2132
+ const available = typeof data === "object" && data !== null && "byteLength" in data && typeof data.byteLength === "number" ? data.byteLength : 0;
2133
+ const elementBytes = ArrayBuffer.isView(data) && "BYTES_PER_ELEMENT" in data && typeof data.BYTES_PER_ELEMENT === "number" ? data.BYTES_PER_ELEMENT : 1;
2134
+ this.#gpuBytes += size === void 0 ? Math.max(0, available - dataOffset * elementBytes) : size * elementBytes;
2135
+ }
2136
+ const result = original.apply(owner, args);
2137
+ if (this.#debug) {
2138
+ const field = GPU_COUNTERS[name];
2139
+ if (field !== void 0) countDebug(field, 1, "gpu", `WebGPU.${name}`);
2140
+ if (start !== void 0)
2141
+ countDebug(`gpu.${name}Ms`, performance.now() - start, "gpu", `WebGPU.${name}`, "ms");
2142
+ }
2143
+ after?.(name, result);
2144
+ return result;
2145
+ };
2146
+ try {
2147
+ target[name] = wrapped;
2148
+ const weak = new WeakRef(target);
2149
+ this.#restore.push(() => {
2150
+ const live = weak.deref();
2151
+ if (live !== void 0) live[name] = original;
2152
+ });
2153
+ } catch {
2154
+ }
2155
+ }
2156
+ }
2157
+ /** The counts since the previous read. */
2158
+ read() {
2159
+ const counters = {
2160
+ gpuBytes: this.#gpuBytes,
2161
+ hostCalls: this.#hostCalls
2162
+ };
2163
+ this.#hostCalls = 0;
2164
+ this.#gpuBytes = 0;
2165
+ const heap = readHeapBytes();
2166
+ if (heap !== void 0) {
2167
+ const previous = this.#lastHeapBytes;
2168
+ this.#lastHeapBytes = heap;
2169
+ if (this.#debug) {
2170
+ countDebug("jsHeapBytesSampled", heap, "memory", "performance.memory.usedJSHeapSize");
2171
+ if (previous !== void 0)
2172
+ countDebug(
2173
+ heap >= previous ? "jsHeapGrowthBytes" : "jsHeapShrinkBytes",
2174
+ Math.abs(heap - previous),
2175
+ "memory",
2176
+ "performance.memory.usedJSHeapSize"
2177
+ );
2178
+ }
2179
+ if (previous !== void 0 && heap >= previous)
2180
+ return { ...counters, jsAllocBytes: heap - previous };
2181
+ return counters;
2182
+ }
2183
+ return counters;
2184
+ }
2185
+ /** Removes every wrapper. A game that disposes its renderer must not leave the counters behind. */
2186
+ uninstall() {
2187
+ for (let index = this.#restore.length - 1; index >= 0; index -= 1) this.#restore[index]?.();
2188
+ this.#restore.length = 0;
2189
+ }
2190
+ };
2191
+ function readHeapBytes() {
2192
+ const perf = globalThis.performance;
2193
+ const used = perf?.memory?.usedJSHeapSize;
2194
+ return typeof used === "number" && Number.isFinite(used) ? used : void 0;
2195
+ }
2196
+ function discardEngineCountsSinceLastFrame(host = globalThis) {
2197
+ host.__tnEngineCounterRebase?.();
2198
+ }
2199
+ function createEngineCounterReader(host = globalThis) {
2200
+ const debug = debugRequested();
2201
+ let last;
2202
+ const read = () => ({
2203
+ ...host.__tnEngineCost,
2204
+ ...host.__tnEngineCounters?.()
2205
+ });
2206
+ return () => {
2207
+ if (!debug && host.__THREENATIVE_ENGINE_COST__ !== true) return void 0;
2208
+ host.__tnEngineCounterRebase ??= () => {
2209
+ if (last !== void 0) last = read();
2210
+ };
2211
+ const totals = read();
2212
+ const previous = last;
2213
+ last = totals;
2214
+ if (previous === void 0) return void 0;
2215
+ const frame = {};
2216
+ for (const [name, total] of Object.entries(totals)) {
2217
+ if (!Number.isFinite(total) || total < 0)
2218
+ throw new Error(`TN_DEBUG: invalid ${name} counter.`);
2219
+ if (isContentScaled(name)) continue;
2220
+ frame[name] = debug && host.__tnDebugSources?.[name]?.unit === "gauge" ? total : Math.max(0, total - (previous[name] ?? 0));
2221
+ }
2222
+ return frame;
2223
+ };
2224
+ }
2225
+ function createCrossingReader(host = globalThis) {
2226
+ let last;
2227
+ return () => {
2228
+ if (typeof host.__tnCrossingCount !== "function") return void 0;
2229
+ const total = host.__tnCrossingCount();
2230
+ if (!Number.isFinite(total)) return void 0;
2231
+ const previous = last;
2232
+ last = total;
2233
+ return previous === void 0 ? void 0 : Math.max(0, total - previous);
2234
+ };
2235
+ }
2236
+
2237
+ export { CORE_VERSION, DEFAULT_PIPELINE_CENSUS_LIMIT, FrameCounters, PIPELINE_CENSUS_CAPABILITY, PIPELINE_CENSUS_VERSION, PipelineCensus, RENDER_CHAIN_MARKER, RENDER_CHAIN_STAGE_ORDER, RENDER_CHAIN_TIERS, RenderChain, VELOCITY_OUTPUT_NAME, VELOCITY_PREVIOUS_BONE_MATRICES, VELOCITY_PREVIOUS_INSTANCE_MATRICES, VELOCITY_PREVIOUS_WORLD_MATRIX, VelocityTracker, counterDeviceOf, createCrossingReader, createEngineCounterReader, createPipelineCensus, discardEngineCountsSinceLastFrame, disposeBatchedMeshVelocity, ensureBatchedMeshVelocity, ensureVelocityOutput, isBatchedMeshVelocityPatched, publishDirectRenderChainReport, readRenderChainObservation, readRenderChainReport, readVelocityPreviousBoneMatrices, readVelocityPreviousMatrices, readVelocityPreviousWorldMatrix, setBatchedMeshMatrixWithVelocity, setBatchedMeshPreviousMatrix, velocityTexture, withVelocityContext };