@threenative/core 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Authored static subtrees: stop recomposing transforms that nobody moves.
3
+ *
4
+ * The matrix walk is 2.22 ms of the reference game's 16.1 ms render phase, and almost none of what
5
+ * it recomputes changed since the previous frame — island geometry, deck fittings, static props and
6
+ * terrain are composed from the same position, quaternion and scale every frame, then multiplied
7
+ * into the same world matrix, for as long as the game runs.
8
+ *
9
+ * **What this deletes, exactly, so the claim can be checked.** Three's `updateMatrixWorld` does
10
+ * three things per object: `updateMatrix()` composes the local matrix when `matrixAutoUpdate`,
11
+ * the world matrix is multiplied out when `matrixWorldNeedsUpdate || force`, and the walk recurses
12
+ * into every child — the recursion is unconditional in three 0.185, so a frozen subtree still gets
13
+ * visited. Freezing removes the two composes and keeps the visit. That is the honest bound: this
14
+ * deletes arithmetic, not traversal, and the traversal is a separate lever with a separate PRD.
15
+ *
16
+ * **Staticness is authored, never guessed.** A heuristic that decides an object has "not moved in
17
+ * 60 frames" is a correctness bug with no reproduction, so nothing here watches gameplay. What the
18
+ * engine does do is check the promise where it is cheap to check it: the root's own local transform
19
+ * is compared against what was frozen, once per frame, and a root the author moved thaws and
20
+ * refreezes itself. That is O(static roots), not O(objects), and it turns the most common way to
21
+ * get this wrong into a non-event. Writes deeper inside a frozen subtree are the author's to
22
+ * announce with `invalidateStatic`, and `TN_RENDERLIST_VALIDATE=1` is what proves they did.
23
+ */
24
+
25
+ import type { Matrix4, Object3D, Quaternion, Vector3 } from "three";
26
+
27
+ /** Marker printed with the static census on each reported window. */
28
+ export const STATIC_TRANSFORM_MARKER = "TN_STATIC_TRANSFORMS";
29
+
30
+ /** What was frozen, and the authored transform it was frozen at. */
31
+ interface IFrozenRoot {
32
+ readonly root: Object3D;
33
+ /** Objects in the subtree at the time it was frozen, including the root. */
34
+ readonly objects: number;
35
+ /** The root's authored transform when it was frozen: position, quaternion, scale, matrix. */
36
+ readonly snapshot: Float64Array;
37
+ /** Bumped every time the subtree is re-armed; the contract a consumer checks, not the flag. */
38
+ version: number;
39
+ }
40
+
41
+ /**
42
+ * Frozen roots, in the order they were marked.
43
+ *
44
+ * A Map keyed by the object, because a root is unmarked by identity and the per-frame check needs
45
+ * to iterate. Insertion order is the report's order, which makes two runs of the same scene produce
46
+ * the same census line.
47
+ */
48
+ const frozen = new Map<Object3D, IFrozenRoot>();
49
+
50
+ const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16;
51
+
52
+ function writeSnapshot(root: Object3D, into: Float64Array): void {
53
+ const position: Vector3 = root.position;
54
+ const quaternion: Quaternion = root.quaternion;
55
+ const scale: Vector3 = root.scale;
56
+ const matrix: Matrix4 = root.matrix;
57
+ into[0] = position.x;
58
+ into[1] = position.y;
59
+ into[2] = position.z;
60
+ into[3] = quaternion.x;
61
+ into[4] = quaternion.y;
62
+ into[5] = quaternion.z;
63
+ into[6] = quaternion.w;
64
+ into[7] = scale.x;
65
+ into[8] = scale.y;
66
+ into[9] = scale.z;
67
+ for (let element = 0; element < 16; element += 1)
68
+ into[10 + element] = matrix.elements[element] ?? 0;
69
+ }
70
+
71
+ function snapshotMatches(root: Object3D, snapshot: Float64Array, scratch: Float64Array): boolean {
72
+ writeSnapshot(root, scratch);
73
+ for (let index = 0; index < SNAPSHOT_LENGTH; index += 1) {
74
+ if (scratch[index] !== snapshot[index]) return false;
75
+ }
76
+ return true;
77
+ }
78
+
79
+ /** Reused by the per-frame check so a frozen scene allocates nothing while it stays frozen. */
80
+ const scratch = new Float64Array(SNAPSHOT_LENGTH);
81
+
82
+ /**
83
+ * Three's own "nothing about me changes between frames" flag, read by its node material observer.
84
+ *
85
+ * A static object is redrawn every frame but skips the per-object work that cannot change: the
86
+ * OBJECT node updates, the object uniform group upload and the attribute scan. Three only trusts it
87
+ * while the world matrix, the material, the geometry and the scene environment are unchanged, so
88
+ * this is the same promise the freeze already makes, said in three's own words.
89
+ */
90
+ function setThreeStatic(object: Object3D, value: boolean): void {
91
+ (object as Object3D & { static?: boolean }).static = value;
92
+ }
93
+
94
+ /**
95
+ * Objects whose local compose *this* turned off, as opposed to a game that composes its own matrix
96
+ * and turned `matrixAutoUpdate` off for its own reasons.
97
+ *
98
+ * The distinction is what lets the validator do its job. For an object the freeze silenced, the
99
+ * authored `position`/`quaternion`/`scale` are still the truth and the frozen `matrix` is the
100
+ * cache, so recomposing from the former is how a stale cache is caught. For an object the game
101
+ * drives by writing `matrix`, the reverse is true and composing would invent a transform.
102
+ */
103
+ const composeSilenced = new WeakSet<Object3D>();
104
+
105
+ /** Whether the static freeze is the reason this object stopped composing its own matrix. */
106
+ export function composeSilencedByFreeze(object: Object3D): boolean {
107
+ return composeSilenced.has(object);
108
+ }
109
+
110
+ /**
111
+ * Roots whose *world* compose the freeze turned off, as opposed to an object that owns its world
112
+ * matrix because the game or the projection writes it directly.
113
+ *
114
+ * `matrixWorldAutoUpdate === false` means "I maintain this myself" in three, and the projection
115
+ * sets it on its mirror as a matter of course. A validator that recomputed those from the parent
116
+ * chain would report every one of them stale.
117
+ */
118
+ const worldSilenced = new WeakSet<Object3D>();
119
+
120
+ /** Whether the static freeze is the reason this object's world matrix is no longer recomposed. */
121
+ export function worldSilencedByFreeze(object: Object3D): boolean {
122
+ return worldSilenced.has(object);
123
+ }
124
+
125
+ /** Freezes the subtree in place and answers how many objects stopped recomposing. */
126
+ function freeze(root: Object3D): number {
127
+ root.updateMatrixWorld(true);
128
+ let objects = 0;
129
+ root.traverse((object) => {
130
+ objects += 1;
131
+ setThreeStatic(object, true);
132
+ if (object.matrixAutoUpdate) composeSilenced.add(object);
133
+ object.matrixAutoUpdate = false;
134
+ object.matrixWorldNeedsUpdate = false;
135
+ });
136
+ // Only the root's own world matrix is a product of something outside the subtree, so only the
137
+ // root needs its world compose suppressed; the children's are already suppressed by the two
138
+ // flags above and would be recomposed identically anyway.
139
+ if (root.matrixWorldAutoUpdate) worldSilenced.add(root);
140
+ root.matrixWorldAutoUpdate = false;
141
+ return objects;
142
+ }
143
+
144
+ /**
145
+ * Marks a subtree static: its transforms are composed once here and never again until something
146
+ * changes them.
147
+ *
148
+ * Idempotent, and it answers the version the subtree is now at, so a caller can assert on the
149
+ * contract rather than on the flag. Marking a root twice re-arms it, which is the same thing
150
+ * `invalidateStatic` does and the reason a generator can emit the call unconditionally.
151
+ */
152
+ export function markStatic(root: Object3D): number {
153
+ const objects = freeze(root);
154
+ const existing = frozen.get(root);
155
+ const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
156
+ writeSnapshot(root, snapshot);
157
+ const version = (existing?.version ?? 0) + 1;
158
+ frozen.set(root, { objects, root, snapshot, version });
159
+ return version;
160
+ }
161
+
162
+ /**
163
+ * Thaws a subtree: every object composes again from the next walk.
164
+ *
165
+ * The flags are restored to three's defaults rather than to whatever they were before, because a
166
+ * game that had already turned `matrixAutoUpdate` off for its own reasons and then marked the
167
+ * subtree static is asking for the same behaviour either way.
168
+ */
169
+ export function unmarkStatic(root: Object3D): void {
170
+ if (!frozen.delete(root)) return;
171
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
172
+ root.traverse((object) => {
173
+ if (composeSilenced.delete(object)) object.matrixAutoUpdate = true;
174
+ setThreeStatic(object, false);
175
+ object.matrixWorldNeedsUpdate = true;
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Announces that something inside a frozen subtree moved. The subtree recomposes once and refreezes
181
+ * at its new transform.
182
+ *
183
+ * Takes the object that moved, or the root; either way the root that owns it is what re-arms, since
184
+ * a world matrix deeper in the subtree is a product of everything above it.
185
+ */
186
+ export function invalidateStatic(object: Object3D): number | undefined {
187
+ let node: Object3D | null = object;
188
+ while (node !== null) {
189
+ if (frozen.has(node)) {
190
+ // Thaw the flags first: `freeze` starts with a forced update, and an object left with
191
+ // `matrixAutoUpdate` off would recompose its world matrix from a stale local one.
192
+ const root = node;
193
+ root.traverse((child) => {
194
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
195
+ child.matrixWorldNeedsUpdate = true;
196
+ });
197
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
198
+ return markStatic(root);
199
+ }
200
+ node = node.parent;
201
+ }
202
+ return undefined;
203
+ }
204
+
205
+ /** Whether this object is a frozen root. */
206
+ export function isStatic(root: Object3D): boolean {
207
+ return frozen.has(root);
208
+ }
209
+
210
+ /**
211
+ * The frozen roots, for the divergence oracle to check directly.
212
+ *
213
+ * The oracle validates what the frame draws, and when the engine's projection is collapsing the
214
+ * scene that is the mirror rather than the authored subtree — which reported three objects
215
+ * checked and zero divergences on a scene with two hundred frozen meshes, one of them genuinely
216
+ * stale. A freeze is authored on the authored scene, so the oracle has to be handed those roots
217
+ * explicitly or it reassures without looking.
218
+ */
219
+ export function staticRoots(): readonly Object3D[] {
220
+ return [...frozen.keys()];
221
+ }
222
+
223
+ /** One window's census of what is frozen and what had to thaw. */
224
+ export interface IStaticTransformCensus {
225
+ /** Subtrees currently frozen. */
226
+ readonly roots: number;
227
+ /** Objects inside them, which is the count that stopped recomposing. */
228
+ readonly objects: number;
229
+ /** Roots the per-frame check found moved, and re-armed, since the previous census. */
230
+ readonly rearmed: number;
231
+ }
232
+
233
+ let rearmedSinceCensus = 0;
234
+
235
+ /**
236
+ * Re-arms any frozen root whose authored transform has changed since it was frozen.
237
+ *
238
+ * Called once per render phase, before the walk. It reads 26 numbers per frozen root and writes
239
+ * nothing when nothing moved, so a scene that stays still pays a comparison per subtree and no
240
+ * allocation at all. It cannot see a write deeper inside the subtree — that is `invalidateStatic`'s
241
+ * job and `TN_RENDERLIST_VALIDATE=1`'s proof — and it does not pretend to.
242
+ */
243
+ export function refreshStaticTransforms(): void {
244
+ if (frozen.size === 0) return;
245
+ for (const entry of frozen.values()) {
246
+ if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
247
+ if (worldSilenced.delete(entry.root)) entry.root.matrixWorldAutoUpdate = true;
248
+ entry.root.traverse((child) => {
249
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
250
+ child.matrixWorldNeedsUpdate = true;
251
+ });
252
+ markStatic(entry.root);
253
+ rearmedSinceCensus += 1;
254
+ }
255
+ }
256
+
257
+ /** The census, and the re-arm counter it resets. */
258
+ export function staticTransformCensus(): IStaticTransformCensus {
259
+ let objects = 0;
260
+ for (const entry of frozen.values()) objects += entry.objects;
261
+ const census: IStaticTransformCensus = {
262
+ objects,
263
+ rearmed: rearmedSinceCensus,
264
+ roots: frozen.size,
265
+ };
266
+ rearmedSinceCensus = 0;
267
+ return census;
268
+ }
269
+
270
+ /** Drops every registration. A game that tore down its scene must not keep its roots alive. */
271
+ export function resetStaticTransforms(): void {
272
+ frozen.clear();
273
+ rearmedSinceCensus = 0;
274
+ }
@@ -0,0 +1,253 @@
1
+ import { StaticDrawUsage } from "three";
2
+ import type { StorageBufferAttribute } from "three/webgpu";
3
+
4
+ /** The standard buffer fields this renderer seam verifies; the device handle stays opaque. */
5
+ export interface IRendererStorageBuffer {
6
+ readonly size: number;
7
+ readonly usage: number;
8
+ readonly mapState: string;
9
+ destroy(): void;
10
+ }
11
+
12
+ /** Exclusive allocation receipt. The solver borrows its handles and never destroys them. */
13
+ export interface IStorageBufferLease {
14
+ readonly device: object;
15
+ readonly buffer: IRendererStorageBuffer;
16
+ readonly byteLength: number;
17
+ readonly released: boolean;
18
+ assertCurrent(): void;
19
+ dispose(): void;
20
+ }
21
+
22
+ /** Exact Three 0.185.1 attribute-manager contract, confined to the renderer adapter. */
23
+ export interface IStorageBufferSource {
24
+ backend?: {
25
+ isWebGPUBackend?: boolean;
26
+ device?: unknown;
27
+ get?: (attribute: StorageBufferAttribute) => unknown;
28
+ destroyAttribute?: (attribute: StorageBufferAttribute) => void;
29
+ };
30
+ _attributes?: {
31
+ update(attribute: StorageBufferAttribute, type: number): void;
32
+ delete(attribute: StorageBufferAttribute): unknown;
33
+ info?: { destroyAttribute(attribute: StorageBufferAttribute): void };
34
+ };
35
+ }
36
+
37
+ function object(value: unknown): value is Record<string, unknown> {
38
+ return typeof value === "object" && value !== null;
39
+ }
40
+
41
+ function deviceLimit(device: unknown): number {
42
+ if (
43
+ !object(device) ||
44
+ typeof device.createBuffer !== "function" ||
45
+ !object(device.queue) ||
46
+ typeof device.queue.writeBuffer !== "function" ||
47
+ !object(device.limits)
48
+ )
49
+ throw new Error("TN_STORAGE_BUFFER_UNSUPPORTED: initialized WebGPU device is required.");
50
+ const { maxBufferSize, maxStorageBufferBindingSize } = device.limits;
51
+ if (
52
+ typeof maxBufferSize !== "number" ||
53
+ !Number.isSafeInteger(maxBufferSize) ||
54
+ maxBufferSize <= 0 ||
55
+ typeof maxStorageBufferBindingSize !== "number" ||
56
+ !Number.isSafeInteger(maxStorageBufferBindingSize) ||
57
+ maxStorageBufferBindingSize <= 0
58
+ )
59
+ throw new Error("TN_STORAGE_BUFFER_UNSUPPORTED: device buffer limits are unavailable.");
60
+ return Math.min(maxBufferSize, maxStorageBufferBindingSize);
61
+ }
62
+
63
+ function validateLayout(attribute: StorageBufferAttribute): Float32Array {
64
+ const a = attribute;
65
+ if (
66
+ a?.isStorageBufferAttribute !== true ||
67
+ !(a.array instanceof Float32Array) ||
68
+ !Number.isSafeInteger(a.version) ||
69
+ a.version < 0 ||
70
+ a.itemSize !== 4 ||
71
+ a.usage !== StaticDrawUsage ||
72
+ !Number.isSafeInteger(a.count) ||
73
+ a.count < 1 ||
74
+ a.array.byteLength !== a.count * 16 ||
75
+ !a.array.every(Number.isFinite)
76
+ )
77
+ throw new Error("TN_STORAGE_BUFFER_LAYOUT: finite Float32 vec4 static storage is required.");
78
+ return a.array;
79
+ }
80
+
81
+ type StorageLayout = { array: Float32Array; bytes: number; count: number; version: number };
82
+
83
+ function matches(attribute: StorageBufferAttribute, layout: StorageLayout): boolean {
84
+ return (
85
+ attribute.array === layout.array &&
86
+ attribute.array.byteLength === layout.bytes &&
87
+ attribute.count === layout.count &&
88
+ attribute.version === layout.version &&
89
+ attribute.itemSize === 4 &&
90
+ attribute.usage === StaticDrawUsage
91
+ );
92
+ }
93
+
94
+ function bufferAt(source: IStorageBufferSource, attribute: StorageBufferAttribute): unknown {
95
+ const data = source.backend?.get?.(attribute);
96
+ return object(data) ? data.buffer : undefined;
97
+ }
98
+
99
+ function buffer(value: unknown, bytes: number): value is IRendererStorageBuffer {
100
+ // Standard WebGPU usage bits: COPY_SRC=4, COPY_DST=8, STORAGE=128.
101
+ return (
102
+ object(value) &&
103
+ value.size === bytes &&
104
+ typeof value.usage === "number" &&
105
+ (value.usage & 140) === 140 &&
106
+ value.mapState === "unmapped" &&
107
+ typeof value.destroy === "function"
108
+ );
109
+ }
110
+
111
+ function releaseOwned(
112
+ source: IStorageBufferSource,
113
+ attribute: StorageBufferAttribute,
114
+ attributes: NonNullable<IStorageBufferSource["_attributes"]>,
115
+ ownedBuffer: unknown,
116
+ ): void {
117
+ if (bufferAt(source, attribute) === ownedBuffer) {
118
+ attributes.delete(attribute);
119
+ // Three deletes its manager record before backend destruction. A previous throw leaves
120
+ // the backend allocation alive even though a repeated manager delete now returns null.
121
+ if (bufferAt(source, attribute) === ownedBuffer) {
122
+ if (
123
+ typeof source.backend?.destroyAttribute !== "function" ||
124
+ typeof attributes.info?.destroyAttribute !== "function"
125
+ )
126
+ throw new Error(
127
+ "TN_STORAGE_BUFFER_CLEANUP: backend allocation remains owned; pinned destruction/accounting retry is unavailable.",
128
+ );
129
+ source.backend.destroyAttribute(attribute);
130
+ attributes.info.destroyAttribute(attribute);
131
+ if (bufferAt(source, attribute) === ownedBuffer)
132
+ throw new Error(
133
+ "TN_STORAGE_BUFFER_CLEANUP: backend retained the owned allocation after destruction.",
134
+ );
135
+ }
136
+ } else if (object(ownedBuffer) && typeof ownedBuffer.destroy === "function")
137
+ ownedBuffer.destroy();
138
+ }
139
+
140
+ /** Owns only explicitly leased attributes, including loads aborted before the first draw. */
141
+ export class StorageBufferLeases {
142
+ readonly #source: () => IStorageBufferSource;
143
+ readonly #releases = new Map<StorageBufferAttribute, () => void>();
144
+ #disposed = false;
145
+
146
+ constructor(source: () => IStorageBufferSource) {
147
+ this.#source = source;
148
+ }
149
+
150
+ allocate(attribute: StorageBufferAttribute): IStorageBufferLease {
151
+ if (this.#disposed) throw new Error("TN_STORAGE_BUFFER_DISPOSED: renderer is disposed.");
152
+ if (this.#releases.has(attribute))
153
+ throw new Error("TN_STORAGE_BUFFER_LEASED: attribute is already leased.");
154
+ const array = validateLayout(attribute);
155
+ const source = this.#source();
156
+ const backend = source.backend;
157
+ const attributes = source._attributes;
158
+ if (
159
+ backend?.isWebGPUBackend !== true ||
160
+ typeof backend.get !== "function" ||
161
+ typeof attributes?.update !== "function" ||
162
+ typeof attributes.delete !== "function"
163
+ )
164
+ throw new Error(
165
+ "TN_STORAGE_BUFFER_UNSUPPORTED: pinned WebGPU attribute-manager seam is unavailable.",
166
+ );
167
+ const device = backend.device;
168
+ const maximum = deviceLimit(device);
169
+ const bytes = array.byteLength;
170
+ if (bytes > maximum)
171
+ throw new Error(`TN_STORAGE_BUFFER_CAPACITY: ${bytes} bytes exceeds ${maximum}.`);
172
+ if (bufferAt(source, attribute) !== undefined)
173
+ throw new Error("TN_STORAGE_BUFFER_OWNERSHIP: attribute already has a buffer.");
174
+ // deviceLimit validated this opaque handle. Consumers validate the compute APIs they need.
175
+ if (!object(device))
176
+ throw new Error("TN_STORAGE_BUFFER_UNSUPPORTED: WebGPU device is unavailable.");
177
+ const layout = { array, bytes, count: attribute.count, version: attribute.version };
178
+ let gpuBuffer: unknown;
179
+ try {
180
+ // AttributeType.STORAGE=3 in the pinned Three cohort. This path also records allocation metrics.
181
+ attributes.update(attribute, 3);
182
+ gpuBuffer = bufferAt(source, attribute);
183
+ if (!matches(attribute, layout) || !buffer(gpuBuffer, bytes))
184
+ throw new Error(
185
+ "TN_STORAGE_BUFFER_LAYOUT: backend storage buffer does not match the requested layout.",
186
+ );
187
+ } catch (error) {
188
+ const failedBuffer = bufferAt(source, attribute);
189
+ const release = () => {
190
+ releaseOwned(source, attribute, attributes, failedBuffer);
191
+ this.#releases.delete(attribute);
192
+ };
193
+ this.#releases.set(attribute, release);
194
+ try {
195
+ release();
196
+ } catch (cleanupError) {
197
+ throw new AggregateError(
198
+ [error, cleanupError],
199
+ "TN_STORAGE_BUFFER_CLEANUP: failed allocation remains owned until teardown.",
200
+ );
201
+ }
202
+ throw error;
203
+ }
204
+ const ownedBuffer = gpuBuffer;
205
+ let released = false;
206
+ const lease: IStorageBufferLease = {
207
+ device,
208
+ buffer: ownedBuffer,
209
+ byteLength: bytes,
210
+ get released() {
211
+ return released;
212
+ },
213
+ assertCurrent: () => {
214
+ const current = this.#source();
215
+ if (
216
+ released ||
217
+ this.#disposed ||
218
+ current.backend !== backend ||
219
+ current._attributes !== attributes ||
220
+ backend.device !== device ||
221
+ bufferAt(source, attribute) !== ownedBuffer ||
222
+ !matches(attribute, layout)
223
+ )
224
+ throw new Error(
225
+ "TN_STORAGE_BUFFER_STALE: renderer, device, buffer or attribute changed.",
226
+ );
227
+ },
228
+ dispose: () => {
229
+ if (released) return;
230
+ // Cleanup must work even after the version/layout becomes stale. Never delete a replacement.
231
+ releaseOwned(source, attribute, attributes, ownedBuffer);
232
+ released = true;
233
+ this.#releases.delete(attribute);
234
+ },
235
+ };
236
+ this.#releases.set(attribute, lease.dispose);
237
+ return lease;
238
+ }
239
+
240
+ dispose(): void {
241
+ if (this.#disposed && this.#releases.size === 0) return;
242
+ this.#disposed = true;
243
+ const failures: unknown[] = [];
244
+ for (const release of [...this.#releases.values()]) {
245
+ try {
246
+ release();
247
+ } catch (error) {
248
+ failures.push(error);
249
+ }
250
+ }
251
+ if (failures.length > 0) throw failures[0];
252
+ }
253
+ }