@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,1253 @@
1
+ import { Group, Vector3, Vector4 } from "three";
2
+ import type { Node, UniformNode } from "three/src/nodes/Nodes.js";
3
+ import * as tsl from "three/tsl";
4
+ import {
5
+ type ComputeNode,
6
+ HalfFloatType,
7
+ LinearFilter,
8
+ RGBAFormat,
9
+ Storage3DTexture,
10
+ } from "three/webgpu";
11
+ import { GPUReadback } from "./gpu-readback.js";
12
+ import type { IRendererLike } from "./renderer.js";
13
+
14
+ type Vec3 = readonly [number, number, number];
15
+ type Vec4 = readonly [number, number, number, number];
16
+ /**
17
+ * A TSL node as the solver handles it: vectors, scalars and storage elements through swizzles that
18
+ * three's types refuse for a storage element or an atomic result. Confined to this module.
19
+ */
20
+ // quality-allow: the solver is arithmetic over TSL nodes, which three 0.185 types per-swizzle.
21
+ // biome-ignore lint/suspicious/noExplicitAny: three's TSL types refuse the swizzles the kernels read.
22
+ type TslNode = Record<string, any>;
23
+ type TslVar = TslNode;
24
+ // quality-allow: the whole TSL namespace is read through one loose record; see TslNode.
25
+ // biome-ignore lint/suspicious/noExplicitAny: see TslNode.
26
+ const tslNodes: Record<string, any> = tsl;
27
+ const {
28
+ Fn,
29
+ If,
30
+ Loop,
31
+ Return,
32
+ abs,
33
+ atomicAdd,
34
+ atomicLoad,
35
+ atomicMax,
36
+ atomicMin,
37
+ atomicStore,
38
+ ceil,
39
+ clamp,
40
+ dot,
41
+ exp,
42
+ float,
43
+ floor,
44
+ hash,
45
+ instanceIndex,
46
+ instancedArray,
47
+ int,
48
+ ivec3,
49
+ length,
50
+ max,
51
+ min,
52
+ select,
53
+ storageTexture,
54
+ textureStore,
55
+ uint,
56
+ uniform,
57
+ uniformArray,
58
+ uvec3,
59
+ vec3,
60
+ vec4,
61
+ } = tslNodes;
62
+
63
+ export interface IFluidBounds {
64
+ readonly min: Vec3;
65
+ readonly max: Vec3;
66
+ }
67
+
68
+ /** An obstacle the water flows around. Boxes carry an xyzw quaternion; spheres have no orientation. */
69
+ export type IFluidCollider =
70
+ | { readonly kind: "sphere"; readonly center: Vec3; readonly radius: number }
71
+ | {
72
+ readonly kind: "box";
73
+ readonly center: Vec3;
74
+ readonly halfExtents: Vec3;
75
+ readonly rotation?: Vec4;
76
+ };
77
+
78
+ export interface IFluidParticlesOptions {
79
+ /** Particle slots. The solver never holds more than this many live particles. */
80
+ readonly capacity: number;
81
+ /** Rest spacing in metres. The smoothing radius is twice this. */
82
+ readonly spacing?: number;
83
+ /** The container. Particles are projected back inside it every iteration. */
84
+ readonly bounds?: IFluidBounds;
85
+ /** Density-constraint iterations per fixed step, 0 to 8. */
86
+ readonly iterations?: number;
87
+ readonly viscosity?: number;
88
+ readonly cohesion?: number;
89
+ readonly vorticity?: number;
90
+ readonly gravity?: number;
91
+ /** Vector speed limit in m/s. Prediction projects radius-sized segments; this is not swept CCD. */
92
+ readonly maxSpeed?: number;
93
+ readonly timeStep?: number;
94
+ /** Colliders updated per step through `setColliders`. */
95
+ readonly maxColliders?: number;
96
+ /** Queued `fill`/`emit` calls consumed per step. Extra calls return `false`. */
97
+ readonly maxSpawns?: number;
98
+ /** Voxel edge of the density volume, in metres. Defaults to half the spacing. */
99
+ readonly voxelSize?: number;
100
+ /** Fixed steps between GPU-to-CPU copies of stats and column heights. */
101
+ readonly readbackEvery?: number;
102
+ /** Extra acceleration (m/s²) added to every particle, from the game's own TSL. */
103
+ readonly force?: (position: Node<"vec3">, velocity: Node<"vec3">, time: Node<"float">) => Node;
104
+ }
105
+
106
+ export interface IFluidParticlesStats {
107
+ readonly count: number;
108
+ /** Mean of `max(0, density - 1)` over live particles; 0 is incompressible. */
109
+ readonly meanCompression: number;
110
+ readonly maxSpeed: number;
111
+ readonly min: Vec3;
112
+ readonly max: Vec3;
113
+ /** Fixed steps between the GPU state these numbers describe and now. */
114
+ readonly staleFrames: number;
115
+ }
116
+
117
+ const DEFAULT_SPACING = 0.22;
118
+ const DEFAULT_BOUNDS: IFluidBounds = { min: [-2.9, 0.0968, -1.6], max: [2.9, 4.65, 1.6] };
119
+ const CELL_CAPACITY = 32;
120
+ const STAT_WORDS = 9;
121
+ const READOUT_HEADER = 16;
122
+ const MAX_STIRS = 4;
123
+ const MAX_DRAINS = 4;
124
+ const FIXED_POINT = 1000;
125
+ const COMPRESSION_SCALE = 100000;
126
+ /** Column height of a column whose water is roofed by a collider; `sample` reads past it. */
127
+ const COVERED = -1e30;
128
+ const COVERED_SEARCH = 8;
129
+ /** Half-width, in columns, of the box filter `sample` averages. */
130
+ const SURFACE_FILTER = 2;
131
+ const MIN_OPEN_COLUMNS = 4;
132
+
133
+ function positive(name: string, value: number): void {
134
+ if (!Number.isFinite(value) || value <= 0)
135
+ throw new Error(`FluidParticles3D.${name} must be positive.`);
136
+ }
137
+
138
+ function nonNegative(name: string, value: number): void {
139
+ if (!Number.isFinite(value) || value < 0)
140
+ throw new Error(`FluidParticles3D.${name} must be non-negative.`);
141
+ }
142
+
143
+ function integerAtLeast(name: string, value: number, least: number): void {
144
+ if (!Number.isInteger(value) || value < least)
145
+ throw new Error(`FluidParticles3D.${name} must be an integer of at least ${least}.`);
146
+ }
147
+
148
+ function finiteVec(name: string, value: readonly number[], length: number): void {
149
+ if (value.length !== length || !value.every(Number.isFinite))
150
+ throw new Error(`FluidParticles3D.${name} must be ${length} finite numbers.`);
151
+ }
152
+
153
+ function nodeVar(node: TslNode): TslVar {
154
+ return node.toVar();
155
+ }
156
+
157
+ function computeKernel(name: string, count: number, body: () => void): ComputeNode {
158
+ const node = Fn(body)().compute(count);
159
+ node.setName(name);
160
+ return node;
161
+ }
162
+
163
+ /** Rotate `vector` by the inverse quaternion's rows, one world-to-local basis row per axis. */
164
+ function basisRows(rotation: Vec4): readonly [Vec3, Vec3, Vec3] {
165
+ finiteVec("collider.rotation", rotation, 4);
166
+ const [x, y, z, w] = rotation;
167
+ const length2 = x * x + y * y + z * z + w * w;
168
+ if (length2 < 1e-12) throw new Error("FluidParticles3D collider rotation must be non-zero.");
169
+ const k = 2 / length2;
170
+ const xx = x * x * k;
171
+ const yy = y * y * k;
172
+ const zz = z * z * k;
173
+ const xy = x * y * k;
174
+ const xz = x * z * k;
175
+ const yz = y * z * k;
176
+ const wx = w * x * k;
177
+ const wy = w * y * k;
178
+ const wz = w * z * k;
179
+ // Columns of R; the rows of R^T are the world-to-local axes.
180
+ return [
181
+ [1 - yy - zz, xy + wz, xz - wy],
182
+ [xy - wz, 1 - xx - zz, yz + wx],
183
+ [xz + wy, yz - wx, 1 - xx - yy],
184
+ ];
185
+ }
186
+
187
+ /**
188
+ * Simulate liquid as particles on the GPU and expose the data, never the look.
189
+ *
190
+ * It is a Position Based Fluids solver (density constraints, XSPH viscosity, cohesion, vorticity
191
+ * confinement) whose passes run as compute kernels every fixed step. Nothing is drawn: `positions`
192
+ * and `velocities` are storage nodes (`.w` of `positions` is the live flag, `.w` of `velocities`
193
+ * is a 0..1 foam hint), `density` is a 3D texture of smoothed particle density a game raymarches
194
+ * or thresholds, and `sample(x, z)` is the free-surface height a `Buoyancy3D` consumes.
195
+ * Appearance — refraction, absorption, foam, spray — stays in the game's `src/render/` code.
196
+ * @situation pour, splash, or dam-break water that fills a container and flows around obstacles
197
+ * @situation simulate water or another liquid as particles in a fluid simulation
198
+ * @situation drop a ball or box into liquid and let it displace and float on the water
199
+ * @situation emit a stream or waterfall of particle fluid and drain it somewhere else
200
+ * @situation sample particle-fluid density or surface height in a game-owned render node
201
+ * @constraint add the fluid through `ctx.add` so renderer attachment, fixed-step dispatch, and release are automatic
202
+ * @constraint a renderer without WebGPU compute throws a named error at attach; it never draws nothing
203
+ * @constraint `emit` recycles the oldest slot once `capacity` slots have been used; `fill` stops at capacity
204
+ * @constraint `sample` and `stats` read a throttled GPU copy and report `staleFrames`; they are never live
205
+ * @override iterations, viscosity, cohesion, vorticity, gravity and maxSpeed tune the solver without changing its pass order
206
+ * @example const water = new FluidParticles3D({ capacity: 6000 });
207
+ * ctx.add(water);
208
+ * water.fill([-2.8, 0.1, -1.5], [-0.6, 3, 1.5]);
209
+ */
210
+ export class FluidParticles3D extends Group {
211
+ readonly capacity: number;
212
+ readonly spacing: number;
213
+ readonly bounds: IFluidBounds;
214
+ readonly iterations: number;
215
+ readonly maxSpeed: number;
216
+ readonly timeStep: number;
217
+ readonly maxColliders: number;
218
+ readonly maxSpawns: number;
219
+ readonly processCadence = "fixed" as const;
220
+ readonly warmupNodes: readonly ComputeNode[];
221
+ /** vec4 per slot: xyz position, w = 1 live / 0 free. */
222
+ readonly positions: ReturnType<typeof instancedArray>;
223
+ /** vec4 per slot: xyz velocity, w = foam 0..1. */
224
+ readonly velocities: ReturnType<typeof instancedArray>;
225
+ /** Smoothed particle density, ~1 inside water; sample it with `texture3D`. */
226
+ readonly density: Storage3DTexture;
227
+ /** Voxel counts of `density`. */
228
+ readonly volumeSize: Vec3;
229
+ /** World-space corner of voxel (0,0,0) and the edge length of one voxel. */
230
+ readonly volumeOrigin: Vec3;
231
+ readonly voxelSize: number;
232
+
233
+ readonly #viscosity: UniformNode<"float", number>;
234
+ readonly #cohesion: UniformNode<"float", number>;
235
+ readonly #vorticity: UniformNode<"float", number>;
236
+ readonly #gravity: UniformNode<"float", number>;
237
+ readonly #time: UniformNode<"float", number>;
238
+ readonly #slots: UniformNode<"uint", number>;
239
+ readonly #spawnCount: UniformNode<"uint", number>;
240
+ readonly #spawnA: TslNode;
241
+ readonly #spawnB: TslNode;
242
+ readonly #spawnC: TslNode;
243
+ readonly #drainCount: UniformNode<"uint", number>;
244
+ readonly #drainMin: TslNode;
245
+ readonly #drainMax: TslNode;
246
+ readonly #stirCount: UniformNode<"uint", number>;
247
+ readonly #stirA: TslNode;
248
+ readonly #stirB: TslNode;
249
+ readonly #colliderCount: UniformNode<"uint", number>;
250
+ readonly #colliderA: TslNode;
251
+ readonly #colliderB: TslNode;
252
+ readonly #colliderRows: readonly [TslNode, TslNode, TslNode];
253
+ readonly #readout: ReturnType<typeof instancedArray>;
254
+ readonly #buffers: readonly ReturnType<typeof instancedArray>[];
255
+ readonly #readback: GPUReadback;
256
+ readonly #columns: readonly [number, number];
257
+ readonly #inject: ComputeNode;
258
+ readonly #predict: ComputeNode;
259
+ readonly #gridClear: ComputeNode;
260
+ readonly #gridBuild: ComputeNode;
261
+ readonly #lambda: ComputeNode;
262
+ readonly #delta: ComputeNode;
263
+ readonly #apply: ComputeNode;
264
+ readonly #velocity: ComputeNode;
265
+ readonly #smooth: ComputeNode;
266
+ readonly #confine: ComputeNode;
267
+ readonly #statsClear: ComputeNode;
268
+ readonly #statsFinalize: ComputeNode;
269
+ readonly #volume: ComputeNode;
270
+ readonly #columnHeights: ComputeNode;
271
+ #renderer: IRendererLike | undefined;
272
+ #cursor = 0;
273
+ #used = 0;
274
+ #queuedSpawns = 0;
275
+ #queuedDrains = 0;
276
+ #queuedStirs = 0;
277
+ #colliders = 0;
278
+ #steps = 0;
279
+ #released = false;
280
+
281
+ constructor(options: IFluidParticlesOptions) {
282
+ integerAtLeast("capacity", options.capacity, 1);
283
+ if (options.capacity > 65536)
284
+ throw new Error("FluidParticles3D.capacity must be at most 65536.");
285
+ const spacing = options.spacing ?? DEFAULT_SPACING;
286
+ const bounds = options.bounds ?? DEFAULT_BOUNDS;
287
+ const iterations = options.iterations ?? 3;
288
+ const viscosity = options.viscosity ?? 0.008;
289
+ const cohesion = options.cohesion ?? 0.03;
290
+ const vorticity = options.vorticity ?? 0.015;
291
+ const gravity = options.gravity ?? 9.81;
292
+ const maxSpeed = options.maxSpeed ?? 18;
293
+ const timeStep = options.timeStep ?? 1 / 60;
294
+ const maxColliders = options.maxColliders ?? 8;
295
+ const maxSpawns = options.maxSpawns ?? 16;
296
+ const voxelSize = options.voxelSize ?? spacing / 2;
297
+ const readbackEvery = options.readbackEvery ?? 4;
298
+ positive("spacing", spacing);
299
+ positive("maxSpeed", maxSpeed);
300
+ positive("timeStep", timeStep);
301
+ positive("voxelSize", voxelSize);
302
+ nonNegative("viscosity", viscosity);
303
+ nonNegative("cohesion", cohesion);
304
+ nonNegative("vorticity", vorticity);
305
+ nonNegative("gravity", gravity);
306
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > 8)
307
+ throw new Error("FluidParticles3D.iterations must be an integer from 0 to 8.");
308
+ integerAtLeast("maxColliders", maxColliders, 1);
309
+ integerAtLeast("maxSpawns", maxSpawns, 1);
310
+ integerAtLeast("readbackEvery", readbackEvery, 1);
311
+ finiteVec("bounds.min", bounds.min, 3);
312
+ finiteVec("bounds.max", bounds.max, 3);
313
+ for (let axis = 0; axis < 3; axis += 1)
314
+ if ((bounds.max[axis] as number) - (bounds.min[axis] as number) < spacing * 2)
315
+ throw new Error(
316
+ "FluidParticles3D.bounds must be at least two spacings wide on every axis.",
317
+ );
318
+
319
+ super();
320
+ this.capacity = options.capacity;
321
+ this.spacing = spacing;
322
+ this.bounds = bounds;
323
+ this.iterations = iterations;
324
+ this.maxSpeed = maxSpeed;
325
+ this.timeStep = timeStep;
326
+ this.maxColliders = maxColliders;
327
+ this.maxSpawns = maxSpawns;
328
+ this.voxelSize = voxelSize;
329
+
330
+ // Kernel constants of the reference solver: h = 2 spacing, unit rest density.
331
+ const radius = spacing * 0.44;
332
+ const h = spacing * 2;
333
+ const h2 = h * h;
334
+ const volumeOfParticle = spacing ** 3;
335
+ const poly6 = 315 / (64 * Math.PI * h ** 9);
336
+ const spiky = -45 / (Math.PI * h ** 6);
337
+ const wSelf = poly6 * h ** 6;
338
+ const wReference = poly6 * (h2 - (0.3 * h) ** 2) ** 3;
339
+ const relaxation = 0.03;
340
+ const wallFriction = 0.08;
341
+ const min3 = bounds.min;
342
+ const max3 = bounds.max;
343
+
344
+ const gridOrigin: Vec3 = [min3[0] - h, min3[1] - h, min3[2] - h];
345
+ const gridDims: Vec3 = [
346
+ Math.ceil((max3[0] - min3[0]) / h) + 3,
347
+ Math.ceil((max3[1] - min3[1]) / h) + 3,
348
+ Math.ceil((max3[2] - min3[2]) / h) + 3,
349
+ ];
350
+ const cells = gridDims[0] * gridDims[1] * gridDims[2];
351
+ this.volumeSize = [
352
+ Math.ceil((max3[0] - min3[0]) / voxelSize),
353
+ Math.ceil((max3[1] - min3[1]) / voxelSize),
354
+ Math.ceil((max3[2] - min3[2]) / voxelSize),
355
+ ];
356
+ this.volumeOrigin = min3;
357
+ const [vx, vy, vz] = this.volumeSize;
358
+ const voxels = vx * vy * vz;
359
+ if (voxels > 4_000_000)
360
+ throw new Error("FluidParticles3D.voxelSize makes a density volume over 4M voxels.");
361
+ this.#columns = [vx, vz];
362
+
363
+ const capacity = this.capacity;
364
+ this.positions = instancedArray(capacity, "vec4");
365
+ this.velocities = instancedArray(capacity, "vec4");
366
+ const previous = instancedArray(capacity, "vec4");
367
+ const deltas = instancedArray(capacity, "vec4");
368
+ const omega = instancedArray(capacity, "vec4");
369
+ const lambdas = instancedArray(capacity, "float");
370
+ const densities = instancedArray(capacity, "float");
371
+ const cellCount = instancedArray(cells, "uint").toAtomic();
372
+ const cellItems = instancedArray(cells * CELL_CAPACITY, "uint");
373
+ const stats = instancedArray(STAT_WORDS, "uint").toAtomic();
374
+ const volumeBuffer = instancedArray(voxels, "float");
375
+ this.#readout = instancedArray(READOUT_HEADER + vx * vz, "float");
376
+ this.#buffers = [
377
+ this.positions,
378
+ this.velocities,
379
+ previous,
380
+ deltas,
381
+ omega,
382
+ lambdas,
383
+ densities,
384
+ cellCount,
385
+ cellItems,
386
+ stats,
387
+ volumeBuffer,
388
+ this.#readout,
389
+ ];
390
+ const readout = this.#readout;
391
+ const positions = this.positions;
392
+ const velocities = this.velocities;
393
+
394
+ this.density = new Storage3DTexture(vx, vy, vz);
395
+ this.density.format = RGBAFormat;
396
+ this.density.type = HalfFloatType;
397
+ this.density.minFilter = LinearFilter;
398
+ this.density.magFilter = LinearFilter;
399
+ this.density.generateMipmaps = false;
400
+ this.density.needsUpdate = true;
401
+
402
+ this.#viscosity = uniform(viscosity);
403
+ this.#cohesion = uniform(cohesion);
404
+ this.#vorticity = uniform(vorticity);
405
+ this.#gravity = uniform(gravity);
406
+ this.#time = uniform(0);
407
+ this.#slots = uniform(0, "uint");
408
+ const zeros = (count: number): Vector4[] => Array.from({ length: count }, () => new Vector4());
409
+ this.#spawnCount = uniform(0, "uint");
410
+ this.#spawnA = uniformArray(zeros(maxSpawns), "vec4");
411
+ this.#spawnB = uniformArray(zeros(maxSpawns), "vec4");
412
+ this.#spawnC = uniformArray(zeros(maxSpawns), "vec4");
413
+ this.#drainCount = uniform(0, "uint");
414
+ this.#drainMin = uniformArray(zeros(MAX_DRAINS), "vec4");
415
+ this.#drainMax = uniformArray(zeros(MAX_DRAINS), "vec4");
416
+ this.#stirCount = uniform(0, "uint");
417
+ this.#stirA = uniformArray(zeros(MAX_STIRS), "vec4");
418
+ this.#stirB = uniformArray(zeros(MAX_STIRS), "vec4");
419
+ this.#colliderCount = uniform(0, "uint");
420
+ this.#colliderA = uniformArray(zeros(maxColliders), "vec4");
421
+ this.#colliderB = uniformArray(zeros(maxColliders), "vec4");
422
+ this.#colliderRows = [
423
+ uniformArray(zeros(maxColliders), "vec4"),
424
+ uniformArray(zeros(maxColliders), "vec4"),
425
+ uniformArray(zeros(maxColliders), "vec4"),
426
+ ];
427
+
428
+ const dt = float(timeStep);
429
+ const live = (index: TslNode): TslNode => positions.element(index).w.greaterThan(0.5);
430
+ const guard = (): void => {
431
+ If(instanceIndex.greaterThanEqual(this.#slots), () => {
432
+ Return();
433
+ });
434
+ If(live(instanceIndex).not(), () => {
435
+ Return();
436
+ });
437
+ };
438
+
439
+ const cellOf = (point: TslNode) =>
440
+ ivec3(
441
+ clamp(
442
+ floor(point.sub(vec3(...gridOrigin)).div(h)),
443
+ vec3(1),
444
+ vec3(gridDims[0] - 2, gridDims[1] - 2, gridDims[2] - 2),
445
+ ),
446
+ );
447
+ const cellId = (cell: TslNode): TslNode =>
448
+ cell.x
449
+ .add(cell.y.mul(gridDims[0]))
450
+ .add(cell.z.mul(gridDims[0] * gridDims[1]))
451
+ .toUint();
452
+
453
+ /** Visit every particle within the smoothing radius of `point`, `self` excluded. */
454
+ const forNeighbours = (
455
+ point: TslNode,
456
+ self: TslNode,
457
+ body: (other: TslNode, offset: TslNode, r2: TslNode) => void,
458
+ ): void => {
459
+ const cell = cellOf(point);
460
+ Loop(27, ({ i: k }: { i: TslNode }) => {
461
+ const dx = k.mod(3).sub(1);
462
+ const dy = k.div(3).mod(3).sub(1);
463
+ const dz = k.div(9).sub(1);
464
+ const id = cellId(cell.add(ivec3(dx, dy, dz)));
465
+ const inCell = min(atomicLoad(cellCount.element(id)), uint(CELL_CAPACITY)).toVar();
466
+ Loop({ start: uint(0), end: inCell, type: "uint" }, ({ i: slot }: { i: TslNode }) => {
467
+ const other = cellItems.element(id.mul(CELL_CAPACITY).add(slot));
468
+ If(other.notEqual(self), () => {
469
+ const offset = point.sub(positions.element(other).xyz);
470
+ const r2 = dot(offset, offset);
471
+ If(r2.lessThan(h2), () => body(other, offset, r2));
472
+ });
473
+ });
474
+ });
475
+ };
476
+ const kernel = (r2: TslNode): TslNode => float(h2).sub(r2).pow(3).mul(poly6);
477
+ const gradientScale = (r: TslNode): TslNode =>
478
+ float(h)
479
+ .sub(r)
480
+ .pow(2)
481
+ .mul(volumeOfParticle * spiky)
482
+ .div(r);
483
+
484
+ const project = (point: TslVar): void => {
485
+ point.assign(clamp(point, vec3(...min3), vec3(...max3)));
486
+ Loop({ start: uint(0), end: this.#colliderCount, type: "uint" }, ({ i }: { i: TslNode }) => {
487
+ const a = this.#colliderA.element(i);
488
+ const b = this.#colliderB.element(i);
489
+ const offset = point.sub(a.xyz);
490
+ If(dot(offset, offset).lessThan(b.w.add(radius).pow(2)), () => {
491
+ If(a.w.lessThan(0.5), () => {
492
+ const reach = b.x.add(radius);
493
+ const distance = length(offset);
494
+ If(distance.lessThan(reach), () => {
495
+ const direction = select(
496
+ distance.lessThan(1e-9),
497
+ vec3(0, 1, 0),
498
+ offset.div(max(distance, 1e-9)),
499
+ );
500
+ point.assign(a.xyz.add(direction.mul(reach)));
501
+ });
502
+ }).Else(() => {
503
+ const rows = this.#colliderRows.map((row) => row.element(i).xyz);
504
+ const local = vec3(
505
+ dot(rows[0] as TslNode, offset),
506
+ dot(rows[1] as TslNode, offset),
507
+ dot(rows[2] as TslNode, offset),
508
+ );
509
+ const half = b.xyz.add(radius);
510
+ const absolute = abs(local);
511
+ If(
512
+ absolute.x
513
+ .lessThan(half.x)
514
+ .and(absolute.y.lessThan(half.y))
515
+ .and(absolute.z.lessThan(half.z)),
516
+ () => {
517
+ const gap = half.sub(absolute);
518
+ const out = nodeVar(local);
519
+ If(gap.x.lessThan(gap.y).and(gap.x.lessThan(gap.z)), () => {
520
+ out.assign(
521
+ vec3(select(local.x.lessThan(0), half.x.negate(), half.x), local.y, local.z),
522
+ );
523
+ })
524
+ .ElseIf(gap.y.lessThan(gap.z), () => {
525
+ out.assign(
526
+ vec3(local.x, select(local.y.lessThan(0), half.y.negate(), half.y), local.z),
527
+ );
528
+ })
529
+ .Else(() => {
530
+ out.assign(
531
+ vec3(local.x, local.y, select(local.z.lessThan(0), half.z.negate(), half.z)),
532
+ );
533
+ });
534
+ const world = (rows[0] as TslNode)
535
+ .mul((out as TslNode).x)
536
+ .add((rows[1] as TslNode).mul((out as TslNode).y))
537
+ .add((rows[2] as TslNode).mul((out as TslNode).z));
538
+ point.assign(a.xyz.add(world));
539
+ },
540
+ );
541
+ });
542
+ });
543
+ });
544
+ // Colliders push outward, possibly past the container: the container wins.
545
+ point.assign(clamp(point, vec3(...min3), vec3(...max3)));
546
+ };
547
+
548
+ this.#inject = computeKernel("fluidParticles.inject", capacity, () => {
549
+ const slot = instanceIndex;
550
+ If(slot.greaterThanEqual(uint(capacity)), () => {
551
+ Return();
552
+ });
553
+ const body = positions.element(slot);
554
+ const motion = velocities.element(slot);
555
+ Loop({ start: uint(0), end: this.#drainCount, type: "uint" }, ({ i }: { i: TslNode }) => {
556
+ const low = this.#drainMin.element(i).xyz;
557
+ const high = this.#drainMax.element(i).xyz;
558
+ const p = body.xyz;
559
+ If(
560
+ body.w
561
+ .greaterThan(0.5)
562
+ .and(p.x.greaterThanEqual(low.x))
563
+ .and(p.x.lessThanEqual(high.x))
564
+ .and(p.y.greaterThanEqual(low.y))
565
+ .and(p.y.lessThanEqual(high.y))
566
+ .and(p.z.greaterThanEqual(low.z))
567
+ .and(p.z.lessThanEqual(high.z)),
568
+ () => {
569
+ body.assign(vec4(p, 0));
570
+ motion.assign(vec4(0));
571
+ },
572
+ );
573
+ });
574
+ Loop({ start: uint(0), end: this.#spawnCount, type: "uint" }, ({ i }: { i: TslNode }) => {
575
+ const a = this.#spawnA.element(i); // min.xyz, first slot
576
+ const b = this.#spawnB.element(i); // lattice dims xyz, particle count
577
+ const c = this.#spawnC.element(i); // velocity.xyz, lattice spacing
578
+ const relative = slot.add(uint(capacity)).sub(a.w.toUint()).mod(uint(capacity));
579
+ If(relative.lessThan(b.w.toUint()), () => {
580
+ const nx = b.x.toUint();
581
+ const nz = b.z.toUint();
582
+ const ix = relative.mod(nx);
583
+ const iz = relative.div(nx).mod(nz);
584
+ const iy = relative.div(nx.mul(nz));
585
+ const jitter = select(
586
+ b.w.greaterThan(1.5),
587
+ vec3(
588
+ hash(slot.add(relative)).sub(0.5),
589
+ hash(slot.add(relative).add(uint(104729))).sub(0.5),
590
+ hash(slot.add(relative).add(uint(7919))).sub(0.5),
591
+ ).mul(c.w.mul(0.1)),
592
+ vec3(0),
593
+ );
594
+ const placed = a.xyz.add(vec3(float(ix), float(iy), float(iz)).mul(c.w)).add(jitter);
595
+ body.assign(vec4(placed, 1));
596
+ motion.assign(vec4(c.xyz, 0));
597
+ });
598
+ });
599
+ });
600
+
601
+ this.#predict = computeKernel("fluidParticles.predict", capacity, () => {
602
+ guard();
603
+ const i = instanceIndex;
604
+ const velocity = nodeVar(velocities.element(i).xyz);
605
+ const position = nodeVar(positions.element(i).xyz);
606
+ Loop({ start: uint(0), end: this.#stirCount, type: "uint" }, ({ i: s }: { i: TslNode }) => {
607
+ const centre = this.#stirA.element(s);
608
+ const offset = position.sub(centre.xyz);
609
+ const distance = length(offset);
610
+ If(distance.lessThan(centre.w), () => {
611
+ const t = float(1).sub(distance.div(centre.w)).mul(this.#stirB.element(s).x);
612
+ velocity.assign(
613
+ velocity.add(
614
+ vec3(
615
+ offset.x.div(distance.add(0.15)).mul(t),
616
+ t.mul(0.65),
617
+ offset.z.div(distance.add(0.15)).mul(t),
618
+ ),
619
+ ),
620
+ );
621
+ });
622
+ });
623
+ velocity.assign(velocity.add(vec3(0, this.#gravity.negate().mul(dt), 0)));
624
+ if (options.force !== undefined)
625
+ velocity.assign(
626
+ velocity.add(
627
+ (
628
+ options.force(position as never, velocity as never, this.#time as never) as TslNode
629
+ ).mul(dt),
630
+ ),
631
+ );
632
+ velocity.assign(velocity.mul(float(maxSpeed).div(max(length(velocity), maxSpeed))));
633
+ previous.element(i).assign(vec4(position, 1));
634
+ // A single 18 m/s step can cross the dam gate completely. Project along the path, with
635
+ // segments no longer than the particle radius (at most four at the default speed/step).
636
+ const substeps = clamp(
637
+ ceil(length(velocity).mul(dt).div(radius)),
638
+ 1,
639
+ Math.max(1, Math.ceil((maxSpeed * timeStep) / radius)),
640
+ )
641
+ .toUint()
642
+ .toVar("fluidSubsteps");
643
+ Loop({ start: uint(0), end: substeps, type: "uint" }, () => {
644
+ position.assign(position.add(velocity.mul(dt).div(float(substeps))));
645
+ project(position);
646
+ });
647
+ positions.element(i).assign(vec4(position, 1));
648
+ velocities.element(i).assign(vec4(velocity, velocities.element(i).w));
649
+ });
650
+
651
+ this.#gridClear = computeKernel("fluidParticles.grid.clear", cells, () => {
652
+ If(instanceIndex.greaterThanEqual(uint(cells)), () => {
653
+ Return();
654
+ });
655
+ atomicStore(cellCount.element(instanceIndex), uint(0));
656
+ });
657
+ this.#gridBuild = computeKernel("fluidParticles.grid.build", capacity, () => {
658
+ guard();
659
+ const id = cellId(cellOf(positions.element(instanceIndex).xyz));
660
+ const slot = atomicAdd(cellCount.element(id), uint(1)).toVar();
661
+ If(slot.lessThan(uint(CELL_CAPACITY)), () => {
662
+ cellItems.element(id.mul(CELL_CAPACITY).add(slot)).assign(instanceIndex);
663
+ });
664
+ });
665
+
666
+ this.#lambda = computeKernel("fluidParticles.lambda", capacity, () => {
667
+ guard();
668
+ const i = instanceIndex;
669
+ const p = positions.element(i).xyz;
670
+ const rho = nodeVar(float(volumeOfParticle * wSelf));
671
+ const gradient = nodeVar(vec3(0));
672
+ const sum = nodeVar(float(0));
673
+ forNeighbours(p, i, (_other, offset, r2) => {
674
+ rho.addAssign(kernel(r2).mul(volumeOfParticle));
675
+ const r = r2.sqrt();
676
+ If(r.greaterThan(1e-6), () => {
677
+ const a = offset.mul(gradientScale(r));
678
+ gradient.addAssign(a);
679
+ sum.addAssign(dot(a, a));
680
+ });
681
+ });
682
+ densities.element(i).assign(rho);
683
+ const constraint = max(rho.sub(1), 0);
684
+ lambdas
685
+ .element(i)
686
+ .assign(constraint.negate().div(sum.add(dot(gradient, gradient)).add(relaxation)));
687
+ });
688
+
689
+ this.#delta = computeKernel("fluidParticles.delta", capacity, () => {
690
+ guard();
691
+ const i = instanceIndex;
692
+ const p = positions.element(i).xyz;
693
+ const own = lambdas.element(i);
694
+ const total = nodeVar(vec3(0));
695
+ forNeighbours(p, i, (other, offset, r2) => {
696
+ const r = r2.sqrt();
697
+ If(r.greaterThan(1e-6), () => {
698
+ const ratio = kernel(r2).div(wReference);
699
+ const tensile = ratio.pow(4).mul(-0.001);
700
+ const strength = own.add(lambdas.element(other)).add(tensile);
701
+ total.addAssign(offset.mul(strength.mul(gradientScale(r))));
702
+ });
703
+ });
704
+ const limit = spacing * 0.24;
705
+ const magnitude = length(total);
706
+ const scale = select(magnitude.greaterThan(limit), float(limit).div(magnitude), float(1));
707
+ deltas.element(i).assign(vec4(total.mul(scale), 0));
708
+ });
709
+
710
+ this.#apply = computeKernel("fluidParticles.apply", capacity, () => {
711
+ guard();
712
+ const i = instanceIndex;
713
+ const p = nodeVar(positions.element(i).xyz.add(deltas.element(i).xyz));
714
+ project(p);
715
+ positions.element(i).assign(vec4(p, 1));
716
+ });
717
+
718
+ this.#velocity = computeKernel("fluidParticles.velocity", capacity, () => {
719
+ guard();
720
+ const i = instanceIndex;
721
+ const v = positions.element(i).xyz.sub(previous.element(i).xyz).div(dt);
722
+ velocities.element(i).assign(vec4(v, velocities.element(i).w));
723
+ });
724
+
725
+ this.#smooth = computeKernel("fluidParticles.smooth", capacity, () => {
726
+ guard();
727
+ const i = instanceIndex;
728
+ const p = positions.element(i).xyz;
729
+ const v = velocities.element(i).xyz;
730
+ const change = nodeVar(vec3(0));
731
+ const curl = nodeVar(vec3(0));
732
+ const neighbours = nodeVar(float(0));
733
+ forNeighbours(p, i, (other, offset, r2) => {
734
+ const w = kernel(r2).mul(volumeOfParticle);
735
+ const dv = velocities.element(other).xyz.sub(v);
736
+ change.addAssign(
737
+ dv.mul(this.#viscosity.mul(w)).sub(offset.mul(this.#cohesion.mul(w).mul(dt).mul(8))),
738
+ );
739
+ neighbours.addAssign(1);
740
+ const r = r2.sqrt();
741
+ If(r.greaterThan(1e-6), () => {
742
+ const s = gradientScale(r);
743
+ curl.addAssign(
744
+ vec3(
745
+ dv.y.mul(offset.z).sub(dv.z.mul(offset.y)),
746
+ dv.z.mul(offset.x).sub(dv.x.mul(offset.z)),
747
+ dv.x.mul(offset.y).sub(dv.y.mul(offset.x)),
748
+ ).mul(s),
749
+ );
750
+ });
751
+ });
752
+ deltas.element(i).assign(vec4(change, 0));
753
+ omega.element(i).assign(vec4(curl, neighbours));
754
+ });
755
+
756
+ this.#confine = computeKernel("fluidParticles.confine", capacity, () => {
757
+ guard();
758
+ const i = instanceIndex;
759
+ const p = positions.element(i).xyz;
760
+ const own = length(omega.element(i).xyz);
761
+ const eta = nodeVar(vec3(0));
762
+ forNeighbours(p, i, (other, offset, r2) => {
763
+ const r = r2.sqrt();
764
+ If(r.greaterThan(1e-6), () => {
765
+ const diff = length(omega.element(other).xyz).sub(own);
766
+ eta.addAssign(offset.mul(gradientScale(r).mul(diff)));
767
+ });
768
+ });
769
+ const w = omega.element(i).xyz;
770
+ const scale = this.#vorticity.mul(dt).div(length(eta).add(1e-5));
771
+ const force = vec3(
772
+ eta.y.mul(w.z).sub(eta.z.mul(w.y)),
773
+ eta.z.mul(w.x).sub(eta.x.mul(w.z)),
774
+ eta.x.mul(w.y).sub(eta.y.mul(w.x)),
775
+ ).mul(scale);
776
+ const limited = clamp(force, vec3(-0.15), vec3(0.15));
777
+ const v = nodeVar(
778
+ velocities
779
+ .element(i)
780
+ .xyz.add(deltas.element(i).xyz)
781
+ .add(select(this.#vorticity.greaterThan(0), limited, vec3(0))),
782
+ );
783
+ const position = positions.element(i).xyz;
784
+ If(position.y.lessThanEqual(min3[1] + 0.002), () => {
785
+ v.assign(vec3(v.x.mul(1 - wallFriction), v.y, v.z.mul(1 - wallFriction)));
786
+ });
787
+ v.assign(v.mul(float(maxSpeed).div(max(length(v), maxSpeed))));
788
+ const speed = length(v);
789
+ const source = clamp(speed.sub(1.5).mul(0.14), 0, 1).mul(
790
+ select(omega.element(i).w.lessThan(22), float(1), float(0.2)),
791
+ );
792
+ const foam = max(velocities.element(i).w.mul(exp(dt.mul(-1.3))), source);
793
+ velocities.element(i).assign(vec4(v, foam));
794
+ atomicAdd(stats.element(0), uint(1));
795
+ atomicAdd(stats.element(1), uint(max(densities.element(i).sub(1), 0).mul(COMPRESSION_SCALE)));
796
+ atomicMax(stats.element(2), uint(speed.mul(FIXED_POINT)));
797
+ for (let axis = 0; axis < 3; axis += 1) {
798
+ const offset = uint(
799
+ max(
800
+ [position.x, position.y, position.z][axis]?.sub(min3[axis] as number).add(1) as TslNode,
801
+ 0,
802
+ ).mul(FIXED_POINT),
803
+ );
804
+ atomicMin(stats.element(3 + axis), offset);
805
+ atomicMax(stats.element(6 + axis), offset);
806
+ }
807
+ });
808
+
809
+ this.#statsClear = computeKernel("fluidParticles.stats.clear", STAT_WORDS, () => {
810
+ If(instanceIndex.greaterThanEqual(uint(STAT_WORDS)), () => {
811
+ Return();
812
+ });
813
+ const word = instanceIndex;
814
+ atomicStore(
815
+ stats.element(word),
816
+ select(word.greaterThanEqual(3).and(word.lessThan(6)), uint(0xffffffff), uint(0)),
817
+ );
818
+ });
819
+ this.#statsFinalize = computeKernel("fluidParticles.stats.finalize", STAT_WORDS, () => {
820
+ If(instanceIndex.greaterThanEqual(uint(STAT_WORDS)), () => {
821
+ Return();
822
+ });
823
+ const word = instanceIndex;
824
+ const count = float(atomicLoad(stats.element(0)));
825
+ const raw = float(atomicLoad(stats.element(word)));
826
+ const axis = word.sub(3).mod(3);
827
+ const base = select(
828
+ axis.equal(0),
829
+ float(min3[0]),
830
+ select(axis.equal(1), float(min3[1]), float(min3[2])),
831
+ );
832
+ const spatial = select(count.lessThan(0.5), float(0), raw.div(FIXED_POINT).sub(1).add(base));
833
+ const value = select(
834
+ word.equal(0),
835
+ raw,
836
+ select(
837
+ word.equal(1),
838
+ raw.div(COMPRESSION_SCALE).div(max(count, 1)),
839
+ select(word.equal(2), raw.div(FIXED_POINT), spatial),
840
+ ),
841
+ );
842
+ readout.element(word).assign(value);
843
+ });
844
+
845
+ this.#volume = computeKernel("fluidParticles.volume", voxels, () => {
846
+ If(instanceIndex.greaterThanEqual(uint(voxels)), () => {
847
+ Return();
848
+ });
849
+ const ix = instanceIndex.mod(uint(vx));
850
+ const iy = instanceIndex.div(uint(vx)).mod(uint(vy));
851
+ const iz = instanceIndex.div(uint(vx * vy));
852
+ const centre = vec3(float(ix), float(iy), float(iz))
853
+ .add(0.5)
854
+ .mul(voxelSize)
855
+ .add(vec3(...min3));
856
+ const total = nodeVar(float(0));
857
+ forNeighbours(centre, uint(0xffffffff), (_other, _offset, r2) => {
858
+ total.addAssign(kernel(r2).mul(volumeOfParticle));
859
+ });
860
+ volumeBuffer.element(instanceIndex).assign(total);
861
+ textureStore(
862
+ storageTexture(this.density).toWriteOnly(),
863
+ uvec3(ix, iy, iz),
864
+ vec4(total, 0, 0, 1),
865
+ ).toWriteOnly();
866
+ });
867
+
868
+ /** Is `point` inside any collider? Used to tell a column roofed by a body from open water. */
869
+ const insideCollider = (point: TslNode): TslNode => {
870
+ const inside = nodeVar(float(0));
871
+ Loop({ start: uint(0), end: this.#colliderCount, type: "uint" }, ({ i }: { i: TslNode }) => {
872
+ const a = this.#colliderA.element(i);
873
+ const b = this.#colliderB.element(i);
874
+ const offset = point.sub(a.xyz);
875
+ If(a.w.lessThan(0.5), () => {
876
+ If(length(offset).lessThan(b.x), () => {
877
+ inside.assign(float(1));
878
+ });
879
+ }).Else(() => {
880
+ const rows = this.#colliderRows.map((row) => row.element(i).xyz);
881
+ const local = abs(
882
+ vec3(
883
+ dot(rows[0] as TslNode, offset),
884
+ dot(rows[1] as TslNode, offset),
885
+ dot(rows[2] as TslNode, offset),
886
+ ),
887
+ );
888
+ If(local.x.lessThan(b.x).and(local.y.lessThan(b.y)).and(local.z.lessThan(b.z)), () => {
889
+ inside.assign(float(1));
890
+ });
891
+ });
892
+ });
893
+ return inside;
894
+ };
895
+
896
+ this.#columnHeights = computeKernel("fluidParticles.columns", vx * vz, () => {
897
+ If(instanceIndex.greaterThanEqual(uint(vx * vz)), () => {
898
+ Return();
899
+ });
900
+ const ix = instanceIndex.mod(uint(vx));
901
+ const iz = instanceIndex.div(uint(vx));
902
+ const top = nodeVar(float(min3[1]));
903
+ const topLayer = nodeVar(int(-1));
904
+ Loop({ start: int(0), end: int(vy), type: "int" }, ({ i: layer }: { i: TslNode }) => {
905
+ const voxel = ix.add(uint(layer).mul(uint(vx))).add(iz.mul(uint(vx * vy)));
906
+ If(volumeBuffer.element(voxel).greaterThan(0.5), () => {
907
+ top.assign(float(layer).add(1).mul(voxelSize).add(min3[1]));
908
+ topLayer.assign(layer);
909
+ });
910
+ });
911
+ // A body on the column displaces its water: what is left under it is the hull's underside
912
+ // (or the bare floor), not the free surface. Flag such a column so `sample` reads its
913
+ // neighbours. `topLayer + 1` is the first voxel above the water, or the floor when dry.
914
+ const covered = nodeVar(float(0));
915
+ for (const above of [0, 1, 2]) {
916
+ const centre = vec3(
917
+ float(ix).add(0.5).mul(voxelSize).add(min3[0]),
918
+ float(topLayer.add(1 + above))
919
+ .add(0.5)
920
+ .mul(voxelSize)
921
+ .add(min3[1]),
922
+ float(iz).add(0.5).mul(voxelSize).add(min3[2]),
923
+ );
924
+ If(insideCollider(centre).greaterThan(0.5), () => {
925
+ covered.assign(float(1));
926
+ });
927
+ }
928
+ readout
929
+ .element(uint(READOUT_HEADER).add(instanceIndex))
930
+ .assign(select(covered.greaterThan(0.5), float(COVERED), top));
931
+ });
932
+
933
+ this.#readback = new GPUReadback({ attribute: readout.value, everyFrames: readbackEvery });
934
+ this.warmupNodes = [
935
+ this.#inject,
936
+ this.#predict,
937
+ this.#gridClear,
938
+ this.#gridBuild,
939
+ this.#lambda,
940
+ this.#delta,
941
+ this.#apply,
942
+ this.#velocity,
943
+ this.#smooth,
944
+ this.#confine,
945
+ this.#statsClear,
946
+ this.#statsFinalize,
947
+ this.#volume,
948
+ this.#columnHeights,
949
+ ];
950
+ this.addEventListener("removed", this.#onRemoved);
951
+ }
952
+
953
+ get released(): boolean {
954
+ return this.#released;
955
+ }
956
+
957
+ /** Slots handed out so far; never above `capacity`. */
958
+ get used(): number {
959
+ return this.#used;
960
+ }
961
+
962
+ get steps(): number {
963
+ return this.#steps;
964
+ }
965
+
966
+ get viscosity(): number {
967
+ return this.#viscosity.value;
968
+ }
969
+
970
+ set viscosity(value: number) {
971
+ nonNegative("viscosity", value);
972
+ this.#viscosity.value = value;
973
+ }
974
+
975
+ get cohesion(): number {
976
+ return this.#cohesion.value;
977
+ }
978
+
979
+ set cohesion(value: number) {
980
+ nonNegative("cohesion", value);
981
+ this.#cohesion.value = value;
982
+ }
983
+
984
+ get vorticity(): number {
985
+ return this.#vorticity.value;
986
+ }
987
+
988
+ set vorticity(value: number) {
989
+ nonNegative("vorticity", value);
990
+ this.#vorticity.value = value;
991
+ }
992
+
993
+ get gravity(): number {
994
+ return this.#gravity.value;
995
+ }
996
+
997
+ set gravity(value: number) {
998
+ nonNegative("gravity", value);
999
+ this.#gravity.value = value;
1000
+ }
1001
+
1002
+ attachRenderer(renderer: IRendererLike): void {
1003
+ if (this.#released) throw new Error("FluidParticles3D cannot be attached after release.");
1004
+ if (this.#renderer === renderer) return;
1005
+ if (renderer.kind !== "webgpu")
1006
+ throw new Error(
1007
+ "FluidParticles3D needs a WebGPU renderer: the solver is compute-only and would draw nothing on this backend.",
1008
+ );
1009
+ if (this.#renderer !== undefined)
1010
+ throw new Error("FluidParticles3D is already attached to a renderer.");
1011
+ this.#renderer = renderer;
1012
+ }
1013
+
1014
+ /**
1015
+ * Place a lattice of particles in `[min, max]`, one per `spacing`, and return how many fit.
1016
+ * Particles never wrap: a full solver places none.
1017
+ */
1018
+ fill(min: Vec3, max: Vec3, velocity: Vec3 = [0, 0, 0]): number {
1019
+ this.#assertLive("fill");
1020
+ finiteVec("fill.min", min, 3);
1021
+ finiteVec("fill.max", max, 3);
1022
+ finiteVec("fill.velocity", velocity, 3);
1023
+ const dims = [0, 1, 2].map(
1024
+ (axis) =>
1025
+ Math.floor(((max[axis] as number) - (min[axis] as number)) / this.spacing + 1e-6) + 1,
1026
+ ) as [number, number, number];
1027
+ if (dims.some((dim) => dim < 1)) throw new Error("FluidParticles3D.fill needs max >= min.");
1028
+ const wanted = dims[0] * dims[1] * dims[2];
1029
+ const room = this.capacity - this.#cursor;
1030
+ const placed = Math.min(wanted, room);
1031
+ if (placed <= 0 || this.#queuedSpawns >= this.maxSpawns) return 0;
1032
+ this.#queueSpawn(min, dims, placed, velocity, this.spacing);
1033
+ this.#cursor += placed;
1034
+ this.#used = Math.min(this.#cursor, this.capacity);
1035
+ return placed;
1036
+ }
1037
+
1038
+ /** Spawn one particle. Once every slot has been used the oldest slot is recycled. */
1039
+ emit(position: Vec3, velocity: Vec3 = [0, 0, 0]): boolean {
1040
+ this.#assertLive("emit");
1041
+ finiteVec("emit.position", position, 3);
1042
+ finiteVec("emit.velocity", velocity, 3);
1043
+ if (this.#queuedSpawns >= this.maxSpawns) return false;
1044
+ const slot = this.#cursor % this.capacity;
1045
+ this.#queueSpawn(position, [1, 1, 1], 1, velocity, 1, slot);
1046
+ this.#cursor += 1;
1047
+ this.#used = Math.min(this.#cursor, this.capacity);
1048
+ return true;
1049
+ }
1050
+
1051
+ /** Free every live particle inside the box on the next step. */
1052
+ drain(min: Vec3, max: Vec3): boolean {
1053
+ this.#assertLive("drain");
1054
+ finiteVec("drain.min", min, 3);
1055
+ finiteVec("drain.max", max, 3);
1056
+ if (this.#queuedDrains >= MAX_DRAINS) return false;
1057
+ (this.#drainMin.array[this.#queuedDrains] as Vector4).set(min[0], min[1], min[2], 0);
1058
+ (this.#drainMax.array[this.#queuedDrains] as Vector4).set(max[0], max[1], max[2], 0);
1059
+ this.#queuedDrains += 1;
1060
+ return true;
1061
+ }
1062
+
1063
+ /** Push particles within `radius` of `point` outward and up, strongest at the centre. */
1064
+ stir(point: Vec3, strength: number, radius: number): boolean {
1065
+ this.#assertLive("stir");
1066
+ finiteVec("stir.point", point, 3);
1067
+ positive("stir.radius", radius);
1068
+ if (!Number.isFinite(strength))
1069
+ throw new Error("FluidParticles3D.stir.strength must be finite.");
1070
+ if (this.#queuedStirs >= MAX_STIRS) return false;
1071
+ (this.#stirA.array[this.#queuedStirs] as Vector4).set(point[0], point[1], point[2], radius);
1072
+ (this.#stirB.array[this.#queuedStirs] as Vector4).set(strength, 0, 0, 0);
1073
+ this.#queuedStirs += 1;
1074
+ return true;
1075
+ }
1076
+
1077
+ /** Replace the colliders. Call it every fixed step with the bodies' current transforms. */
1078
+ setColliders(colliders: readonly IFluidCollider[]): void {
1079
+ this.#assertLive("setColliders");
1080
+ if (colliders.length > this.maxColliders)
1081
+ throw new Error(`FluidParticles3D.setColliders accepts at most ${this.maxColliders}.`);
1082
+ // Validate every collider before writing any, so a throw leaves the previous set intact.
1083
+ const rows = colliders.map((collider) => {
1084
+ finiteVec("collider.center", collider.center, 3);
1085
+ if (collider.kind === "sphere") {
1086
+ positive("collider.radius", collider.radius);
1087
+ return undefined;
1088
+ }
1089
+ finiteVec("collider.halfExtents", collider.halfExtents, 3);
1090
+ if (collider.halfExtents.some((half) => half <= 0))
1091
+ throw new Error("FluidParticles3D.collider.halfExtents must be positive.");
1092
+ return basisRows(collider.rotation ?? [0, 0, 0, 1]);
1093
+ });
1094
+ colliders.forEach((collider, index) => {
1095
+ const a = this.#colliderA.array[index] as Vector4;
1096
+ const b = this.#colliderB.array[index] as Vector4;
1097
+ if (collider.kind === "sphere") {
1098
+ a.set(...collider.center, 0);
1099
+ b.set(collider.radius, 0, 0, collider.radius);
1100
+ return;
1101
+ }
1102
+ a.set(...collider.center, 1);
1103
+ b.set(...collider.halfExtents, new Vector3(...collider.halfExtents).length());
1104
+ (rows[index] as readonly Vec3[]).forEach((row, axis) =>
1105
+ (this.#colliderRows[axis]?.array[index] as Vector4).set(row[0], row[1], row[2], 0),
1106
+ );
1107
+ });
1108
+ this.#colliders = colliders.length;
1109
+ }
1110
+
1111
+ /**
1112
+ * Free-surface height near `(x, z)`, box-filtered over open columns of the newest landed GPU
1113
+ * copy; `bounds.min.y` where no water is near or nothing has landed yet. Shaped for `Buoyancy3D`'s `surface`.
1114
+ */
1115
+ sample(x: number, z: number, _time = 0): { readonly height: number } {
1116
+ const data = this.#readback.data;
1117
+ const floor = this.bounds.min[1];
1118
+ if (
1119
+ data === undefined ||
1120
+ x < this.bounds.min[0] ||
1121
+ x > this.bounds.max[0] ||
1122
+ z < this.bounds.min[2] ||
1123
+ z > this.bounds.max[2]
1124
+ )
1125
+ return { height: floor };
1126
+ const [columns, rows] = this.#columns;
1127
+ const minimumOpen = Math.min(MIN_OPEN_COLUMNS, columns * rows);
1128
+ const cx = Math.round(
1129
+ clampNumber((x - this.bounds.min[0]) / this.voxelSize - 0.5, 0, columns - 1),
1130
+ );
1131
+ const cz = Math.round(
1132
+ clampNumber((z - this.bounds.min[2]) / this.voxelSize - 0.5, 0, rows - 1),
1133
+ );
1134
+ // A box-filter over the open columns near the point: splash noise averages out, and a column
1135
+ // roofed by a body (flagged COVERED) is read through the open water around it, widening until
1136
+ // enough of it is found.
1137
+ for (let radius = SURFACE_FILTER; radius <= COVERED_SEARCH; radius += 1) {
1138
+ let sum = 0;
1139
+ let found = 0;
1140
+ for (let pz = Math.max(0, cz - radius); pz <= Math.min(rows - 1, cz + radius); pz += 1)
1141
+ for (let px = Math.max(0, cx - radius); px <= Math.min(columns - 1, cx + radius); px += 1) {
1142
+ const value = data[READOUT_HEADER + px + pz * columns] ?? COVERED;
1143
+ if (value > COVERED / 2) {
1144
+ sum += value;
1145
+ found += 1;
1146
+ }
1147
+ }
1148
+ if (found >= minimumOpen) return { height: sum / found };
1149
+ }
1150
+ return { height: floor };
1151
+ }
1152
+
1153
+ /** Surface height at `(x, z)`; see {@link sample}. */
1154
+ heightAt(x: number, z: number): number {
1155
+ return this.sample(x, z).height;
1156
+ }
1157
+
1158
+ /**
1159
+ * Fixed steps between the GPU state the newest copy holds and now; grows until the first copy
1160
+ * lands. `sample` and `heightAt` read the same copy, so this is their age too.
1161
+ */
1162
+ get staleFrames(): number {
1163
+ return this.#readback.staleFrames;
1164
+ }
1165
+
1166
+ /** Counts and extremes from the newest landed GPU copy, or `undefined` before one lands. */
1167
+ get stats(): IFluidParticlesStats | undefined {
1168
+ const sample = this.#readback.sample;
1169
+ if (sample === undefined) return undefined;
1170
+ const d = sample.data;
1171
+ return {
1172
+ count: d[0] ?? 0,
1173
+ meanCompression: d[1] ?? 0,
1174
+ maxSpeed: d[2] ?? 0,
1175
+ min: [d[3] ?? 0, d[4] ?? 0, d[5] ?? 0],
1176
+ max: [d[6] ?? 0, d[7] ?? 0, d[8] ?? 0],
1177
+ staleFrames: sample.staleFrames,
1178
+ };
1179
+ }
1180
+
1181
+ process(renderer = this.#renderer): void {
1182
+ if (this.#released) return;
1183
+ if (renderer === undefined) throw new Error("FluidParticles3D is not attached to a renderer.");
1184
+ this.#time.value += this.timeStep;
1185
+ this.#slots.value = this.#used;
1186
+ this.#spawnCount.value = this.#queuedSpawns;
1187
+ this.#drainCount.value = this.#queuedDrains;
1188
+ this.#stirCount.value = this.#queuedStirs;
1189
+ this.#colliderCount.value = this.#colliders;
1190
+ if (this.#queuedSpawns > 0 || this.#queuedDrains > 0) renderer.compute(this.#inject);
1191
+ this.#queuedSpawns = 0;
1192
+ this.#queuedDrains = 0;
1193
+ if (this.#used > 0) {
1194
+ renderer.compute(this.#predict);
1195
+ for (let iteration = 0; iteration < this.iterations; iteration += 1) {
1196
+ renderer.compute(this.#gridClear);
1197
+ renderer.compute(this.#gridBuild);
1198
+ renderer.compute(this.#lambda);
1199
+ renderer.compute(this.#delta);
1200
+ renderer.compute(this.#apply);
1201
+ }
1202
+ renderer.compute(this.#gridClear);
1203
+ renderer.compute(this.#gridBuild);
1204
+ renderer.compute(this.#velocity);
1205
+ renderer.compute(this.#statsClear);
1206
+ renderer.compute(this.#smooth);
1207
+ renderer.compute(this.#confine);
1208
+ renderer.compute(this.#statsFinalize);
1209
+ renderer.compute(this.#volume);
1210
+ renderer.compute(this.#columnHeights);
1211
+ }
1212
+ this.#queuedStirs = 0;
1213
+ this.#steps += 1;
1214
+ this.#readback.request(renderer);
1215
+ }
1216
+
1217
+ detach(): void {
1218
+ if (this.#released) return;
1219
+ this.#renderer = undefined;
1220
+ for (const node of this.warmupNodes) node.dispose();
1221
+ this.density.dispose();
1222
+ for (const buffer of this.#buffers) buffer.value.dispose();
1223
+ this.#readback.dispose();
1224
+ this.#released = true;
1225
+ }
1226
+
1227
+ #queueSpawn(
1228
+ first: Vec3,
1229
+ dims: Vec3,
1230
+ count: number,
1231
+ velocity: Vec3,
1232
+ spacing: number,
1233
+ slot = this.#cursor % this.capacity,
1234
+ ): void {
1235
+ const index = this.#queuedSpawns;
1236
+ (this.#spawnA.array[index] as Vector4).set(first[0], first[1], first[2], slot);
1237
+ (this.#spawnB.array[index] as Vector4).set(dims[0], dims[1], dims[2], count);
1238
+ (this.#spawnC.array[index] as Vector4).set(velocity[0], velocity[1], velocity[2], spacing);
1239
+ this.#queuedSpawns += 1;
1240
+ }
1241
+
1242
+ #assertLive(name: string): void {
1243
+ if (this.#released) throw new Error(`FluidParticles3D cannot ${name} after release.`);
1244
+ }
1245
+
1246
+ #onRemoved = (): void => {
1247
+ if (this.#renderer !== undefined) this.detach();
1248
+ };
1249
+ }
1250
+
1251
+ function clampNumber(value: number, low: number, high: number): number {
1252
+ return Math.min(high, Math.max(low, value));
1253
+ }