@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.
- package/capabilities.json +2019 -59
- package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
- package/dist/hot.d.ts +5 -5
- package/dist/index.d.ts +1131 -105
- package/dist/index.js +15201 -4782
- package/dist/model-lod-BDAUYgsS.d.ts +197 -0
- package/dist/playtest.d.ts +6 -4
- package/dist/playtest.js +84 -11
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.d.ts +5 -3
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +1596 -17
- package/dist/world.js +17035 -521
- package/gpl/fixtures/make_world_fixture.py +184 -0
- package/gpl/recipes/_common.py +11 -0
- package/gpl/recipes/decimate.py +11 -5
- package/gpl/recipes/export_world.py +699 -0
- package/mcp/blender-server.mjs +61 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +55 -21
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +8246 -389
- package/scripts/apply-three-patch.mjs +123 -41
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2390 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +564 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +839 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
- package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
|
@@ -0,0 +1,728 @@
|
|
|
1
|
+
import { Object3D } from "three";
|
|
2
|
+
import { Fn, float, instanceIndex, instancedArray, uniform, vec2, vec4 } from "three/tsl";
|
|
3
|
+
import type { ComputeNode, StorageBufferNode } from "three/webgpu";
|
|
4
|
+
import type { IComputeDriven } from "../compute-driven.js";
|
|
5
|
+
import { GPUReadback } from "../gpu-readback.js";
|
|
6
|
+
import { createRandom } from "../random.js";
|
|
7
|
+
import type { IRendererLike } from "../renderer.js";
|
|
8
|
+
import { bitReverseIndices, butterflyStageCount, log2Exact } from "./fft.js";
|
|
9
|
+
|
|
10
|
+
/** One band of the spectrum, drawn on its own patch. */
|
|
11
|
+
export interface ISpectralOceanCascade {
|
|
12
|
+
/** The world-space edge length, in metres, this cascade's grid tiles across. */
|
|
13
|
+
readonly patchSize: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ISpectralOceanOptions {
|
|
17
|
+
/** Grid resolution per cascade. A power of two; the transform has no other shape. */
|
|
18
|
+
readonly resolution: number;
|
|
19
|
+
/**
|
|
20
|
+
* The cascades, largest patch first.
|
|
21
|
+
*
|
|
22
|
+
* Each one carries only the wavelengths the next-smaller patch cannot resolve, so the bands do
|
|
23
|
+
* not overlap and a wave is never counted twice. One cascade is a toy: the join between bands is
|
|
24
|
+
* where a spectral ocean visibly fails, so there is nothing to look at until there are two.
|
|
25
|
+
*/
|
|
26
|
+
readonly cascades: readonly ISpectralOceanCascade[];
|
|
27
|
+
readonly windSpeed: number;
|
|
28
|
+
/** Wind heading in radians. */
|
|
29
|
+
readonly windDirection: number;
|
|
30
|
+
readonly gravity: number;
|
|
31
|
+
/** Overall spectrum scale. A wave height decision, so the game owns the number. */
|
|
32
|
+
readonly amplitude: number;
|
|
33
|
+
/**
|
|
34
|
+
* How sharply waves align with the wind, as the exponent on the directional spread.
|
|
35
|
+
*
|
|
36
|
+
* A spectrum-tuning number with no defensible default, so there is none.
|
|
37
|
+
*/
|
|
38
|
+
readonly directionality: number;
|
|
39
|
+
/** Horizontal displacement scale. Zero is a pure heightfield; higher values sharpen crests. */
|
|
40
|
+
readonly choppiness: number;
|
|
41
|
+
/** Waves shorter than this are cut off, in metres. */
|
|
42
|
+
readonly smallWaveCutoff: number;
|
|
43
|
+
readonly seed: number;
|
|
44
|
+
/**
|
|
45
|
+
* Which clock advances the simulation. Defaults to the game's fixed step.
|
|
46
|
+
*
|
|
47
|
+
* Fixed, because this sea is something the game reads: `sampleHeight` reports its age in frames,
|
|
48
|
+
* and a field advanced by the display makes that age mean a different amount of time on every
|
|
49
|
+
* machine. A game whose ocean is only ever looked at can pass `"render"` and pay for exactly the
|
|
50
|
+
* frames it draws.
|
|
51
|
+
*/
|
|
52
|
+
readonly cadence?: "fixed" | "render";
|
|
53
|
+
/**
|
|
54
|
+
* The grid the CPU height query is sampled on, per side. Zero disables the query entirely.
|
|
55
|
+
*
|
|
56
|
+
* This is not the simulation resolution. It is the size of the only thing copied back off the
|
|
57
|
+
* GPU, so it is the whole cost of being able to float something: `readbackResolution` squared
|
|
58
|
+
* pairs of height and vertical-velocity floats, every `readbackEveryFrames` frames.
|
|
59
|
+
*/
|
|
60
|
+
readonly readbackResolution: number;
|
|
61
|
+
/** Frames between height copies. Ignored when `readbackResolution` is zero. */
|
|
62
|
+
readonly readbackEveryFrames: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A height read from the CPU copy, with the age of the frame that produced it. */
|
|
66
|
+
export interface ISpectralOceanHeight {
|
|
67
|
+
readonly height: number;
|
|
68
|
+
/** Metres per second at this same point and sample time, for temporal age correction. */
|
|
69
|
+
readonly verticalVelocity: number;
|
|
70
|
+
/**
|
|
71
|
+
* Frames between the GPU state this height came from and now.
|
|
72
|
+
*
|
|
73
|
+
* A spectral ocean cannot offer an exact CPU height — there is no closed form, only texels the
|
|
74
|
+
* GPU made — so this number is the contract. A caller that ignores it floats a hull on water
|
|
75
|
+
* that is not the water being drawn, and nothing in the frame says so.
|
|
76
|
+
*/
|
|
77
|
+
readonly staleFrames: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface ICascadeState {
|
|
81
|
+
readonly patchSize: number;
|
|
82
|
+
readonly kMin: number;
|
|
83
|
+
readonly kMax: number;
|
|
84
|
+
readonly initialSpectrum: StorageBufferNode<"vec4">;
|
|
85
|
+
readonly work: StorageBufferNode<"vec4">;
|
|
86
|
+
readonly scratch: StorageBufferNode<"vec4">;
|
|
87
|
+
readonly displacement: StorageBufferNode<"vec4">;
|
|
88
|
+
readonly passes: readonly ComputeNode[];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const TWO_PI = Math.PI * 2;
|
|
92
|
+
|
|
93
|
+
function positiveInteger(name: string, value: number): number {
|
|
94
|
+
if (!Number.isInteger(value) || value <= 0)
|
|
95
|
+
throw new Error(`SpectralOcean.${name} must be a positive integer.`);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function finiteNumber(name: string, value: number): number {
|
|
100
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
101
|
+
throw new Error(`SpectralOcean.${name} must be a finite number.`);
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function positiveNumber(name: string, value: number): number {
|
|
106
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
|
|
107
|
+
throw new Error(`SpectralOcean.${name} must be a positive number.`);
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The band each cascade owns, so no wavelength is simulated twice.
|
|
113
|
+
*
|
|
114
|
+
* A cascade resolves wavenumbers up to its own Nyquist. Giving each one everything below its
|
|
115
|
+
* Nyquist and above the previous, larger patch's Nyquist partitions the spectrum exactly. Summing
|
|
116
|
+
* overlapping cascades instead is the classic spectral-ocean bug: the water is too tall, and it is
|
|
117
|
+
* too tall in a way that reads as "the amplitude needs tuning".
|
|
118
|
+
*/
|
|
119
|
+
export function cascadeBands(
|
|
120
|
+
resolution: number,
|
|
121
|
+
cascades: readonly ISpectralOceanCascade[],
|
|
122
|
+
): readonly { readonly kMin: number; readonly kMax: number }[] {
|
|
123
|
+
const bands: { kMin: number; kMax: number }[] = [];
|
|
124
|
+
for (let index = 0; index < cascades.length; index += 1) {
|
|
125
|
+
const nyquist = (Math.PI * resolution) / (cascades[index] as ISpectralOceanCascade).patchSize;
|
|
126
|
+
const previous =
|
|
127
|
+
index === 0
|
|
128
|
+
? 0
|
|
129
|
+
: (Math.PI * resolution) / (cascades[index - 1] as ISpectralOceanCascade).patchSize;
|
|
130
|
+
bands.push({
|
|
131
|
+
kMin: previous,
|
|
132
|
+
kMax: index === cascades.length - 1 ? Number.POSITIVE_INFINITY : nyquist,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return bands;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The Phillips spectrum's energy at one wavenumber, band-limited to one cascade.
|
|
140
|
+
*
|
|
141
|
+
* On the CPU on purpose. Everything here is a decision a test can check — a spectrum that is
|
|
142
|
+
* subtly wrong produces an ocean that still looks like an ocean, so "it moves and it is blue" is
|
|
143
|
+
* not evidence of anything.
|
|
144
|
+
*/
|
|
145
|
+
export function phillipsEnergy(
|
|
146
|
+
kx: number,
|
|
147
|
+
kz: number,
|
|
148
|
+
options: {
|
|
149
|
+
readonly windSpeed: number;
|
|
150
|
+
readonly windDirection: number;
|
|
151
|
+
readonly gravity: number;
|
|
152
|
+
readonly amplitude: number;
|
|
153
|
+
readonly directionality: number;
|
|
154
|
+
readonly smallWaveCutoff: number;
|
|
155
|
+
readonly kMin: number;
|
|
156
|
+
readonly kMax: number;
|
|
157
|
+
},
|
|
158
|
+
): number {
|
|
159
|
+
const kLength = Math.hypot(kx, kz);
|
|
160
|
+
if (kLength < 1e-6) return 0;
|
|
161
|
+
if (kLength < options.kMin || kLength >= options.kMax) return 0;
|
|
162
|
+
const largestWave = (options.windSpeed * options.windSpeed) / options.gravity;
|
|
163
|
+
const alignment =
|
|
164
|
+
(kx * Math.cos(options.windDirection) + kz * Math.sin(options.windDirection)) / kLength;
|
|
165
|
+
// Waves running against the wind carry no energy; the exponent is how sharply that falls off.
|
|
166
|
+
if (alignment <= 0) return 0;
|
|
167
|
+
const spread = alignment ** (2 * options.directionality);
|
|
168
|
+
const kSquared = kLength * kLength;
|
|
169
|
+
const suppression = Math.exp(-1 / (kSquared * largestWave * largestWave));
|
|
170
|
+
const cutoff = Math.exp(-kSquared * options.smallWaveCutoff * options.smallWaveCutoff);
|
|
171
|
+
return (options.amplitude * suppression * spread * cutoff) / (kSquared * kSquared);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The complex amplitudes at t=0 for one cascade, packed as `(h0, conj(h0(-k)))` per texel.
|
|
176
|
+
*
|
|
177
|
+
* Exported because determinism is a claim this makes and a test has to be able to check it: the
|
|
178
|
+
* same seed and the same parameters must produce the same field, or nothing downstream can be
|
|
179
|
+
* asserted at all.
|
|
180
|
+
*/
|
|
181
|
+
export function initialSpectrumData(
|
|
182
|
+
resolution: number,
|
|
183
|
+
patchSize: number,
|
|
184
|
+
band: { readonly kMin: number; readonly kMax: number },
|
|
185
|
+
options: {
|
|
186
|
+
readonly windSpeed: number;
|
|
187
|
+
readonly windDirection: number;
|
|
188
|
+
readonly gravity: number;
|
|
189
|
+
readonly amplitude: number;
|
|
190
|
+
readonly directionality: number;
|
|
191
|
+
readonly smallWaveCutoff: number;
|
|
192
|
+
readonly seed: number;
|
|
193
|
+
},
|
|
194
|
+
): Float32Array {
|
|
195
|
+
const random = createRandom(options.seed);
|
|
196
|
+
const count = resolution * resolution;
|
|
197
|
+
const gaussian = new Float32Array(count * 2);
|
|
198
|
+
for (let index = 0; index < count; index += 1) {
|
|
199
|
+
// Box-Muller from the seeded stream: two independent standard normals per texel.
|
|
200
|
+
const first = Math.max(random(), 1e-9);
|
|
201
|
+
const second = random();
|
|
202
|
+
const radius = Math.sqrt(-2 * Math.log(first));
|
|
203
|
+
gaussian[index * 2] = radius * Math.cos(TWO_PI * second);
|
|
204
|
+
gaussian[index * 2 + 1] = radius * Math.sin(TWO_PI * second);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const data = new Float32Array(count * 4);
|
|
208
|
+
const step = TWO_PI / patchSize;
|
|
209
|
+
// Each sample stands for one cell of the wavenumber plane, so it carries that cell's width.
|
|
210
|
+
// Without it `amplitude` would mean a different wave height at every patch size.
|
|
211
|
+
const spacing = step;
|
|
212
|
+
const half = resolution / 2;
|
|
213
|
+
const energyOptions = { ...options, kMin: band.kMin, kMax: band.kMax };
|
|
214
|
+
for (let y = 0; y < resolution; y += 1) {
|
|
215
|
+
for (let x = 0; x < resolution; x += 1) {
|
|
216
|
+
const index = y * resolution + x;
|
|
217
|
+
const kx = (x - half) * step;
|
|
218
|
+
const kz = (y - half) * step;
|
|
219
|
+
// The Nyquist row is its own mirror — negating its wavevector lands back on itself — so it
|
|
220
|
+
// cannot carry a conjugate pair. Left in, it makes the spectrum non-Hermitian along one line
|
|
221
|
+
// of texels and leaks an imaginary part into the height. One texel row of the shortest
|
|
222
|
+
// resolvable wave is the whole cost of dropping it.
|
|
223
|
+
const selfMirrored = x === 0 || y === 0;
|
|
224
|
+
const amplitude = selfMirrored
|
|
225
|
+
? 0
|
|
226
|
+
: Math.sqrt(phillipsEnergy(kx, kz, energyOptions) / 2) * spacing;
|
|
227
|
+
data[index * 4] = (gaussian[index * 2] as number) * amplitude;
|
|
228
|
+
data[index * 4 + 1] = (gaussian[index * 2 + 1] as number) * amplitude;
|
|
229
|
+
|
|
230
|
+
// conj(h0(-k)): the mirrored texel's noise against the mirrored wavevector's energy. This
|
|
231
|
+
// is what makes the spectrum Hermitian, and a Hermitian spectrum is what makes the inverse
|
|
232
|
+
// transform produce a real height instead of half of one.
|
|
233
|
+
const mirrorX = (resolution - x) % resolution;
|
|
234
|
+
const mirrorY = (resolution - y) % resolution;
|
|
235
|
+
const mirror = mirrorY * resolution + mirrorX;
|
|
236
|
+
const mirrorAmplitude = selfMirrored
|
|
237
|
+
? 0
|
|
238
|
+
: Math.sqrt(phillipsEnergy(-kx, -kz, energyOptions) / 2) * spacing;
|
|
239
|
+
data[index * 4 + 2] = (gaussian[mirror * 2] as number) * mirrorAmplitude;
|
|
240
|
+
data[index * 4 + 3] = -(gaussian[mirror * 2 + 1] as number) * mirrorAmplitude;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return data;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Bilinear height at a world position, from a square grid that tiles every `patchSize` metres.
|
|
248
|
+
*
|
|
249
|
+
* Separated from the class so the sampling can be tested against a field a test wrote itself,
|
|
250
|
+
* rather than against whatever the GPU happened to produce.
|
|
251
|
+
*/
|
|
252
|
+
export function sampleGrid(
|
|
253
|
+
grid: Float32Array,
|
|
254
|
+
resolution: number,
|
|
255
|
+
patchSize: number,
|
|
256
|
+
x: number,
|
|
257
|
+
z: number,
|
|
258
|
+
stride = 1,
|
|
259
|
+
offset = 0,
|
|
260
|
+
): number {
|
|
261
|
+
const scale = resolution / patchSize;
|
|
262
|
+
const u = x * scale;
|
|
263
|
+
const v = z * scale;
|
|
264
|
+
const x0 = Math.floor(u);
|
|
265
|
+
const v0 = Math.floor(v);
|
|
266
|
+
const fx = u - x0;
|
|
267
|
+
const fz = v - v0;
|
|
268
|
+
const wrap = (value: number) => ((value % resolution) + resolution) % resolution;
|
|
269
|
+
const xa = wrap(x0);
|
|
270
|
+
const xb = wrap(x0 + 1);
|
|
271
|
+
const za = wrap(v0);
|
|
272
|
+
const zb = wrap(v0 + 1);
|
|
273
|
+
const topLeft = grid[(za * resolution + xa) * stride + offset] as number;
|
|
274
|
+
const topRight = grid[(za * resolution + xb) * stride + offset] as number;
|
|
275
|
+
const bottomLeft = grid[(zb * resolution + xa) * stride + offset] as number;
|
|
276
|
+
const bottomRight = grid[(zb * resolution + xb) * stride + offset] as number;
|
|
277
|
+
const top = topLeft + (topRight - topLeft) * fx;
|
|
278
|
+
const bottom = bottomLeft + (bottomRight - bottomLeft) * fx;
|
|
279
|
+
return top + (bottom - top) * fz;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* A spectral ocean: cascaded wave spectra, inverse-transformed on the GPU every frame.
|
|
284
|
+
*
|
|
285
|
+
* It draws nothing. The game builds its own mesh and its own material and reads
|
|
286
|
+
* `cascadeDisplacement(index)`; every colour, every foam threshold, every sky this water reflects
|
|
287
|
+
* is the game's, and none of it can be changed from here.
|
|
288
|
+
*
|
|
289
|
+
* What it offers that an analytic wave function cannot is the look. What it cannot offer is an
|
|
290
|
+
* exact CPU height: there is no closed form, only the texels the GPU produced, so `sampleHeight`
|
|
291
|
+
* is a throttled copy that is always some frames behind and always says how many. A game that
|
|
292
|
+
* needs the height to be exact wants an analytic field instead — that is a different contract, and
|
|
293
|
+
* the reason this class has a different name rather than a flag.
|
|
294
|
+
*/
|
|
295
|
+
export class SpectralOcean extends Object3D implements IComputeDriven {
|
|
296
|
+
readonly resolution: number;
|
|
297
|
+
readonly cascades: readonly ISpectralOceanCascade[];
|
|
298
|
+
readonly processCadence: "fixed" | "render";
|
|
299
|
+
readonly warmupNodes: readonly ComputeNode[];
|
|
300
|
+
/** Floats copied off the GPU per readback, so a report can state the cost rather than imply it. */
|
|
301
|
+
readonly readbackFloats: number;
|
|
302
|
+
|
|
303
|
+
#time = uniform(0);
|
|
304
|
+
#heightDelta = uniform(0);
|
|
305
|
+
#heightTime: number | undefined;
|
|
306
|
+
#cascadeStates: ICascadeState[] = [];
|
|
307
|
+
#heightField: StorageBufferNode<"vec2"> | undefined;
|
|
308
|
+
#heightPass: ComputeNode | undefined;
|
|
309
|
+
#readback: GPUReadback | undefined;
|
|
310
|
+
#readbackResolution: number;
|
|
311
|
+
#renderer: IRendererLike | undefined;
|
|
312
|
+
#released = false;
|
|
313
|
+
#steps = 0;
|
|
314
|
+
|
|
315
|
+
constructor(options: ISpectralOceanOptions) {
|
|
316
|
+
super();
|
|
317
|
+
const resolution = positiveInteger("resolution", options.resolution);
|
|
318
|
+
log2Exact(resolution);
|
|
319
|
+
if (!Array.isArray(options.cascades) || options.cascades.length === 0)
|
|
320
|
+
throw new Error("SpectralOcean.cascades must hold at least one cascade.");
|
|
321
|
+
for (const cascade of options.cascades)
|
|
322
|
+
positiveNumber("cascades[].patchSize", cascade.patchSize);
|
|
323
|
+
for (let index = 1; index < options.cascades.length; index += 1) {
|
|
324
|
+
if (
|
|
325
|
+
(options.cascades[index] as ISpectralOceanCascade).patchSize >=
|
|
326
|
+
(options.cascades[index - 1] as ISpectralOceanCascade).patchSize
|
|
327
|
+
) {
|
|
328
|
+
throw new Error(
|
|
329
|
+
"SpectralOcean.cascades must be ordered from largest patchSize to smallest.",
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
positiveNumber("windSpeed", options.windSpeed);
|
|
334
|
+
finiteNumber("windDirection", options.windDirection);
|
|
335
|
+
positiveNumber("gravity", options.gravity);
|
|
336
|
+
positiveNumber("amplitude", options.amplitude);
|
|
337
|
+
positiveNumber("directionality", options.directionality);
|
|
338
|
+
finiteNumber("choppiness", options.choppiness);
|
|
339
|
+
positiveNumber("smallWaveCutoff", options.smallWaveCutoff);
|
|
340
|
+
finiteNumber("seed", options.seed);
|
|
341
|
+
if (!Number.isInteger(options.readbackResolution) || options.readbackResolution < 0)
|
|
342
|
+
throw new Error("SpectralOcean.readbackResolution must be a non-negative integer.");
|
|
343
|
+
if (options.readbackResolution > 0) {
|
|
344
|
+
log2Exact(options.readbackResolution);
|
|
345
|
+
positiveInteger("readbackEveryFrames", options.readbackEveryFrames);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (
|
|
349
|
+
options.cadence !== undefined &&
|
|
350
|
+
options.cadence !== "fixed" &&
|
|
351
|
+
options.cadence !== "render"
|
|
352
|
+
)
|
|
353
|
+
throw new Error('SpectralOcean.cadence must be "fixed" or "render".');
|
|
354
|
+
this.processCadence = options.cadence ?? "fixed";
|
|
355
|
+
this.resolution = resolution;
|
|
356
|
+
this.cascades = [...options.cascades];
|
|
357
|
+
this.#readbackResolution = options.readbackResolution;
|
|
358
|
+
this.readbackFloats = options.readbackResolution * options.readbackResolution * 2;
|
|
359
|
+
|
|
360
|
+
const bands = cascadeBands(resolution, this.cascades);
|
|
361
|
+
const warmup: ComputeNode[] = [];
|
|
362
|
+
for (let index = 0; index < this.cascades.length; index += 1) {
|
|
363
|
+
const cascade = this.cascades[index] as ISpectralOceanCascade;
|
|
364
|
+
const band = bands[index] as { kMin: number; kMax: number };
|
|
365
|
+
const state = this.#buildCascade(cascade.patchSize, band, {
|
|
366
|
+
amplitude: options.amplitude,
|
|
367
|
+
choppiness: options.choppiness,
|
|
368
|
+
directionality: options.directionality,
|
|
369
|
+
gravity: options.gravity,
|
|
370
|
+
// Each cascade draws from its own stream so two cascades never share a wave.
|
|
371
|
+
seed: options.seed + index * 7919,
|
|
372
|
+
smallWaveCutoff: options.smallWaveCutoff,
|
|
373
|
+
windDirection: options.windDirection,
|
|
374
|
+
windSpeed: options.windSpeed,
|
|
375
|
+
});
|
|
376
|
+
this.#cascadeStates.push(state);
|
|
377
|
+
warmup.push(...state.passes);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (this.#readbackResolution > 0) {
|
|
381
|
+
const { field, pass } = this.#buildHeightPass(this.#readbackResolution);
|
|
382
|
+
this.#heightField = field;
|
|
383
|
+
this.#heightPass = pass;
|
|
384
|
+
warmup.push(pass);
|
|
385
|
+
this.#readback = new GPUReadback({
|
|
386
|
+
attribute: field.value,
|
|
387
|
+
everyFrames: options.readbackEveryFrames,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
this.warmupNodes = warmup;
|
|
391
|
+
this.addEventListener("removed", this.#onRemoved);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
get released(): boolean {
|
|
395
|
+
return this.#released;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Simulation steps dispatched. A report that cannot count its own dispatches proves nothing. */
|
|
399
|
+
get steps(): number {
|
|
400
|
+
return this.#steps;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** How old the CPU height copy is, or `undefined` when the height query is switched off. */
|
|
404
|
+
get staleFrames(): number | undefined {
|
|
405
|
+
return this.#readback?.staleFrames;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** The `(displaceX, height, displaceZ, fold)` buffer the game's material reads. */
|
|
409
|
+
cascadeDisplacement(index: number): StorageBufferNode<"vec4"> {
|
|
410
|
+
const state = this.#cascadeStates[index];
|
|
411
|
+
if (state === undefined) throw new Error(`SpectralOcean has no cascade ${index}.`);
|
|
412
|
+
return state.displacement;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** The world-space tile size of one cascade, which the game's material needs to place it. */
|
|
416
|
+
cascadePatchSize(index: number): number {
|
|
417
|
+
const state = this.#cascadeStates[index];
|
|
418
|
+
if (state === undefined) throw new Error(`SpectralOcean has no cascade ${index}.`);
|
|
419
|
+
return state.patchSize;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Seconds of wave time. The game advances it, so a paused game has a paused sea. */
|
|
423
|
+
advance(seconds: number): void {
|
|
424
|
+
if (!Number.isFinite(seconds)) throw new Error("SpectralOcean.advance needs a finite time.");
|
|
425
|
+
this.#time.value = seconds;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* The surface height at a world position, and how many frames behind it is.
|
|
430
|
+
*
|
|
431
|
+
* `undefined` until the first copy lands, and `undefined` forever when the height query was
|
|
432
|
+
* switched off — never zero, because a hull floating at zero is indistinguishable from a hull
|
|
433
|
+
* floating at sea level and that is exactly the mistake this must not allow.
|
|
434
|
+
*/
|
|
435
|
+
sampleHeight(x: number, z: number): ISpectralOceanHeight | undefined {
|
|
436
|
+
if (this.#readback === undefined) return undefined;
|
|
437
|
+
const sample = this.#readback.sample;
|
|
438
|
+
if (sample === undefined) return undefined;
|
|
439
|
+
const patch = (this.#cascadeStates[0] as ICascadeState).patchSize;
|
|
440
|
+
return {
|
|
441
|
+
height: sampleGrid(sample.data, this.#readbackResolution, patch, x, z, 2),
|
|
442
|
+
verticalVelocity: sampleGrid(sample.data, this.#readbackResolution, patch, x, z, 2, 1),
|
|
443
|
+
staleFrames: sample.staleFrames,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
attachRenderer(renderer: IRendererLike): void {
|
|
448
|
+
if (this.#released) throw new Error("SpectralOcean cannot be attached after release.");
|
|
449
|
+
this.#renderer = renderer;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
process(renderer = this.#renderer): void {
|
|
453
|
+
if (this.#released) return;
|
|
454
|
+
if (renderer === undefined) throw new Error("SpectralOcean is not attached to a renderer.");
|
|
455
|
+
// One `compute()` for the whole transform. Three submits a command buffer per call, so a call
|
|
456
|
+
// per pass was ~20 submits a frame for two cascades, and a submit is where the GPU process
|
|
457
|
+
// makes the renderer wait: 60 submits a frame with a 70 ms stall every few dozen of them.
|
|
458
|
+
// An array runs in one compute pass in order, which is all a ping-pong transform needs.
|
|
459
|
+
const passes = this.#cascadeStates.flatMap((state) => state.passes);
|
|
460
|
+
if (this.#heightPass !== undefined) {
|
|
461
|
+
const now = this.#time.value;
|
|
462
|
+
const delta = now - (this.#heightTime ?? now);
|
|
463
|
+
this.#heightDelta.value = Number.isFinite(delta) && delta > 0 ? delta : 0;
|
|
464
|
+
this.#heightTime = now;
|
|
465
|
+
passes.push(this.#heightPass);
|
|
466
|
+
}
|
|
467
|
+
renderer.compute(passes);
|
|
468
|
+
if (this.#heightPass !== undefined) this.#readback?.request(renderer);
|
|
469
|
+
this.#steps += 1;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
detach(): void {
|
|
473
|
+
if (this.#released) return;
|
|
474
|
+
this.removeEventListener("removed", this.#onRemoved);
|
|
475
|
+
this.#renderer = undefined;
|
|
476
|
+
for (const state of this.#cascadeStates) {
|
|
477
|
+
for (const pass of state.passes) pass.dispose();
|
|
478
|
+
state.initialSpectrum.value.dispose();
|
|
479
|
+
state.work.value.dispose();
|
|
480
|
+
state.scratch.value.dispose();
|
|
481
|
+
state.displacement.value.dispose();
|
|
482
|
+
}
|
|
483
|
+
this.#cascadeStates = [];
|
|
484
|
+
this.#heightPass?.dispose();
|
|
485
|
+
this.#heightField?.value.dispose();
|
|
486
|
+
this.#heightPass = undefined;
|
|
487
|
+
this.#heightField = undefined;
|
|
488
|
+
this.#readback?.dispose();
|
|
489
|
+
this.#readback = undefined;
|
|
490
|
+
this.#released = true;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
#onRemoved = (): void => this.detach();
|
|
494
|
+
|
|
495
|
+
#buildCascade(
|
|
496
|
+
patchSize: number,
|
|
497
|
+
band: { readonly kMin: number; readonly kMax: number },
|
|
498
|
+
tuning: {
|
|
499
|
+
readonly amplitude: number;
|
|
500
|
+
readonly choppiness: number;
|
|
501
|
+
readonly directionality: number;
|
|
502
|
+
readonly gravity: number;
|
|
503
|
+
readonly seed: number;
|
|
504
|
+
readonly smallWaveCutoff: number;
|
|
505
|
+
readonly windDirection: number;
|
|
506
|
+
readonly windSpeed: number;
|
|
507
|
+
},
|
|
508
|
+
): ICascadeState {
|
|
509
|
+
const size = this.resolution;
|
|
510
|
+
const count = size * size;
|
|
511
|
+
const initial = instancedArray(
|
|
512
|
+
initialSpectrumData(size, patchSize, band, tuning),
|
|
513
|
+
"vec4",
|
|
514
|
+
) as StorageBufferNode<"vec4">;
|
|
515
|
+
const work = instancedArray(count, "vec4") as StorageBufferNode<"vec4">;
|
|
516
|
+
const scratch = instancedArray(count, "vec4") as StorageBufferNode<"vec4">;
|
|
517
|
+
const displacement = instancedArray(count, "vec4") as StorageBufferNode<"vec4">;
|
|
518
|
+
const reversal = instancedArray(
|
|
519
|
+
Float32Array.from(bitReverseIndices(size)),
|
|
520
|
+
"float",
|
|
521
|
+
) as StorageBufferNode<"float">;
|
|
522
|
+
|
|
523
|
+
const gridSize = float(size);
|
|
524
|
+
const time = this.#time;
|
|
525
|
+
const passes: ComputeNode[] = [];
|
|
526
|
+
|
|
527
|
+
// Spectrum evolution: h(k, t) from the fixed amplitudes, packed as two complex fields so one
|
|
528
|
+
// transform carries four real outputs — height and displaceX in the first, displaceZ and the
|
|
529
|
+
// fold in the second.
|
|
530
|
+
passes.push(
|
|
531
|
+
Fn(() => {
|
|
532
|
+
const index = float(instanceIndex);
|
|
533
|
+
const x = index.mod(gridSize);
|
|
534
|
+
const y = index.div(gridSize).floor();
|
|
535
|
+
const step = float(TWO_PI / patchSize);
|
|
536
|
+
const kx = x.sub(gridSize.mul(0.5)).mul(step);
|
|
537
|
+
const kz = y.sub(gridSize.mul(0.5)).mul(step);
|
|
538
|
+
const kLength = kx.mul(kx).add(kz.mul(kz)).sqrt().max(1e-6);
|
|
539
|
+
const omega = kLength.mul(tuning.gravity).sqrt().mul(time);
|
|
540
|
+
const cos = omega.cos();
|
|
541
|
+
const sin = omega.sin();
|
|
542
|
+
const amplitudes = initial.element(instanceIndex);
|
|
543
|
+
const heightRe = amplitudes.x
|
|
544
|
+
.mul(cos)
|
|
545
|
+
.sub(amplitudes.y.mul(sin))
|
|
546
|
+
.add(amplitudes.z.mul(cos))
|
|
547
|
+
.add(amplitudes.w.mul(sin));
|
|
548
|
+
const heightIm = amplitudes.x
|
|
549
|
+
.mul(sin)
|
|
550
|
+
.add(amplitudes.y.mul(cos))
|
|
551
|
+
.sub(amplitudes.z.mul(sin))
|
|
552
|
+
.add(amplitudes.w.mul(cos));
|
|
553
|
+
// Multiplying by -i turns the height spectrum into a horizontal displacement spectrum.
|
|
554
|
+
const displaceXRe = kx.div(kLength).mul(heightIm);
|
|
555
|
+
const displaceXIm = kx.div(kLength).mul(heightRe).negate();
|
|
556
|
+
const displaceZRe = kz.div(kLength).mul(heightIm);
|
|
557
|
+
const displaceZIm = kz.div(kLength).mul(heightRe).negate();
|
|
558
|
+
// The trace of the horizontal displacement's Jacobian: how much the surface folds onto
|
|
559
|
+
// itself. It is a simulation quantity; what counts as foam is the game's threshold.
|
|
560
|
+
const foldRe = kLength.mul(heightRe);
|
|
561
|
+
const foldIm = kLength.mul(heightIm);
|
|
562
|
+
work
|
|
563
|
+
.element(instanceIndex)
|
|
564
|
+
.assign(
|
|
565
|
+
vec4(
|
|
566
|
+
heightRe.sub(displaceXIm),
|
|
567
|
+
heightIm.add(displaceXRe),
|
|
568
|
+
displaceZRe.sub(foldIm),
|
|
569
|
+
displaceZIm.add(foldRe),
|
|
570
|
+
),
|
|
571
|
+
);
|
|
572
|
+
})().compute(count),
|
|
573
|
+
);
|
|
574
|
+
|
|
575
|
+
// The transform: gather into bit-reversed order, then one in-place butterfly stage per pass,
|
|
576
|
+
// rows first and then columns. Each stage's pairs touch disjoint slots, so a stage needs no
|
|
577
|
+
// barrier and no ping-pong buffer.
|
|
578
|
+
passes.push(this.#reversePass(work, scratch, reversal, "row"));
|
|
579
|
+
for (let stage = 0; stage < butterflyStageCount(size); stage += 1) {
|
|
580
|
+
passes.push(this.#butterflyPass(scratch, stage, "row"));
|
|
581
|
+
}
|
|
582
|
+
passes.push(this.#reversePass(scratch, work, reversal, "column"));
|
|
583
|
+
for (let stage = 0; stage < butterflyStageCount(size); stage += 1) {
|
|
584
|
+
passes.push(this.#butterflyPass(work, stage, "column"));
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// Unpack: normalise by the transform length and undo the half-grid origin shift the
|
|
588
|
+
// wavevectors were built around.
|
|
589
|
+
passes.push(
|
|
590
|
+
Fn(() => {
|
|
591
|
+
const index = float(instanceIndex);
|
|
592
|
+
const x = index.mod(gridSize);
|
|
593
|
+
const y = index.div(gridSize).floor();
|
|
594
|
+
// No 1/N² here on purpose. The wave synthesis is the unnormalised sum
|
|
595
|
+
// `h(x) = Σ h̃(k,t)·e^{ik·x}`; the transform's length is not part of it. Dividing by it
|
|
596
|
+
// made the sea shrink four-fold every time a game doubled `resolution`, which is a quality
|
|
597
|
+
// knob and must not be a wave-height knob. The physical scale rides on `Δk` in `h0`.
|
|
598
|
+
const sign = x.add(y).mod(2).mul(-2).add(1);
|
|
599
|
+
const scale = sign;
|
|
600
|
+
const transformed = work.element(instanceIndex);
|
|
601
|
+
displacement
|
|
602
|
+
.element(instanceIndex)
|
|
603
|
+
.assign(
|
|
604
|
+
vec4(
|
|
605
|
+
transformed.y.mul(scale).mul(tuning.choppiness),
|
|
606
|
+
transformed.x.mul(scale),
|
|
607
|
+
transformed.z.mul(scale).mul(tuning.choppiness),
|
|
608
|
+
transformed.w.mul(scale),
|
|
609
|
+
),
|
|
610
|
+
);
|
|
611
|
+
})().compute(count),
|
|
612
|
+
);
|
|
613
|
+
|
|
614
|
+
return {
|
|
615
|
+
patchSize,
|
|
616
|
+
kMin: band.kMin,
|
|
617
|
+
kMax: band.kMax,
|
|
618
|
+
initialSpectrum: initial,
|
|
619
|
+
work,
|
|
620
|
+
scratch,
|
|
621
|
+
displacement,
|
|
622
|
+
passes,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
#reversePass(
|
|
627
|
+
source: StorageBufferNode<"vec4">,
|
|
628
|
+
target: StorageBufferNode<"vec4">,
|
|
629
|
+
reversal: StorageBufferNode<"float">,
|
|
630
|
+
axis: "row" | "column",
|
|
631
|
+
): ComputeNode {
|
|
632
|
+
const size = this.resolution;
|
|
633
|
+
const count = size * size;
|
|
634
|
+
const gridSize = float(size);
|
|
635
|
+
return Fn(() => {
|
|
636
|
+
const index = float(instanceIndex);
|
|
637
|
+
const column = index.mod(gridSize);
|
|
638
|
+
const row = index.div(gridSize).floor();
|
|
639
|
+
const moved =
|
|
640
|
+
axis === "row"
|
|
641
|
+
? row.mul(gridSize).add(reversal.element(column.toUint()))
|
|
642
|
+
: reversal.element(row.toUint()).mul(gridSize).add(column);
|
|
643
|
+
target.element(instanceIndex).assign(source.element(moved.toUint()));
|
|
644
|
+
})().compute(count);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
#butterflyPass(
|
|
648
|
+
buffer: StorageBufferNode<"vec4">,
|
|
649
|
+
stage: number,
|
|
650
|
+
axis: "row" | "column",
|
|
651
|
+
): ComputeNode {
|
|
652
|
+
const size = this.resolution;
|
|
653
|
+
const half = 1 << stage;
|
|
654
|
+
const pairsPerLine = size / 2;
|
|
655
|
+
const gridSize = float(size);
|
|
656
|
+
return Fn(() => {
|
|
657
|
+
const thread = float(instanceIndex);
|
|
658
|
+
const line = thread.div(float(pairsPerLine)).floor();
|
|
659
|
+
const pair = thread.mod(float(pairsPerLine));
|
|
660
|
+
const twiddleIndex = pair.mod(float(half));
|
|
661
|
+
const low = pair
|
|
662
|
+
.div(float(half))
|
|
663
|
+
.floor()
|
|
664
|
+
.mul(float(half * 2))
|
|
665
|
+
.add(twiddleIndex);
|
|
666
|
+
const high = low.add(float(half));
|
|
667
|
+
const angle = twiddleIndex.mul(float(TWO_PI / (2 * half)));
|
|
668
|
+
const wRe = angle.cos();
|
|
669
|
+
const wIm = angle.sin();
|
|
670
|
+
const lowIndex = axis === "row" ? line.mul(gridSize).add(low) : low.mul(gridSize).add(line);
|
|
671
|
+
const highIndex =
|
|
672
|
+
axis === "row" ? line.mul(gridSize).add(high) : high.mul(gridSize).add(line);
|
|
673
|
+
const a = buffer.element(lowIndex.toUint()).toVar();
|
|
674
|
+
const b = buffer.element(highIndex.toUint()).toVar();
|
|
675
|
+
const firstRe = b.x.mul(wRe).sub(b.y.mul(wIm));
|
|
676
|
+
const firstIm = b.x.mul(wIm).add(b.y.mul(wRe));
|
|
677
|
+
const secondRe = b.z.mul(wRe).sub(b.w.mul(wIm));
|
|
678
|
+
const secondIm = b.z.mul(wIm).add(b.w.mul(wRe));
|
|
679
|
+
buffer
|
|
680
|
+
.element(lowIndex.toUint())
|
|
681
|
+
.assign(vec4(a.x.add(firstRe), a.y.add(firstIm), a.z.add(secondRe), a.w.add(secondIm)));
|
|
682
|
+
buffer
|
|
683
|
+
.element(highIndex.toUint())
|
|
684
|
+
.assign(vec4(a.x.sub(firstRe), a.y.sub(firstIm), a.z.sub(secondRe), a.w.sub(secondIm)));
|
|
685
|
+
})().compute(size * pairsPerLine);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Sums every cascade's height onto one small grid, which is the only thing copied to the CPU.
|
|
690
|
+
*
|
|
691
|
+
* Reading the simulation grids back instead would move megabytes a frame to answer a question
|
|
692
|
+
* about a handful of floating bodies. This pass answers it at the resolution the caller actually
|
|
693
|
+
* asked for.
|
|
694
|
+
*/
|
|
695
|
+
#buildHeightPass(readbackResolution: number): {
|
|
696
|
+
field: StorageBufferNode<"vec2">;
|
|
697
|
+
pass: ComputeNode;
|
|
698
|
+
} {
|
|
699
|
+
const count = readbackResolution * readbackResolution;
|
|
700
|
+
const field = instancedArray(count, "vec2") as StorageBufferNode<"vec2">;
|
|
701
|
+
const states = this.#cascadeStates;
|
|
702
|
+
const basePatch = (states[0] as ICascadeState).patchSize;
|
|
703
|
+
const simulationSize = this.resolution;
|
|
704
|
+
const pass = Fn(() => {
|
|
705
|
+
const index = float(instanceIndex);
|
|
706
|
+
const gridSize = float(readbackResolution);
|
|
707
|
+
const x = index.mod(gridSize);
|
|
708
|
+
const y = index.div(gridSize).floor();
|
|
709
|
+
const worldX = x.div(gridSize).mul(float(basePatch));
|
|
710
|
+
const worldZ = y.div(gridSize).mul(float(basePatch));
|
|
711
|
+
const total = float(0).toVar();
|
|
712
|
+
for (const state of states) {
|
|
713
|
+
const scale = float(simulationSize / state.patchSize);
|
|
714
|
+
const sampleX = worldX.mul(scale).floor().mod(float(simulationSize));
|
|
715
|
+
const sampleZ = worldZ.mul(scale).floor().mod(float(simulationSize));
|
|
716
|
+
const offset = sampleZ.mul(float(simulationSize)).add(sampleX);
|
|
717
|
+
total.addAssign(state.displacement.element(offset.toUint()).y);
|
|
718
|
+
}
|
|
719
|
+
const previous = field.element(instanceIndex).x.toVar();
|
|
720
|
+
const delta = this.#heightDelta;
|
|
721
|
+
const velocity = delta
|
|
722
|
+
.greaterThan(0)
|
|
723
|
+
.select(total.sub(previous).div(delta.max(1e-6)), float(0));
|
|
724
|
+
field.element(instanceIndex).assign(vec2(total, velocity));
|
|
725
|
+
})().compute(count);
|
|
726
|
+
return { field, pass };
|
|
727
|
+
}
|
|
728
|
+
}
|