@threenative/core 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -0,0 +1,648 @@
1
+ import { Box3, type Camera, Frustum, Matrix4, Sphere, Sprite, Vector3 } from "three";
2
+ import type { Node, UniformNode } from "three/src/nodes/Nodes.js";
3
+ import {
4
+ Fn,
5
+ If,
6
+ Loop,
7
+ deltaTime,
8
+ instanceIndex,
9
+ instancedArray,
10
+ max,
11
+ min,
12
+ time,
13
+ uint,
14
+ uniform,
15
+ vec3,
16
+ vec4,
17
+ } from "three/tsl";
18
+ import type { ComputeNode, SpriteNodeMaterial, StorageBufferNode } from "three/webgpu";
19
+ import type { IComputeDriven } from "./compute-driven.js";
20
+ import { GPUReadback } from "./gpu-readback.js";
21
+ import type { IBudgetCandidate } from "./particle-significance.js";
22
+ import type { IRendererLike } from "./renderer.js";
23
+
24
+ /** A slot that was never spawned: far enough in the past that every age reads as "dead". */
25
+ const DEAD_BIRTH = -1e6;
26
+
27
+ export interface IGPUParticles3DBuffers {
28
+ readonly positions: StorageBufferNode<"vec3">;
29
+ readonly velocities: StorageBufferNode<"vec3">;
30
+ /** Emitter-clock second of each slot's last spawn. Present only when `spawn` is given. */
31
+ readonly births?: StorageBufferNode<"float">;
32
+ }
33
+
34
+ /** The engine clock, as TSL nodes, handed to `process` as its second argument. */
35
+ export interface IGPUParticles3DRuntime {
36
+ readonly time: Node<"float">;
37
+ readonly delta: Node<"float">;
38
+ }
39
+
40
+ /** Engine-owned uniforms for one `emitParticle` call. The slot is `(first + instanceIndex) % amount`. */
41
+ export interface IGPUParticles3DSpawnRequest {
42
+ readonly first: UniformNode<"uint", number>;
43
+ readonly count: UniformNode<"uint", number>;
44
+ readonly origin: UniformNode<"vec3", Vector3>;
45
+ readonly direction: UniformNode<"vec3", Vector3>;
46
+ readonly seed: UniformNode<"float", number>;
47
+ readonly time: Node<"float">;
48
+ }
49
+
50
+ /** Buffers a spawn-driven emitter's kernels receive: `births` always exists. */
51
+ export interface IGPUParticles3DSpawnBuffers extends IGPUParticles3DBuffers {
52
+ readonly births: StorageBufferNode<"float">;
53
+ }
54
+
55
+ interface IGPUParticles3DBaseOptions {
56
+ readonly amount: number;
57
+ readonly material: SpriteNodeMaterial;
58
+ /** World space when `spawn` is given, emitter space otherwise. */
59
+ readonly localCoords?: boolean;
60
+ /**
61
+ * Override the local bounds from frame zero and skip GPU measurement.
62
+ * @situation Supply known bounds for a particle cloud.
63
+ * @constraint Must be a finite, non-empty box in the emitter's local space.
64
+ */
65
+ readonly bounds?: Box3;
66
+ /**
67
+ * Metres added around the world box. Defaults to half the largest world scale.
68
+ * @situation Cover the sprite quad; name padding when the material uses scaleNode.
69
+ * @constraint Must be finite and non-negative, in world metres.
70
+ */
71
+ readonly padding?: number;
72
+ /**
73
+ * Keep buffers on pause, or restart on return with clear. Defaults to pause.
74
+ * @situation Choose whether a returning effect continues or starts again.
75
+ * @constraint Must be pause or clear.
76
+ */
77
+ readonly onCull?: "pause" | "clear";
78
+ /**
79
+ * Seconds continuously outside the view before culling. Defaults to 1.
80
+ * @situation Avoid toggling effects near the view edge; Infinity disables view culling.
81
+ * @constraint Must be non-negative; Infinity is allowed.
82
+ */
83
+ readonly graceSeconds?: number;
84
+ /**
85
+ * Frames between GPU bounds measurements. Defaults to 8.
86
+ * @situation Trade readback cost for a delayed view of the cloud bounds.
87
+ * @constraint Must be a positive integer; paused emitters do not measure.
88
+ */
89
+ readonly boundsEveryFrames?: number;
90
+ }
91
+
92
+ /** The closed-form tier: every particle is a function of time, `start` seeds the buffers. */
93
+ export interface IGPUParticles3DClosedFormOptions extends IGPUParticles3DBaseOptions {
94
+ readonly start: (buffers: IGPUParticles3DBuffers) => ComputeNode;
95
+ readonly process: (
96
+ buffers: IGPUParticles3DBuffers,
97
+ runtime: IGPUParticles3DRuntime,
98
+ ) => ComputeNode;
99
+ readonly spawn?: undefined;
100
+ readonly lifetime?: undefined;
101
+ readonly maxSpawnPerFrame?: undefined;
102
+ }
103
+
104
+ /** The spawn tier: a burst is a request, and the engine owns the slots and the birth stamps. */
105
+ export interface IGPUParticles3DSpawnOptions extends IGPUParticles3DBaseOptions {
106
+ /** Optional here: the engine already resets every birth. */
107
+ readonly start?: (buffers: IGPUParticles3DSpawnBuffers) => ComputeNode;
108
+ readonly process: (
109
+ buffers: IGPUParticles3DSpawnBuffers,
110
+ runtime: IGPUParticles3DRuntime,
111
+ ) => ComputeNode;
112
+ /**
113
+ * Writes one burst. Dispatched over `amount` threads per `emitParticle`: a thread with
114
+ * `instanceIndex >= request.count` returns at once. ponytail: costs `amount` threads per emit;
115
+ * upgrade to an indirect dispatch of `count` threads if `amount` passes about 100,000.
116
+ */
117
+ readonly spawn: (
118
+ buffers: IGPUParticles3DSpawnBuffers,
119
+ request: IGPUParticles3DSpawnRequest,
120
+ ) => ComputeNode;
121
+ /** Game-owned longest life in seconds. Lets `stats.recycledLive` count slots recycled while alive. */
122
+ readonly lifetime?: number;
123
+ /** Cap on particles spawned between two `process` calls. Defaults to `amount`. */
124
+ readonly maxSpawnPerFrame?: number;
125
+ }
126
+
127
+ export type IGPUParticles3DOptions = IGPUParticles3DClosedFormOptions | IGPUParticles3DSpawnOptions;
128
+
129
+ export interface IEmitParticleRequest {
130
+ readonly count?: number;
131
+ readonly origin?: { readonly x: number; readonly y: number; readonly z: number };
132
+ readonly direction?: { readonly x: number; readonly y: number; readonly z: number };
133
+ readonly seed?: number;
134
+ }
135
+
136
+ export interface IGPUParticles3DStats {
137
+ /** Particles requested but not spawned (over `amount` or over `maxSpawnPerFrame`). */
138
+ readonly clamped: number;
139
+ /** Particles spawned. */
140
+ readonly spawned: number;
141
+ /** Live slots overwritten by the ring. `undefined` without the `lifetime` option, never `0`. */
142
+ readonly recycledLive: number | undefined;
143
+ }
144
+
145
+ const LANES = 256;
146
+ const worldBox = new Box3();
147
+ const viewProjection = new Matrix4();
148
+ const frustum = new Frustum();
149
+ const sphere = new Sphere();
150
+ const cameraPosition = new Vector3();
151
+
152
+ /** Fold GPU lane extrema into local bounds; reject missing or non-finite samples. */
153
+ export function foldBounds(data: Float32Array): Box3 | undefined {
154
+ if (data.length === 0 || data.length % 8 !== 0 || !data.every(Number.isFinite)) return undefined;
155
+ const lanes = data.length / 8;
156
+ const box = new Box3();
157
+ for (let lane = 0; lane < lanes; lane += 1) {
158
+ const lo = lane * 4;
159
+ const hi = (lane + lanes) * 4;
160
+ const lowX = data[lo];
161
+ const highX = data[hi];
162
+ if (lowX === undefined || highX === undefined) return undefined;
163
+ if (lowX > highX) continue;
164
+ for (let axis = 0; axis < 3; axis += 1) {
165
+ const low = data[lo + axis];
166
+ const high = data[hi + axis];
167
+ if (low === undefined || high === undefined) return undefined;
168
+ box.min.setComponent(axis, Math.min(box.min.getComponent(axis), low));
169
+ box.max.setComponent(axis, Math.max(box.max.getComponent(axis), high));
170
+ }
171
+ }
172
+ return box.isEmpty() ? undefined : box;
173
+ }
174
+
175
+ function computeNode(name: string, value: unknown): ComputeNode {
176
+ if (
177
+ value === null ||
178
+ typeof value !== "object" ||
179
+ (value as { isComputeNode?: unknown }).isComputeNode !== true
180
+ ) {
181
+ throw new Error(`GPUParticles3D.${name} must return a TSL compute node.`);
182
+ }
183
+ return value as ComputeNode;
184
+ }
185
+
186
+ function finite(name: string, value: number): number {
187
+ if (!Number.isFinite(value)) throw new Error(`GPUParticles3D.${name} must be a finite number.`);
188
+ return value;
189
+ }
190
+
191
+ function setVector(
192
+ uniformNode: UniformNode<"vec3", Vector3>,
193
+ name: string,
194
+ v: { readonly x: number; readonly y: number; readonly z: number } | undefined,
195
+ ): void {
196
+ const target = uniformNode.value as Vector3;
197
+ if (v === undefined) return void target.set(0, 0, 0);
198
+ target.set(finite(`${name}.x`, v.x), finite(`${name}.y`, v.y), finite(`${name}.z`, v.z));
199
+ }
200
+
201
+ interface ISpawnState {
202
+ readonly births: StorageBufferNode<"float">;
203
+ readonly request: IGPUParticles3DSpawnRequest;
204
+ readonly spawn: ComputeNode;
205
+ readonly stamp: ComputeNode;
206
+ readonly reset: ComputeNode;
207
+ }
208
+
209
+ export class GPUParticles3D extends Sprite implements IComputeDriven {
210
+ readonly amount: number;
211
+ readonly buffers: IGPUParticles3DBuffers;
212
+ readonly processCadence = "render" as const;
213
+ readonly warmupNodes: readonly ComputeNode[];
214
+ readonly localCoords: boolean;
215
+ emitting = true;
216
+ #start: ComputeNode | undefined;
217
+ #process: ComputeNode;
218
+ #spawn: ISpawnState | undefined;
219
+ #renderer: IRendererLike | undefined;
220
+ #released = false;
221
+ #lifetime: number | undefined;
222
+ #maxPerFrame: number;
223
+ #cursor = 0;
224
+ #spawnedThisFrame = 0;
225
+ #seed = 0;
226
+ #clamped = 0;
227
+ #spawned = 0;
228
+ #recycledLive = 0;
229
+ #warned = false;
230
+ /** Recent requests: wall-clock second, first ring sequence number, count. Pruned past `lifetime`. */
231
+ #log: { at: number; first: number; count: number }[] = [];
232
+ readonly #boundsOverride: Box3 | undefined;
233
+ #measuredBounds: Box3 | undefined;
234
+ readonly #padding: number | undefined;
235
+ readonly #onCull: "pause" | "clear";
236
+ #graceSeconds = 1;
237
+ readonly #boundsEveryFrames: number;
238
+ readonly #partials: StorageBufferNode<"vec4"> | undefined;
239
+ readonly #reduce: ComputeNode | undefined;
240
+ #readback: GPUReadback | undefined;
241
+ #frame = 0;
242
+ #lastMeasure = 0;
243
+ #lands = 0;
244
+ #dispatches = 0;
245
+ #outsideSince: number | undefined;
246
+ #authoredVisible = true;
247
+ #hiddenByCull = false;
248
+ #yielded = false;
249
+ #state: "running" | "paused" | "cleared" = "running";
250
+ #reason: "outside-view" | "over-budget" | undefined;
251
+ #transitions = 0;
252
+
253
+ /** Cooperate with measured frame-budget shedding without changing particle storage. */
254
+ readonly budget: IBudgetCandidate = {
255
+ significance: (camera) => {
256
+ if (
257
+ this.#released ||
258
+ !this.emitting ||
259
+ !this.#authoredVisible ||
260
+ this.castShadow ||
261
+ this.#reason === "outside-view"
262
+ )
263
+ return undefined;
264
+ this.updateWorldMatrix(true, false);
265
+ if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
266
+ if (this.measuredBounds === undefined) {
267
+ sphere.center.setFromMatrixPosition(this.matrixWorld);
268
+ sphere.radius = 0;
269
+ } else {
270
+ this.measuredBounds.getBoundingSphere(sphere).applyMatrix4(this.matrixWorld);
271
+ }
272
+ cameraPosition.setFromMatrixPosition(camera.matrixWorld);
273
+ return (
274
+ (sphere.radius + this.#worldPadding) /
275
+ Math.max(sphere.center.distanceTo(cameraPosition), 1e-3)
276
+ );
277
+ },
278
+ yield: (yielded) => {
279
+ this.#yielded = yielded;
280
+ },
281
+ };
282
+
283
+ constructor(options: IGPUParticles3DOptions) {
284
+ if (!Number.isInteger(options.amount) || options.amount <= 0)
285
+ throw new Error("GPUParticles3D.amount must be a positive integer.");
286
+ if (options.material === undefined) throw new Error("GPUParticles3D.material is required.");
287
+ if (options.spawn !== undefined && typeof options.spawn !== "function")
288
+ throw new Error("GPUParticles3D.spawn must be a function.");
289
+ if (options.start !== undefined || options.spawn === undefined) {
290
+ if (typeof options.start !== "function")
291
+ throw new Error("GPUParticles3D.start must be a function.");
292
+ }
293
+ if (typeof options.process !== "function")
294
+ throw new Error("GPUParticles3D.process must be a function.");
295
+ if (options.lifetime !== undefined && !(options.lifetime > 0))
296
+ throw new Error("GPUParticles3D.lifetime must be a positive number.");
297
+ const maxPerFrame = options.maxSpawnPerFrame ?? options.amount;
298
+ if (!Number.isInteger(maxPerFrame) || maxPerFrame <= 0)
299
+ throw new Error("GPUParticles3D.maxSpawnPerFrame must be a positive integer.");
300
+ const boundsEveryFrames = options.boundsEveryFrames ?? 8;
301
+ if (!Number.isInteger(boundsEveryFrames) || boundsEveryFrames <= 0)
302
+ throw new Error("GPUParticles3D.boundsEveryFrames must be a positive integer.");
303
+ if (options.padding !== undefined && (!Number.isFinite(options.padding) || options.padding < 0))
304
+ throw new Error("GPUParticles3D.padding must be finite and non-negative.");
305
+ if (options.onCull !== undefined && options.onCull !== "pause" && options.onCull !== "clear")
306
+ throw new Error("GPUParticles3D.onCull must be pause or clear.");
307
+ if (
308
+ options.bounds !== undefined &&
309
+ (options.bounds.isBox3 !== true ||
310
+ options.bounds.isEmpty() ||
311
+ ![...options.bounds.min.toArray(), ...options.bounds.max.toArray()].every(Number.isFinite))
312
+ )
313
+ throw new Error("GPUParticles3D.bounds must be a finite, non-empty Box3.");
314
+ super(options.material);
315
+ // Separate authored visibility from culling so a game hide while culled survives recovery.
316
+ Object.defineProperty(this, "visible", {
317
+ configurable: true,
318
+ enumerable: true,
319
+ get: () => this.#authoredVisible && !this.#hiddenByCull,
320
+ set: (visible: boolean) => {
321
+ this.#authoredVisible = visible;
322
+ },
323
+ });
324
+ this.#boundsOverride = options.bounds;
325
+ this.#padding = options.padding;
326
+ this.#onCull = options.onCull ?? "pause";
327
+ this.graceSeconds = options.graceSeconds ?? 1;
328
+ this.#boundsEveryFrames = boundsEveryFrames;
329
+ this.amount = options.amount;
330
+ this.#lifetime = options.lifetime;
331
+ this.#maxPerFrame = maxPerFrame;
332
+ const positions = instancedArray(options.amount, "vec3");
333
+ const velocities = instancedArray(options.amount, "vec3");
334
+ const births =
335
+ options.spawn === undefined ? undefined : instancedArray(options.amount, "float");
336
+ this.buffers =
337
+ births === undefined ? { positions, velocities } : { positions, velocities, births };
338
+ options.material.positionNode = this.buffers.positions.toAttribute();
339
+ this.count = options.amount;
340
+ // Three tests a Sprite as a unit quad, ignoring the particle cloud.
341
+ this.frustumCulled = false;
342
+ this.localCoords = options.localCoords ?? options.spawn === undefined;
343
+ if (!this.localCoords) {
344
+ // Buffer positions are world positions: no parent may move a live particle.
345
+ this.matrixAutoUpdate = false;
346
+ this.matrixWorldAutoUpdate = false;
347
+ this.matrixWorld.identity();
348
+ }
349
+ this.#start =
350
+ options.start === undefined
351
+ ? undefined
352
+ : computeNode(
353
+ "start",
354
+ (options.start as (b: IGPUParticles3DBuffers) => ComputeNode)(this.buffers),
355
+ );
356
+ this.#process = computeNode(
357
+ "process",
358
+ (options.process as (b: IGPUParticles3DBuffers, r: IGPUParticles3DRuntime) => ComputeNode)(
359
+ this.buffers,
360
+ { time: time as Node<"float">, delta: deltaTime as Node<"float"> },
361
+ ),
362
+ );
363
+ if (options.spawn !== undefined && births !== undefined)
364
+ this.#spawn = this.#buildSpawn(options.spawn, births);
365
+ if (options.bounds === undefined) {
366
+ const partials = instancedArray(2 * LANES, "vec4");
367
+ const positions = this.buffers.positions;
368
+ const amount = this.amount;
369
+ this.#partials = partials;
370
+ this.#reduce = Fn(() => {
371
+ const lo = vec3(1e30).toVar();
372
+ const hi = vec3(-1e30).toVar();
373
+ Loop({ start: instanceIndex, end: amount, type: "uint", update: LANES }, ({ i }) => {
374
+ const position = positions.element(i);
375
+ lo.assign(min(lo, position));
376
+ hi.assign(max(hi, position));
377
+ });
378
+ partials.element(instanceIndex).assign(vec4(lo, 0));
379
+ partials.element(instanceIndex.add(LANES)).assign(vec4(hi, 0));
380
+ })().compute(LANES);
381
+ this.#readback = new GPUReadback({ attribute: partials.value, everyFrames: 1 });
382
+ }
383
+ this.warmupNodes = [
384
+ ...(this.#start === undefined ? [] : [this.#start]),
385
+ ...(this.#spawn === undefined
386
+ ? []
387
+ : [this.#spawn.reset, this.#spawn.stamp, this.#spawn.spawn]),
388
+ this.#process,
389
+ ...(this.#reduce === undefined ? [] : [this.#reduce]),
390
+ ];
391
+ this.addEventListener("removed", this.#onRemoved);
392
+ }
393
+
394
+ #buildSpawn(
395
+ spawn: IGPUParticles3DSpawnOptions["spawn"],
396
+ births: StorageBufferNode<"float">,
397
+ ): ISpawnState {
398
+ const amount = this.amount;
399
+ const request: IGPUParticles3DSpawnRequest = {
400
+ first: uniform(0, "uint"),
401
+ count: uniform(0, "uint"),
402
+ origin: uniform(new Vector3()),
403
+ direction: uniform(new Vector3()),
404
+ seed: uniform(0),
405
+ time: time as Node<"float">,
406
+ };
407
+ const stamp = Fn(() => {
408
+ If(instanceIndex.lessThan(request.count), () => {
409
+ births.element(request.first.add(instanceIndex).mod(uint(amount))).assign(time);
410
+ });
411
+ })().compute(amount);
412
+ const reset = Fn(() => {
413
+ births.element(instanceIndex).assign(DEAD_BIRTH);
414
+ })().compute(amount);
415
+ return {
416
+ births,
417
+ request,
418
+ reset,
419
+ spawn: computeNode("spawn", spawn({ ...this.buffers, births }, request)),
420
+ stamp,
421
+ };
422
+ }
423
+
424
+ get released(): boolean {
425
+ return this.#released;
426
+ }
427
+
428
+ get stats(): IGPUParticles3DStats {
429
+ return {
430
+ clamped: this.#clamped,
431
+ recycledLive: this.#lifetime === undefined ? undefined : this.#recycledLive,
432
+ spawned: this.#spawned,
433
+ };
434
+ }
435
+
436
+ /** Seconds outside view before culling; Infinity disables it at runtime. */
437
+ get graceSeconds(): number {
438
+ return this.#graceSeconds;
439
+ }
440
+
441
+ set graceSeconds(value: number) {
442
+ if ((!Number.isFinite(value) && value !== Number.POSITIVE_INFINITY) || value < 0)
443
+ throw new Error("GPUParticles3D.graceSeconds must be non-negative.");
444
+ this.#graceSeconds = value;
445
+ }
446
+
447
+ attachRenderer(renderer: IRendererLike): void {
448
+ if (this.#released) throw new Error("GPUParticles3D cannot be attached after release.");
449
+ if (this.#renderer === renderer) return;
450
+ this.#renderer = renderer;
451
+ this.#runStart(renderer);
452
+ }
453
+
454
+ /** The override or newest landed local bounds; absent until a valid sample lands. */
455
+ get measuredBounds(): Box3 | undefined {
456
+ return this.#boundsOverride ?? this.#measuredBounds;
457
+ }
458
+
459
+ /** Simulation compute calls, excluding starts and bounds reduction. */
460
+ get dispatches(): number {
461
+ return this.#dispatches;
462
+ }
463
+
464
+ /** Current cull state and the number of state changes. */
465
+ get cull(): {
466
+ readonly state: "running" | "paused" | "cleared";
467
+ readonly reason: "outside-view" | "over-budget" | undefined;
468
+ readonly transitions: number;
469
+ } {
470
+ return { state: this.#state, reason: this.#reason, transitions: this.#transitions };
471
+ }
472
+
473
+ get #worldPadding(): number {
474
+ return this.#padding ?? 0.5 * this.matrixWorld.getMaxScaleOnAxis();
475
+ }
476
+
477
+ process(
478
+ renderer = this.#renderer,
479
+ camera?: Camera,
480
+ _covered?: boolean,
481
+ _view?: undefined,
482
+ simulatedSeconds?: number,
483
+ ): void {
484
+ if (this.#released || !this.emitting) return;
485
+ if (renderer === undefined) throw new Error("GPUParticles3D is not attached to a renderer.");
486
+ let readback = this.#readback;
487
+ if (readback !== undefined && readback.stats.lands !== this.#lands) {
488
+ this.#lands = readback.stats.lands;
489
+ this.#measuredBounds = readback.data === undefined ? undefined : foldBounds(readback.data);
490
+ }
491
+ let reason: "outside-view" | "over-budget" | undefined;
492
+ if (camera !== undefined && !this.castShadow && this.#authoredVisible) {
493
+ const bounds = this.measuredBounds;
494
+ if (bounds !== undefined && this.#graceSeconds !== Number.POSITIVE_INFINITY) {
495
+ if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
496
+ this.updateWorldMatrix(true, false);
497
+ viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
498
+ frustum.setFromProjectionMatrix(
499
+ viewProjection,
500
+ camera.coordinateSystem,
501
+ camera.reversedDepth,
502
+ );
503
+ worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
504
+ // ponytail: bounds lag by boundsEveryFrames; grace delays culling and paused clouds do not move.
505
+ if (frustum.intersectsBox(worldBox)) this.#outsideSince = undefined;
506
+ else {
507
+ // Wall time is only for callers without a loop clock.
508
+ const now = simulatedSeconds ?? performance.now() / 1000;
509
+ this.#outsideSince ??= now;
510
+ if (now - this.#outsideSince >= this.#graceSeconds) reason = "outside-view";
511
+ }
512
+ } else this.#outsideSince = undefined;
513
+ reason ??= this.#yielded ? "over-budget" : undefined;
514
+ } else this.#outsideSince = undefined;
515
+ const state =
516
+ reason === undefined ? "running" : this.#onCull === "clear" ? "cleared" : "paused";
517
+ if (state !== this.#state) {
518
+ this.#transitions += 1;
519
+ if (state === "running" && this.#onCull === "clear") this.restart();
520
+ this.#state = state;
521
+ readback = this.#readback;
522
+ }
523
+ this.#reason = reason;
524
+ if (reason !== undefined) {
525
+ this.#hiddenByCull = true;
526
+ return;
527
+ }
528
+ this.#hiddenByCull = false;
529
+ renderer.compute(this.#process);
530
+ this.#spawnedThisFrame = 0;
531
+ this.#dispatches += 1;
532
+ this.#frame += 1;
533
+ if (
534
+ readback !== undefined &&
535
+ this.#reduce !== undefined &&
536
+ typeof renderer.readback === "function" &&
537
+ !readback.pending &&
538
+ !(readback.stats.failures > 0 && readback.stats.lands === 0) &&
539
+ this.#frame - this.#lastMeasure >= this.#boundsEveryFrames
540
+ ) {
541
+ this.#lastMeasure = this.#frame;
542
+ renderer.compute(this.#reduce);
543
+ readback.request(renderer);
544
+ }
545
+ }
546
+
547
+ /**
548
+ * Spawns `count` particles at `origin` (world space unless `localCoords`). Every call gets its own ring
549
+ * slots, so a second burst never touches the first one's live particles. No readback.
550
+ */
551
+ emitParticle(request: IEmitParticleRequest = {}): void {
552
+ if (this.#released) throw new Error("GPUParticles3D cannot emit after release.");
553
+ if (this.#spawn === undefined)
554
+ throw new Error("GPUParticles3D.emitParticle requires a spawn kernel.");
555
+ if (this.#renderer === undefined)
556
+ throw new Error("GPUParticles3D is not attached to a renderer.");
557
+ const asked = request.count ?? 1;
558
+ if (!Number.isInteger(asked) || asked < 0)
559
+ throw new Error("GPUParticles3D.emitParticle count must be a non-negative integer.");
560
+ const { request: uniforms } = this.#spawn;
561
+ setVector(uniforms.origin, "origin", request.origin);
562
+ setVector(uniforms.direction, "direction", request.direction);
563
+ uniforms.seed.value = finite("seed", request.seed ?? this.#seed++);
564
+ const count = Math.min(asked, this.amount, this.#maxPerFrame - this.#spawnedThisFrame);
565
+ if (count < asked) {
566
+ this.#clamped += asked - count;
567
+ if (!this.#warned) {
568
+ this.#warned = true;
569
+ console.warn(
570
+ `GPUParticles3D: spawn request of ${asked} clamped to ${count} (amount ${this.amount}, maxSpawnPerFrame ${this.#maxPerFrame}).`,
571
+ );
572
+ }
573
+ }
574
+ if (count === 0) return;
575
+ this.#countRecycled(count);
576
+ uniforms.first.value = this.#cursor % this.amount;
577
+ uniforms.count.value = count;
578
+ this.#cursor += count;
579
+ this.#spawnedThisFrame += count;
580
+ this.#spawned += count;
581
+ this.#renderer.compute(this.#spawn.stamp);
582
+ this.#renderer.compute(this.#spawn.spawn);
583
+ }
584
+
585
+ /** Reruns `start`. A spawn-driven emitter instead kills every particle and rewinds the ring. */
586
+ restart(): void {
587
+ if (this.#released) throw new Error("GPUParticles3D cannot restart after release.");
588
+ if (this.#renderer === undefined)
589
+ throw new Error("GPUParticles3D is not attached to a renderer.");
590
+ this.#runStart(this.#renderer);
591
+ // Restarted positions invalidate old bounds, including a pending copy.
592
+ this.#readback?.dispose();
593
+ this.#readback =
594
+ this.#partials === undefined
595
+ ? undefined
596
+ : new GPUReadback({ attribute: this.#partials.value, everyFrames: 1 });
597
+ this.#measuredBounds = undefined;
598
+ this.#lands = 0;
599
+ this.#outsideSince = undefined;
600
+ this.#lastMeasure = this.#frame - this.#boundsEveryFrames;
601
+ }
602
+
603
+ detach(): void {
604
+ if (this.#released) return;
605
+ this.#renderer = undefined;
606
+ this.#start?.dispose();
607
+ this.#process.dispose();
608
+ if (this.#spawn !== undefined) {
609
+ this.#spawn.spawn.dispose();
610
+ this.#spawn.stamp.dispose();
611
+ this.#spawn.reset.dispose();
612
+ this.#spawn.births.value.dispose();
613
+ }
614
+ this.#reduce?.dispose();
615
+ this.#readback?.dispose();
616
+ this.#partials?.value.dispose();
617
+ this.buffers.positions.value.dispose();
618
+ this.buffers.velocities.value.dispose();
619
+ this.#released = true;
620
+ }
621
+
622
+ #runStart(renderer: IRendererLike): void {
623
+ if (this.#start !== undefined) renderer.compute(this.#start);
624
+ if (this.#spawn === undefined) return;
625
+ renderer.compute(this.#spawn.reset);
626
+ this.#cursor = 0;
627
+ this.#spawnedThisFrame = 0;
628
+ this.#log = [];
629
+ }
630
+
631
+ /** Counts the slots this request overwrites that a recent request filled less than `lifetime` ago. */
632
+ #countRecycled(count: number): void {
633
+ const lifetime = this.#lifetime;
634
+ if (lifetime === undefined) return;
635
+ const now = performance.now() / 1000;
636
+ const first = this.#cursor;
637
+ const overwritten = first - this.amount;
638
+ this.#log = this.#log.filter((entry) => now - entry.at < lifetime);
639
+ for (const entry of this.#log) {
640
+ const lo = Math.max(entry.first, overwritten);
641
+ const hi = Math.min(entry.first + entry.count, overwritten + count);
642
+ if (hi > lo) this.#recycledLive += hi - lo;
643
+ }
644
+ this.#log.push({ at: now, count, first });
645
+ }
646
+
647
+ #onRemoved = (): void => this.detach();
648
+ }