@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,1399 @@
1
+ // Ported from Ultra Elements src/vfx/GroundField.js @698b720 (MIT, Copyright (c) 2026 Humpalumps). JavaScript copied verbatim; GLSL transliterated to TSL.
2
+ import {
3
+ AddEquation,
4
+ type Camera,
5
+ Color,
6
+ CustomBlending,
7
+ DataTexture,
8
+ FloatType,
9
+ HalfFloatType,
10
+ LinearFilter,
11
+ NearestFilter,
12
+ OneFactor,
13
+ OrthographicCamera,
14
+ RGBAFormat,
15
+ RenderTarget,
16
+ RepeatWrapping,
17
+ Scene,
18
+ type Texture,
19
+ Vector2,
20
+ Vector4,
21
+ } from "three";
22
+ import {
23
+ Break,
24
+ Fn,
25
+ If,
26
+ Loop,
27
+ abs,
28
+ atan,
29
+ clamp,
30
+ cos,
31
+ dot,
32
+ exp,
33
+ exp2,
34
+ float,
35
+ floor,
36
+ fract,
37
+ int,
38
+ ivec2,
39
+ length,
40
+ log,
41
+ log2,
42
+ max,
43
+ min,
44
+ mix,
45
+ pow,
46
+ screenCoordinate,
47
+ select,
48
+ sin,
49
+ smoothstep,
50
+ sqrt,
51
+ step,
52
+ texture,
53
+ textureLoad,
54
+ uniform,
55
+ uv,
56
+ vec2,
57
+ vec3,
58
+ vec4,
59
+ } from "three/tsl";
60
+ import { type Node, NodeMaterial, QuadMesh, type TextureNode } from "three/webgpu";
61
+ import { ARENA, U, groundA, groundB, hash12, hash33, setGroundTexture } from "./common.js";
62
+
63
+ type F = Node<"float">;
64
+ type V2 = Node<"vec2">;
65
+ type V4 = Node<"vec4">;
66
+ type B = Node<"bool">;
67
+ type TexNode = TextureNode<"vec4">;
68
+
69
+ // Ground reaction field: a floor-aligned 40 x 40 m ping-pong pair (RGBA16F MRT, linear, clamp)
70
+ // A = (heat, char, wet, frost) B = (crack, acid, corruption, glow)
71
+ // The sim pass steps every reaction, applies this frame's splats (uniform-bounded loop) and
72
+ // adds this frame's particle paint (paintScene, drawn additively into a cleared paint target).
73
+ // Frost, crack and corruption above 1 are "potential": a front advances into a neighbour with
74
+ // max(neighbour) - drop, so the initial potential sets the reach. Fronts are gated by a baked
75
+ // mask (frost: dendrite tips + noise, crack: voronoi vein network, corruption: warped veins).
76
+ // Slow decays use stochastic rounding: fp16 has 10 mantissa bits, so a tau = 25 s decay at
77
+ // 144 Hz (0.03% per frame) would otherwise round to no change at all.
78
+ //
79
+ // Partial update: a 1024^2 MRT pass is bandwidth bound (~0.11 ms on a 3060 even as a plain
80
+ // copy), so a frame only touches part of the field. Splats (and touch()) register regions
81
+ // that are stepped every frame (up to 4 "fast" boxes clustered from the live regions, padded
82
+ // by how far their fronts can reach); the rest is stepped in 32 rotating row bands with each
83
+ // band's accumulated dt, so slow decays still run everywhere. Last frame's rects are copied
84
+ // so both ping-pong targets stay identical outside what was stepped. Boxes may overlap (an
85
+ // overlap is just computed twice, identically). Paint only lands inside the fast boxes:
86
+ // spells that paint with particles must touch() their area.
87
+ //
88
+ // Engine (ThreeNative's C++ engine over WebGPU), each forced and named ENGINE-GAP below:
89
+ // - no multi-target RenderTarget: A and B are two targets each, stepped by two passes (A's
90
+ // reactions read only A, B's only B, so each pass computes its own half);
91
+ // - no scissor on a RenderTarget: each pass draws its whole target once; the shader steps the same
92
+ // fast boxes and band and copies every other texel, so the field is identical, only upstream's
93
+ // bandwidth saving is lost;
94
+ // - no uniform array read at a computed index: the splats and probe points live in small float
95
+ // DataTextures (as common.ts packs the world);
96
+ // - no synchronous readPixels / PBO fences: the fp16 rounding test and the probes read back
97
+ // through readRenderTargetPixelsAsync.
98
+
99
+ export const MAX_SPLATS = 16,
100
+ MAX_PROBES = 16;
101
+ const SPLAT_VEC4 = 5;
102
+ const MAX_REGIONS = 32;
103
+ const MAX_BOXES = 4;
104
+ const BANDS = 32;
105
+ const PATTERNS: Record<string, number> = { radial: 0, lichtenberg: 1, ring: 2, noise: 3, line: 4 };
106
+ // craters: where a heavy radial crack splat (crack >= 2: a meteor, not a spike's base) landed, so
107
+ // the floor draws its fractures radiating from there and concentric between them. (x, z, radius,
108
+ // strength fading with the cracks); the arena material reads them by reference.
109
+ // ponytail: one field, so module-level; the oldest/weakest of 4 is overwritten
110
+ export const CRACK_SOURCES = Array.from({ length: 4 }, () => new Vector4());
111
+ // hot line cracks (fissure vents): A = (x, z, x2, z2), B = (half-width, strength, seed, -); the arena
112
+ // floor draws the main fissure and en-echelon side cracks along them instead of the cell network
113
+ export const FISSURE_A = Array.from({ length: 4 }, () => new Vector4());
114
+ export const FISSURE_B = Array.from({ length: 4 }, () => new Vector4());
115
+
116
+ // particle paint: upstream's RawShaderMaterial (GLSL3) with ...PAINT_BLENDING and PAINT_FRAG_HEAD
117
+ // (two outputs), drawn into paintScene with paintCamera (ortho, ground rect). Outputs are per-frame
118
+ // increments. ENGINE-GAP: the MRT draw of SIM_FRAG kills the tab (see IFieldTarget): a painter adds
119
+ // into A from paintScene and into B from paintSceneB.
120
+ export const PAINT_BLENDING = {
121
+ transparent: true,
122
+ depthTest: false,
123
+ depthWrite: false,
124
+ blending: CustomBlending,
125
+ blendEquation: AddEquation,
126
+ blendSrc: OneFactor,
127
+ blendDst: OneFactor,
128
+ blendEquationAlpha: AddEquation,
129
+ blendSrcAlpha: OneFactor,
130
+ blendDstAlpha: OneFactor,
131
+ };
132
+
133
+ // per-frame helpers live at module level: no closures allocated in update()
134
+ const area = (b: Vector4) => (b.z - b.x) * (b.w - b.y);
135
+ const decay = (dt: number, tau: number) => Math.exp(-dt / tau);
136
+ const G = ARENA.ground;
137
+ const P = ARENA.pool;
138
+
139
+ // --- FIELD_GLSL -------------------------------------------------------------------------
140
+ const G_MIN = () => vec2(G.min.x, G.min.y);
141
+ const G_SIZE = G.size;
142
+ const texelWorld = (fragCoord: V2, n: number): V2 => G_MIN().add(fragCoord.div(n).mul(G_SIZE));
143
+ const inPool = (xz: V2): B => {
144
+ const d = abs(xz.sub(vec2(P.center.x, P.center.y)));
145
+ return d.x.lessThan(P.half.x).and(d.y.lessThan(P.half.y));
146
+ };
147
+ // GLSL mod (x - y * floor(x / y)), spelled out so a negative x wraps the same on every back end
148
+ const gmod = (x: F, y: F | number): F => x.sub(floor(x.div(y)).mul(y));
149
+ const vnoise = Fn(([x]: [V2]) => {
150
+ const i = floor(x);
151
+ const u0 = fract(x);
152
+ const u = u0.mul(u0).mul(float(3.0).sub(u0.mul(2.0)));
153
+ return mix(
154
+ mix(hash12(i), hash12(i.add(vec2(1, 0))), u.x),
155
+ mix(hash12(i.add(vec2(0, 1))), hash12(i.add(vec2(1, 1))), u.x),
156
+ u.y,
157
+ );
158
+ });
159
+ const fbm2 = (x: V2): F =>
160
+ vnoise(x)
161
+ .mul(0.5)
162
+ .add(vnoise(x.mul(2.03).add(17.1)).mul(0.3))
163
+ .add(vnoise(x.mul(4.11).add(3.7)).mul(0.2));
164
+ // value noise periodic in x (period per) and optionally y (perY > 0); integer periods only
165
+ const vnoiseP = (x: V2, per: number, perY: number): F => {
166
+ const i = floor(x);
167
+ const u0 = fract(x);
168
+ const u = u0.mul(u0).mul(float(3.0).sub(u0.mul(2.0)));
169
+ const i0 = vec2(gmod(i.x, per), perY > 0.0 ? gmod(i.y, perY) : i.y);
170
+ const i1 = vec2(gmod(i.x.add(1.0), per), perY > 0.0 ? gmod(i.y.add(1.0), perY) : i.y.add(1.0));
171
+ return mix(
172
+ mix(hash12(i0), hash12(vec2(i1.x, i0.y)), u.x),
173
+ mix(hash12(vec2(i0.x, i1.y)), hash12(i1), u.x),
174
+ u.y,
175
+ );
176
+ };
177
+
178
+ // Static gate mask, baked once at field resolution (world-locked):
179
+ // r frost needles (ridged streaks on hexagonal axes), g crack veins (voronoi edges, 2 scales), b corruption veins (warped), a fbm
180
+ // distance to the nearest voronoi edge (F2-F1 bisector distance, Quilez), in cells
181
+ const voronoiEdge = Fn(([x, seed]: [V2, F]) => {
182
+ const i = floor(x);
183
+ const fr = fract(x);
184
+ const mg = vec2(0.0).toVar();
185
+ const mr = vec2(0.0).toVar();
186
+ const md = float(8.0).toVar();
187
+ // ponytail: both scans unrolled (9 + 25 cells): a one-time bake, no nested loop names needed
188
+ for (let y = -1; y <= 1; y++)
189
+ for (let k = -1; k <= 1; k++) {
190
+ const g = vec2(k, y);
191
+ const o = hash33(vec3(i.add(g), seed)).xy;
192
+ const r = g.add(o).sub(fr).toVar();
193
+ const d = dot(r, r);
194
+ If(d.lessThan(md), () => {
195
+ md.assign(d);
196
+ mr.assign(r);
197
+ mg.assign(g);
198
+ });
199
+ }
200
+ md.assign(8.0);
201
+ for (let y = -2; y <= 2; y++)
202
+ for (let k = -2; k <= 2; k++) {
203
+ const g = mg.add(vec2(k, y));
204
+ const o = hash33(vec3(i.add(g), seed)).xy;
205
+ const r = g.add(o).sub(fr).toVar();
206
+ If(dot(mr.sub(r), mr.sub(r)).greaterThan(1e-5), () => {
207
+ md.assign(min(md, dot(mr.add(r).mul(0.5), r.sub(mr).normalize())));
208
+ });
209
+ }
210
+ return md;
211
+ });
212
+
213
+ function maskNode(uNeedle: F): V4 {
214
+ const vUv = uv() as unknown as V2;
215
+ const w = G_MIN().add(vUv.mul(G_SIZE));
216
+ // five fbms: crack warp xy, corruption warp xy, frost wobble
217
+ const nv = [0, 1, 2, 3, 4].map((j) => fbm2(w.mul(j < 2 ? 0.9 : j < 4 ? 1.7 : 5.0).add(j * 9.1)));
218
+ const nv4 = nv[4] as F;
219
+ // ice grows needles along its hexagonal axes: thin ridged streaks at 0/60/120 degrees
220
+ // (long along the axis, ~3 cm across), wobbled a little so they aren't ruler-straight
221
+ let frost: F = float(0.0);
222
+ for (let k = 0; k < 3; k++) {
223
+ const an = k * 1.0472;
224
+ // mat2(cos, sin, -sin, cos) * w (column-major)
225
+ const c = Math.cos(an);
226
+ const s = Math.sin(an);
227
+ const q = vec2(w.x.mul(c).sub(w.y.mul(s)), w.x.mul(s).add(w.y.mul(c))).add(
228
+ vec2(0.0, nv4.sub(0.5).mul(0.25)),
229
+ );
230
+ frost = max(
231
+ frost,
232
+ float(1.0).sub(
233
+ abs(
234
+ vnoise(vec2(q.x.mul(1.3), q.y.mul(uNeedle)).add(k * 31.7))
235
+ .mul(2.0)
236
+ .sub(1.0),
237
+ ),
238
+ ),
239
+ );
240
+ }
241
+ const wc = w.add(
242
+ vec2(nv[0] as F, nv[1] as F)
243
+ .sub(0.5)
244
+ .mul(0.6),
245
+ );
246
+ const wv = w.add(
247
+ vec2(nv[2] as F, nv[3] as F)
248
+ .sub(0.5)
249
+ .mul(1.4),
250
+ );
251
+ // edge distance in metres for: crack plates (~1.4 m), sub-cracks (~0.45 m), and corruption's
252
+ // strongly warped ~0.9 m cells (organic tendrils)
253
+ const e = [1.4, 0.45, 0.9].map((cell, l) =>
254
+ voronoiEdge((l === 2 ? wv : wc).div(cell), float(l + 1)).mul(cell),
255
+ ) as [F, F, F];
256
+ // >= 2 texels wide at 1024^2, so a diagonal vein stays 4-connected for the fronts. Noise
257
+ // removes about half the sub-crack edges: cracks fork and dead-end instead of closing cells.
258
+ const gaps = vnoise(w.mul(1.6).add(70.0));
259
+ const crack = max(
260
+ float(1.0)
261
+ .sub(smoothstep(0.02, 0.08, e[0]))
262
+ .mul(smoothstep(0.25, 0.35, gaps)),
263
+ float(1.0)
264
+ .sub(smoothstep(0.01, 0.06, e[1]))
265
+ .mul(0.75)
266
+ .mul(smoothstep(0.5, 0.6, gaps)),
267
+ );
268
+ const corr = float(1.0).sub(smoothstep(0.02, 0.08, e[2]));
269
+ // a: tileable fbm, 60 cells across the field; the sim samples it as splat noise (snoise)
270
+ let a: F = float(0.0);
271
+ let amp = 0.5;
272
+ for (let o = 0; o < 3; o++) {
273
+ const per = 60.0 * (1 << o);
274
+ a = a.add(vnoiseP(vUv.mul(per), per, per).mul(amp));
275
+ amp *= o === 0 ? 0.6 : 0.67;
276
+ }
277
+ return vec4(frost, crack, corr, clamp(a.sub(0.5).mul(1.6).add(0.5), 0.0, 1.0));
278
+ }
279
+
280
+ // SIM_FRAG, split per output (ENGINE-GAP: no MRT)
281
+ interface ISimInputs {
282
+ n: number;
283
+ src: TexNode; // uA or uB
284
+ mask: TexNode;
285
+ paint: TexNode; // uPaintA or uPaintB
286
+ splat: TexNode;
287
+ uSplatCount: F;
288
+ uSeed: F;
289
+ uRound: F;
290
+ uK: (F & { value: Vector4 })[];
291
+ uFast: (F & { value: Vector4 })[];
292
+ uBand: F & { value: Vector4 };
293
+ uPaintOn: F;
294
+ }
295
+
296
+ // smooth tileable noise from the mask's fbm channel; x in noise cells (60 per field width).
297
+ // ENGINE-GAP: the engine samples a RenderTarget texture clamped whatever its wrapS/wrapT, so the
298
+ // repeat the mask's wrap asks for is done here (fract); upstream: texture(uMask, x / 60.0).a
299
+ const snoise = (mask: TexNode, x: V2): F =>
300
+ (mask.sample(fract(x.mul(1.0 / 60.0))) as unknown as TexNode).level(float(0)).a;
301
+ const splatAt = (s: ISimInputs, i: F, k: number): V4 =>
302
+ textureLoad(s.splat, ivec2(i.mul(SPLAT_VEC4).add(k).toInt(), 0)) as unknown as V4;
303
+
304
+ // coverage of splat i at world xz w
305
+ function splatShape(s: ISimInputs, i: F, w: V2): F {
306
+ const s0 = splatAt(s, i, 0);
307
+ const s3 = splatAt(s, i, 3);
308
+ const s4 = splatAt(s, i, 4);
309
+ const pat = s0.w;
310
+ const R = s0.z;
311
+ const seed = s3.x;
312
+ const m = float(0.0).toVar();
313
+ const ca = cos(s3.y);
314
+ const sa = sin(s3.y);
315
+ const d = w.sub(s0.xy);
316
+ const nd = vec2(ca.mul(d.x).sub(sa.mul(d.y)), sa.mul(d.x).add(ca.mul(d.y)))
317
+ .div(R)
318
+ .toVar();
319
+ const r = length(nd).toVar();
320
+ const n = snoise(s.mask, nd.mul(3.0).add(seed.mul(7.31))).toVar();
321
+ If(pat.equal(4.0), () => {
322
+ // line (x, z) -> (x2, z2), half-width s4.x: jagged, tapered at both ends
323
+ const ab = s3.zw.sub(s0.xy);
324
+ const q = w.sub(s0.xy);
325
+ const L = max(length(ab), 1e-3);
326
+ const t = ab.div(L);
327
+ const along = dot(q, t);
328
+ const off = dot(q, vec2(t.y.negate(), t.x)).add(
329
+ snoise(s.mask, vec2(along.mul(2.2), seed.mul(7.31)))
330
+ .sub(0.5)
331
+ .mul(s4.x)
332
+ .mul(3.0),
333
+ );
334
+ const h = clamp(along.div(L), 0.0, 1.0);
335
+ const hw = s4.x.mul(
336
+ float(0.35).add(sqrt(clamp(min(h, float(1.0).sub(h)).mul(6.0), 0.0, 1.0)).mul(0.65)),
337
+ );
338
+ m.assign(
339
+ smoothstep(hw, hw.mul(0.2), abs(off))
340
+ .mul(float(0.7).add(snoise(s.mask, w.mul(9.0).add(seed)).mul(0.3)))
341
+ .mul(step(hw.negate(), along))
342
+ .mul(step(along, L.add(hw))),
343
+ );
344
+ }).Else(() => {
345
+ If(r.lessThan(1.6), () => {
346
+ If(pat.equal(0.0), () => {
347
+ m.assign(
348
+ smoothstep(1.0, 0.35, r.add(n.sub(0.5).mul(0.45))).mul(float(0.65).add(n.mul(0.5))),
349
+ );
350
+ }).Else(() => {
351
+ If(pat.equal(2.0), () => {
352
+ // ring at R, width s4.x (metres); s4.y > 0: lobed and broken (radius wanders)
353
+ const cs = nd.div(max(r, 1e-3));
354
+ const lob = snoise(s.mask, cs.mul(1.4).add(seed.mul(3.7)))
355
+ .sub(0.5)
356
+ .mul(3.0)
357
+ .mul(s4.y);
358
+ const x = r.sub(1.0).sub(lob).mul(R).div(s4.x).add(n.sub(0.5).mul(1.2));
359
+ m.assign(
360
+ exp(x.mul(x).mul(-2.0))
361
+ .mul(float(0.6).add(n.mul(0.6)))
362
+ .mul(
363
+ mix(
364
+ 1.0,
365
+ smoothstep(0.3, 0.55, snoise(s.mask, cs.mul(2.7).add(seed.mul(1.9)))),
366
+ min(s4.y.mul(3.0), 1.0),
367
+ ),
368
+ ),
369
+ );
370
+ }).Else(() => {
371
+ If(pat.equal(3.0), () => {
372
+ m.assign(
373
+ smoothstep(1.0, 0.6, r).mul(
374
+ smoothstep(
375
+ 0.45,
376
+ 0.62,
377
+ snoise(s.mask, nd.mul(2.2).add(seed.mul(3.1)).add(0.5)).add(
378
+ float(1.0).sub(r).mul(0.15),
379
+ ),
380
+ ),
381
+ ),
382
+ );
383
+ }).Else(() => {
384
+ // lichtenberg: polar ridged noise stretched along the radius, so ridges run outward.
385
+ // Angle is periodic (no seam). Each octave doubles the channels, starts further out,
386
+ // wanders more, thins with radius and only shows near its parent channel: a fork.
387
+ const th = atan(nd.y, nd.x).div(6.2831853).add(0.5);
388
+ const lr = log(max(r, 0.03));
389
+ const near = float(1.0).toVar();
390
+ for (let o = 0; o < 4; o++) {
391
+ const fo = o;
392
+ const k = 7.0 * (1 << o);
393
+ const warp = snoise(
394
+ s.mask,
395
+ nd
396
+ .mul(1.5 + fo)
397
+ .add(seed)
398
+ .add(fo * 3.3),
399
+ )
400
+ .sub(0.5)
401
+ .mul(0.25 / k + 0.02); // turns
402
+ const ridge = float(1.0)
403
+ .sub(
404
+ abs(
405
+ vnoiseP(
406
+ vec2(
407
+ th.add(warp).mul(k),
408
+ lr
409
+ .mul(0.6)
410
+ .add(seed.mul(13.0))
411
+ .add(fo * 5.1),
412
+ ),
413
+ k,
414
+ 0.0,
415
+ )
416
+ .mul(2.0)
417
+ .sub(1.0),
418
+ ),
419
+ )
420
+ .toVar();
421
+ const reach = smoothstep(0.05 + fo * 0.12, 0.15 + fo * 0.15, r);
422
+ m.assign(
423
+ max(
424
+ m,
425
+ pow(
426
+ ridge,
427
+ r
428
+ .mul(1.5)
429
+ .add(0.5)
430
+ .mul(30.0 + fo * 12.0),
431
+ )
432
+ .mul(near)
433
+ .mul(reach)
434
+ .mul(1.0 - fo * 0.1),
435
+ ),
436
+ );
437
+ near.mulAssign(smoothstep(0.2, 0.6, ridge));
438
+ }
439
+ const core = smoothstep(0.32, 0.0, r.add(n.sub(0.5).mul(0.3)));
440
+ m.assign(max(core, m).mul(smoothstep(1.0, 0.55, r.add(n.sub(0.5).mul(0.3)))));
441
+ });
442
+ });
443
+ });
444
+ });
445
+ });
446
+ return m;
447
+ }
448
+
449
+ // the prelude both passes share: the fragment, its step kind and the per-step factors
450
+ function simPrelude(s: ISimInputs) {
451
+ const fc = (screenCoordinate as unknown as V2).xy;
452
+ const p = ivec2(floor(fc) as unknown as Node<"ivec2">);
453
+ const inRect = (b: V4): B =>
454
+ fc.x
455
+ .greaterThanEqual(b.x)
456
+ .and(fc.y.greaterThanEqual(b.y))
457
+ .and(fc.x.lessThan(b.z))
458
+ .and(fc.y.lessThan(b.w));
459
+ let fast: B = inRect(s.uFast[0] as unknown as V4);
460
+ for (let i = 1; i < MAX_BOXES; i++) fast = fast.or(inRect(s.uFast[i] as unknown as V4));
461
+ const band = inRect(s.uBand as unknown as V4);
462
+ const K = (i: number): V4 => select(fast, s.uK[i] as unknown as V4, s.uK[i + 7] as unknown as V4);
463
+ const hi = s.n - 1;
464
+ const fl = floor(fc);
465
+ const load = (x: F, y: F): V4 => textureLoad(s.src, ivec2(x.toInt(), y.toInt())) as unknown as V4;
466
+ const xl = max(fl.x.sub(1.0), 0.0);
467
+ const xr = min(fl.x.add(1.0), hi);
468
+ const yd = max(fl.y.sub(1.0), 0.0);
469
+ const yu = min(fl.y.add(1.0), hi);
470
+ return { fc, p, fast, band, K, fl, load, xl, xr, yd, yu };
471
+ }
472
+
473
+ function splatLoop(s: ISimInputs, fast: B, w: V2, apply: (i: F, m: F) => void): void {
474
+ const splats = select(fast, s.uSplatCount, float(0.0)); // splats always lie inside the fast boxes
475
+ Loop(MAX_SPLATS, ({ i }: { i: Node<"int"> }) => {
476
+ const fi = float(i);
477
+ If(fi.greaterThanEqual(splats), () => {
478
+ Break();
479
+ });
480
+ const m = splatShape(s, fi, w).toVar();
481
+ apply(fi, m);
482
+ });
483
+ }
484
+
485
+ // stochastic rounding (1 ulp of dither, placed for how this GPU converts to fp16) keeps the
486
+ // tiny per-step decays unbiased; then snap dust to exact zero so idle texels stay 0
487
+ function roundOut(v: V4, dither: F, uRound: F): V4 {
488
+ const ulp = exp2(floor(log2(max(v, vec4(6.2e-5)))).sub(10.0));
489
+ const r = v.add(dither.add(uRound).mul(ulp));
490
+ return r.mul(step(vec4(1.0 / 1024.0), r));
491
+ }
492
+
493
+ const simA = (s: ISimInputs) =>
494
+ Fn(() => {
495
+ const { fc, p, fast, band, K, fl, load, xl, xr, yd, yu } = simPrelude(s);
496
+ const a = textureLoad(s.src, p) as unknown as V4;
497
+ const out = vec4(a).toVar();
498
+ // copy: keeps both ping-pong targets identical outside what was stepped
499
+ If(fast.or(band), () => {
500
+ const K0 = K(0);
501
+ const K1 = K(1);
502
+ const K2 = K(2);
503
+ const K5 = K(5);
504
+ const K6 = K(6);
505
+ const aL = load(xl, fl.y);
506
+ const aR = load(xr, fl.y);
507
+ const aD = load(fl.x, yd);
508
+ const aU = load(fl.x, yu);
509
+ // diagonals of frost only: an 8-neighbour count tells a dendrite tip (1) from a flat front (3)
510
+ const fDL = load(xl, yd).w;
511
+ const fDR = load(xr, yd).w;
512
+ const fUL = load(xl, yu).w;
513
+ const fUR = load(xr, yu).w;
514
+ const mask = textureLoad(s.mask, p) as unknown as V4;
515
+ const w = texelWorld(fc, s.n).toVar();
516
+ const rnd = hash33(vec3(fc, s.uSeed)).toVar();
517
+
518
+ const heat = a.x.toVar();
519
+ const chr = a.y.toVar();
520
+ const wet = a.z.toVar();
521
+ const frost = a.w.toVar();
522
+ const fVis = min(frost, 1.0).toVar();
523
+
524
+ // heat: 5-tap diffusion, decay, water evaporates (latent heat cools), frost melts to wet
525
+ heat.addAssign(aL.x.add(aR.x).add(aD.x).add(aU.x).sub(heat.mul(4.0)).mul(K0.y));
526
+ heat.mulAssign(K0.x);
527
+ const evap = min(wet, K1.x.mul(heat)).toVar();
528
+ wet.subAssign(evap);
529
+ heat.subAssign(evap.mul(0.35));
530
+ // branch-free on purpose here and below: FXC (ANGLE/D3D) compile time grows with every if
531
+ frost.assign(select(heat.greaterThan(0.05), min(frost, 1.0), frost)); // heat kills potential: no spreading into fire
532
+ const melt = min(frost, K1.z.mul(heat)).toVar();
533
+ frost.subAssign(melt);
534
+ wet.addAssign(melt);
535
+ heat.assign(max(heat.sub(melt.mul(0.5)), 0.0));
536
+ // char grows where hot and dry, then fades
537
+ chr.addAssign(K0.z.mul(smoothstep(0.15, 0.7, heat)).mul(float(1.0).sub(min(wet, 1.0))));
538
+ chr.mulAssign(K0.w);
539
+ wet.mulAssign(K1.y);
540
+
541
+ // frost front: dendrite tips advance at full rate, flat fronts at a fifth; water freezes
542
+ // freely and with a smaller drop, so puddles and the pool ice over in sheets
543
+ const frozenN = step(0.2, aL.w)
544
+ .add(step(0.2, aR.w))
545
+ .add(step(0.2, aD.w))
546
+ .add(step(0.2, aU.w))
547
+ .add(step(0.2, fDL))
548
+ .add(step(0.2, fDR))
549
+ .add(step(0.2, fUL))
550
+ .add(step(0.2, fUR));
551
+ const fMax = max(
552
+ max(max(aL.w, aR.w), max(aD.w, aU.w)),
553
+ max(max(fDL, fDR), max(fUL, fUR)).sub(K2.y.mul(0.414)),
554
+ );
555
+ const onWater = wet.greaterThan(0.3);
556
+ // New frost nucleates by a Packard-style snowflake rule: where exactly one 8-neighbour is
557
+ // frozen (a tip), flanks (2-3 neighbours) rarely, so fingers stay thin and fork instead of
558
+ // merging into a disc. Inside existing frost the potential flows freely to feed the tips.
559
+ const fGate = select(
560
+ onWater.or(frost.greaterThan(0.2)),
561
+ float(1.0),
562
+ step(K2.z, mask.r).mul(
563
+ select(
564
+ frozenN.lessThan(1.5),
565
+ float(1.0),
566
+ select(frozenN.lessThan(2.5), float(0.02), float(0.001)),
567
+ ),
568
+ ),
569
+ ).toVar();
570
+ // band steps decay the neighbours too (uK6): over its long dt, undecayed neighbours would
571
+ // refill every texel and stall the decay of whole frozen areas. Per frame it's negligible
572
+ // and the fast steps keep the reach the look was tuned with.
573
+ // the drop per texel (so a front's reach) varies over ~3 m patches, x0.55..1.6: frost reaches
574
+ // further where the stone is colder, and a splat's front grows into lobes, never a circle
575
+ const fReach = select(
576
+ onWater,
577
+ K2.w,
578
+ float(0.55).add(
579
+ (
580
+ (s.mask.sample(fract(w.mul(1 / 150))) as unknown as TexNode) // ENGINE-GAP: fract, see snoise
581
+ .level(float(0)) as unknown as V4
582
+ ).a.mul(1.05),
583
+ ),
584
+ ).toVar();
585
+ const fGrow = fMax.mul(K6.x).sub(K2.y.mul(fReach)).toVar();
586
+ const fOld = fVis;
587
+ frost.mulAssign(K1.w);
588
+ frost.assign(max(frost, fGrow.mul(step(rnd.x, K2.x.mul(fGate))).mul(step(heat, 0.05))));
589
+ wet.addAssign(
590
+ max(fOld.sub(min(frost, 1.0)), 0.0)
591
+ .mul(0.8)
592
+ .mul(step(heat, 0.05)),
593
+ ); // natural thaw -> puddle
594
+
595
+ // the pool stays full; frost on it is the ice sheet (frost x wet), heat is quenched
596
+ const pool = select(inPool(w), float(1.0), float(0.0));
597
+ wet.assign(max(wet, pool));
598
+ heat.mulAssign(mix(1.0, K5.y, pool));
599
+
600
+ const A = vec4(heat, chr, wet, frost).toVar();
601
+ If(fast.and(s.uPaintOn.equal(1.0)), () => {
602
+ A.addAssign(textureLoad(s.paint, p) as unknown as V4);
603
+ });
604
+ splatLoop(s, fast, w, (i, m) => {
605
+ const s1 = splatAt(s, i, 1);
606
+ // potential channels take the max (re-splatting doesn't stack reach); negative erases
607
+ A.assign(
608
+ vec4(
609
+ A.xyz.add(s1.xyz.mul(m)),
610
+ select(s1.w.greaterThanEqual(0.0), max(A.w, s1.w.mul(m)), A.w.add(s1.w.mul(m))),
611
+ ),
612
+ );
613
+ });
614
+ A.assign(clamp(A, vec4(0.0), vec4(2.0, 1.0, 1.0, 4.0)));
615
+ out.assign(roundOut(A, rnd.x, s.uRound));
616
+ });
617
+ return out;
618
+ })();
619
+
620
+ const simB = (s: ISimInputs) =>
621
+ Fn(() => {
622
+ const { fc, p, fast, band, K, fl, load, xl, xr, yd, yu } = simPrelude(s);
623
+ const b = textureLoad(s.src, p) as unknown as V4;
624
+ const out = vec4(b).toVar();
625
+ If(fast.or(band), () => {
626
+ const K3 = K(3);
627
+ const K4 = K(4);
628
+ const K5 = K(5);
629
+ const K6 = K(6);
630
+ const bL = load(xl, fl.y);
631
+ const bR = load(xr, fl.y);
632
+ const bD = load(fl.x, yd);
633
+ const bU = load(fl.x, yu);
634
+ const mask = textureLoad(s.mask, p) as unknown as V4;
635
+ const w = texelWorld(fc, s.n).toVar();
636
+ const rnd = hash33(vec3(fc, s.uSeed)).toVar();
637
+ const crack = b.x.toVar();
638
+ const acid = b.y.toVar();
639
+ const corr = b.z.toVar();
640
+ const glow = b.w.toVar();
641
+
642
+ // crack front along the vein network
643
+ const cMax = max(max(bL.x, bR.x), max(bD.x, bU.x));
644
+ crack.mulAssign(K3.z);
645
+ crack.assign(
646
+ max(
647
+ crack,
648
+ cMax
649
+ .mul(K6.y)
650
+ .sub(K3.y)
651
+ .mul(step(rnd.y, K3.x.mul(step(0.45, mask.g)))),
652
+ ),
653
+ );
654
+
655
+ // corruption: spreads as a lobed stain (faster where the fbm is high), falling off with distance
656
+ // from its source; the arena material draws the crack network through it, so the field itself
657
+ // carries no veins (a vein-gated front read as one even tiling of glowing cells)
658
+ const vMax = max(max(bL.z, bR.z), max(bD.z, bU.z));
659
+ corr.mulAssign(K4.z);
660
+ const vGate = float(0.15).add(mask.a.mul(mask.a).mul(0.85));
661
+ corr.assign(
662
+ max(
663
+ corr,
664
+ vMax
665
+ .mul(K6.z)
666
+ .sub(K4.y)
667
+ .mul(step(rnd.z, K4.x.mul(vGate))),
668
+ ),
669
+ );
670
+ corr.assign(max(corr.sub(K5.z.mul(glow)), 0.0)); // holy light burns corruption away
671
+
672
+ // acid: slow decay, slight spread; glow: fast decay
673
+ acid.addAssign(bL.y.add(bR.y).add(bD.y).add(bU.y).sub(acid.mul(4.0)).mul(K5.x));
674
+ acid.mulAssign(K3.w);
675
+ glow.mulAssign(K4.w);
676
+
677
+ const Bv = vec4(crack, acid, corr, glow).toVar();
678
+ If(fast.and(s.uPaintOn.equal(1.0)), () => {
679
+ Bv.addAssign(textureLoad(s.paint, p) as unknown as V4);
680
+ });
681
+ splatLoop(s, fast, w, (i, m) => {
682
+ const s2 = splatAt(s, i, 2);
683
+ const y = Bv.y.add(s2.y.mul(m));
684
+ const ww = Bv.w.add(s2.w.mul(m));
685
+ Bv.assign(
686
+ vec4(
687
+ select(s2.x.greaterThanEqual(0.0), max(Bv.x, s2.x.mul(m)), Bv.x.add(s2.x.mul(m))),
688
+ y,
689
+ select(s2.z.greaterThanEqual(0.0), max(Bv.z, s2.z.mul(m)), Bv.z.add(s2.z.mul(m))),
690
+ ww,
691
+ ),
692
+ );
693
+ });
694
+ Bv.assign(clamp(Bv, vec4(0.0), vec4(4.0, 1.0, 4.0, 8.0)));
695
+ out.assign(roundOut(Bv, fract(rnd.x.add(0.618)), s.uRound));
696
+ });
697
+ return out;
698
+ })();
699
+
700
+ // probe pass: per probe two texels (A, B) at the probe's world xz
701
+ const probeNode = (probeTex: TexNode) =>
702
+ Fn(() => {
703
+ const x = floor((screenCoordinate as unknown as V2).x);
704
+ const i = floor(x.mul(0.5));
705
+ const xz = (textureLoad(probeTex, ivec2(i.toInt(), 0)) as unknown as V4).xy;
706
+ return select(gmod(x, 2.0).lessThan(0.5), groundA(xz), groundB(xz));
707
+ })();
708
+
709
+ // what GroundField draws with (three's WebGPURenderer subset)
710
+ export interface IFieldRenderer {
711
+ setRenderTarget(target: RenderTarget | null): void;
712
+ getRenderTarget(): RenderTarget | null;
713
+ render(scene: object, camera: Camera): void;
714
+ getClearColor(target: Color): Color;
715
+ getClearAlpha(): number;
716
+ setClearColor(color: Color | number, alpha?: number): void;
717
+ readRenderTargetPixelsAsync(
718
+ target: RenderTarget,
719
+ x: number,
720
+ y: number,
721
+ w: number,
722
+ h: number,
723
+ ): Promise<ArrayLike<number>>;
724
+ // ENGINE-GAP: the Wasm renderer refuses a render() while two frames are still on the GPU and
725
+ // counts it here; a refused field pass would lose its splats (see _step)
726
+ info?: { engine?: { frameGateSkips?: number } };
727
+ }
728
+
729
+ // ENGINE-GAP: MRT (count: 2, mrtNode = mrt({ oA, oB })) kills the tab here: the engine binds only the
730
+ // fragmentNode's textures ("t_nodeMapN has no texture this draw" with fragmentNode = oA), and
731
+ // fragmentNode = oA + oB * 0 (FluidVolume's workaround) closes the renderer with no console error.
732
+ // One ping-pong state stays a pair of targets (A, B), read as textures[0] / [1].
733
+ interface IFieldTarget {
734
+ a: RenderTarget;
735
+ b: RenderTarget;
736
+ textures: [Texture, Texture];
737
+ }
738
+
739
+ interface IRegion {
740
+ x0: number;
741
+ z0: number;
742
+ x1: number;
743
+ z1: number;
744
+ until: number;
745
+ }
746
+
747
+ export interface ISplat {
748
+ x?: number;
749
+ z?: number;
750
+ radius?: number;
751
+ heat?: number;
752
+ char?: number;
753
+ wet?: number;
754
+ frost?: number;
755
+ crack?: number;
756
+ acid?: number;
757
+ corruption?: number;
758
+ glow?: number;
759
+ pattern?: string;
760
+ seed?: number;
761
+ angle?: number;
762
+ x2?: number;
763
+ z2?: number;
764
+ width?: number;
765
+ lobe?: number;
766
+ }
767
+
768
+ export class GroundField {
769
+ readonly renderer: IFieldRenderer;
770
+ readonly size: number;
771
+ readonly partial: boolean;
772
+ readonly targets: [IFieldTarget, IFieldTarget];
773
+ parity = 0;
774
+ // live-tunable rates (world units, seconds); turned into per-step factors in update()
775
+ params = {
776
+ heatTau: 2.5,
777
+ heatDiffusion: 0.012,
778
+ charRate: 1.4,
779
+ charTau: 25,
780
+ evaporation: 0.9,
781
+ wetTau: 45,
782
+ melt: 1.2,
783
+ frostTau: 7,
784
+ frostSpeed: 1.6,
785
+ frostDrop: 0.4,
786
+ frostThreshold: 0.88,
787
+ frostWaterDrop: 0.2,
788
+ crackSpeed: 4,
789
+ crackDrop: 0.6,
790
+ crackTau: 9,
791
+ corruptionSpeed: 1.1,
792
+ corruptionDrop: 0.4,
793
+ corruptionTau: 14,
794
+ acidTau: 14,
795
+ acidSpread: 0.0015,
796
+ glowTau: 1,
797
+ poolQuench: 0.3,
798
+ cleanse: 1.5,
799
+ };
800
+ readonly mask: RenderTarget;
801
+ readonly splatVecs: Vector4[];
802
+ splatCount = 0;
803
+ seed = 0;
804
+ fp16Truncates = false;
805
+ time = 0;
806
+ readonly regions: IRegion[];
807
+ readonly boxes: Vector4[]; // texel rects [x0, y0, x1, y1) stepped this frame
808
+ boxCount = 0;
809
+ band = 0;
810
+ readonly bandDt: Float32Array;
811
+ private _full = true; // next update steps everything (after clear)
812
+ private _q = new Vector4();
813
+ private _u = new Vector4();
814
+ private readonly _k: Vector4[];
815
+ private readonly _bandRect: Vector4;
816
+ private readonly _splatData: Float32Array;
817
+ private readonly _splatTex: DataTexture;
818
+ private readonly _uni: {
819
+ uSplatCount: F & { value: number };
820
+ uSeed: F & { value: number };
821
+ uRound: F & { value: number };
822
+ uPaintOn: F & { value: number };
823
+ };
824
+ private readonly _srcA: TexNode;
825
+ private readonly _srcB: TexNode;
826
+ private readonly _simA: NodeMaterial;
827
+ private readonly _simB: NodeMaterial;
828
+ private readonly _zero: NodeMaterial;
829
+ private readonly _quad: QuadMesh;
830
+ readonly paintTargetA: RenderTarget;
831
+ readonly paintTargetB: RenderTarget;
832
+ private readonly _clearColor = new Color();
833
+ readonly paintScene = new Scene();
834
+ readonly paintSceneB = new Scene();
835
+ readonly paintCamera: OrthographicCamera;
836
+ // probes
837
+ readonly probes = new Float32Array(MAX_PROBES * 8); // per probe: heat, char, wet, frost, crack, acid, corruption, glow
838
+ probeCount = 0; // probes in the last completed read
839
+ private _probeN = 0;
840
+ private readonly _probeXZ: Vector2[];
841
+ private readonly _probeData = new Float32Array(MAX_PROBES * 4);
842
+ private readonly _probeTex: DataTexture;
843
+ readonly probeRT: RenderTarget;
844
+ private readonly _probeMat: NodeMaterial;
845
+ private _probeReading = false;
846
+ private _maskMat: NodeMaterial | null; // ENGINE-GAP: kept until the bake gets past the frame gate
847
+
848
+ // partial: false steps the whole field every frame (reference / debugging, ~0.1 ms at 1024^2)
849
+ constructor(renderer: IFieldRenderer, size = 1024, { partial = true } = {}) {
850
+ this.renderer = renderer;
851
+ this.size = size;
852
+ this.partial = partial;
853
+ const opts = {
854
+ type: HalfFloatType,
855
+ format: RGBAFormat,
856
+ minFilter: LinearFilter,
857
+ magFilter: LinearFilter,
858
+ depthBuffer: false,
859
+ };
860
+ // ENGINE-GAP: a RenderTarget takes no wrapS / wrapT / generateMipmaps option: the wraps are set
861
+ // on its texture (ClampToEdge is the default) and a target has no mip chain
862
+
863
+ const pair = (): IFieldTarget => {
864
+ const a = new RenderTarget(size, size, opts);
865
+ const b = new RenderTarget(size, size, opts);
866
+ return { a, b, textures: [a.texture, b.texture] };
867
+ };
868
+ this.targets = [pair(), pair()];
869
+
870
+ // the sim texelFetches r/g/b; splats sample a (tileable) filtered, so repeat + linear
871
+ this.mask = new RenderTarget(size, size, {
872
+ minFilter: LinearFilter,
873
+ magFilter: LinearFilter,
874
+ depthBuffer: false,
875
+ });
876
+ this.mask.texture.wrapS = this.mask.texture.wrapT = RepeatWrapping;
877
+ const maskMat = new NodeMaterial();
878
+ maskMat.fragmentNode = maskNode(float(9 * Math.min(1, size / 1024)));
879
+
880
+ this.splatVecs = Array.from({ length: MAX_SPLATS * SPLAT_VEC4 }, () => new Vector4());
881
+ this._splatData = new Float32Array(MAX_SPLATS * SPLAT_VEC4 * 4);
882
+ this._splatTex = new DataTexture(
883
+ this._splatData,
884
+ MAX_SPLATS * SPLAT_VEC4,
885
+ 1,
886
+ RGBAFormat,
887
+ FloatType,
888
+ );
889
+ this._splatTex.minFilter = this._splatTex.magFilter = NearestFilter;
890
+ this._splatTex.needsUpdate = true;
891
+ // per-step factors, [0..6] for the fast boxes (this frame's dt), [7..13] for the band (its
892
+ // accumulated dt); layout in simA / simB
893
+ const uK = Array.from(
894
+ { length: 14 },
895
+ () => uniform(new Vector4()) as unknown as F & { value: Vector4 },
896
+ );
897
+ this._k = uK.map((u) => u.value);
898
+ const uFast = Array.from(
899
+ { length: MAX_BOXES },
900
+ () => uniform(new Vector4()) as unknown as F & { value: Vector4 },
901
+ );
902
+ const uBand = uniform(new Vector4()) as unknown as F & { value: Vector4 };
903
+ this._uni = {
904
+ uSplatCount: uniform(0) as unknown as F & { value: number },
905
+ uSeed: uniform(0) as unknown as F & { value: number },
906
+ uRound: uniform(-0.5) as unknown as F & { value: number }, // dither offset in ulps: -0.5 if fp16 writes round to nearest, 0 if they truncate
907
+ uPaintOn: uniform(0) as unknown as F & { value: number },
908
+ };
909
+ // partial-update bookkeeping (world-space regions -> texel rects); all preallocated
910
+ this.regions = Array.from({ length: MAX_REGIONS }, () => ({
911
+ x0: 0,
912
+ z0: 0,
913
+ x1: 0,
914
+ z1: 0,
915
+ until: -1,
916
+ }));
917
+ this.boxes = uFast.map((u) => u.value);
918
+ this._bandRect = uBand.value;
919
+ this.bandDt = new Float32Array(BANDS);
920
+
921
+ // particle paint: x right, y = +z (camera below the floor looking up keeps both axes positive).
922
+ // Its own targets, so overlapping fast boxes can't add the same paint twice.
923
+ const paintOpts = { ...opts, minFilter: NearestFilter, magFilter: NearestFilter };
924
+ this.paintTargetA = new RenderTarget(size, size, paintOpts);
925
+ this.paintTargetB = new RenderTarget(size, size, paintOpts);
926
+ this.paintCamera = new OrthographicCamera(
927
+ G.min.x,
928
+ G.min.x + G.size,
929
+ G.min.y + G.size,
930
+ G.min.y,
931
+ 0,
932
+ 200,
933
+ );
934
+ this.paintCamera.position.set(0, -100, 0);
935
+ this.paintCamera.up.set(0, 0, 1);
936
+ this.paintCamera.lookAt(0, 0, 0);
937
+ this.paintCamera.updateMatrixWorld();
938
+
939
+ const t0 = this.targets[0];
940
+ this._srcA = texture(t0.textures[0]) as unknown as TexNode;
941
+ this._srcB = texture(t0.textures[1]) as unknown as TexNode;
942
+ const maskTex = texture(this.mask.texture) as unknown as TexNode;
943
+ const splatTex = texture(this._splatTex) as unknown as TexNode;
944
+ const inputs = (src: TexNode, paint: RenderTarget): ISimInputs => ({
945
+ n: size,
946
+ src,
947
+ mask: maskTex,
948
+ paint: texture(paint.texture) as unknown as TexNode,
949
+ splat: splatTex,
950
+ ...this._uni,
951
+ uK,
952
+ uFast,
953
+ uBand,
954
+ });
955
+ this._simA = new NodeMaterial();
956
+ this._simA.fragmentNode = simA(inputs(this._srcA, this.paintTargetA));
957
+ this._simB = new NodeMaterial();
958
+ this._simB.fragmentNode = simB(inputs(this._srcB, this.paintTargetB));
959
+ this._zero = new NodeMaterial();
960
+ this._zero.fragmentNode = vec4(0.0);
961
+ this._quad = new QuadMesh(maskMat);
962
+
963
+ // probes
964
+ this._probeXZ = Array.from({ length: MAX_PROBES }, () => new Vector2());
965
+ this._probeTex = new DataTexture(this._probeData, MAX_PROBES, 1, RGBAFormat, FloatType);
966
+ this._probeTex.minFilter = this._probeTex.magFilter = NearestFilter;
967
+ this._probeTex.needsUpdate = true;
968
+ this.probeRT = new RenderTarget(MAX_PROBES * 2, 1, {
969
+ type: FloatType,
970
+ minFilter: NearestFilter,
971
+ magFilter: NearestFilter,
972
+ depthBuffer: false,
973
+ });
974
+
975
+ // the bake: the mask once (the sim then reads it)
976
+ this._maskMat = maskMat;
977
+ this._bakeMask();
978
+ // fp16 render-target writes truncate on some GPUs (ANGLE/D3D11 measured: 1 + 0.75 ulp -> 1)
979
+ // and round on others; a truncating GPU with +-0.5 ulp dither decays ~20% too fast
980
+ const roundRT = new RenderTarget(1, 1, opts);
981
+ const roundMat = new NodeMaterial();
982
+ roundMat.fragmentNode = vec4(1.0 + 0.75 / 1024.0);
983
+ this._draw(roundMat, roundRT);
984
+ roundMat.dispose();
985
+ renderer
986
+ .readRenderTargetPixelsAsync(roundRT, 0, 0, 1, 1)
987
+ .then((half) => {
988
+ this.fp16Truncates = half[0] === 0x3c00;
989
+ this._uni.uRound.value = this.fp16Truncates ? 0 : -0.5;
990
+ })
991
+ .finally(() => roundRT.dispose());
992
+ this.clear();
993
+ // after clear(): U.uGroundA/B hold this field's textures, so the probe reads the field
994
+ this._probeMat = new NodeMaterial();
995
+ this._probeMat.fragmentNode = probeNode(texture(this._probeTex) as unknown as TexNode);
996
+ }
997
+
998
+ get current(): IFieldTarget {
999
+ return this.targets[this.parity] as IFieldTarget;
1000
+ }
1001
+
1002
+ // queue a splat for the next update (<= 16 per frame; extras are dropped)
1003
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: upstream Ultra Elements code, copied verbatim
1004
+ splat({
1005
+ x = 0,
1006
+ z = 0,
1007
+ radius = 1,
1008
+ heat = 0,
1009
+ char = 0,
1010
+ wet = 0,
1011
+ frost = 0,
1012
+ crack = 0,
1013
+ acid = 0,
1014
+ corruption = 0,
1015
+ glow = 0,
1016
+ pattern = "radial",
1017
+ seed = Math.random() * 100,
1018
+ angle = 0,
1019
+ x2 = x,
1020
+ z2 = z,
1021
+ width = 0,
1022
+ lobe = 0,
1023
+ }: ISplat = {}): boolean {
1024
+ if (this.splatCount >= MAX_SPLATS) return false;
1025
+ const v = this.splatVecs;
1026
+ const o = this.splatCount * SPLAT_VEC4;
1027
+ (v[o] as Vector4).set(x, z, radius, PATTERNS[pattern] ?? 0);
1028
+ (v[o + 1] as Vector4).set(heat, char, wet, frost);
1029
+ (v[o + 2] as Vector4).set(crack, acid, corruption, glow);
1030
+ (v[o + 3] as Vector4).set(seed % 100, angle, x2, z2);
1031
+ const w = width || (pattern === "line" ? radius : radius * 0.18);
1032
+ (v[o + 4] as Vector4).set(w, lobe, 0, 0); // line half-width / ring width, ring lobes
1033
+ this.splatCount++;
1034
+ if (pattern === "radial" && crack >= 2) {
1035
+ let i = 0;
1036
+ for (let j = 1; j < 4; j++)
1037
+ if ((CRACK_SOURCES[j] as Vector4).w < (CRACK_SOURCES[i] as Vector4).w) i = j;
1038
+ (CRACK_SOURCES[i] as Vector4).set(x, z, radius, crack);
1039
+ }
1040
+ if (pattern === "line" && crack >= 1.5 && heat > 0.1 && w >= 0.25) {
1041
+ // a growing vent re-splats from the same start every frame: update its slot, else the weakest
1042
+ let i = -1;
1043
+ let m = 0;
1044
+ for (let j = 0; j < 4; j++) {
1045
+ const a = FISSURE_A[j] as Vector4;
1046
+ if ((FISSURE_B[j] as Vector4).y > 0 && Math.abs(a.x - x) < 0.05 && Math.abs(a.y - z) < 0.05)
1047
+ i = j;
1048
+ if ((FISSURE_B[j] as Vector4).y < (FISSURE_B[m] as Vector4).y) m = j;
1049
+ }
1050
+ if (i < 0) {
1051
+ i = m;
1052
+ (FISSURE_B[i] as Vector4).set(0, 0, 0, 0);
1053
+ }
1054
+ const fb = FISSURE_B[i] as Vector4;
1055
+ (FISSURE_A[i] as Vector4).set(x, z, x2, z2);
1056
+ fb.set(Math.max(w, fb.x), Math.max(crack, fb.y), seed % 97, 0);
1057
+ }
1058
+
1059
+ // region the splat's effects live in: its footprint, plus how far fronts and heat can
1060
+ // travel, for as long as they keep moving (afterwards the bands carry the slow decay)
1061
+ const p = this.params;
1062
+ const ext = pattern === "line" ? w * 2.5 : radius * 1.6;
1063
+ const reach = Math.max(
1064
+ frost / p.frostDrop,
1065
+ crack / p.crackDrop,
1066
+ corruption / p.corruptionDrop,
1067
+ 0,
1068
+ );
1069
+ const life = Math.min(
1070
+ 20,
1071
+ Math.max(
1072
+ heat > 0 ? 3 * p.heatTau : 0,
1073
+ glow > 0 ? 3 * p.glowTau : 0,
1074
+ frost > 0 ? (reach / p.frostSpeed) * 1.5 + 1 : 0,
1075
+ crack > 0 ? (reach / p.crackSpeed) * 1.5 + 1 : 0,
1076
+ corruption > 0 ? (reach / p.corruptionSpeed) * 2 + 1 : 0,
1077
+ 0.5,
1078
+ ),
1079
+ );
1080
+ const m = ext + reach + (heat > 0 ? 0.6 : 0.1);
1081
+ this._region(
1082
+ Math.min(x, x2) - m,
1083
+ Math.min(z, z2) - m,
1084
+ Math.max(x, x2) + m,
1085
+ Math.max(z, z2) + m,
1086
+ life,
1087
+ );
1088
+ // ice on the pool spreads in a sheet much further than on stone: keep the whole pool live
1089
+ if (
1090
+ frost > 0 &&
1091
+ Math.abs(x - P.center.x) < P.half.x + m &&
1092
+ Math.abs(z - P.center.y) < P.half.y + m
1093
+ )
1094
+ this._region(
1095
+ P.center.x - P.half.x,
1096
+ P.center.y - P.half.y,
1097
+ P.center.x + P.half.x,
1098
+ P.center.y + P.half.y,
1099
+ life,
1100
+ );
1101
+ return true;
1102
+ }
1103
+
1104
+ // keep a world area stepped every frame for `seconds` (e.g. where particles paint)
1105
+ touch(x: number, z: number, radius: number, seconds = 1): void {
1106
+ this._region(x - radius, z - radius, x + radius, z + radius, seconds);
1107
+ }
1108
+
1109
+ _region(x0: number, z0: number, x1: number, z1: number, seconds: number): void {
1110
+ let r: IRegion | null = null;
1111
+ let soonest = this.regions[0] as IRegion;
1112
+ for (const q of this.regions) {
1113
+ if (q.until < this.time) {
1114
+ r = q;
1115
+ break;
1116
+ }
1117
+ if (q.until < soonest.until) soonest = q;
1118
+ }
1119
+ let until = this.time + seconds;
1120
+ if (!r) {
1121
+ // ponytail: all slots live -> merge into the soonest-expiring one (a superset, still correct)
1122
+ r = soonest;
1123
+ // biome-ignore lint/style/noParameterAssign: upstream Ultra Elements code, copied verbatim
1124
+ x0 = Math.min(x0, r.x0);
1125
+ // biome-ignore lint/style/noParameterAssign: upstream Ultra Elements code, copied verbatim
1126
+ z0 = Math.min(z0, r.z0);
1127
+ // biome-ignore lint/style/noParameterAssign: upstream Ultra Elements code, copied verbatim
1128
+ x1 = Math.max(x1, r.x1);
1129
+ // biome-ignore lint/style/noParameterAssign: upstream Ultra Elements code, copied verbatim
1130
+ z1 = Math.max(z1, r.z1);
1131
+ until = Math.max(until, r.until);
1132
+ }
1133
+ r.x0 = x0;
1134
+ r.z0 = z0;
1135
+ r.x1 = x1;
1136
+ r.z1 = z1;
1137
+ r.until = until;
1138
+ }
1139
+
1140
+ update(dt: number): void {
1141
+ if (this._maskMat) this._bakeMask();
1142
+ this.time += dt;
1143
+ const cd = decay(dt, this.params.crackTau);
1144
+ for (const c of CRACK_SOURCES) c.w *= cd;
1145
+ for (const b of FISSURE_B) b.y *= cd;
1146
+ const n = this.size;
1147
+ const k = this._k;
1148
+ const band = this._bandRect;
1149
+ for (const b of this.boxes) b.set(0, 0, 0, 0);
1150
+ if (this._full || !this.partial) {
1151
+ (this.boxes[0] as Vector4).set(0, 0, n, n);
1152
+ this.boxCount = 1;
1153
+ band.set(0, 0, 0, 0);
1154
+ this._full = false;
1155
+ } else {
1156
+ this._cluster();
1157
+ const h = n / BANDS;
1158
+ band.set(0, this.band * h, n, (this.band + 1) * h);
1159
+ }
1160
+ for (let i = 0; i < BANDS; i++) this.bandDt[i] = (this.bandDt[i] as number) + dt;
1161
+ if (band.w === 0) this.bandDt.fill(0); // full step: every band is current
1162
+ this._factors(k, 0, dt, false);
1163
+ this._factors(k, 7, this.bandDt[this.band] as number, true);
1164
+ // ponytail: texels that just left the fast boxes get their band's whole accumulated dt
1165
+ // (slightly early decay at a region's edge); per-texel step times would need a channel
1166
+ this.bandDt[this.band] = 0;
1167
+ this._step();
1168
+ this.band = (this.band + 1) % BANDS;
1169
+ this._readProbes();
1170
+ }
1171
+
1172
+ // live regions -> <= 4 texel boxes (overlap allowed). A region joins a box when the union
1173
+ // is cheaper than drawing both, else opens a box; with all 4 open it joins the cheapest.
1174
+ // Then boxes whose union is cheaper than the pair are fused.
1175
+ // ponytail: greedy, order dependent; fine for a handful of spells, k-means if arenas get busy
1176
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: upstream Ultra Elements code, copied verbatim
1177
+ _cluster(): void {
1178
+ const n = this.size;
1179
+ const B = this.boxes;
1180
+ const q = this._q;
1181
+ const u = this._u;
1182
+ const s = n / G.size;
1183
+ let nb = 0;
1184
+ for (const r of this.regions) {
1185
+ if (r.until < this.time) continue;
1186
+ q.set(
1187
+ Math.round((r.x0 - G.min.x) * s),
1188
+ Math.round((r.z0 - G.min.y) * s),
1189
+ Math.round((r.x1 - G.min.x) * s),
1190
+ Math.round((r.z1 - G.min.y) * s),
1191
+ );
1192
+ q.clampScalar(0, n);
1193
+ if (q.z <= q.x || q.w <= q.y) continue;
1194
+ // join the box where the union costs least extra over drawing both; only when that
1195
+ // saves texels, unless all boxes are taken
1196
+ let best = -1;
1197
+ let extra = Number.POSITIVE_INFINITY;
1198
+ for (let i = 0; i < nb; i++) {
1199
+ const b = B[i] as Vector4;
1200
+ u.set(Math.min(b.x, q.x), Math.min(b.y, q.y), Math.max(b.z, q.z), Math.max(b.w, q.w));
1201
+ const e = area(u) - area(b) - area(q);
1202
+ if ((e < 0 || nb === MAX_BOXES) && e < extra) {
1203
+ best = i;
1204
+ extra = e;
1205
+ }
1206
+ }
1207
+ if (best < 0) {
1208
+ (B[nb++] as Vector4).copy(q);
1209
+ continue;
1210
+ }
1211
+ const b = B[best] as Vector4;
1212
+ b.set(Math.min(b.x, q.x), Math.min(b.y, q.y), Math.max(b.z, q.z), Math.max(b.w, q.w));
1213
+ }
1214
+ for (let i = 0; i < nb; i++)
1215
+ for (let j = i + 1; j < nb; j++) {
1216
+ const a = B[i] as Vector4;
1217
+ const b = B[j] as Vector4;
1218
+ u.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.z, b.z), Math.max(a.w, b.w));
1219
+ if (area(u) >= area(a) + area(b)) continue;
1220
+ a.copy(u);
1221
+ b.copy(B[--nb] as Vector4);
1222
+ (B[nb] as Vector4).set(0, 0, 0, 0);
1223
+ j = i; // a grew: recheck it against everything after it
1224
+ }
1225
+ this.boxCount = nb;
1226
+ }
1227
+
1228
+ // per-step factors for a step of length dt into uK[o .. o + 6] (layout in simA / simB):
1229
+ // 0 heat decay, heat diffusion alpha, char gain, char decay
1230
+ // 1 evaporation, wet decay, melt, frost decay
1231
+ // 2 frost advance p, frost drop/texel, frost threshold, frost drop factor on water
1232
+ // 3 crack p, crack drop, crack decay, acid decay
1233
+ // 4 corruption p, corruption drop, corruption decay, glow decay
1234
+ // 5 acid alpha, pool quench, cleanse, dt
1235
+ // 6 neighbour decay for the frost, crack, corruption fronts (1 in fast steps), unused
1236
+ _factors(k: Vector4[], o: number, dt: number, band: boolean): void {
1237
+ const p = this.params;
1238
+ const dx = G.size / this.size;
1239
+ const adv = dt / dx; // front advance probability = speed * adv
1240
+ const K = (i: number) => k[o + i] as Vector4;
1241
+ K(0).set(
1242
+ decay(dt, p.heatTau),
1243
+ Math.min(0.2, (p.heatDiffusion * dt) / (dx * dx)),
1244
+ p.charRate * dt,
1245
+ decay(dt, p.charTau),
1246
+ );
1247
+ K(1).set(p.evaporation * dt, decay(dt, p.wetTau), p.melt * dt, decay(dt, p.frostTau));
1248
+ K(2).set(Math.min(1, p.frostSpeed * adv), p.frostDrop * dx, p.frostThreshold, p.frostWaterDrop);
1249
+ K(3).set(
1250
+ Math.min(1, p.crackSpeed * adv),
1251
+ p.crackDrop * dx,
1252
+ decay(dt, p.crackTau),
1253
+ decay(dt, p.acidTau),
1254
+ );
1255
+ K(4).set(
1256
+ Math.min(1, p.corruptionSpeed * adv),
1257
+ p.corruptionDrop * dx,
1258
+ decay(dt, p.corruptionTau),
1259
+ decay(dt, p.glowTau),
1260
+ );
1261
+ K(5).set(
1262
+ Math.min(0.2, (p.acidSpread * dt) / (dx * dx)),
1263
+ decay(dt, p.poolQuench),
1264
+ p.cleanse * dt,
1265
+ dt,
1266
+ );
1267
+ if (band) K(6).set(K(1).w, K(3).z, K(4).z, 0);
1268
+ else K(6).set(1, 1, 1, 0);
1269
+ }
1270
+
1271
+ // ENGINE-GAP: frames the Wasm renderer's gate refused so far (0 on renderers without the gate)
1272
+ _skips(): number {
1273
+ return this.renderer.info?.engine?.frameGateSkips ?? 0;
1274
+ }
1275
+
1276
+ _bakeMask(): void {
1277
+ const before = this._skips();
1278
+ this._draw(this._maskMat as NodeMaterial, this.mask);
1279
+ if (this._skips() !== before) return; // refused: the next update() bakes again
1280
+ this._maskMat?.dispose();
1281
+ this._maskMat = null;
1282
+ }
1283
+
1284
+ _step(): void {
1285
+ const r = this.renderer;
1286
+ const skips = this._skips();
1287
+ const u = this._uni;
1288
+ const src = this.targets[this.parity] as IFieldTarget;
1289
+ const dst = this.targets[this.parity ^ 1] as IFieldTarget;
1290
+ this._srcA.value = src.textures[0];
1291
+ this._srcB.value = src.textures[1];
1292
+ u.uSplatCount.value = this.splatCount;
1293
+ u.uSeed.value = this.seed = (this.seed + 1) % 4096;
1294
+ if (this.splatCount > 0) {
1295
+ for (let i = 0; i < this.splatCount * SPLAT_VEC4; i++)
1296
+ (this.splatVecs[i] as Vector4).toArray(this._splatData, i * 4);
1297
+ this._splatTex.needsUpdate = true;
1298
+ }
1299
+ const nb = this.boxCount;
1300
+ const painting =
1301
+ (this.paintScene.children.length > 0 || this.paintSceneB.children.length > 0) && nb > 0;
1302
+ u.uPaintOn.value = painting ? 1 : 0;
1303
+ if (painting) {
1304
+ r.getClearColor(this._clearColor);
1305
+ const ca = r.getClearAlpha();
1306
+ r.setClearColor(0x000000, 0);
1307
+ // ENGINE-GAP: no MRT; a target draw clears to the clear colour first (upstream: clear, then draw)
1308
+ const prev = r.getRenderTarget();
1309
+ r.setRenderTarget(this.paintTargetA);
1310
+ r.render(this.paintScene, this.paintCamera);
1311
+ r.setRenderTarget(this.paintTargetB);
1312
+ r.render(this.paintSceneB, this.paintCamera);
1313
+ r.setRenderTarget(prev);
1314
+ r.setClearColor(this._clearColor, ca);
1315
+ }
1316
+ // ENGINE-GAP: no RenderTarget scissor. Upstream draws scissored rects over everything stepped
1317
+ // now or last frame; the whole target drawn once steps the same texels and copies the rest.
1318
+ this._draw(this._simA, dst.a);
1319
+ this._draw(this._simB, dst.b);
1320
+ // ENGINE-GAP: a pass the frame gate refused left dst stale: keep src, the splats and the
1321
+ // ground textures, and step again next frame (upstream draws are never refused)
1322
+ if (this._skips() !== skips) return;
1323
+ this.splatCount = 0;
1324
+ this.parity ^= 1;
1325
+ setGroundTexture(U.uGroundA, dst.textures[0]);
1326
+ setGroundTexture(U.uGroundB, dst.textures[1]);
1327
+ }
1328
+
1329
+ // one fullscreen pass into target (upstream: FullscreenQuad.render)
1330
+ _draw(material: NodeMaterial, target: RenderTarget): void {
1331
+ const r = this.renderer;
1332
+ const prev = r.getRenderTarget();
1333
+ this._quad.material = material;
1334
+ r.setRenderTarget(target);
1335
+ this._quad.render(r as unknown as Parameters<QuadMesh["render"]>[0]);
1336
+ r.setRenderTarget(prev);
1337
+ }
1338
+
1339
+ clear(): void {
1340
+ for (const t of this.targets) {
1341
+ this._draw(this._zero, t.a);
1342
+ this._draw(this._zero, t.b);
1343
+ }
1344
+ this.splatCount = 0;
1345
+ for (const c of CRACK_SOURCES) c.set(0, 0, 0, 0);
1346
+ for (const b of FISSURE_B) b.set(0, 0, 0, 0);
1347
+ for (const q of this.regions) q.until = -1;
1348
+ this._full = true;
1349
+ // the pool (wet = 1) is restamped by every step; the next update() steps the whole field
1350
+ setGroundTexture(U.uGroundA, this.current.textures[0]);
1351
+ setGroundTexture(U.uGroundB, this.current.textures[1]);
1352
+ }
1353
+
1354
+ // --- probes: async readback (upstream: PBO + fence, UW WaterQuery pattern) ---
1355
+ // points: [[x, z], ...] (<= 16). Results land in this.probes a few frames later.
1356
+ setProbes(points: readonly (readonly [number, number] | number[])[]): void {
1357
+ this._probeN = Math.min(points.length, MAX_PROBES);
1358
+ for (let i = 0; i < this._probeN; i++) {
1359
+ const pt = points[i] as number[];
1360
+ (this._probeXZ[i] as Vector2).set(pt[0] as number, pt[1] as number);
1361
+ }
1362
+ }
1363
+
1364
+ _readProbes(): void {
1365
+ if (!this._probeN || this._probeReading) return;
1366
+ for (let i = 0; i < this._probeN; i++)
1367
+ (this._probeXZ[i] as Vector2).toArray(this._probeData, i * 4);
1368
+ this._probeTex.needsUpdate = true;
1369
+ this._draw(this._probeMat, this.probeRT);
1370
+ const count = this._probeN;
1371
+ this._probeReading = true;
1372
+ this.renderer
1373
+ .readRenderTargetPixelsAsync(this.probeRT, 0, 0, count * 2, 1)
1374
+ .then((px) => {
1375
+ for (let i = 0; i < count * 8; i++) this.probes[i] = px[i] as number;
1376
+ this.probeCount = count;
1377
+ })
1378
+ .finally(() => {
1379
+ this._probeReading = false;
1380
+ });
1381
+ }
1382
+
1383
+ dispose(): void {
1384
+ for (const t of this.targets) {
1385
+ t.a.dispose();
1386
+ t.b.dispose();
1387
+ }
1388
+ this.mask.dispose();
1389
+ this.probeRT.dispose();
1390
+ this.paintTargetA.dispose();
1391
+ this.paintTargetB.dispose();
1392
+ this._simA.dispose();
1393
+ this._simB.dispose();
1394
+ this._probeMat.dispose();
1395
+ this._zero.dispose();
1396
+ this._splatTex.dispose();
1397
+ this._probeTex.dispose();
1398
+ }
1399
+ }