@driftengine/physics 4.8.3 → 4.8.4

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/dist/exact.js ADDED
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Transcendentals that give the same bits on every JavaScript engine.
3
+ *
4
+ * **Not more accurate than `Math`, and that is not what they are for.** These are within a couple
5
+ * of units in the last place of correctly rounded, which is about what a platform `sin` gives you.
6
+ * What they are is *reproducible*: ECMAScript declines to specify `sin`, `cos`, `exp`, `acos` and
7
+ * eighteen more, so two engines may differ by an ulp, and an ulp is enough to make two peers running
8
+ * the same simulation disagree — first invisibly, then completely.
9
+ *
10
+ * **In physics rather than core since 4.8.4**: a skinned cloth's damping needs `exp` and its bending
11
+ * `acos`, the simulation set may not call the platform's, and physics imports no other package. Core
12
+ * re-exports physics wholesale, so `exactExp` from `@driftengine/core` is the same function.
13
+ *
14
+ * `scripts/determinism.mjs` is the gate that refuses the unspecified ones inside the simulation set
15
+ * and names the twenty-two. Its header carries the other half of the argument: `+ - * /` are IEEE
16
+ * 754 operations by specification, JavaScript permits no fused-multiply-add contraction, and
17
+ * `Math.sqrt` is required correctly rounded and is *not* on that list. **So everything below uses
18
+ * only those five operations**, which is the whole design: reproducibility by construction rather
19
+ * than by hoping two engines chose the same algorithm.
20
+ *
21
+ * ---
22
+ *
23
+ * ## What is here, and what is deliberately not
24
+ *
25
+ * `exactSin`, `exactCos`, `exactExp`, `exactAcos` and `exactLog`. Five, because five is what the
26
+ * engine and its first consumer actually reach for: the terrain binding's slope angle needs `acos`,
27
+ * a lockstep fixture rotating anything needs `sin` and `cos`, exponential decay needs `exp`, and a
28
+ * detector's box prior is a logit of the patch grid, which needs `log`.
29
+ *
30
+ * **`atan2` is absent.** It is the obvious fifth and nothing here needs one: `shape.ts` sorts by a
31
+ * comparison key computed from two in-plane axes rather than by an angle, and `joints.ts` compares
32
+ * a quaternion component against a half-angle's sine. *Reversed by* a site that genuinely needs a
33
+ * signed angle from two components, at which point it arrives with its own golden vectors.
34
+ *
35
+ * ## Nothing in core imports these
36
+ *
37
+ * Deliberately. `core-only` is the one size figure in this repository that every consumer pays, and
38
+ * a module reachable from `createRenderer` is in it whether anybody calls it or not. These are
39
+ * reached by the script bindings and by consumers who ask for them, so tree-shaking keeps them out
40
+ * of a bundle that does not, which is measured rather than assumed.
41
+ *
42
+ * ## The coefficients
43
+ *
44
+ * The polynomial and rational coefficients are fdlibm's, which is the ancestor of most platform
45
+ * libms and is public domain. They are written as literals: **a literal is the same number on
46
+ * every engine, which is the only property being bought.** Their provenance matters less than their
47
+ * fixity — a coefficient somebody re-derived to one more digit is a different function, and
48
+ * `exact.test.ts`'s golden bit patterns are what would catch that.
49
+ */
50
+ /*
51
+ * π/2 in four pieces, most significant first, so a large multiple of it can be removed without
52
+ * losing the small remainder in the subtraction.
53
+ *
54
+ * **Two pieces are not enough and the measurement says so**: at an angle of 740 radians a two-part
55
+ * reduction leaves `sin` and `cos` 18.5 ulps out, because `k * PIO2_1` needs more than 53 bits once
56
+ * `k` grows. Three brings it under two ulps for the cost of two multiplies.
57
+ *
58
+ * **`PIO2_TAIL` and `PIO2_TAIL_LO` are one number in two halves, not two successive corrections.**
59
+ * fdlibm carries a fourth constant, `pio2_1t`, which is the tail for its *single*-iteration path;
60
+ * `pio2_2` is the same tail rounded differently, with `pio2_2t` as its own tail, and the two paths
61
+ * are alternatives. Refining the first with the second is not more accurate, it is wrong: it
62
+ * subtracts the tail twice and took `sin` to 2.2e11 ulps out, which is how this comment came to be
63
+ * here.
64
+ */
65
+ const PIO2_1 = 1.5707963267341256;
66
+ const PIO2_TAIL = 6.077100506303966e-11;
67
+ const PIO2_TAIL_LO = 2.0222662487959506e-21;
68
+ const TWO_OVER_PI = 0.6366197723675814;
69
+ const HALF_PI = 1.5707963267948966;
70
+ const PI = 3.141592653589793;
71
+ /* fdlibm's `__kernel_sin` coefficients. */
72
+ const S1 = -1.6666666666666632e-1;
73
+ const S2 = 8.33333333332249e-3;
74
+ const S3 = -1.984126982985795e-4;
75
+ const S4 = 2.7557313707070068e-6;
76
+ const S5 = -2.5050760253406863e-8;
77
+ const S6 = 1.5896909952115501e-10;
78
+ /* fdlibm's `__kernel_cos` coefficients. */
79
+ const C1 = 4.1666666666666602e-2;
80
+ const C2 = -1.388888888887411e-3;
81
+ const C3 = 2.480158728947673e-5;
82
+ const C4 = -2.7557314351390663e-7;
83
+ const C5 = 2.0875723212981748e-9;
84
+ const C6 = -1.1359647557788195e-11;
85
+ /* fdlibm's `asin` rational, numerator then denominator. */
86
+ const P0 = 1.6666666666666666e-1;
87
+ const P1 = -3.2556581862240092e-1;
88
+ const P2 = 2.0121253213486293e-1;
89
+ const P3 = -4.0055534500679411e-2;
90
+ const P4 = 7.9153499428981453e-4;
91
+ const P5 = 3.4793310759602117e-5;
92
+ const Q1 = -2.4033949117344142;
93
+ const Q2 = 2.0209457602335057;
94
+ const Q3 = -6.8828397160545329e-1;
95
+ const Q4 = 7.7038150555901935e-2;
96
+ /** ln 2, split for the same reason π/2 is. */
97
+ const LN2_HI = 0.6931471803691238;
98
+ const LN2_LO = 1.9082149292705877e-10;
99
+ const ONE_OVER_LN2 = 1.4426950408889634;
100
+ /** 2^(2^i), for i = 0 to 9. Every one is exact, so a product of them is exact. */
101
+ const POW2 = [
102
+ 2, 4, 16, 256, 65536, 4294967296, 1.8446744073709552e19, 3.402823669209385e38,
103
+ 1.157920892373162e77, 1.3407807929942597e154,
104
+ ];
105
+ /**
106
+ * Two to an integer power, by binary decomposition of the exponent.
107
+ *
108
+ * Multiplication by a power of two is exact in IEEE 754, so this is exact wherever it does not
109
+ * overflow — which is what makes it a legitimate substitute for the `Math.pow` a range reduction
110
+ * would otherwise reach for.
111
+ *
112
+ * A large negative exponent lands on zero instead of a subnormal, because the reciprocal is taken
113
+ * after the product overflows. That is `exp` underflowing to zero, which is where it was going.
114
+ */
115
+ function pow2(exponent) {
116
+ let remaining = exponent < 0 ? -exponent : exponent;
117
+ let result = 1;
118
+ let index = 0;
119
+ while (remaining > 0 && index < POW2.length) {
120
+ if ((remaining & 1) === 1)
121
+ result *= POW2[index];
122
+ remaining >>= 1;
123
+ index += 1;
124
+ }
125
+ return exponent < 0 ? 1 / result : result;
126
+ }
127
+ /** sin on [-π/4, π/4]. */
128
+ function sinKernel(x) {
129
+ const z = x * x;
130
+ const poly = S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))));
131
+ return x + x * z * poly;
132
+ }
133
+ /** cos on [-π/4, π/4]. */
134
+ function cosKernel(x) {
135
+ const z = x * x;
136
+ const poly = C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))));
137
+ return 1 - 0.5 * z + z * z * poly;
138
+ }
139
+ /**
140
+ * Fold an angle into [-π/4, π/4] and say which quadrant it came from.
141
+ *
142
+ * Cody-Waite: the multiple of π/2 is removed in pieces, so the subtraction that produces a small
143
+ * remainder from two large numbers does not lose the bits it is supposed to keep. One-piece
144
+ * reduction is accurate to about 1e-8 at an angle of a thousand radians, which for a simulation
145
+ * that accumulates rotation is the difference between an object facing forward and facing sideways
146
+ * after a few minutes.
147
+ */
148
+ function reduce(x) {
149
+ const k = Math.round(x * TWO_OVER_PI);
150
+ /* The leading piece, whose product with `k` is exact for every `k` a simulation reaches. */
151
+ const head = x - k * PIO2_1;
152
+ /*
153
+ * The tail, in two halves. `head - tail` loses the bits below its own last place, and
154
+ * `PIO2_TAIL_LO - (head - r - tail)` is exactly those bits recovered — the same
155
+ * subtract-and-recover fdlibm uses on its two-iteration path.
156
+ */
157
+ const tail = k * PIO2_TAIL;
158
+ let r = head - tail;
159
+ const lost = k * PIO2_TAIL_LO - (head - r - tail);
160
+ r = r - lost;
161
+ return { r, quadrant: ((k % 4) + 4) % 4 };
162
+ }
163
+ /** `Math.sin`, reproducibly. NaN in, NaN out; an infinity answers NaN, as `Math.sin` does. */
164
+ export function exactSin(x) {
165
+ if (!Number.isFinite(x))
166
+ return Number.NaN;
167
+ const { r, quadrant } = reduce(x);
168
+ switch (quadrant) {
169
+ case 0:
170
+ return sinKernel(r);
171
+ case 1:
172
+ return cosKernel(r);
173
+ case 2:
174
+ return -sinKernel(r);
175
+ default:
176
+ return -cosKernel(r);
177
+ }
178
+ }
179
+ /** `Math.cos`, reproducibly. */
180
+ export function exactCos(x) {
181
+ if (!Number.isFinite(x))
182
+ return Number.NaN;
183
+ const { r, quadrant } = reduce(x);
184
+ switch (quadrant) {
185
+ case 0:
186
+ return cosKernel(r);
187
+ case 1:
188
+ return -sinKernel(r);
189
+ case 2:
190
+ return -cosKernel(r);
191
+ default:
192
+ return sinKernel(r);
193
+ }
194
+ }
195
+ /**
196
+ * `Math.exp`, reproducibly.
197
+ *
198
+ * Reduce by a multiple of ln 2 into [-ln2/2, ln2/2], sum the Taylor series there, and scale by a
199
+ * power of two. **A degree-14 series and not a shorter minimax**, because on that interval the
200
+ * fifteenth term is about 4e-20 — below the precision of a double — so the series is exact to the
201
+ * representation and there is nothing a fitted polynomial would buy.
202
+ */
203
+ export function exactExp(x) {
204
+ if (Number.isNaN(x))
205
+ return Number.NaN;
206
+ if (x === Number.POSITIVE_INFINITY)
207
+ return Number.POSITIVE_INFINITY;
208
+ if (x === Number.NEGATIVE_INFINITY)
209
+ return 0;
210
+ if (x > 709.782712893384)
211
+ return Number.POSITIVE_INFINITY;
212
+ if (x < -745.1332191019411)
213
+ return 0;
214
+ const k = Math.round(x * ONE_OVER_LN2);
215
+ const r = x - k * LN2_HI - k * LN2_LO;
216
+ /* Horner over 1/n!, highest term first. */
217
+ let sum = 1 / 87178291200; // 1/14!
218
+ sum = 1 / 6227020800 + r * sum; // 1/13!
219
+ sum = 1 / 479001600 + r * sum; // 1/12!
220
+ sum = 1 / 39916800 + r * sum; // 1/11!
221
+ sum = 1 / 3628800 + r * sum; // 1/10!
222
+ sum = 1 / 362880 + r * sum; // 1/9!
223
+ sum = 1 / 40320 + r * sum; // 1/8!
224
+ sum = 1 / 5040 + r * sum; // 1/7!
225
+ sum = 1 / 720 + r * sum; // 1/6!
226
+ sum = 1 / 120 + r * sum; // 1/5!
227
+ sum = 1 / 24 + r * sum; // 1/4!
228
+ sum = 1 / 6 + r * sum; // 1/3!
229
+ sum = 0.5 + r * sum;
230
+ sum = 1 + r * sum;
231
+ sum = 1 + r * sum;
232
+ return sum * pow2(k);
233
+ }
234
+ /* fdlibm's `log` polynomial in s², for log(1 + f) around f = 0 by way of s = f / (2 + f). */
235
+ const LG1 = 6.66666666666673513e-1;
236
+ const LG2 = 3.999999999940941908e-1;
237
+ const LG3 = 2.857142874366239149e-1;
238
+ const LG4 = 2.222219843214978396e-1;
239
+ const LG5 = 1.818357216161805012e-1;
240
+ const LG6 = 1.531383769920937332e-1;
241
+ const LG7 = 1.479819860511658591e-1;
242
+ const TWO54 = 1.8014398509481984e16;
243
+ const SMALLEST_NORMAL = 2.2250738585072014e-308;
244
+ /* A double's two words, for reading and setting an exponent; one view, reused. */
245
+ const words = new DataView(new ArrayBuffer(8));
246
+ /**
247
+ * `Math.log`, reproducibly: fdlibm's algorithm, which is also V8's.
248
+ *
249
+ * Take the power of two out as `k` and leave a significand in [√2/2, √2), so that `f = m - 1` is
250
+ * small either side of zero; then log(1 + f) = f - f²/2 + s·(f²/2 + R(s²)) with s = f/(2 + f), and
251
+ * `k·ln 2` added back in two parts so the large part loses nothing. The exponent is read and the
252
+ * significand rescaled through the double's own words — integer operations, not transcendentals.
253
+ */
254
+ export function exactLog(x) {
255
+ if (Number.isNaN(x) || x < 0)
256
+ return Number.NaN;
257
+ if (x === 0)
258
+ return Number.NEGATIVE_INFINITY;
259
+ if (x === Number.POSITIVE_INFINITY)
260
+ return x;
261
+ let k = 0;
262
+ let value = x;
263
+ if (value < SMALLEST_NORMAL) {
264
+ k = -54;
265
+ value *= TWO54;
266
+ }
267
+ words.setFloat64(0, value);
268
+ let hx = words.getUint32(0);
269
+ k += (hx >>> 20) - 1023;
270
+ hx &= 0x000fffff;
271
+ /* Keep the significand at or above √2/2: past √2, halve it and count one more power of two. */
272
+ const i = (hx + 0x95f64) & 0x100000;
273
+ words.setUint32(0, hx | (i ^ 0x3ff00000));
274
+ k += i >>> 20;
275
+ const f = words.getFloat64(0) - 1;
276
+ if ((0x000fffff & (2 + hx)) < 3) {
277
+ /* |f| < 2^-20: two terms of the series are the whole answer. */
278
+ if (f === 0)
279
+ return k === 0 ? 0 : k * LN2_HI + k * LN2_LO;
280
+ const r = f * f * (0.5 - 0.3333333333333333 * f);
281
+ return k === 0 ? f - r : k * LN2_HI - (r - k * LN2_LO - f);
282
+ }
283
+ const s = f / (2 + f);
284
+ const z = s * s;
285
+ const w = z * z;
286
+ const t1 = w * (LG2 + w * (LG4 + w * LG6));
287
+ const t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
288
+ const r = t2 + t1;
289
+ /* Far enough from one that f²/2 is worth carrying apart from f. */
290
+ if (((hx - 0x6147a) | (0x6b851 - hx)) > 0) {
291
+ const half = 0.5 * f * f;
292
+ return k === 0
293
+ ? f - (half - s * (half + r))
294
+ : k * LN2_HI - (half - (s * (half + r) + k * LN2_LO) - f);
295
+ }
296
+ return k === 0 ? f - s * (f - r) : k * LN2_HI - (s * (f - r) - k * LN2_LO - f);
297
+ }
298
+ /** fdlibm's `asin` rational on `z = x²`, valid where `z` is small. */
299
+ function asinRational(z) {
300
+ const numerator = z * (P0 + z * (P1 + z * (P2 + z * (P3 + z * (P4 + z * P5)))));
301
+ const denominator = 1 + z * (Q1 + z * (Q2 + z * (Q3 + z * Q4)));
302
+ return numerator / denominator;
303
+ }
304
+ /**
305
+ * `Math.acos`, reproducibly. Outside [-1, 1] this answers NaN, as `Math.acos` does.
306
+ *
307
+ * Three branches rather than one, and the split at ±0.5 is the reason it is accurate near the ends:
308
+ * `acos` has infinite derivative at ±1, so a polynomial in `x` loses its footing there. Substituting
309
+ * `s = sqrt((1 ∓ x)/2)` moves the awkward point to zero, where a polynomial is comfortable — which
310
+ * is also why `sqrt` being exactly rounded matters here rather than being a convenience.
311
+ */
312
+ export function exactAcos(x) {
313
+ if (Number.isNaN(x) || x > 1 || x < -1)
314
+ return Number.NaN;
315
+ if (x === 1)
316
+ return 0;
317
+ if (x === -1)
318
+ return PI;
319
+ if (x >= 0.5) {
320
+ const z = (1 - x) / 2;
321
+ const s = Math.sqrt(z);
322
+ return 2 * (s + s * asinRational(z));
323
+ }
324
+ if (x <= -0.5) {
325
+ const z = (1 + x) / 2;
326
+ const s = Math.sqrt(z);
327
+ return PI - 2 * (s + s * asinRational(z));
328
+ }
329
+ const z = x * x;
330
+ return HALF_PI - (x + x * asinRational(z));
331
+ }
package/dist/index.d.ts CHANGED
@@ -58,6 +58,15 @@ export type { EscapeResult, EscapeVeto, StallEscapeOptions, StallInput } from '.
58
58
  export { ESCAPE_EASED, ESCAPE_IDLE, ESCAPE_PUSHED, ESCAPE_SEALED, StallEscape, } from './stallEscape.ts';
59
59
  export type { ClothOptions } from './cloth.ts';
60
60
  export { ClothBody, makeClothGrid } from './cloth.ts';
61
+ export { SkinnedCloth } from './skinnedCloth.ts';
62
+ export { ClothControl } from './clothControl.ts';
63
+ export type { ClothDevice } from './clothControl.ts';
64
+ export type { ClothTargets } from './clothTargets.ts';
65
+ export { validateClothSetup } from './skinnedClothSetup.ts';
66
+ export { exactAcos, exactCos, exactExp, exactLog, exactSin } from './exact.ts';
67
+ export { batchesOf, colourConstraints } from './clothBatches.ts';
68
+ export type { ClothBatches } from './clothBatches.ts';
69
+ export type { BendingConstraints, ClothCollider, ClothLimits, DistanceConstraints, ResolvedClothParameters, SkinnedClothParameters, SkinnedClothSetup, TetherConstraints, } from './skinnedClothSetup.ts';
61
70
  export type { Collider, ColliderBytes, ColliderGroup } from './colliderSet.ts';
62
71
  export { ColliderSet, boxCollider, colliderFromShape } from './colliderSet.ts';
63
72
  export { fingerprintBodies, fingerprintColliders } from './fingerprint.ts';
package/dist/index.js CHANGED
@@ -23,6 +23,25 @@ export { accelerateAlong } from './groundMotor.js';
23
23
  export { applyBuoyancy, createBuoyancy } from './buoyancy.js';
24
24
  export { ESCAPE_EASED, ESCAPE_IDLE, ESCAPE_PUSHED, ESCAPE_SEALED, StallEscape, } from './stallEscape.js';
25
25
  export { ClothBody, makeClothGrid } from './cloth.js';
26
+ /*
27
+ * Cloth anchored to a skeleton rather than a world: a garment. The CPU solver is the reference and
28
+ * runs under WebGL2 and in Node; `@driftengine/core` runs the same kernels on WebGPU.
29
+ */
30
+ export { SkinnedCloth } from './skinnedCloth.js';
31
+ /*
32
+ * The schedule both solvers share — poses, whole steps, resets and the blend — and the device
33
+ * interface the GPU solver implements, with what it reads: the targets' matrices and colliders,
34
+ * and the set-up checked and batched exactly as the CPU solver checks and batches it.
35
+ */
36
+ export { ClothControl } from './clothControl.js';
37
+ export { validateClothSetup } from './skinnedClothSetup.js';
38
+ /*
39
+ * Transcendentals that give the same bits on every engine. Here rather than in core since 4.8.4,
40
+ * because the simulation needs them and this package imports nothing; core re-exports them with
41
+ * the rest of physics.
42
+ */
43
+ export { exactAcos, exactCos, exactExp, exactLog, exactSin } from './exact.js';
44
+ export { batchesOf, colourConstraints } from './clothBatches.js';
26
45
  export { ColliderSet, boxCollider, colliderFromShape } from './colliderSet.js';
27
46
  export { fingerprintBodies, fingerprintColliders } from './fingerprint.js';
28
47
  export { combineMassProperties, createMassProperties, shapeMassProperties } from './mass.js';
@@ -0,0 +1,63 @@
1
+ import type { ResolvedClothParameters, SkinnedClothSetup } from './skinnedClothSetup.ts';
2
+ /**
3
+ * A garment's particles, constraints and solver state, stepped at the set-up's fixed step. Read
4
+ * `positions` after a step, or `interpolate` between the last two for a frame's `alpha`. The
5
+ * schedule — poses, steps, resets, the blend — is `ClothControl`'s; this is its CPU device.
6
+ */
7
+ export declare class SkinnedCloth {
8
+ /** How many particles. */
9
+ readonly count: number;
10
+ /** Where each particle is now, three floats a particle. */
11
+ readonly positions: Float32Array;
12
+ /** Metres a second, three floats a particle. */
13
+ readonly velocities: Float32Array;
14
+ readonly inverseMass: Float32Array;
15
+ /** The parameters with their defaults filled in. */
16
+ readonly parameters: ResolvedClothParameters;
17
+ /** Where each particle was when the last step began, for drawing on `alpha`. */
18
+ private readonly stepStart;
19
+ /** Where each particle was when the current substep began, for its velocity. */
20
+ private readonly substepStart;
21
+ private readonly distance;
22
+ private readonly bending;
23
+ private readonly tethers;
24
+ private readonly control;
25
+ private readonly targets;
26
+ private readonly limits;
27
+ private readonly colliders;
28
+ /** The air the cloth drags toward, metres a second: the set-up's until `setWind` says otherwise. */
29
+ private readonly wind;
30
+ constructor(setup: SkinnedClothSetup);
31
+ /**
32
+ * The air the steps to come drag the cloth toward, world space, metres a second: the frame's
33
+ * sample of the scene's one wind, so a garment moves with the smoke and the grass rather than
34
+ * with a second wind of its own. See `AGENTS.md`, "One wind, sampled once".
35
+ */
36
+ setWind(x: number, y: number, z: number): void;
37
+ /** See `ClothControl.setPose`. */
38
+ setPose(globals: Float32Array, model: Float32Array): void;
39
+ /** See `ClothControl.reset`. */
40
+ reset(): void;
41
+ /** See `ClothControl.advance`. */
42
+ advance(dt: number): number;
43
+ /** How far the time handed to `advance` reaches into the next step, 0 to 1. */
44
+ get alpha(): number;
45
+ /** Each particle between the start and the end of the last step, at `alpha`, into `out`. */
46
+ interpolate(alpha: number, out: Float32Array): void;
47
+ /** One fixed step, all the way to the latest pose: for a caller in the engine's fixed-step loop. */
48
+ step(): void;
49
+ /** Every particle at its latest skinned position, at rest. */
50
+ private rest;
51
+ /**
52
+ * One fixed step, `fraction` of the way from the last pose to the latest: carried by the share of
53
+ * the character's motion it does not keep, its kinematic particles placed, then its substeps —
54
+ * each predicted, constrained, limited and turned into velocities.
55
+ */
56
+ private stepAt;
57
+ /** The limits and the colliders, after the constraints, so a garment pulling into the body loses. */
58
+ private limit;
59
+ /** After a reset, the share of the simulation drawn grows from nothing to all over the blend. */
60
+ private blend;
61
+ /** Every batch of one kind, in colour order. */
62
+ private solve;
63
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * A skinned cloth on the CPU: the reference solver, and the one WebGL2 and Node run.
3
+ *
4
+ * **Whole fixed steps, whatever the frame.** The set-up names its step (a garment's is 1/60); a
5
+ * caller in the engine's own fixed-step loop calls `step` once a tick, and any other calls `advance`
6
+ * with the frame's time and the remainder waits for the next frame. The cloth therefore behaves the
7
+ * same at 60, 120 and 144 frames a second, and a frame draws it on `alpha` between its last two
8
+ * steps — the engine's rule, and what keeps a high refresh rate from drawing the same cloth twice.
9
+ *
10
+ * **What it gives up**: an `advance` of a long time runs that many steps, with no ceiling; a caller
11
+ * that stalls for a second gets a second of cloth. The engine's loop clamps its own catch-up, and a
12
+ * caller outside it is expected to clamp the time it hands over.
13
+ *
14
+ * Every step allocates nothing. The WebGPU solver in `@driftengine/core` runs the same kernels over
15
+ * the same data (`skinnedClothSolve.ts`, `clothLimits.ts`) under the same `ClothControl`, and is held
16
+ * to this one by a parity check on the device.
17
+ */
18
+ import { batchesOf } from './clothBatches.js';
19
+ import { ClothControl } from './clothControl.js';
20
+ import { applyColliders, applyMaxDistance, applyStops } from './clothLimits.js';
21
+ import { carryParticles } from './clothPose.js';
22
+ import { exactExp } from './exact.js';
23
+ import { finishParticles, predictParticles, solveBendingBatch, solveDistanceBatch, solveTethers, } from './skinnedClothSolve.js';
24
+ import { validateClothSetup } from './skinnedClothSetup.js';
25
+ function solvable(name, indices, arity, rest, compliance, inverseMass, given) {
26
+ const batches = batchesOf(name, indices, arity, inverseMass, given);
27
+ return { indices, rest, compliance, lambda: new Float32Array(rest.length), batches };
28
+ }
29
+ /**
30
+ * A garment's particles, constraints and solver state, stepped at the set-up's fixed step. Read
31
+ * `positions` after a step, or `interpolate` between the last two for a frame's `alpha`. The
32
+ * schedule — poses, steps, resets, the blend — is `ClothControl`'s; this is its CPU device.
33
+ */
34
+ export class SkinnedCloth {
35
+ /** How many particles. */
36
+ count;
37
+ /** Where each particle is now, three floats a particle. */
38
+ positions;
39
+ /** Metres a second, three floats a particle. */
40
+ velocities;
41
+ inverseMass;
42
+ /** The parameters with their defaults filled in. */
43
+ parameters;
44
+ /** Where each particle was when the last step began, for drawing on `alpha`. */
45
+ stepStart;
46
+ /** Where each particle was when the current substep began, for its velocity. */
47
+ substepStart;
48
+ distance;
49
+ bending;
50
+ tethers;
51
+ control;
52
+ targets;
53
+ limits;
54
+ colliders;
55
+ /** The air the cloth drags toward, metres a second: the set-up's until `setWind` says otherwise. */
56
+ wind;
57
+ constructor(setup) {
58
+ validateClothSetup(setup);
59
+ this.count = setup.positions.length / 3;
60
+ this.positions = new Float32Array(setup.positions);
61
+ this.velocities = new Float32Array(setup.positions.length);
62
+ this.stepStart = new Float32Array(setup.positions);
63
+ this.substepStart = new Float32Array(setup.positions.length);
64
+ this.inverseMass = new Float32Array(setup.inverseMass);
65
+ const { distance, bending } = setup;
66
+ this.distance = solvable('distance', distance.pairs, 2, distance.rest, distance.compliance, this.inverseMass, distance.batches);
67
+ this.bending =
68
+ bending === undefined
69
+ ? null
70
+ : solvable('bending', bending.quads, 4, bending.rest, bending.compliance, this.inverseMass, bending.batches);
71
+ this.tethers = setup.tethers ?? null;
72
+ this.limits = setup.limits ?? {};
73
+ this.colliders = setup.colliders?.length ?? 0;
74
+ /* Made once, so a step builds nothing: the control calls back into the private step. */
75
+ const device = {
76
+ targetsChanged: () => { },
77
+ rest: () => {
78
+ this.rest();
79
+ },
80
+ step: (fraction, blend) => {
81
+ this.stepAt(fraction, blend);
82
+ },
83
+ };
84
+ this.control = new ClothControl(setup, device);
85
+ this.parameters = this.control.parameters;
86
+ this.targets = this.control.targets;
87
+ this.wind = [...this.parameters.wind];
88
+ }
89
+ /**
90
+ * The air the steps to come drag the cloth toward, world space, metres a second: the frame's
91
+ * sample of the scene's one wind, so a garment moves with the smoke and the grass rather than
92
+ * with a second wind of its own. See `AGENTS.md`, "One wind, sampled once".
93
+ */
94
+ setWind(x, y, z) {
95
+ this.wind[0] = x;
96
+ this.wind[1] = y;
97
+ this.wind[2] = z;
98
+ }
99
+ /** See `ClothControl.setPose`. */
100
+ setPose(globals, model) {
101
+ this.control.setPose(globals, model);
102
+ }
103
+ /** See `ClothControl.reset`. */
104
+ reset() {
105
+ this.control.reset();
106
+ }
107
+ /** See `ClothControl.advance`. */
108
+ advance(dt) {
109
+ return this.control.advance(dt);
110
+ }
111
+ /** How far the time handed to `advance` reaches into the next step, 0 to 1. */
112
+ get alpha() {
113
+ return this.control.alpha;
114
+ }
115
+ /** Each particle between the start and the end of the last step, at `alpha`, into `out`. */
116
+ interpolate(alpha, out) {
117
+ const from = this.stepStart;
118
+ const to = this.positions;
119
+ for (let i = 0; i < to.length; i++) {
120
+ const a = from[i];
121
+ out[i] = a + (to[i] - a) * alpha;
122
+ }
123
+ }
124
+ /** One fixed step, all the way to the latest pose: for a caller in the engine's fixed-step loop. */
125
+ step() {
126
+ this.control.step();
127
+ }
128
+ /** Every particle at its latest skinned position, at rest. */
129
+ rest() {
130
+ this.positions.set(this.targets.latest);
131
+ this.stepStart.set(this.positions);
132
+ this.velocities.fill(0);
133
+ }
134
+ /**
135
+ * One fixed step, `fraction` of the way from the last pose to the latest: carried by the share of
136
+ * the character's motion it does not keep, its kinematic particles placed, then its substeps —
137
+ * each predicted, constrained, limited and turned into velocities.
138
+ */
139
+ stepAt(fraction, blend) {
140
+ /* Where the last step ended, kinematic particles included, before this one moves anything. */
141
+ this.stepStart.set(this.positions);
142
+ const { step, substeps, iterations, damping, drag, gravity } = this.parameters;
143
+ const wind = this.wind;
144
+ const targets = this.targets;
145
+ carryParticles(this.positions, this.velocities, this.inverseMass, targets.modelBefore, targets.modelNow, this.parameters.linearInertia, this.parameters.angularInertia);
146
+ placeKinematic(this.positions, this.inverseMass, targets.position);
147
+ const h = step / substeps;
148
+ const invH = 1 / h;
149
+ const invH2 = invH * invH;
150
+ const keep = exactExp(damping * h);
151
+ const dragKeep = exactExp(drag * h);
152
+ for (let s = 0; s < substeps; s++) {
153
+ predictParticles(this.positions, this.substepStart, this.velocities, this.inverseMass, h, keep, dragKeep, gravity, wind);
154
+ this.distance.lambda.fill(0);
155
+ this.bending?.lambda.fill(0);
156
+ for (let pass = 0; pass < iterations; pass++) {
157
+ this.solve(this.distance, solveDistanceBatch, invH2);
158
+ if (this.bending !== null)
159
+ this.solve(this.bending, solveBendingBatch, invH2);
160
+ const tethers = this.tethers;
161
+ if (tethers !== null) {
162
+ solveTethers(this.positions, tethers.particles, tethers.anchors, tethers.lengths);
163
+ }
164
+ }
165
+ this.limit();
166
+ finishParticles(this.positions, this.substepStart, this.velocities, this.inverseMass, invH);
167
+ }
168
+ if (blend > 0)
169
+ this.blend(blend);
170
+ }
171
+ /** The limits and the colliders, after the constraints, so a garment pulling into the body loses. */
172
+ limit() {
173
+ const { positions, inverseMass, targets, limits } = this;
174
+ const { maxDistanceScale, margin } = this.parameters;
175
+ if (limits.maxDistance !== undefined) {
176
+ applyMaxDistance(positions, inverseMass, targets.position, limits.maxDistance, maxDistanceScale);
177
+ }
178
+ if (limits.backstop !== undefined) {
179
+ applyStops(positions, inverseMass, targets.position, targets.normal, limits.backstop, -1);
180
+ }
181
+ if (limits.frontstop !== undefined) {
182
+ applyStops(positions, inverseMass, targets.position, targets.normal, limits.frontstop, 1);
183
+ }
184
+ if (this.colliders > 0) {
185
+ applyColliders(positions, inverseMass, limits.thickness ?? null, margin, targets.colliderEnds, targets.colliderRadii, this.colliders);
186
+ }
187
+ }
188
+ /** After a reset, the share of the simulation drawn grows from nothing to all over the blend. */
189
+ blend(share) {
190
+ const target = this.targets.position;
191
+ for (let i = 0; i < this.positions.length; i++) {
192
+ const t = target[i];
193
+ this.positions[i] = t + (this.positions[i] - t) * share;
194
+ this.velocities[i] = this.velocities[i] * share;
195
+ }
196
+ }
197
+ /** Every batch of one kind, in colour order. */
198
+ solve(kind, kernel, invH2) {
199
+ const { batches, order } = kind.batches;
200
+ for (let b = 0; b + 1 < batches.length; b++) {
201
+ kernel(this.positions, this.inverseMass, kind.indices, kind.rest, kind.compliance, kind.lambda, order, batches[b], batches[b + 1], invH2);
202
+ }
203
+ }
204
+ }
205
+ /** Every kinematic particle exactly where skinning puts it at this step. */
206
+ function placeKinematic(position, inverseMass, target) {
207
+ for (let i = 0; i < inverseMass.length; i++) {
208
+ if (inverseMass[i] !== 0)
209
+ continue;
210
+ position[i * 3] = target[i * 3];
211
+ position[i * 3 + 1] = target[i * 3 + 1];
212
+ position[i * 3 + 2] = target[i * 3 + 2];
213
+ }
214
+ }