@null3d/wind 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,252 @@
1
+ // The wind's analytic field: the air's velocity at a place and a time, with no state between
2
+ // frames. The wind blows along a heading that is slower near the ground, a gust travels through it,
3
+ // and a noise-built swirl curls the air without making it pile up. The pushes that a page makes add
4
+ // short-lived vortices behind a moving body.
5
+ //
6
+ // The field is incompressible by construction: its swirl is the curl of a stream function, a push is
7
+ // a vortex, and a gust turns about its own center. Its divergence is therefore zero in the
8
+ // continuum, and the tests check that the discrete form keeps it near zero.
9
+ //
10
+ // The grid's compute shader and its WebGL2 form hold the same formula, and the noise functions
11
+ // mirror the engine's `null3d::noise`, so both forms give the same numbers. A test reads the two
12
+ // shader copies and fails when they drift apart or when a constant here changes without them.
13
+ //
14
+ // This form is the mirror of the add-on's WebAssembly: a test and a page's read outside a frame
15
+ // use it, and a frame's ask for many places runs the same formula in `crates/null3d-wind-wasm`, on
16
+ // the engine's job workers. A test compares the two.
17
+ /**
18
+ * The first value of `null3d::noise`'s `pcg3d` hash, as a signed whole number. The library returns
19
+ * three, but value noise reads only the first, and this form makes no tuple and no closure.
20
+ *
21
+ * Each step keeps its number in the 32 bits that a whole number holds. The hash is the same 32 bits
22
+ * either way, and the top 24 come out the same. Read as unsigned, about half of them pass the
23
+ * largest number that the browser keeps in the value itself, and it makes an object of each such
24
+ * number it returns. So the steps wrap with `| 0` rather than `>>> 0`.
25
+ */
26
+ export function lattice(x, y, z) {
27
+ let px = (Math.imul(x, 1664525) + 1013904223) | 0;
28
+ let py = (Math.imul(y, 1664525) + 1013904223) | 0;
29
+ let pz = (Math.imul(z, 1664525) + 1013904223) | 0;
30
+ px = (px + Math.imul(py, pz)) | 0;
31
+ py = (py + Math.imul(pz, px)) | 0;
32
+ pz = (pz + Math.imul(px, py)) | 0;
33
+ px = (px ^ (px >>> 16)) | 0;
34
+ py = (py ^ (py >>> 16)) | 0;
35
+ pz = (pz ^ (pz >>> 16)) | 0;
36
+ px = (px + Math.imul(py, pz)) | 0;
37
+ py = (py + Math.imul(pz, px)) | 0;
38
+ pz = (pz + Math.imul(px, py)) | 0;
39
+ return px;
40
+ }
41
+ /** A number from 0 up to 1 made from the top 24 bits of a hash. */
42
+ function toUnit(hash) {
43
+ return (hash >>> 8) / 16777216;
44
+ }
45
+ /** Perlin's fade curve, flat at both ends. */
46
+ function fade(t) {
47
+ return t * t * t * (t * (t * 6 - 15) + 10);
48
+ }
49
+ /** A blend of two numbers, written out so that a sample makes no closure. */
50
+ function blend(a, b, t) {
51
+ return a + (b - a) * t;
52
+ }
53
+ /** A value noise corner's number: the hash's first value, from 0 up to 1. */
54
+ function corner(x, y, z) {
55
+ return toUnit(lattice(x, y, z));
56
+ }
57
+ /** `null3d::noise`'s value noise in 3D, from 0 to 1. */
58
+ export function value3(px, py, pz) {
59
+ const fx = Math.floor(px);
60
+ const fy = Math.floor(py);
61
+ const fz = Math.floor(pz);
62
+ const u = fade(px - fx);
63
+ const v = fade(py - fy);
64
+ const w = fade(pz - fz);
65
+ const near = blend(blend(blend(corner(fx, fy, fz), corner(fx + 1, fy, fz), u), blend(corner(fx, fy + 1, fz), corner(fx + 1, fy + 1, fz), u), v), blend(blend(corner(fx, fy, fz + 1), corner(fx + 1, fy, fz + 1), u), blend(corner(fx, fy + 1, fz + 1), corner(fx + 1, fy + 1, fz + 1), u), v), w);
66
+ return near;
67
+ }
68
+ /** Makes the empty ring that a page's pushes go into. The slots are made once, here. */
69
+ export function createPushRing() {
70
+ const slots = Array.from({ length: RING_SLOTS }, () => ({
71
+ x: 0,
72
+ z: 0,
73
+ strength: 0,
74
+ born: 0,
75
+ }));
76
+ let next = 0;
77
+ const take = (gust) => {
78
+ const index = gust ? GUST_SLOT : next;
79
+ if (!gust)
80
+ next = (next + 1) % PUSH_SLOTS;
81
+ return index;
82
+ };
83
+ return {
84
+ slots,
85
+ take,
86
+ add(x, z, strength, born, gust) {
87
+ const index = take(gust);
88
+ const slot = slots[index];
89
+ slot.x = x;
90
+ slot.z = z;
91
+ slot.strength = strength;
92
+ slot.born = born;
93
+ return index;
94
+ },
95
+ };
96
+ }
97
+ /** Makes the three vectors of a reading from the field's settings. */
98
+ export function createReading(state) {
99
+ return {
100
+ base: [state.speed, state.heading, state.ground, state.seed],
101
+ gust: [state.gustStrength, state.gustRadius, state.gustWave, state.gustSpeed],
102
+ swirl: [state.swirl, state.swirlScale, state.swirlDrift, 0],
103
+ sent: [0, 0, 0, SENT_NONE],
104
+ };
105
+ }
106
+ /**
107
+ * The time that a reading holds when no page has sent a gust: a born time that no frame reaches, so
108
+ * the sent gust's life is over at every frame time.
109
+ */
110
+ export const SENT_NONE = -1e9;
111
+ /** Writes the field's settings into a reading's vectors, in place, so a reader re-reads them. */
112
+ export function writeReading(state, reading) {
113
+ reading.base[0] = state.speed;
114
+ reading.base[1] = state.heading;
115
+ reading.base[2] = state.ground;
116
+ reading.base[3] = state.seed;
117
+ reading.gust[0] = state.gustStrength;
118
+ reading.gust[1] = state.gustRadius;
119
+ reading.gust[2] = state.gustWave;
120
+ reading.gust[3] = state.gustSpeed;
121
+ reading.swirl[0] = state.swirl;
122
+ reading.swirl[1] = state.swirlScale;
123
+ reading.swirl[2] = state.swirlDrift;
124
+ }
125
+ /** The height over which the air slows to the ground, in meters. */
126
+ export const GROUND_HEIGHT = 2;
127
+ /** How long a push lasts before it has faded away, in seconds. */
128
+ export const PUSH_LIFE = 3;
129
+ /** The pushes that the field holds: the newest replaces the oldest. */
130
+ export const PUSH_SLOTS = 3;
131
+ /** The slot that holds the newest gust, after the pushes, so a page's pushes never push it out. */
132
+ export const GUST_SLOT = PUSH_SLOTS;
133
+ /** The slots of the ring: the pushes, then the gust. */
134
+ export const RING_SLOTS = PUSH_SLOTS + 1;
135
+ /** The distance over which the noise's curl is measured, in noise cells. */
136
+ export const CURL_STEP = 0.02;
137
+ /** The settings that a page gets when it names none. */
138
+ export function defaultFieldState() {
139
+ return {
140
+ speed: 4,
141
+ heading: 0,
142
+ ground: 0.65,
143
+ gustStrength: 3.5,
144
+ gustRadius: 14,
145
+ gustWave: 2,
146
+ gustSpeed: 6,
147
+ pushRadius: 6,
148
+ swirl: 1.6,
149
+ swirlScale: 0.06,
150
+ swirlDrift: 0.5,
151
+ seed: 0,
152
+ };
153
+ }
154
+ /**
155
+ * The height's factor of the wind, from 1 at the top to `1 - ground` at the ground, so a plant's
156
+ * crown moves more than its base.
157
+ */
158
+ export function profile(state, y) {
159
+ return 1 - state.ground * Math.exp(-Math.max(y, 0) / GROUND_HEIGHT);
160
+ }
161
+ /** The stream function of the swirl, in noise cells, at a place and a time. */
162
+ function stream(state, x, y, z, t) {
163
+ const drift = state.swirlDrift * t;
164
+ return value3(x * state.swirlScale + drift + state.seed, y * state.swirlScale, z * state.swirlScale + drift * 0.5);
165
+ }
166
+ /**
167
+ * The air's velocity at a world place and a sketch time, in meters a second, written into `out` as
168
+ * `[x, y, z]`. It allocates nothing and reads no state that a frame changes.
169
+ */
170
+ export function analyticVelocity(state, pushes, x, y, z, t, out) {
171
+ const height = profile(state, y);
172
+ const cos = Math.cos(state.heading);
173
+ const sin = Math.sin(state.heading);
174
+ let vx = cos * state.speed * height;
175
+ let vz = sin * state.speed * height;
176
+ // The gust: a wave of turns that travels along the heading, so the air curls as it passes. The
177
+ // turns are rings about the gust's center and depend only on the distance to it, so a ring of
178
+ // air turns without piling up.
179
+ const travel = state.gustSpeed * t;
180
+ const gx = x - cos * travel;
181
+ const gz = z - sin * travel;
182
+ const radius = state.gustRadius;
183
+ const distance = Math.sqrt(gx * gx + gz * gz) / radius;
184
+ const reach = distance * distance;
185
+ if (reach < 9) {
186
+ const envelope = Math.exp(-reach) * Math.cos(distance * state.gustWave) * state.gustStrength * height;
187
+ vx += (gz / radius) * envelope;
188
+ vz -= (gx / radius) * envelope;
189
+ }
190
+ // The swirl: the curl of one stream function in the ground plane, so the air turns without
191
+ // piling up. `psi` varies slowly, so a short step measures the slope.
192
+ const step = CURL_STEP / state.swirlScale;
193
+ const front = stream(state, x, y, z + step, t);
194
+ const back = stream(state, x, y, z - step, t);
195
+ const right = stream(state, x + step, y, z, t);
196
+ const left = stream(state, x - step, y, z, t);
197
+ vx += ((front - back) / (2 * step)) * state.swirl * height;
198
+ vz -= ((right - left) / (2 * step)) * state.swirl * height;
199
+ // The pushes and the gust: a vortex around each push, which fades as it ages, or a wave about a
200
+ // center that travels along the heading for the gust. The walk over the ring is the mirror of
201
+ // the loop that the field's WebAssembly runs, and a test holds the two equal.
202
+ for (let i = 0; i < pushes.length; i++) {
203
+ const slot = pushes[i];
204
+ if (!slot || slot.strength === 0)
205
+ continue;
206
+ let dx = x - slot.x;
207
+ let dz = z - slot.z;
208
+ let radius = state.pushRadius;
209
+ let turn = 0;
210
+ if (i === GUST_SLOT) {
211
+ // A gust: its wave's center has traveled along the heading since it was sent.
212
+ const age = t - slot.born;
213
+ const travel = state.gustSpeed * age;
214
+ dx -= cos * travel;
215
+ dz -= sin * travel;
216
+ radius = state.gustRadius;
217
+ const distance = Math.sqrt(dx * dx + dz * dz) / radius;
218
+ const reach = distance * distance;
219
+ if (reach < 9)
220
+ turn = Math.exp(-reach) * Math.cos(distance * state.gustWave);
221
+ }
222
+ else {
223
+ const age = t - slot.born;
224
+ if (age >= 0 && age <= PUSH_LIFE) {
225
+ const fadeOut = 1 - age / PUSH_LIFE;
226
+ const reach = radius * radius;
227
+ turn = Math.exp(-(dx * dx + dz * dz) / reach) * fadeOut;
228
+ }
229
+ }
230
+ if (turn === 0)
231
+ continue;
232
+ const strength = slot.strength * turn * height;
233
+ vx += (dz / radius) * strength;
234
+ vz -= (dx / radius) * strength;
235
+ }
236
+ out[0] = vx;
237
+ out[1] = 0;
238
+ out[2] = vz;
239
+ return out;
240
+ }
241
+ /** The divergence of the field at a place and a time, in a second, measured over a short step. */
242
+ export function divergence(state, pushes, x, y, z, t, step = 0.25) {
243
+ const a = [0, 0, 0];
244
+ const b = [0, 0, 0];
245
+ analyticVelocity(state, pushes, x + step, y, z, t, a);
246
+ analyticVelocity(state, pushes, x - step, y, z, t, b);
247
+ let sum = (a[0] - b[0]) / (2 * step);
248
+ analyticVelocity(state, pushes, x, y, z + step, t, a);
249
+ analyticVelocity(state, pushes, x, y, z - step, t, b);
250
+ sum += (a[2] - b[2]) / (2 * step);
251
+ return sum;
252
+ }
@@ -0,0 +1,34 @@
1
+ import type { WindReading } from './analytic.js';
2
+ /** The place of the place count in the request. */
3
+ export declare const COUNT = 0;
4
+ /** The place of the settings: the base wind, the gust, the swirl, the push's width and the time. */
5
+ export declare const SETTINGS = 1;
6
+ /** The place of the ring: four slots of `SLOT_FLOATS` numbers each. */
7
+ export declare const RING = 14;
8
+ /** The place of the first place's numbers. */
9
+ export declare const POINTS = 30;
10
+ /** The numbers of each ring slot: its place across the ground, its strength and its birth time. */
11
+ export declare const SLOT_FLOATS = 4;
12
+ /** The most places that one ask takes, from the request buffer that the module holds. */
13
+ export declare const MAX_PLACES = 5400;
14
+ /** The numbers that a request buffer holds at least, so a small growth costs no allocation. */
15
+ export declare const STEP = 256;
16
+ /**
17
+ * The numbers that a frame gives the ask, by their places in the array that carries them: the
18
+ * push's width and the sketch time. A frame writes them into the array rather than passing them as
19
+ * arguments, because the browser makes a number object of each fraction that a call it does not
20
+ * inline takes.
21
+ */
22
+ export declare const ASK_PUSH_RADIUS = 0;
23
+ /** The place of the sketch time among the numbers that a frame gives the ask. */
24
+ export declare const ASK_TIME = 1;
25
+ /** The numbers that the array holds. */
26
+ export declare const ASK_NUMBERS = 2;
27
+ /**
28
+ * Writes the settings, the ring and the places into `request`, which holds the places from `POINTS`
29
+ * on. `points` holds three numbers a place, `ring` one slot after another, and `numbers` the push's
30
+ * width and the sketch time. The call answers nothing, so no number crosses back to the caller on a
31
+ * frame where the browser does not inline it; the caller already knows the count from the places it
32
+ * passed.
33
+ */
34
+ export declare function fillRequest(request: Float32Array, points: Float32Array, reading: WindReading, ring: Float32Array, numbers: Float64Array): void;
@@ -0,0 +1,47 @@
1
+ /** The place of the place count in the request. */
2
+ export const COUNT = 0;
3
+ /** The place of the settings: the base wind, the gust, the swirl, the push's width and the time. */
4
+ export const SETTINGS = 1;
5
+ /** The place of the ring: four slots of `SLOT_FLOATS` numbers each. */
6
+ export const RING = 14;
7
+ /** The place of the first place's numbers. */
8
+ export const POINTS = 30;
9
+ /** The numbers of each ring slot: its place across the ground, its strength and its birth time. */
10
+ export const SLOT_FLOATS = 4;
11
+ /** The most places that one ask takes, from the request buffer that the module holds. */
12
+ export const MAX_PLACES = 5_400;
13
+ /** The numbers that a request buffer holds at least, so a small growth costs no allocation. */
14
+ export const STEP = 256;
15
+ /**
16
+ * The numbers that a frame gives the ask, by their places in the array that carries them: the
17
+ * push's width and the sketch time. A frame writes them into the array rather than passing them as
18
+ * arguments, because the browser makes a number object of each fraction that a call it does not
19
+ * inline takes.
20
+ */
21
+ export const ASK_PUSH_RADIUS = 0;
22
+ /** The place of the sketch time among the numbers that a frame gives the ask. */
23
+ export const ASK_TIME = 1;
24
+ /** The numbers that the array holds. */
25
+ export const ASK_NUMBERS = 2;
26
+ /**
27
+ * Writes the settings, the ring and the places into `request`, which holds the places from `POINTS`
28
+ * on. `points` holds three numbers a place, `ring` one slot after another, and `numbers` the push's
29
+ * width and the sketch time. The call answers nothing, so no number crosses back to the caller on a
30
+ * frame where the browser does not inline it; the caller already knows the count from the places it
31
+ * passed.
32
+ */
33
+ export function fillRequest(request, points, reading, ring, numbers) {
34
+ request[COUNT] = points.length / 3;
35
+ // The settings are the three vectors that a reader already holds, the push's width and the
36
+ // time. The swirl's vector holds a fourth number that nothing reads, so only three of its
37
+ // numbers go in.
38
+ request.set(reading.base, SETTINGS);
39
+ request.set(reading.gust, SETTINGS + 4);
40
+ request[SETTINGS + 8] = reading.swirl[0];
41
+ request[SETTINGS + 9] = reading.swirl[1];
42
+ request[SETTINGS + 10] = reading.swirl[2];
43
+ request[SETTINGS + 11] = numbers[ASK_PUSH_RADIUS];
44
+ request[SETTINGS + 12] = numbers[ASK_TIME];
45
+ request.set(ring, RING);
46
+ request.set(points, POINTS);
47
+ }
@@ -0,0 +1,14 @@
1
+ import type { Task } from '@null3d/engine';
2
+ /**
3
+ * The task that a page's ask runs. Its module is this one, which the build emits as the worker
4
+ * loads it, and its WebAssembly is the add-on's field.
5
+ */
6
+ export declare const FIELD_TASK: Task;
7
+ /** What the worker gives back: the answer, unless the page shares the memory it wrote. */
8
+ interface FieldOutput {
9
+ output: Float32Array | null;
10
+ transfer?: Transferable[];
11
+ }
12
+ /** Works out the air at each place in the request, and answers with the velocities. */
13
+ export declare function run(input: unknown, wasm: (name: string) => WebAssembly.Module): FieldOutput | Promise<FieldOutput>;
14
+ export {};
@@ -0,0 +1,54 @@
1
+ import { COUNT, MAX_PLACES } from './field-layout.js';
2
+ /**
3
+ * The task that a page's ask runs. Its module is this one, which the build emits as the worker
4
+ * loads it, and its WebAssembly is the add-on's field.
5
+ */
6
+ export const FIELD_TASK = {
7
+ name: 'wind-field',
8
+ script: new URL('./field-task.js', import.meta.url),
9
+ wasm: [
10
+ {
11
+ name: 'field',
12
+ url: new URL('../dist/wind.wasm', import.meta.url),
13
+ what: "the wind's field",
14
+ },
15
+ ],
16
+ };
17
+ /** The module, started once in each worker that runs the task. */
18
+ let started;
19
+ /** Starts the add-on's WebAssembly, or gives the one that this worker already started. */
20
+ function start(module) {
21
+ if (started)
22
+ return started;
23
+ const instance = new WebAssembly.Instance(module, {});
24
+ const exports = instance.exports;
25
+ started = { exports, floats: new Float32Array(exports.memory.buffer) };
26
+ return started;
27
+ }
28
+ /** Works out the air at each place in the request, and answers with the velocities. */
29
+ export function run(input, wasm) {
30
+ const { request, answer } = input;
31
+ const field = start(wasm('field'));
32
+ const { exports } = field;
33
+ // The module keeps its buffers and never grows its memory, so its view stays valid. A newer
34
+ // view answers anyway, so a module that grows is read rather than written past.
35
+ if (field.floats.buffer !== exports.memory.buffer)
36
+ field.floats = new Float32Array(exports.memory.buffer);
37
+ const count = request[COUNT];
38
+ if (count > MAX_PLACES)
39
+ throw new Error(`the wind field takes ${MAX_PLACES} places in one call, and this call asked for ${count}. Ask fewer places, or ask again in the next frame.`);
40
+ const at = exports.request(request.length * 4);
41
+ if (at === 0)
42
+ throw new Error(`the wind field takes ${MAX_PLACES} places in one call, and this call asked for ${count}. Ask fewer places, or ask again in the next frame.`);
43
+ field.floats.set(request, at / 4);
44
+ const status = exports.probe();
45
+ if (status !== 0)
46
+ throw new Error(`the wind field could not read the request: status ${status}.`);
47
+ const length = exports.response_length();
48
+ answer.set(new Float32Array(exports.memory.buffer, exports.response(), length / 4));
49
+ // A page whose buffer is shared reads the answer where it lies. Any other page gets the answer
50
+ // back, which the engine moves rather than copies.
51
+ if (answer.buffer instanceof SharedArrayBuffer)
52
+ return { output: null };
53
+ return { output: answer, transfer: [answer.buffer] };
54
+ }
package/lib/field.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { type Task } from '@null3d/engine';
2
+ import type { WindReading } from './analytic.js';
3
+ /** The first code that the add-on's own errors use. */
4
+ export declare const WIND_CODES = 2400;
5
+ /** An error that the add-on raises, with its own code and a message that says how to fix it. */
6
+ export declare function windError(code: number, detail: string): Error;
7
+ /**
8
+ * The air at places, worked out in a job worker. A call fills one request and sends it; the answer
9
+ * lands in the page's own array before the next frame's update. A call that arrives while an answer
10
+ * is still on its way fills the other buffer and sends one more ask when that answer comes, so a
11
+ * page that asks in every frame never queues more than one ask. The two buffers matter where the
12
+ * page shares its memory: the engine hands a shared buffer to the worker without copying it, so a
13
+ * second call may not write the bytes of the ask before it.
14
+ */
15
+ export declare class WindProbes {
16
+ private readonly run;
17
+ /** The two request buffers, of which one is filled while the other's answer is on its way. */
18
+ private readonly requests;
19
+ /** The buffer that a call fills. The other buffer is the ask that is on its way. */
20
+ private fill;
21
+ /** The task's input, which keeps its shape so a call makes no object. */
22
+ private readonly input;
23
+ /** The answer array of the ask that is on its way. */
24
+ private out;
25
+ private nextOut;
26
+ private inFlight;
27
+ private queued;
28
+ private reported;
29
+ private dropReported;
30
+ private stopped;
31
+ /** True where the page's memory can be shared with a worker, so the answer needs no copy back. */
32
+ private readonly shared;
33
+ /** `run` sends a task, which a test replaces to run one without a worker. */
34
+ constructor(run?: (task: Task, input: unknown) => Promise<unknown>);
35
+ /**
36
+ * Asks for the air at each place in `points`, three numbers a place across the ground, and puts
37
+ * the velocities in `out`, three numbers a place. `numbers` holds the push's width and the sketch
38
+ * time, which a frame writes into an array rather than passing as arguments, so the call takes no
39
+ * fraction that the browser would make a number object of. The answer arrives before the next
40
+ * frame.
41
+ */
42
+ ask(points: Float32Array, out: Float32Array, reading: WindReading, ring: Float32Array, numbers: Float64Array): void;
43
+ /** Stops asking, and ignores the answer that is still on its way. */
44
+ stop(): void;
45
+ /** Grows the buffer that a call fills, when the call asks for more places than it held. */
46
+ private reserve;
47
+ /** Sends the buffer that the last call filled, and frees the one that is on its way. */
48
+ private send;
49
+ /** Takes the answer, or sends the ask that waited for it. */
50
+ private readonly answered;
51
+ /** Reports the first dropped ask, and keeps the frames going. */
52
+ private reportDrop;
53
+ /** Reports the first failure and keeps the frames going. */
54
+ private readonly refused;
55
+ /** Makes a buffer that a worker may share, where the page allows sharing. */
56
+ private make;
57
+ }
package/lib/field.js ADDED
@@ -0,0 +1,140 @@
1
+ // The wind's analytic field in the engine's job workers: the task, the request that the sketch
2
+ // fills for it, and the call that asks for the air at places. A page that moves its own objects
3
+ // with the air asks here in a frame; the worker answers before the next frame's update.
4
+ //
5
+ // The call keeps one request buffer, so a frame's ask allocates nothing but the task's promise. The
6
+ // buffer grows when a page first asks for more places than it held before.
7
+ import { runTask } from '@null3d/engine';
8
+ import { fillRequest, MAX_PLACES, POINTS, STEP } from './field-layout.js';
9
+ import { FIELD_TASK } from './field-task.js';
10
+ /** The first code that the add-on's own errors use. */
11
+ export const WIND_CODES = 2400;
12
+ /** An error that the add-on raises, with its own code and a message that says how to fix it. */
13
+ export function windError(code, detail) {
14
+ return new Error(`wind E${code}: ${detail}`);
15
+ }
16
+ /**
17
+ * The air at places, worked out in a job worker. A call fills one request and sends it; the answer
18
+ * lands in the page's own array before the next frame's update. A call that arrives while an answer
19
+ * is still on its way fills the other buffer and sends one more ask when that answer comes, so a
20
+ * page that asks in every frame never queues more than one ask. The two buffers matter where the
21
+ * page shares its memory: the engine hands a shared buffer to the worker without copying it, so a
22
+ * second call may not write the bytes of the ask before it.
23
+ */
24
+ export class WindProbes {
25
+ run;
26
+ /** The two request buffers, of which one is filled while the other's answer is on its way. */
27
+ requests;
28
+ /** The buffer that a call fills. The other buffer is the ask that is on its way. */
29
+ fill = 0;
30
+ /** The task's input, which keeps its shape so a call makes no object. */
31
+ input;
32
+ /** The answer array of the ask that is on its way. */
33
+ out;
34
+ nextOut;
35
+ inFlight = false;
36
+ queued = false;
37
+ reported = false;
38
+ dropReported = false;
39
+ stopped = false;
40
+ /** True where the page's memory can be shared with a worker, so the answer needs no copy back. */
41
+ shared = typeof SharedArrayBuffer !== 'undefined';
42
+ /** `run` sends a task, which a test replaces to run one without a worker. */
43
+ constructor(run = runTask) {
44
+ this.run = run;
45
+ this.requests = [this.make(2 * POINTS), this.make(2 * POINTS)];
46
+ this.input = { request: this.requests[0], answer: new Float32Array(3) };
47
+ }
48
+ /**
49
+ * Asks for the air at each place in `points`, three numbers a place across the ground, and puts
50
+ * the velocities in `out`, three numbers a place. `numbers` holds the push's width and the sketch
51
+ * time, which a frame writes into an array rather than passing as arguments, so the call takes no
52
+ * fraction that the browser would make a number object of. The answer arrives before the next
53
+ * frame.
54
+ */
55
+ ask(points, out, reading, ring, numbers) {
56
+ if (this.stopped)
57
+ return;
58
+ if (points.length % 3 !== 0)
59
+ throw windError(WIND_CODES, `got ${points.length} numbers for the places, which take three numbers each.`);
60
+ const count = points.length / 3;
61
+ if (count > MAX_PLACES)
62
+ throw windError(WIND_CODES + 1, `got ${count} places; one call takes ${MAX_PLACES} at most. Ask the rest in the next frame.`);
63
+ if (out.length < points.length)
64
+ throw windError(WIND_CODES + 2, `got ${out.length} numbers for the answer; ${points.length} places take three numbers each.`);
65
+ this.reserve(points.length);
66
+ fillRequest(this.requests[this.fill], points, reading, ring, numbers);
67
+ this.nextOut = out;
68
+ if (this.inFlight) {
69
+ // One ask can wait for the answer that is on its way. A second one replaces it, because
70
+ // the free buffer holds the ask that waits, so the newest ask wins and the one it
71
+ // replaces is dropped: its array keeps the numbers it held. Say so, rather than let a
72
+ // page read an array that no answer will fill.
73
+ if (this.queued)
74
+ this.reportDrop();
75
+ this.queued = true;
76
+ return;
77
+ }
78
+ this.send();
79
+ }
80
+ /** Stops asking, and ignores the answer that is still on its way. */
81
+ stop() {
82
+ this.stopped = true;
83
+ }
84
+ /** Grows the buffer that a call fills, when the call asks for more places than it held. */
85
+ reserve(numbers) {
86
+ const request = this.requests[this.fill];
87
+ if (request.length >= POINTS + numbers)
88
+ return;
89
+ const floats = Math.ceil((POINTS + numbers) / STEP) * STEP;
90
+ this.requests[this.fill] = this.make(floats);
91
+ }
92
+ /** Sends the buffer that the last call filled, and frees the one that is on its way. */
93
+ send() {
94
+ const out = this.nextOut;
95
+ const sent = this.fill;
96
+ // The other buffer takes the next call, so the ask that is on its way keeps its bytes.
97
+ this.fill = 1 - this.fill;
98
+ this.inFlight = true;
99
+ this.out = out;
100
+ // The worker writes into the page's array where the memory is shared, and gives the answer
101
+ // back otherwise, which the engine moves rather than copies.
102
+ this.input.request = this.requests[sent];
103
+ this.input.answer = out;
104
+ this.run(FIELD_TASK, this.input).then(this.answered, this.refused);
105
+ }
106
+ /** Takes the answer, or sends the ask that waited for it. */
107
+ answered = (answer) => {
108
+ this.inFlight = false;
109
+ if (this.stopped)
110
+ return;
111
+ // A shared answer is already in the page's array; a copied one lands in it here.
112
+ if (answer)
113
+ this.out?.set(answer);
114
+ if (this.queued) {
115
+ this.queued = false;
116
+ this.send();
117
+ }
118
+ };
119
+ /** Reports the first dropped ask, and keeps the frames going. */
120
+ reportDrop() {
121
+ if (this.dropReported)
122
+ return;
123
+ this.dropReported = true;
124
+ console.error("wind: a read arrived while one already waited for its answer, so the newest ask replaced it and the earlier answer's array keeps its numbers. Keep one read in a frame, and read its answer in the next frame's update.");
125
+ }
126
+ /** Reports the first failure and keeps the frames going. */
127
+ refused = (error) => {
128
+ this.inFlight = false;
129
+ this.queued = false;
130
+ if (this.reported)
131
+ return;
132
+ this.reported = true;
133
+ console.error(`wind: the field's job worker did not answer, so the air at a page's own places stays as it was. ${error instanceof Error ? error.message : String(error)}`);
134
+ };
135
+ /** Makes a buffer that a worker may share, where the page allows sharing. */
136
+ make(floats) {
137
+ const bytes = floats * 4;
138
+ return new Float32Array(this.shared ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes));
139
+ }
140
+ }