@wardic/core 1.0.0-rc.9 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/Batch.d.ts +244 -0
  2. package/dist/Batch.d.ts.map +1 -0
  3. package/dist/Batch.js +1862 -0
  4. package/dist/Batch.js.map +1 -0
  5. package/dist/DragRecognizer.d.ts +16 -1
  6. package/dist/DragRecognizer.d.ts.map +1 -1
  7. package/dist/DragRecognizer.js +87 -1
  8. package/dist/DragRecognizer.js.map +1 -1
  9. package/dist/InputSource.d.ts +21 -0
  10. package/dist/InputSource.d.ts.map +1 -1
  11. package/dist/InputSource.js.map +1 -1
  12. package/dist/Machine.d.ts.map +1 -1
  13. package/dist/Machine.js +4 -67
  14. package/dist/Machine.js.map +1 -1
  15. package/dist/Playback.d.ts.map +1 -1
  16. package/dist/Playback.js +7 -6
  17. package/dist/Playback.js.map +1 -1
  18. package/dist/Recognizer.d.ts +35 -2
  19. package/dist/Recognizer.d.ts.map +1 -1
  20. package/dist/Recognizer.js +211 -16
  21. package/dist/Recognizer.js.map +1 -1
  22. package/dist/Reorder.d.ts +7 -5
  23. package/dist/Reorder.d.ts.map +1 -1
  24. package/dist/Reorder.js +60 -23
  25. package/dist/Reorder.js.map +1 -1
  26. package/dist/Sequence.d.ts +7 -2
  27. package/dist/Sequence.d.ts.map +1 -1
  28. package/dist/Sequence.js +8 -2
  29. package/dist/Sequence.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +1 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/internal/keyframes.d.ts +40 -0
  35. package/dist/internal/keyframes.d.ts.map +1 -0
  36. package/dist/internal/keyframes.js +70 -0
  37. package/dist/internal/keyframes.js.map +1 -0
  38. package/dist/internal/playhead.d.ts +16 -0
  39. package/dist/internal/playhead.d.ts.map +1 -0
  40. package/dist/internal/playhead.js +6 -0
  41. package/dist/internal/playhead.js.map +1 -0
  42. package/dist/internal/stepper.d.ts +6 -0
  43. package/dist/internal/stepper.d.ts.map +1 -1
  44. package/dist/internal/stepper.js +16 -0
  45. package/dist/internal/stepper.js.map +1 -1
  46. package/dist/internal/watch.d.ts +6 -0
  47. package/dist/internal/watch.d.ts.map +1 -1
  48. package/dist/internal/watch.js +7 -0
  49. package/dist/internal/watch.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/Batch.ts +2128 -0
  52. package/src/DragRecognizer.ts +97 -2
  53. package/src/InputSource.ts +25 -0
  54. package/src/Machine.ts +4 -93
  55. package/src/Playback.ts +7 -13
  56. package/src/Recognizer.ts +242 -17
  57. package/src/Reorder.ts +83 -27
  58. package/src/Sequence.ts +20 -5
  59. package/src/index.ts +1 -0
  60. package/src/internal/keyframes.ts +98 -0
  61. package/src/internal/playhead.ts +19 -0
  62. package/src/internal/stepper.ts +16 -0
  63. package/src/internal/watch.ts +15 -0
package/src/Batch.ts ADDED
@@ -0,0 +1,2128 @@
1
+ /**
2
+ * A Batch: many Subjects animated on the same keys as one run on the Frame loop, for a list, a grid or
3
+ * a chart's points that move together. Each member's values, velocities and targets are kept by
4
+ * index, so a new target turns every member toward it at the speed it already has, and a change
5
+ * costs an array write per member, not an animation each. An Environment's writer draws each member
6
+ * as it moves. A change can be driven by a Playhead, as Playback controls drive an animation, toward
7
+ * targets (`animate`) or through each member's key's own stops (`keyframes`, a sequence's Segment).
8
+ *
9
+ * @example
10
+ * import * as Batch from "@wardic/core/Batch"
11
+ *
12
+ * const grid = Batch.make({ keys: ["x", "y"], writer, transition: { type: "spring", visualDuration: 0.4 } })
13
+ * const slots = [first, second, third].map((tile) => Batch.enter(grid, tile, { x: 0, y: 0 }))
14
+ * Batch.retarget(grid, slots, (slot, k) => cellOf(slot)[k])
15
+ */
16
+ // #665, ADR-0069 decisions 10–18 and *Amendment (#665)*. Tier 2 (ADR-0008): for binding and Environment
17
+ // authors; an app reaches a Batch through its binding's `createBatch`. State by index in typed arrays,
18
+ // a member's keys at `slot * stride + k` (#663's shape); stepped by `Spring.matrixFor`'s exact step
19
+ // (#370), the probe's loop (`.tmp/564-canvas/perf/group.ts` on `probe/564-canvas`).
20
+ import * as Arr from "effect/Array"
21
+ import * as Effect from "effect/Effect"
22
+ import { identity } from "effect/Function"
23
+ import * as Inspectable from "effect/Inspectable"
24
+ import * as Iter from "effect/Iterable"
25
+ import * as Match from "effect/Match"
26
+ import { type Pipeable, pipeArguments } from "effect/Pipeable"
27
+ import * as Predicate from "effect/Predicate"
28
+ import type { Invariant } from "effect/Types"
29
+ import * as UndefinedOr from "effect/UndefinedOr"
30
+ import type * as Easing from "./Easing.ts"
31
+ import type * as Frame from "./Frame.ts"
32
+ import type * as FrameLoop from "./FrameLoop.ts"
33
+ import * as Machine from "./Machine.ts"
34
+ import type * as Playback from "./Playback.ts"
35
+ import * as Scalar from "./Scalar.ts"
36
+ import * as Spring from "./Spring.ts"
37
+ import { dual } from "./internal/dual.ts"
38
+ import { tickOf, writableOf } from "./internal/playhead.ts"
39
+ import { resolveKeyframes } from "./internal/keyframes.ts"
40
+ import { checked, fn, literals, nonNegative, positive, union } from "./internal/options.ts"
41
+ import { keyframeAt, type Pass, passAt, type ResolvedRun, type ResolvedTween, stopTimesOf } from "./internal/stepper.ts"
42
+
43
+ const TypeId = "~@wardic/core/Batch"
44
+
45
+ /**
46
+ * How an Environment draws a Batch's members: whether it can draw a key, and its write for one Batch's
47
+ * keys, built once when the Batch is made. The write gets a member's Subject and its values, the
48
+ * Batch's keys in order from `base`: plain numbers, read as it's called.
49
+ */
50
+ // ADR-0069, *Amendment (#665)*: positional, so a frame builds no record per member.
51
+ export interface Writer<S> {
52
+ /** Whether it can draw `key`. */
53
+ readonly writes: (key: string) => boolean
54
+ /** Its write for a Batch with these keys, in this order. */
55
+ readonly forKeys: (keys: ReadonlyArray<string>) => (subject: S, positions: Float64Array, base: number) => void
56
+ /** Called once a frame, after every member's write: for a writer that hands what it wrote on in one go. */
57
+ readonly flush?: () => void
58
+ }
59
+
60
+ /** A transition a Batch runs a key with: a spring, or a tween. */
61
+ export type Transition =
62
+ | ({ readonly type: "spring" } & Omit<Machine.SpringOptions, "from" | "velocity">)
63
+ | ({ readonly type: "tween" } & Machine.TweenOptions)
64
+
65
+ /** One transition for every key, or one per key by its name, with `default` for the keys it doesn't name. */
66
+ export type Transitions = Transition | Readonly<Record<string, Transition>>
67
+
68
+ /** `retarget`'s options. */
69
+ export interface RetargetOptions {
70
+ /**
71
+ * How this change's keys move: a key it doesn't give, nor its `default`, moves by the Batch's own. Or
72
+ * a function of a member's slot and its key's index, for members whose keys move differently. Give the
73
+ * same object for members that move alike: they then step together.
74
+ */
75
+ // #665: the DOM's Default transition, a scale toward 0 on a spring of its own.
76
+ readonly transition?: Transitions | ((slot: number, k: number) => Transition)
77
+ /**
78
+ * Seconds each member waits before it moves, after its transition's own delay: one for all, or by
79
+ * its rank among the members this change moves, of `n`, as `Stagger.make`'s delays are.
80
+ */
81
+ // ADR-0069, *Amendment (#665)*: the movers, as Motion's `animate(elements)` counts what it's given.
82
+ readonly delay?: number | ((rank: number, n: number) => number)
83
+ /**
84
+ * Where a member's key starts from, `NaN` for where it is: it starts there, at `velocity`'s speed (0
85
+ * when it gives none), toward its target, the one it has when `targetOf` gives `NaN`. For a driver
86
+ * handing a member's keys back.
87
+ */
88
+ // #665's PR 4 (ADR-0069 decision 17): the Batch takes a key back from the member's value and speed.
89
+ readonly from?: (slot: number, k: number) => number
90
+ /** Each started key's speed, with `from`. */
91
+ readonly velocity?: (slot: number, k: number) => number
92
+ /**
93
+ * How far each member's change has run, in seconds, its delay included, or `NaN` for from its start:
94
+ * read once, at the member's first step, which draws the keys this change turns there, at the speed
95
+ * they have there (a spring's by its closed form, a tween's by its curve), and steps on from it at the
96
+ * next. A spring under its rest thresholds there lands at that next step. For an Appear animation taken
97
+ * over, read in the frame that draws it.
98
+ */
99
+ // #706, Q3 and Q8: a server-rendered member's Appear animation, taken over at its Handoff.
100
+ readonly startAt?: (slot: number) => number
101
+ }
102
+
103
+ /** `make`'s options. */
104
+ export interface Options<S> {
105
+ /** The keys its members animate, fixed when it's made. */
106
+ readonly keys: ReadonlyArray<string>
107
+ /** How its members are drawn. */
108
+ readonly writer: Writer<S>
109
+ /** How its keys move, unless a change gives its own: every key needs one, its own or `default`. */
110
+ readonly transition: Transitions
111
+ /** How many members it holds before it grows. Default 16. */
112
+ readonly capacity?: number
113
+ /** Called once a frame, after every member's write: Motion's `onUpdate`, for the whole Batch. */
114
+ // ADR-0069 decision 16: never per member.
115
+ readonly onFrame?: () => void
116
+ }
117
+
118
+ /** A Batch of Subjects `S`: built by `make`, never as a literal. */
119
+ export interface Batch<S> extends Pipeable, Inspectable.Inspectable {
120
+ readonly [TypeId]: { readonly _S: Invariant<S> }
121
+ /** The keys its members animate, in the order its writer reads them. */
122
+ readonly keys: ReadonlyArray<string>
123
+ }
124
+
125
+ // --- The table: the transitions a Batch's keys run -----------------------------
126
+ //
127
+ // ADR-0069, *Amendment (#665)*. Each member's key records its rule: the index of the transition it runs.
128
+ // An entry is held by the keys that run it, and freed for reuse once none does, so the table holds only
129
+ // what its keys run now, whatever bag each change brings. The Batch's own transitions are pinned.
130
+
131
+ /**
132
+ * An entry's kind: a spring, a tween, a spring that ends at its `duration`, a freed entry, or a driven
133
+ * change's keyframes, each of its keys through stops of its own.
134
+ */
135
+ // #359: a spring set by duration lands there. #665, Q36: keyframes, a Sequence's Segment of a Batch.
136
+ const SPRING = 0
137
+ const TWEEN = 1
138
+ const TIMED = 2
139
+ const FREE = 3
140
+ const KEYFRAMES = 4
141
+
142
+ /** Numbers in a spring entry's matrix for this frame: `dd`, `dv`, `vd`, `vv`. */
143
+ const MATRIX = 4
144
+
145
+ /** How many entries a table holds before it grows. */
146
+ const TABLE_START = 8
147
+
148
+ /** The most entries a table holds at once: a rule is a `Uint16Array`'s. */
149
+ const TABLE_MAX = 65536
150
+
151
+ /** A transition in a Batch's table, resolved once: a spring's physics, or a tween's curve. */
152
+ interface Entry {
153
+ readonly kind: typeof SPRING | typeof TWEEN | typeof TIMED | typeof KEYFRAMES
154
+ readonly delay: number
155
+ readonly spring: Spring.Resolved
156
+ readonly tween: ResolvedTween
157
+ }
158
+
159
+ // --- A slot's flags -------------------------------------------------------------
160
+
161
+ /** A member holds it, from its `enter` to its `leave`. */
162
+ const LIVE = 1
163
+ /** It moves in the plain list: every key on the Batch's own spring. */
164
+ const IN_PLAIN = 2
165
+ /** It moves in the ruled list: each key by its rule. */
166
+ const IN_RULED = 4
167
+ /** A change counted it among its movers: a slot given twice moves once. */
168
+ const COUNTED = 8
169
+ /**
170
+ * A change started it partway (`startAt`), read at its first step: the keys that change turned have
171
+ * `elapsed` `NaN` until then. It's in `startList`, which each step's start pass reads before the loops.
172
+ */
173
+ const STARTS = 16
174
+ /** The start pass drew it this step: its loop keeps it, unstepped, and clears the flag. */
175
+ const STARTED = 32
176
+
177
+ /** A Batch's state, which only this module's operations write. */
178
+ interface State<S> {
179
+ readonly keys: ReadonlyArray<string>
180
+ readonly stride: number
181
+ /** Each key's index, by its name. */
182
+ readonly indexOfKey: Readonly<Record<string, number>>
183
+ capacity: number
184
+ /** How many slots have ever been entered: every slot below is a member's. */
185
+ used: number
186
+ readonly subjects: Array<S | undefined>
187
+ positions: Float64Array
188
+ velocities: Float64Array
189
+ targets: Float64Array
190
+ elapsed: Float64Array
191
+ delays: Float64Array
192
+ restDeltas: Float64Array
193
+ restSpeeds: Float64Array
194
+ /** Where each member's key started its change: a tween's start, a driven change's to seek from. */
195
+ origins: Float64Array
196
+ /** How fast each member's key was moving when its change started: a driven change's to seek from. */
197
+ originVelocities: Float64Array
198
+ /** Each member's key's rule: its entry in the table. */
199
+ rules: Uint16Array
200
+ /** A change's new targets, `NaN` for a key it keeps: its first pass's, read by its second. */
201
+ pending: Float64Array
202
+ /** A change's members that move, in order: its first pass's. */
203
+ movers: Int32Array
204
+ /**
205
+ * Per slot, `LIVE` while a member holds it, `IN_PLAIN` or `IN_RULED` while it moves. A member a change
206
+ * gives another transition moves to the ruled list and stays until it rests; the plain list drops it
207
+ * at its next step. One byte, so each step reads one per member.
208
+ */
209
+ flags: Uint8Array
210
+ /** The slots a `leave` freed, the next `enter`'s. */
211
+ readonly free: Array<number>
212
+ /** Each `STARTS` member's `startAt`, by slot, read once at its first step. */
213
+ readonly startAts: Array<((slot: number) => number) | undefined>
214
+ /** The `STARTS` members, in the order their changes came: the next step's start pass. */
215
+ readonly startList: Array<number>
216
+ /** The members moving with every key on the Batch's own spring, `plainCount` of them: one matrix for all. */
217
+ plainList: Int32Array
218
+ plainCount: number
219
+ /** The members moving with a key on another transition, `ruledCount` of them: each key by its rule. */
220
+ // ADR-0069, *Amendment (#665)*: read per key for every member, the rules cost a step 13–16% (Bun, Node;
221
+ // 10,000 members), so the members on the Batch's own spring step as if there were none.
222
+ ruledList: Int32Array
223
+ ruledCount: number
224
+ /** The table's entries, by rule. */
225
+ readonly entries: Array<Entry>
226
+ /** Each entry's kind by its rule, read per key in place of the entry. */
227
+ kinds: Uint8Array
228
+ /** Each spring entry's matrix for this frame's `dt`, `MATRIX` numbers an entry: worked out once a frame. */
229
+ matrices: Float64Array
230
+ /** How many keys run each entry; a pinned entry isn't counted. */
231
+ uses: Uint32Array
232
+ /** Each entry's driven change, while it plays: the entry's keys step at its Playhead's speed. */
233
+ readonly drivers: Array<AnimationState<S> | undefined>
234
+ /** Each entry's step this frame: the frame's `dt`, or a driven entry's at its Playhead's speed. */
235
+ dts: Float64Array
236
+ /** The animations playing, each checked for its landing once a frame. */
237
+ readonly animations: Set<AnimationState<S>>
238
+ /** The bag each entry was given as: a transition, or a keyframes change's own. */
239
+ readonly bags: Array<object | undefined>
240
+ /** Each entry's rule, by the bag it was given as. */
241
+ readonly ruleByBag: Map<object, number>
242
+ /** The freed entries, the next transition's. */
243
+ readonly freeRules: Array<number>
244
+ /** How many entries are the Batch's own, never freed: the first. */
245
+ pinned: number
246
+ /** Each key's own rule: what it runs when a change gives it none. */
247
+ ownRules: ReadonlyArray<number>
248
+ readonly write: (subject: S, positions: Float64Array, base: number) => void
249
+ readonly flush: () => void
250
+ readonly onFrame: () => void
251
+ /** How many steps it has taken: a driven change works its tick out once in each. */
252
+ frame: number
253
+ /** The run stepping it now, by its number, or 0 for none. */
254
+ running: number
255
+ /** How many runs it has had: the next one's number. */
256
+ runs: number
257
+ }
258
+
259
+ const Proto = {
260
+ [TypeId]: { _S: identity },
261
+ ...Inspectable.BaseProto,
262
+ toJSON(this: State<unknown>) {
263
+ return {
264
+ _id: "Batch",
265
+ keys: this.keys,
266
+ members: this.used - this.free.length,
267
+ moving: this.plainCount + this.ruledCount,
268
+ transitions: this.entries.length - this.freeRules.length,
269
+ }
270
+ },
271
+ pipe() {
272
+ return pipeArguments(this, arguments)
273
+ },
274
+ }
275
+
276
+ /** Whether `u` is a Batch. */
277
+ export const isBatch = (u: unknown): u is Batch<unknown> => Predicate.hasProperty(u, TypeId)
278
+
279
+ const stateOf = <S>(batch: Batch<S>): State<S> => batch as unknown as State<S>
280
+
281
+ const noop = (): void => {}
282
+
283
+ /** No spring: a tween's entry's. */
284
+ const NO_SPRING: Spring.Resolved = Spring.resolve({})
285
+
286
+ /** No tween: a spring's entry's. */
287
+ const NO_TWEEN: ResolvedTween = Machine.resolveTween({})
288
+
289
+ /** The transitions a Batch runs: springs and tweens alone (ADR-0069, decision 11), no keyframes, inertia or decay. */
290
+ const RunType = /*#__PURE__*/ literals(["spring", "tween"])
291
+
292
+ /** A change's delay: seconds, or a function of a mover's rank and how many move. */
293
+ const Delay = /*#__PURE__*/ union([nonNegative, fn<(rank: number, n: number) => number>("a function of a mover's rank and how many move")])
294
+
295
+ /** A spring's entry: one that ends at its duration is timed (#359). */
296
+ const springEntry = (transition: Transition): Entry => {
297
+ const spring = Spring.resolve(transition as Machine.SpringOptions)
298
+ if (Spring.endsOnTime(spring)) return { kind: TIMED, delay: spring.delay, spring, tween: NO_TWEEN }
299
+ return { kind: SPRING, delay: spring.delay, spring, tween: NO_TWEEN }
300
+ }
301
+
302
+ /** A tween's entry. */
303
+ const tweenEntry = (transition: Transition): Entry => {
304
+ const tween = Machine.resolveTween(transition as Machine.TweenOptions)
305
+ return { kind: TWEEN, delay: tween.delay, spring: NO_SPRING, tween }
306
+ }
307
+
308
+ /** A checked transition's entry, by its `type`. */
309
+ const entryByType: (transition: Transition) => Entry = /*#__PURE__*/ Match.type<Transition>().pipe(
310
+ Match.discriminator("type")("tween", tweenEntry),
311
+ Match.orElse(springEntry),
312
+ )
313
+
314
+ /** `transition`, resolved for the table: its `type` checked, and its bag (`Spring.resolve`, `resolveTween`). */
315
+ const entryFor = (transition: Transition): Entry => {
316
+ checked(RunType, transition.type, "type")
317
+ return entryByType(transition)
318
+ }
319
+
320
+ /** Whether `transitions` is one transition, not one per key. */
321
+ const isTransition = (transitions: Transitions): transitions is Transition => Predicate.hasProperty(transitions, "type")
322
+
323
+ /** `transition`'s rule in `state`'s table: its entry, or a new one at its first use, in a freed entry if there is one. */
324
+ const ruleFor = <S>(state: State<S>, transition: Transition): number => {
325
+ const known = state.ruleByBag.get(transition)
326
+ if (Predicate.isNotUndefined(known)) return known
327
+ return entryRuleOf(state, transition, entryFor(transition))
328
+ }
329
+
330
+ /** A new entry for `bag` in `state`'s table: its rule, a freed one if there is one. */
331
+ const entryRuleOf = <S>(state: State<S>, bag: object, entry: Entry): number => {
332
+ const freed = state.freeRules.pop()
333
+ let rule = state.entries.length
334
+ if (Predicate.isNotUndefined(freed)) rule = freed
335
+ if (rule === TABLE_MAX) {
336
+ throw new Machine.OptionError({ message: `Expected at most ${TABLE_MAX} transitions running at once\n at ["transition"]` })
337
+ }
338
+ if (rule === state.kinds.length) {
339
+ state.kinds = grown(state.kinds, rule * 2)
340
+ state.matrices = grown(state.matrices, rule * 2 * MATRIX)
341
+ state.uses = grown(state.uses, rule * 2)
342
+ state.dts = grown(state.dts, rule * 2)
343
+ }
344
+ state.entries[rule] = entry
345
+ state.drivers[rule] = undefined
346
+ state.bags[rule] = bag
347
+ state.kinds[rule] = entry.kind
348
+ state.uses[rule] = 0
349
+ state.ruleByBag.set(bag, rule)
350
+ return rule
351
+ }
352
+
353
+ /** One more key runs `rule`. */
354
+ const hold = <S>(state: State<S>, rule: number): void => {
355
+ if (rule < state.pinned) return
356
+ state.uses[rule] = state.uses[rule] + 1
357
+ }
358
+
359
+ /** One key fewer runs `rule`: once none does, its entry is freed. */
360
+ const release = <S>(state: State<S>, rule: number): void => {
361
+ if (rule < state.pinned) return
362
+ if (state.kinds[rule] === FREE) return
363
+ if (state.uses[rule] > 0) state.uses[rule] = state.uses[rule] - 1
364
+ if (state.uses[rule] > 0) return
365
+ const bag = state.bags[rule]
366
+ // Forgotten at a rest already (`forgetTransitions`).
367
+ if (Predicate.isUndefined(bag)) return
368
+ state.kinds[rule] = FREE
369
+ state.ruleByBag.delete(bag)
370
+ state.bags[rule] = undefined
371
+ state.freeRules.push(rule)
372
+ }
373
+
374
+ /** `transitions`' bag for each of `state`'s keys, by index: its own, or its `default`; `undefined` where it gives neither. */
375
+ // Once a change, per key.
376
+ const bagsOf = <S>(state: State<S>, transitions: Transitions): ReadonlyArray<Transition | undefined> => {
377
+ if (isTransition(transitions)) return Arr.map(state.keys, () => transitions)
378
+ return Arr.map(state.keys, (key) => {
379
+ const given = transitions[key]
380
+ if (Predicate.isNotUndefined(given)) return given
381
+ return transitions["default"]
382
+ })
383
+ }
384
+
385
+ /** `transitions`' rule for each of `state`'s keys, by index; a key it doesn't name, nor its `default`, takes `fallback`'s. */
386
+ const rulesOf = <S>(state: State<S>, transitions: Transitions, fallback: (k: number) => number): ReadonlyArray<number> =>
387
+ Arr.map(bagsOf(state, transitions), (bag, k) => {
388
+ if (Predicate.isUndefined(bag)) return fallback(k)
389
+ return ruleFor(state, bag)
390
+ })
391
+
392
+ /** A key `make`'s transitions leave without one: every key needs its own or the `default`. */
393
+ const unnamedKey = <S>(state: State<S>) => (k: number): number => {
394
+ throw new Machine.OptionError({ message: `Expected a transition for each key, or a "default"\n at ["transition"]["${state.keys[k]}"]` })
395
+ }
396
+
397
+ /**
398
+ * A Batch of no members yet, on `options.keys`, drawn by `options.writer`.
399
+ *
400
+ * @example
401
+ * const grid = Batch.make({ keys: ["x", "y"], writer, transition: { type: "spring" } })
402
+ */
403
+ export const make = <S>(options: Options<S>): Batch<S> => {
404
+ Arr.forEach(options.keys, (key, k) => {
405
+ if (options.writer.writes(key)) return
406
+ throw new Machine.OptionError({ message: `Expected a key its writer draws, got ${JSON.stringify(key)}\n at ["keys"][${k}]` })
407
+ })
408
+ const capacity = Math.ceil(checked(positive, UndefinedOr.match(options.capacity, { onUndefined: () => 16, onDefined: identity }), "capacity"))
409
+ const stride = options.keys.length
410
+ const size = capacity * stride
411
+ const state: State<S> = {
412
+ keys: options.keys,
413
+ stride,
414
+ indexOfKey: Arr.reduce(options.keys, {}, (indices: Record<string, number>, key, k) => {
415
+ indices[key] = k
416
+ return indices
417
+ }),
418
+ capacity,
419
+ used: 0,
420
+ subjects: [],
421
+ positions: new Float64Array(size),
422
+ velocities: new Float64Array(size),
423
+ targets: new Float64Array(size),
424
+ elapsed: new Float64Array(size),
425
+ delays: new Float64Array(size),
426
+ restDeltas: new Float64Array(size),
427
+ restSpeeds: new Float64Array(size),
428
+ origins: new Float64Array(size),
429
+ originVelocities: new Float64Array(size),
430
+ rules: new Uint16Array(size),
431
+ pending: new Float64Array(size),
432
+ movers: new Int32Array(capacity),
433
+ flags: new Uint8Array(capacity),
434
+ free: [],
435
+ startAts: [],
436
+ startList: [],
437
+ plainList: new Int32Array(capacity),
438
+ plainCount: 0,
439
+ ruledList: new Int32Array(capacity),
440
+ ruledCount: 0,
441
+ entries: [],
442
+ kinds: new Uint8Array(TABLE_START),
443
+ matrices: new Float64Array(TABLE_START * MATRIX),
444
+ uses: new Uint32Array(TABLE_START),
445
+ drivers: [],
446
+ dts: new Float64Array(TABLE_START),
447
+ animations: new Set(),
448
+ bags: [],
449
+ ruleByBag: new Map(),
450
+ freeRules: [],
451
+ pinned: 0,
452
+ ownRules: [],
453
+ write: options.writer.forKeys(options.keys),
454
+ flush: UndefinedOr.match(options.writer.flush, { onUndefined: () => noop, onDefined: identity }),
455
+ onFrame: UndefinedOr.match(options.onFrame, { onUndefined: () => noop, onDefined: identity }),
456
+ frame: 0,
457
+ running: 0,
458
+ runs: 0,
459
+ }
460
+ // The Batch's own transitions, pinned: the first entries, rule 0 the first key's.
461
+ state.ownRules = rulesOf(state, options.transition, unnamedKey(state))
462
+ state.pinned = state.entries.length
463
+ return Object.assign(Object.create(Proto), state)
464
+ }
465
+
466
+ /** A change's rule for each key, when its transitions are one or one per key; the Batch's own else. */
467
+ // Once a change.
468
+ const changeRulesOf = <S>(state: State<S>, transitions: RetargetOptions["transition"]): ReadonlyArray<number> => {
469
+ if (Predicate.isUndefined(transitions)) return state.ownRules
470
+ if (Predicate.isFunction(transitions)) return state.ownRules
471
+ return rulesOf(state, transitions, (k) => state.ownRules[k])
472
+ }
473
+
474
+ /**
475
+ * A change's rule for a member's key, when its transition is a function of them: the bag it gives,
476
+ * the last one's rule again when it's the same, while the table still holds it.
477
+ */
478
+ // Most members give the bag the last one gave: one comparison, where `ruleFor` is a Map lookup per
479
+ // member's key (#665's Chromium profile, 1,000 members).
480
+ const ruleAtOf = <S>(state: State<S>, given: RetargetOptions["transition"]): ((slot: number, k: number) => number) | undefined => {
481
+ if (!Predicate.isFunction(given)) return undefined
482
+ let lastBag: Transition | undefined = undefined
483
+ let lastRule = 0
484
+ return (slot, k) => {
485
+ const bag = given(slot, k)
486
+ if (bag === lastBag && state.bags[lastRule] === bag) return lastRule
487
+ lastBag = bag
488
+ lastRule = ruleFor(state, bag)
489
+ return lastRule
490
+ }
491
+ }
492
+
493
+ /** No delay: a change's that gives none. */
494
+ const NO_DELAY = (): number => 0
495
+
496
+ /** A change's delay as a function of a mover's rank and how many move: once a change. */
497
+ const delayOfChange: (delay: RetargetOptions["delay"]) => (rank: number, n: number) => number = /*#__PURE__*/ Match.type<
498
+ RetargetOptions["delay"]
499
+ >().pipe(
500
+ Match.when(Predicate.isUndefined, () => NO_DELAY),
501
+ Match.when(Predicate.isNumber, (seconds) => (): number => seconds),
502
+ Match.orElse((delayOf: (rank: number, n: number) => number) => delayOf),
503
+ )
504
+
505
+ /**
506
+ * A new member, `subject`, starting from `start`'s values (a key it doesn't give starts at 0): its
507
+ * slot, which every other operation takes.
508
+ *
509
+ * @example
510
+ * const slot = Batch.enter(grid, tile, { x: 0, y: 0 })
511
+ */
512
+ export const enter: {
513
+ <S>(subject: S, start: Readonly<Record<string, number>>): (self: Batch<S>) => number
514
+ <S>(self: Batch<S>, subject: S, start: Readonly<Record<string, number>>): number
515
+ } = dual(3, <S>(self: Batch<S>, subject: S, start: Readonly<Record<string, number>>): number => {
516
+ const state = stateOf(self)
517
+ const slot = slotFor(state)
518
+ state.subjects[slot] = subject
519
+ // A start a member that left never took isn't this one's.
520
+ state.flags[slot] = (state.flags[slot] & ~(STARTS | STARTED)) | LIVE
521
+ const base = slot * state.stride
522
+ Arr.forEach(state.keys, (key, k) => {
523
+ const given = start[key]
524
+ let value = 0
525
+ if (Predicate.isNotUndefined(given)) value = given
526
+ const at = base + k
527
+ state.positions[at] = value
528
+ state.targets[at] = value
529
+ // Its origin too: a tween steps every key of a member it moves, and one no change has turned lerps
530
+ // from its origin to its target, both its start (#712).
531
+ state.origins[at] = value
532
+ state.velocities[at] = 0
533
+ // A reused slot keeps nothing of the member before: at rest on its start, on its own transition.
534
+ state.elapsed[at] = 0
535
+ state.delays[at] = 0
536
+ release(state, state.rules[at])
537
+ state.rules[at] = state.ownRules[k]
538
+ })
539
+ return slot
540
+ })
541
+
542
+ /**
543
+ * The member at `slot` leaves: it isn't written again, and its slot goes to the next to enter.
544
+ *
545
+ * @example
546
+ * Batch.leave(grid, slot)
547
+ */
548
+ // Its slot stays in its moving list until the next step drops it: no search per leave.
549
+ export const leave: {
550
+ (slot: number): <S>(self: Batch<S>) => void
551
+ <S>(self: Batch<S>, slot: number): void
552
+ } = dual(2, <S>(self: Batch<S>, slot: number): void => {
553
+ const state = stateOf(self)
554
+ if ((state.flags[slot] & LIVE) === 0) return
555
+ state.flags[slot] = state.flags[slot] & ~LIVE
556
+ state.subjects[slot] = undefined
557
+ state.free.push(slot)
558
+ })
559
+
560
+ /**
561
+ * The member at `slot` is drawn on `subject` from now on: its values, speed, targets and delays carry
562
+ * on as they were. For an element its framework made again for the same member.
563
+ *
564
+ * @example
565
+ * Batch.replace(grid, slot, element)
566
+ */
567
+ export const replace: {
568
+ <S>(slot: number, subject: S): (self: Batch<S>) => void
569
+ <S>(self: Batch<S>, slot: number, subject: S): void
570
+ } = dual(3, <S>(self: Batch<S>, slot: number, subject: S): void => {
571
+ const state = stateOf(self)
572
+ if ((state.flags[slot] & LIVE) === 0) return
573
+ state.subjects[slot] = subject
574
+ })
575
+
576
+ /** A slot for a new member: one a `leave` freed, else the next, the arrays doubled when they're full. */
577
+ const slotFor = <S>(state: State<S>): number => {
578
+ const freed = state.free.pop()
579
+ if (Predicate.isNotUndefined(freed)) return freed
580
+ const slot = state.used
581
+ if (slot === state.capacity) grow(state, state.capacity * 2)
582
+ state.used = slot + 1
583
+ return slot
584
+ }
585
+
586
+ /** `from` copied into a new array of `size`: a grown Batch's. */
587
+ const grown = <A extends Float64Array | Int32Array | Uint8Array | Uint16Array | Uint32Array>(from: A, size: number): A => {
588
+ const to = new (from.constructor as new (size: number) => A)(size)
589
+ to.set(from)
590
+ return to
591
+ }
592
+
593
+ /** `state`'s arrays grown to hold `capacity` members, every member's state copied across. */
594
+ const grow = <S>(state: State<S>, capacity: number): void => {
595
+ const size = capacity * state.stride
596
+ state.capacity = capacity
597
+ state.positions = grown(state.positions, size)
598
+ state.velocities = grown(state.velocities, size)
599
+ state.targets = grown(state.targets, size)
600
+ state.elapsed = grown(state.elapsed, size)
601
+ state.delays = grown(state.delays, size)
602
+ state.restDeltas = grown(state.restDeltas, size)
603
+ state.restSpeeds = grown(state.restSpeeds, size)
604
+ state.origins = grown(state.origins, size)
605
+ state.originVelocities = grown(state.originVelocities, size)
606
+ state.rules = grown(state.rules, size)
607
+ state.pending = grown(state.pending, size)
608
+ state.movers = grown(state.movers, capacity)
609
+ state.flags = grown(state.flags, capacity)
610
+ state.plainList = grown(state.plainList, capacity)
611
+ state.ruledList = grown(state.ruledList, capacity)
612
+ }
613
+
614
+ /**
615
+ * The key at `at` turned on `rule` toward `goal`, from `start` at `speed`, waiting `wait` past its
616
+ * transition's own delay: its rule held, and its start, its speed then and its rest thresholds kept.
617
+ * A driven change's, at its play; `retarget` keeps the same writes inline, less the speed.
618
+ */
619
+ // Per key a driven change plays: plain writes.
620
+ const turn = <S>(state: State<S>, at: number, rule: number, goal: number, start: number, speed: number, wait: number): void => {
621
+ const entry = state.entries[rule]
622
+ const before = state.rules[at]
623
+ if (before !== rule) {
624
+ hold(state, rule)
625
+ release(state, before)
626
+ state.rules[at] = rule
627
+ }
628
+ state.targets[at] = goal
629
+ state.origins[at] = start
630
+ state.originVelocities[at] = speed
631
+ state.delays[at] = entry.delay + wait
632
+ const distance = goal - start
633
+ state.restDeltas[at] = Spring.restDeltaFor(entry.spring, distance)
634
+ state.restSpeeds[at] = Spring.restSpeedFor(entry.spring, distance)
635
+ // A spring that ends at its duration starts from rest, as Motion's (#359).
636
+ if (entry.kind !== TIMED) return
637
+ state.velocities[at] = 0
638
+ state.originVelocities[at] = 0
639
+ }
640
+
641
+ /**
642
+ * One change: each of `slots`' members turned toward `targetOf(slot, k)` for its `k`th key (`NaN`
643
+ * keeps that key's target). A member whose targets are unchanged gets nothing. It returns how many
644
+ * members it sets off from rest.
645
+ *
646
+ * @example
647
+ * const grid = Batch.make({ keys: ["x", "y"], writer, transition: { type: "spring" } })
648
+ * Batch.retarget(grid, slots, (slot, k) => cellOf(slot)[k], { delay: Stagger.make(0.02) })
649
+ */
650
+ export const retarget: {
651
+ (slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options?: RetargetOptions): <S>(self: Batch<S>) => number
652
+ <S>(self: Batch<S>, slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options?: RetargetOptions): number
653
+ } = dual(isBatch, <S>(self: Batch<S>, slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options?: RetargetOptions): number => {
654
+ const state = stateOf(self)
655
+ const { stride, pending, movers, targets, flags } = state
656
+ // Per member per key at a change, a Batch's own loops over its typed arrays, as its step's (ADR-0025,
657
+ // *Amendment (#665)*): `Arr.forEach` over the slots cost a closure call each. The first pass keeps
658
+ // each new target and finds the members that move, so the second can count them for their delays.
659
+ let n = 0
660
+ const given = slots.length
661
+ const fromOf = UndefinedOr.map(options, (bag) => bag.from)
662
+ const starts = Predicate.isNotUndefined(fromOf)
663
+ const speedOf = UndefinedOr.map(options, (bag) => bag.velocity)
664
+ for (let g = 0; g < given; g++) {
665
+ const slot = slots[g]
666
+ const flag = flags[slot]
667
+ // A member that left takes no change; one given twice moves once.
668
+ if ((flag & LIVE) === 0) continue
669
+ if ((flag & COUNTED) !== 0) continue
670
+ const base = slot * stride
671
+ let moves = false
672
+ for (let k = 0; k < stride; k++) {
673
+ const at = base + k
674
+ let target = targetOf(slot, k)
675
+ // A key started from a value given (#665's PR 4): there now, at its speed, toward its target, the
676
+ // one it has unless a new one's given. A member it's given for moves, so it's set off below: its
677
+ // target is cleared here, so it turns there even onto the one it had.
678
+ if (starts) {
679
+ const jump = (fromOf as (slot: number, k: number) => number)(slot, k)
680
+ if (!Number.isNaN(jump)) {
681
+ if (Number.isNaN(target)) target = targets[at]
682
+ state.positions[at] = jump
683
+ state.velocities[at] = 0
684
+ if (Predicate.isNotUndefined(speedOf)) state.velocities[at] = speedOf(slot, k)
685
+ targets[at] = Number.NaN
686
+ }
687
+ }
688
+ pending[at] = target
689
+ if (!Number.isNaN(target) && target !== targets[at]) moves = true
690
+ }
691
+ if (!moves) continue
692
+ flags[slot] = flag | COUNTED
693
+ movers[n] = slot
694
+ n++
695
+ }
696
+ // A change that moves nothing touches no transition.
697
+ if (n === 0) return 0
698
+ const transitions = UndefinedOr.map(options, (bag) => bag.transition)
699
+ const rules = changeRulesOf(state, transitions)
700
+ const ruleAt = ruleAtOf(state, transitions)
701
+ const delay = UndefinedOr.map(options, (bag) => bag.delay)
702
+ if (Predicate.isNotUndefined(delay)) checked(Delay, delay, "delay")
703
+ const delayOf = delayOfChange(delay)
704
+ // This change's transitions are held while it runs, so a key it moves off one doesn't free one it
705
+ // gives another key; one it gives no key is freed after.
706
+ const held = Arr.dedupe(rules)
707
+ Arr.forEach(held, (rule) => hold(state, rule))
708
+ const driven = state.animations.size > 0
709
+ // Started partway (#706): each key it turns waits, `elapsed` `NaN`, for its member's first step to read where.
710
+ const startAt = UndefinedOr.map(options, (bag) => bag.startAt)
711
+ let fresh = 0
712
+ if (Predicate.isNotUndefined(startAt)) fresh = Number.NaN
713
+ let setOff = 0
714
+ for (let rank = 0; rank < n; rank++) {
715
+ const slot = movers[rank]
716
+ const base = slot * stride
717
+ const wait = delayOf(rank, n)
718
+ // Whether a key it turns runs anything but the Batch's own spring.
719
+ let ruled = false
720
+ for (let k = 0; k < stride; k++) {
721
+ const at = base + k
722
+ const target = pending[at]
723
+ if (Number.isNaN(target)) continue
724
+ if (target === targets[at]) continue
725
+ let rule = rules[k]
726
+ if (Predicate.isNotUndefined(ruleAt)) rule = ruleAt(slot, k)
727
+ const entry = state.entries[rule]
728
+ if (rule !== 0 || entry.kind !== SPRING) ruled = true
729
+ // Taken from a driven change its Playhead holds, it starts from rest (#464).
730
+ if (driven && heldAt(state, at)) state.velocities[at] = 0
731
+ // `turn`'s body, inline, less its start's speed, which a driven change sets at its play and a start
732
+ // partway at its first step.
733
+ const before = state.rules[at]
734
+ if (before !== rule) {
735
+ hold(state, rule)
736
+ release(state, before)
737
+ state.rules[at] = rule
738
+ }
739
+ targets[at] = target
740
+ state.origins[at] = state.positions[at]
741
+ state.elapsed[at] = fresh
742
+ state.delays[at] = entry.delay + wait
743
+ const distance = target - state.positions[at]
744
+ state.restDeltas[at] = Spring.restDeltaFor(entry.spring, distance)
745
+ state.restSpeeds[at] = Spring.restSpeedFor(entry.spring, distance)
746
+ // A spring that ends at its duration starts from rest, as Motion's (#359).
747
+ if (entry.kind === TIMED) state.velocities[at] = 0
748
+ }
749
+ let flag = flags[slot] & ~COUNTED
750
+ if (Predicate.isNotUndefined(startAt)) {
751
+ if ((flag & STARTS) === 0) state.startList.push(slot)
752
+ flag = flag | STARTS
753
+ state.startAts[slot] = startAt
754
+ }
755
+ flags[slot] = flag
756
+ if ((flag & (IN_PLAIN | IN_RULED)) === 0) setOff++
757
+ // Into the ruled list, out of the plain one (which drops it at its next step); else into the plain
758
+ // list, if it's in neither.
759
+ if (ruled && (flag & IN_RULED) === 0) {
760
+ flags[slot] = (flag & ~IN_PLAIN) | IN_RULED
761
+ state.ruledList[state.ruledCount] = slot
762
+ state.ruledCount = state.ruledCount + 1
763
+ }
764
+ if (!ruled && (flag & (IN_PLAIN | IN_RULED)) === 0) {
765
+ flags[slot] = flag | IN_PLAIN
766
+ state.plainList[state.plainCount] = slot
767
+ state.plainCount = state.plainCount + 1
768
+ }
769
+ }
770
+ Arr.forEach(held, (rule) => release(state, rule))
771
+ return setOff
772
+ })
773
+
774
+ /** Whether any member moves: one `step` would move. */
775
+ export const isMoving = <S>(self: Batch<S>): boolean => {
776
+ const state = stateOf(self)
777
+ return state.plainCount + state.ruledCount > 0
778
+ }
779
+
780
+ /**
781
+ * Steps every moving member by `dt` seconds and writes each one: whether nothing moves now. The run
782
+ * on the Frame loop calls it each tick.
783
+ */
784
+ // Per frame (ADR-0025, ADR-0030 decisions 10 and 11): `dt` clamped once (#78), then the two moving
785
+ // lists. Each steps a key by `springValues`' exact step, or `Machine.tween`'s, its spring's matrix
786
+ // worked out once a frame: called per key, `matrixFor` cost the step 2.5× (#665).
787
+ export const step = <S>(self: Batch<S>, dt: number): boolean => {
788
+ const state = stateOf(self)
789
+ const clamped = Math.min(dt, Machine.MAX_DT)
790
+ state.frame = state.frame + 1
791
+ if (state.startList.length > 0) startPass(state, clamped)
792
+ if (state.plainCount > 0) stepPlain(state, clamped)
793
+ if (state.ruledCount > 0) stepRuled(state, clamped)
794
+ if (state.animations.size > 0) Iter.forEach(state.animations, checkLanding)
795
+ state.flush()
796
+ state.onFrame()
797
+ // Counted after `onFrame`: a change it makes keeps the run going.
798
+ if (state.plainCount + state.ruledCount > 0) return false
799
+ // A driven change playing, paused at rest, still holds its entries.
800
+ if (state.entries.length > state.pinned && state.animations.size === 0) forgetTransitions(state)
801
+ return true
802
+ }
803
+
804
+ /**
805
+ * Writes every member where it is now, with no step, then flushes the writer: a change that started its
806
+ * members from their targets (`retarget`'s `from`), drawn now, before the page paints, where the run would
807
+ * draw it at its next tick.
808
+ */
809
+ // #712: a Batch Reorder group's first read of its element places its items at once. Once a change, over
810
+ // every slot (ADR-0025, *Amendment (#665)*): a counted loop.
811
+ export const draw = <S>(self: Batch<S>): void => {
812
+ const state = stateOf(self)
813
+ const { flags, subjects, positions, stride, write } = state
814
+ for (let slot = 0; slot < state.used; slot++) {
815
+ if ((flags[slot] & LIVE) === 0) continue
816
+ write(subjects[slot] as S, positions, slot * stride)
817
+ }
818
+ state.flush()
819
+ }
820
+
821
+ /**
822
+ * At rest, every transition but the Batch's own is forgotten: no member moves, so no rule is read
823
+ * until a change sets it again.
824
+ */
825
+ // Once a rest, over every member's key (#665).
826
+ const forgetTransitions = <S>(state: State<S>): void => {
827
+ const { pinned, stride } = state
828
+ state.entries.length = pinned
829
+ state.bags.length = pinned
830
+ state.drivers.length = pinned
831
+ state.freeRules.length = 0
832
+ state.uses.fill(0)
833
+ state.ruleByBag.clear()
834
+ Arr.forEach(state.bags, (bag, rule) => state.ruleByBag.set(UndefinedOr.getOrThrow(bag), rule))
835
+ // Rest is not the per-frame path: a counted loop over every member's keys, once.
836
+ for (let at = 0; at < state.used * stride; at++) state.rules[at] = state.ownRules[at % stride]
837
+ }
838
+
839
+ /** The members in the plain list, every key on the Batch's own spring, by one matrix. */
840
+ // Per frame. The ruled list's loop below, less its read of each key's rule and kind (#665).
841
+ const stepPlain = <S>(state: State<S>, clamped: number): void => {
842
+ const { stride, positions, velocities, targets, elapsed, delays, restDeltas, restSpeeds, plainList, flags, subjects, write } = state
843
+ const spring = state.entries[0].spring
844
+ const m = Spring.matrixFor(spring, clamped)
845
+ const dd = m.dd
846
+ const dv = m.dv
847
+ const vd = m.vd
848
+ const vv = m.vv
849
+ const count = state.plainCount
850
+ let kept = 0
851
+ for (let a = 0; a < count; a++) {
852
+ const slot = plainList[a]
853
+ const flag = flags[slot]
854
+ // A member a change gave another transition is the ruled list's now; one that left is dropped here,
855
+ // unwritten. One the start pass drew this step is kept, unstepped (#706).
856
+ if (flag !== (LIVE | IN_PLAIN)) {
857
+ if (flag === (LIVE | IN_PLAIN | STARTED)) {
858
+ flags[slot] = LIVE | IN_PLAIN
859
+ plainList[kept] = slot
860
+ kept++
861
+ continue
862
+ }
863
+ if ((flag & IN_PLAIN) !== 0) flags[slot] = flag & ~IN_PLAIN
864
+ continue
865
+ }
866
+ const base = slot * stride
867
+ let still = true
868
+ for (let k = 0; k < stride; k++) {
869
+ const at = base + k
870
+ const goal = targets[at]
871
+ const time = elapsed[at] + clamped
872
+ let position = positions[at]
873
+ let speed = velocities[at]
874
+ // Only the part of this tick past the delay moves it: all of it, or, the frame its delay ends, a part.
875
+ const simDt = Math.max(0, Math.min(clamped, time - delays[at]))
876
+ if (simDt === clamped) {
877
+ const d = position - goal
878
+ position = goal + dd * d + dv * speed
879
+ speed = vd * d + vv * speed
880
+ }
881
+ if (simDt > 0 && simDt < clamped) {
882
+ const part = Spring.matrixFor(spring, simDt)
883
+ const d = position - goal
884
+ position = goal + part.dd * d + part.dv * speed
885
+ speed = part.vd * d + part.vv * speed
886
+ }
887
+ const settled = simDt > 0 && Math.abs(speed) <= restSpeeds[at] && Math.abs(position - goal) <= restDeltas[at]
888
+ if (settled) {
889
+ position = goal
890
+ speed = 0
891
+ }
892
+ if (!settled) still = false
893
+ positions[at] = position
894
+ velocities[at] = speed
895
+ elapsed[at] = time
896
+ }
897
+ write(subjects[slot] as S, positions, base)
898
+ // At rest: still its member's, in neither list.
899
+ if (still) {
900
+ flags[slot] = LIVE
901
+ continue
902
+ }
903
+ plainList[kept] = slot
904
+ kept++
905
+ }
906
+ state.plainCount = kept
907
+ }
908
+
909
+ /** A tween's step for the key at `at`, written in place: whether it has landed. */
910
+ // Per frame: `Machine.tween`'s value, eased from the key's start, its speed from its last frame.
911
+ const stepTween = <S>(state: State<S>, at: number, tween: ResolvedTween, time: number, dt: number): boolean => {
912
+ const delay = state.delays[at]
913
+ // By its duration as given: a 0 s tween lands as its delay ends, at that very time (#706), where its
914
+ // resolved duration, at least `Number.EPSILON` so it divides, would hold it a step longer.
915
+ const landed = time >= delay + tween.seconds
916
+ // Landed, at its target.
917
+ let next = state.targets[at]
918
+ if (!landed) next = Scalar.lerp(state.origins[at], state.targets[at], tween.ease(Scalar.clamp(Math.max(0, time - delay) / tween.duration, 0, 1)))
919
+ if (landed) state.velocities[at] = 0
920
+ if (!landed && dt > 0) state.velocities[at] = (next - state.positions[at]) / dt
921
+ state.positions[at] = next
922
+ return landed
923
+ }
924
+
925
+ /** The members in the ruled list, each key by the transition its rule names: a spring's matrix, or a tween. */
926
+ // Per frame. Each spring entry's matrix for this `dt`, once, then plain reads by rule (#665).
927
+ const stepRuled = <S>(state: State<S>, clamped: number): void => {
928
+ const { stride, entries, kinds, matrices, dts, drivers, rules, positions, velocities, targets, elapsed, delays, restDeltas, restSpeeds, ruledList, flags, subjects, write } = state
929
+ // Each entry's step: the frame's, or a driven change's at its Playhead's speed, which moves its time;
930
+ // then each spring's matrix for it, once.
931
+ let driven = false
932
+ for (let e = 0; e < entries.length; e++) {
933
+ const kind = kinds[e]
934
+ if (kind === FREE) continue
935
+ let dt = clamped
936
+ const driver = drivers[e]
937
+ if (Predicate.isNotUndefined(driver)) {
938
+ driven = true
939
+ dt = drivenStep(driver, clamped, state.frame)
940
+ }
941
+ dts[e] = dt
942
+ // A step of 0 s too, the identity: the loop below moves a spring by its matrix whenever all its step
943
+ // is past the delay, which 0 s is, and the matrix a 0 s step skipped was the last frame's, or zeros,
944
+ // landing every spring on its target (a Clock's tick can be 0 s; #706).
945
+ if (kind === TWEEN || dt < 0) continue
946
+ const m = Spring.matrixFor(entries[e].spring, dt)
947
+ matrices[e * MATRIX] = m.dd
948
+ matrices[e * MATRIX + 1] = m.dv
949
+ matrices[e * MATRIX + 2] = m.vd
950
+ matrices[e * MATRIX + 3] = m.vv
951
+ }
952
+ // While a driven change plays, each key steps by its entry's own step, out of line: read per key, it
953
+ // cost every ruled member's step 5% (Bun and Chromium, 10,000 members; #665).
954
+ if (driven) {
955
+ stepRuledDriven(state)
956
+ return
957
+ }
958
+ const count = state.ruledCount
959
+ let kept = 0
960
+ for (let a = 0; a < count; a++) {
961
+ const slot = ruledList[a]
962
+ const flag = flags[slot]
963
+ // A member that left is dropped here, unwritten; one the start pass drew this step is kept, unstepped (#706).
964
+ if (flag !== (LIVE | IN_RULED)) {
965
+ if ((flag & LIVE) === 0) {
966
+ flags[slot] = flag & ~IN_RULED
967
+ continue
968
+ }
969
+ if ((flag & STARTED) !== 0) {
970
+ flags[slot] = flag & ~STARTED
971
+ ruledList[kept] = slot
972
+ kept++
973
+ continue
974
+ }
975
+ }
976
+ const base = slot * stride
977
+ let still = true
978
+ for (let k = 0; k < stride; k++) {
979
+ const at = base + k
980
+ const rule = rules[at]
981
+ const kind = kinds[rule]
982
+ const time = elapsed[at] + clamped
983
+ elapsed[at] = time
984
+ // A tween, out of line.
985
+ if (kind === TWEEN) {
986
+ if (!stepTween(state, at, entries[rule].tween, time, clamped)) still = false
987
+ continue
988
+ }
989
+ // A spring, as `springValues`': only the part of this tick past the delay moves it.
990
+ const goal = targets[at]
991
+ const delay = delays[at]
992
+ let position = positions[at]
993
+ let speed = velocities[at]
994
+ const simDt = Math.max(0, Math.min(clamped, time - delay))
995
+ if (simDt === clamped) {
996
+ const mi = rule * MATRIX
997
+ const d = position - goal
998
+ position = goal + matrices[mi] * d + matrices[mi + 1] * speed
999
+ speed = matrices[mi + 2] * d + matrices[mi + 3] * speed
1000
+ }
1001
+ if (simDt > 0 && simDt < clamped) {
1002
+ const part = Spring.matrixFor(entries[rule].spring, simDt)
1003
+ const d = position - goal
1004
+ position = goal + part.dd * d + part.dv * speed
1005
+ speed = part.vd * d + part.vv * speed
1006
+ }
1007
+ // A spring rests by its thresholds; one that ends at its duration, there (#359).
1008
+ let settled = simDt > 0 && Math.abs(speed) <= restSpeeds[at] && Math.abs(position - goal) <= restDeltas[at]
1009
+ if (kind === TIMED) settled = time - delay >= entries[rule].spring.duration
1010
+ if (settled) {
1011
+ position = goal
1012
+ speed = 0
1013
+ }
1014
+ if (!settled) still = false
1015
+ positions[at] = position
1016
+ velocities[at] = speed
1017
+ }
1018
+ write(subjects[slot] as S, positions, base)
1019
+ // At rest: still its member's, in neither list (a member is in one at most).
1020
+ if (still) {
1021
+ flags[slot] = LIVE
1022
+ continue
1023
+ }
1024
+ ruledList[kept] = slot
1025
+ kept++
1026
+ }
1027
+ state.ruledCount = kept
1028
+ }
1029
+
1030
+ /** The members in the ruled list while a driven change plays: each key by its entry's step this frame, forwards or back. */
1031
+ // Per frame, while a driven change plays: `stepRuled`'s loop, by each entry's `dt`.
1032
+ const stepRuledDriven = <S>(state: State<S>): void => {
1033
+ const { stride, entries, kinds, matrices, dts, rules, positions, velocities, targets, elapsed, delays, restDeltas, restSpeeds, ruledList, flags, subjects, write } = state
1034
+ const count = state.ruledCount
1035
+ let kept = 0
1036
+ for (let a = 0; a < count; a++) {
1037
+ const slot = ruledList[a]
1038
+ const flag = flags[slot]
1039
+ // A member that left is dropped here, unwritten; one the start pass drew this step is kept, unstepped (#706).
1040
+ if (flag !== (LIVE | IN_RULED)) {
1041
+ if ((flag & LIVE) === 0) {
1042
+ flags[slot] = flag & ~IN_RULED
1043
+ continue
1044
+ }
1045
+ if ((flag & STARTED) !== 0) {
1046
+ flags[slot] = flag & ~STARTED
1047
+ ruledList[kept] = slot
1048
+ kept++
1049
+ continue
1050
+ }
1051
+ }
1052
+ const base = slot * stride
1053
+ let still = true
1054
+ for (let k = 0; k < stride; k++) {
1055
+ const at = base + k
1056
+ const rule = rules[at]
1057
+ const kind = kinds[rule]
1058
+ const dt = dts[rule]
1059
+ // Played backwards: its value worked out again where its Playhead has gone back to, out of line.
1060
+ if (dt < 0) {
1061
+ if (!stepBack(state, at, rule, dt)) still = false
1062
+ continue
1063
+ }
1064
+ const time = elapsed[at] + dt
1065
+ elapsed[at] = time
1066
+ // A tween, out of line.
1067
+ if (kind === TWEEN) {
1068
+ if (!stepTween(state, at, entries[rule].tween, time, dt)) still = false
1069
+ continue
1070
+ }
1071
+ // Keyframes, out of line: only a driven change's.
1072
+ if (kind === KEYFRAMES) {
1073
+ if (!stepKeyframes(state, at, rule, time, dt)) still = false
1074
+ continue
1075
+ }
1076
+ // A spring, as `springValues`': only the part of this tick past the delay moves it.
1077
+ const goal = targets[at]
1078
+ const delay = delays[at]
1079
+ let position = positions[at]
1080
+ let speed = velocities[at]
1081
+ const simDt = Math.max(0, Math.min(dt, time - delay))
1082
+ if (simDt > 0 && simDt === dt) {
1083
+ const mi = rule * MATRIX
1084
+ const d = position - goal
1085
+ position = goal + matrices[mi] * d + matrices[mi + 1] * speed
1086
+ speed = matrices[mi + 2] * d + matrices[mi + 3] * speed
1087
+ }
1088
+ if (simDt > 0 && simDt < dt) {
1089
+ const part = Spring.matrixFor(entries[rule].spring, simDt)
1090
+ const d = position - goal
1091
+ position = goal + part.dd * d + part.dv * speed
1092
+ speed = part.vd * d + part.vv * speed
1093
+ }
1094
+ // A spring rests by its thresholds; one that ends at its duration, there (#359). Held by a paused
1095
+ // Playhead, one already on its target is at rest.
1096
+ let settled = simDt > 0 && Math.abs(speed) <= restSpeeds[at] && Math.abs(position - goal) <= restDeltas[at]
1097
+ if (kind === TIMED) settled = time - delay >= entries[rule].spring.duration
1098
+ if (dt === 0) settled = speed === 0 && position === goal && time >= delay
1099
+ if (settled) {
1100
+ position = goal
1101
+ speed = 0
1102
+ }
1103
+ if (!settled) still = false
1104
+ positions[at] = position
1105
+ velocities[at] = speed
1106
+ }
1107
+ write(subjects[slot] as S, positions, base)
1108
+ // At rest: still its member's, in neither list (a member is in one at most).
1109
+ if (still) {
1110
+ flags[slot] = LIVE
1111
+ continue
1112
+ }
1113
+ ruledList[kept] = slot
1114
+ kept++
1115
+ }
1116
+ state.ruledCount = kept
1117
+ }
1118
+
1119
+ // --- A change driven by a Playhead ---------------------------------------------
1120
+ //
1121
+ // #665, ADR-0069 decision 15: what `createAnimate`'s Playback controls act on when they animate a Batch.
1122
+ // The change keeps each of its keys' start, so a seek works its value out where it'd be, exactly, from
1123
+ // the spring's closed form (`Spring.matrixFor` over the time) or the tween's curve. Its transitions are
1124
+ // entries of its own whose keys step at its Playhead's speed. A later change of one of its keys takes it,
1125
+ // as a ward's Retarget takes an Imperative animation's (#433): the change can't land then. Keyframes
1126
+ // (Q36): a Sequence's Segment of a Batch, each key through its own stops, on one entry of the change's.
1127
+
1128
+ const AnimationTypeId = "~@wardic/core/Batch/Animation"
1129
+
1130
+ /** A change of a Batch driven by a Playhead: built by `animate`, which `play`, `stop`, `cancel` and `durationOf` take. */
1131
+ // The Batch module's second data type, so its TypeId names it after the module's (pipeable.md, rule 2).
1132
+ export interface Animation extends Pipeable, Inspectable.Inspectable {
1133
+ readonly [AnimationTypeId]: typeof AnimationTypeId
1134
+ }
1135
+
1136
+ /** `animate`'s options: a change's, and its Playhead, its first stops and its landing's callback. */
1137
+ export interface AnimateOptions extends RetargetOptions {
1138
+ /** What drives it: its keys step at its speed, hold while it's paused, and move its time. */
1139
+ readonly head: Playback.Playhead
1140
+ /** Each member's key's first stop, `NaN` for where it is: it starts there, from rest. */
1141
+ readonly from?: (slot: number, k: number) => number
1142
+ /** Called once every key it moves has landed while it still moves it, or at its play when it moves none. */
1143
+ readonly onLanded?: () => void
1144
+ /**
1145
+ * Called for each member it's given, once, as every key of it it still moves has landed: at its
1146
+ * first play for a member it moves nothing of; never for one whose keys a later change took.
1147
+ */
1148
+ // #665, Q47: a keyed Batch's leavers, each removed as its own exit lands.
1149
+ readonly onMemberLanded?: (slot: number) => void
1150
+ }
1151
+
1152
+ /**
1153
+ * A member's key's keyframes, for `keyframes`: its stops, `NaN` for the stop before (the key's value at
1154
+ * its first play, first), and the run through them, as `Machine.keyframes` takes them.
1155
+ */
1156
+ export interface Keyframes {
1157
+ readonly stops: ReadonlyArray<number>
1158
+ readonly transition: Machine.KeyframesOptions
1159
+ }
1160
+
1161
+ /** `keyframes`' options: its Playhead, and its landing's callback. */
1162
+ export interface KeyframesOptions {
1163
+ /** What drives it: its keys step at its speed, hold while it's paused, and move its time. */
1164
+ readonly head: Playback.Playhead
1165
+ /** Called once every key it moves has reached its last stop while it still moves it, or at its play when it moves none. */
1166
+ readonly onLanded?: () => void
1167
+ }
1168
+
1169
+ /** A key's keyframes in a driven change, resolved at its first play: its stops filled, their times, its easings and its run. */
1170
+ interface Track {
1171
+ readonly stops: Float64Array
1172
+ readonly stopTimes: ReadonlyArray<number>
1173
+ readonly eases: ReadonlyArray<Easing.Easing>
1174
+ readonly run: ResolvedRun
1175
+ readonly reverse: boolean
1176
+ readonly delay: number
1177
+ /** When it ends, from its start: its delay and its run, `Infinity` for one that repeats for ever. */
1178
+ readonly end: number
1179
+ }
1180
+
1181
+ /** An animation's state: its change, worked out at its first play, and what it moves. */
1182
+ interface AnimationState<S> {
1183
+ readonly state: State<S>
1184
+ /** Its transition for a member's key: its own copy, so its entry, and the Playhead driving it, are its alone. */
1185
+ readonly bag: (slot: number, k: number) => Transition
1186
+ readonly options: AnimateOptions
1187
+ readonly slots: ReadonlyArray<number>
1188
+ readonly targetOf: (slot: number, k: number) => number
1189
+ /** Each member's key's keyframes: a `keyframes` change's, in place of its targets and transitions. */
1190
+ readonly keyframesOf: ((slot: number, k: number) => Keyframes | undefined) | undefined
1191
+ /** A `keyframes` change's track for each of its keys, by its index in `ats`, and that index by the key's place in the Batch's arrays. */
1192
+ tracks: ReadonlyArray<Track>
1193
+ indexAt: Int32Array
1194
+ /** Its keys, by index into the Batch's arrays, and each one's start, its speed then, its target and its wait. */
1195
+ ats: Int32Array
1196
+ starts: Float64Array
1197
+ speeds: Float64Array
1198
+ goals: Float64Array
1199
+ waits: Float64Array
1200
+ /** Each of its keys' entry while it plays, and its distinct entries, each held once for it. */
1201
+ rules: Uint16Array
1202
+ held: ReadonlyArray<number>
1203
+ started: boolean
1204
+ playing: boolean
1205
+ duration: number | undefined
1206
+ /** Its time, as a driven machine keeps its own (`Playback.drive`), and its Playhead's after each step. */
1207
+ time: number
1208
+ /** The step its tick was last worked out in, and that tick: once a step, whatever entries it drives. */
1209
+ frame: number
1210
+ dt: number
1211
+ /** Played from partway through: its first step lands where it was played from, as a driven machine's (`Playback.drive`). */
1212
+ landing: boolean
1213
+ /** Each member it moves, by rank, its first key's index in `ats`, and one past the last's; whether each has been told it landed. */
1214
+ firsts: Int32Array
1215
+ told: Uint8Array
1216
+ /** The members it's given that it moves nothing of, told they landed at its first play. */
1217
+ idle: ReadonlyArray<number>
1218
+ idleTold: boolean
1219
+ }
1220
+
1221
+ const AnimationProto = {
1222
+ [AnimationTypeId]: AnimationTypeId,
1223
+ ...Inspectable.BaseProto,
1224
+ toJSON(this: AnimationState<unknown>) {
1225
+ return { _id: "Batch.Animation", keys: this.ats.length, playing: this.playing }
1226
+ },
1227
+ pipe() {
1228
+ return pipeArguments(this, arguments)
1229
+ },
1230
+ }
1231
+
1232
+ /** Whether `u` is a Batch's Animation. */
1233
+ export const isAnimation = (u: unknown): u is Animation => Predicate.hasProperty(u, AnimationTypeId)
1234
+
1235
+ const animationOf = (self: Animation): AnimationState<unknown> => self as unknown as AnimationState<unknown>
1236
+
1237
+ /** The slot whose key is at `at`. */
1238
+ const slotAt = <S>(state: State<S>, at: number): number => Math.floor(at / state.stride)
1239
+
1240
+ /** A step's time, a frame at 60 Hz: what a tween's speed is worked out over, and `durationOf` steps by. */
1241
+ const FRAME = Machine.CATCH_UP_DT
1242
+
1243
+ /**
1244
+ * A driven change's tick this step: the frame's at its Playhead's speed, 0 while it's paused. Worked out
1245
+ * once a step, however many entries it drives, which moves its time and its Playhead's.
1246
+ */
1247
+ // Per frame, per driven entry: as `Playback.drive`'s, its own time kept and written (#433).
1248
+ const drivenStep = <S>(animation: AnimationState<S>, clamped: number, frame: number): number => {
1249
+ if (animation.frame === frame) return animation.dt
1250
+ animation.frame = frame
1251
+ const head = animation.options.head
1252
+ let by = 0
1253
+ // Played from partway through, its first step lands there, whatever the `dt`, as `Playback.drive`'s does.
1254
+ const landing = animation.landing
1255
+ animation.landing = false
1256
+ if (!landing && !head.paused) by = tickOf(head, clamped, Machine.MAX_DT)
1257
+ animation.dt = by
1258
+ animation.time = Math.max(0, animation.time + by)
1259
+ writableOf(head).time = animation.time
1260
+ return by
1261
+ }
1262
+
1263
+ /** Whether the key at `at` is held by a paused Playhead: it hands on no speed, as a held element's frames read 0 (#464). */
1264
+ // Per key per change, while a driven change plays.
1265
+ const heldAt = <S>(state: State<S>, at: number): boolean => {
1266
+ const driver = state.drivers[state.rules[at]]
1267
+ if (Predicate.isUndefined(driver)) return false
1268
+ return driver.options.head.paused
1269
+ }
1270
+
1271
+ /**
1272
+ * The key at `at`'s value and speed at `time` into its change, from its start: a spring's by its closed
1273
+ * form, a tween's by its curve, keyframes' by their stops. Whether it has landed there. A spring under its
1274
+ * rest thresholds lands there when it `rests`; else it's left where its closed form has it, to land at its
1275
+ * next step (a start partway, drawn where the Appear animation it takes over drew it, #706).
1276
+ */
1277
+ const valueAt = <S>(state: State<S>, at: number, rule: number, time: number, rests: boolean): boolean => {
1278
+ const entry = state.entries[rule]
1279
+ if (entry.kind === KEYFRAMES) return keyframesAt(state, at, rule, time)
1280
+ const delay = state.delays[at]
1281
+ const goal = state.targets[at]
1282
+ const from = state.origins[at]
1283
+ const active = Math.max(0, time - delay)
1284
+ if (entry.kind === TWEEN) {
1285
+ const tween = entry.tween
1286
+ const landed = time >= delay + tween.seconds
1287
+ // Landed, at its target, as `stepTween`'s.
1288
+ let value = goal
1289
+ if (!landed) value = Scalar.lerp(from, goal, tween.ease(Scalar.clamp(active / tween.duration, 0, 1)))
1290
+ const before = Scalar.lerp(from, goal, tween.ease(Scalar.clamp(Math.max(0, active - FRAME) / tween.duration, 0, 1)))
1291
+ state.positions[at] = value
1292
+ state.velocities[at] = (value - before) / FRAME
1293
+ if (landed) state.velocities[at] = 0
1294
+ return landed
1295
+ }
1296
+ if (active === 0) {
1297
+ state.positions[at] = from
1298
+ state.velocities[at] = state.originVelocities[at]
1299
+ return false
1300
+ }
1301
+ const m = Spring.matrixFor(entry.spring, active)
1302
+ const d = from - goal
1303
+ const v0 = state.originVelocities[at]
1304
+ let position = goal + m.dd * d + m.dv * v0
1305
+ let speed = m.vd * d + m.vv * v0
1306
+ let landed = rests && Math.abs(speed) <= state.restSpeeds[at] && Math.abs(position - goal) <= state.restDeltas[at]
1307
+ if (entry.kind === TIMED) landed = active >= entry.spring.duration
1308
+ if (landed) {
1309
+ position = goal
1310
+ speed = 0
1311
+ }
1312
+ state.positions[at] = position
1313
+ state.velocities[at] = speed
1314
+ return landed
1315
+ }
1316
+
1317
+ /**
1318
+ * Each step's start pass, before the loops: each `STARTS` member where its change's `startAt` says, drawn,
1319
+ * and flagged `STARTED` so its loop keeps it unstepped; one given `NaN` moves from its start, its loop
1320
+ * stepping it as any other.
1321
+ */
1322
+ // Once a member, at its first step after a change that starts it partway (#706): out of the loops, which
1323
+ // only clear a flag, so their code is the same size it was (Bun's step was 5–9% slower with this in them).
1324
+ const startPass = <S>(state: State<S>, dt: number): void => {
1325
+ const { flags, startList } = state
1326
+ // Over the members a change started partway since the last step: a counted loop, as the step's.
1327
+ for (let i = 0; i < startList.length; i++) {
1328
+ const slot = startList[i]
1329
+ const flag = flags[slot]
1330
+ if ((flag & STARTS) === 0) continue
1331
+ flags[slot] = flag & ~STARTS
1332
+ // A member that left takes no start, nor keeps one.
1333
+ if ((flag & LIVE) === 0) {
1334
+ state.startAts[slot] = undefined
1335
+ continue
1336
+ }
1337
+ if (startedPartway(state, slot, dt)) flags[slot] = flags[slot] | STARTED
1338
+ }
1339
+ startList.length = 0
1340
+ }
1341
+
1342
+ /**
1343
+ * A member's start partway: where its change's `startAt` says, or, given `NaN`, nowhere yet (its keys wait
1344
+ * at its start, and its loop moves it this step). Whether it started there, drawn: the keys the change
1345
+ * turned at that time, unlanded (`valueAt`'s `rests`), from the speed they had when it came; its other
1346
+ * moving keys a step on from where they are, as its loop would.
1347
+ */
1348
+ const startedPartway = <S>(state: State<S>, slot: number, dt: number): boolean => {
1349
+ const { stride, elapsed, rules, positions, velocities, targets, originVelocities, startAts } = state
1350
+ const startAt = UndefinedOr.getOrThrow(startAts[slot])
1351
+ startAts[slot] = undefined
1352
+ const time = startAt(slot)
1353
+ const base = slot * stride
1354
+ const started = !Number.isNaN(time)
1355
+ for (let k = 0; k < stride; k++) {
1356
+ const at = base + k
1357
+ const turned = Number.isNaN(elapsed[at])
1358
+ // From its start, given `NaN`: its loop moves it.
1359
+ if (turned && !started) elapsed[at] = 0
1360
+ if (!started) continue
1361
+ if (turned) {
1362
+ // Nothing has moved it since its change: its speed is the one it came with.
1363
+ originVelocities[at] = velocities[at]
1364
+ elapsed[at] = time
1365
+ valueAt(state, at, rules[at], time, false)
1366
+ continue
1367
+ }
1368
+ if (velocities[at] === 0 && positions[at] === targets[at]) continue
1369
+ stepKey(state, at, rules[at], dt)
1370
+ }
1371
+ if (started) state.write(state.subjects[slot] as S, positions, base)
1372
+ return started
1373
+ }
1374
+
1375
+ /**
1376
+ * The key at `at` a step of `dt` on, as the loops step it: a tween's, keyframes', or a spring's by its
1377
+ * matrix for the part past its delay, landing by its thresholds or its duration.
1378
+ */
1379
+ // Rare: a key the loops don't reach this step, of a member started partway that another change moves.
1380
+ const stepKey = <S>(state: State<S>, at: number, rule: number, dt: number): void => {
1381
+ const entry = state.entries[rule]
1382
+ const time = state.elapsed[at] + dt
1383
+ state.elapsed[at] = time
1384
+ if (entry.kind === TWEEN) {
1385
+ stepTween(state, at, entry.tween, time, dt)
1386
+ return
1387
+ }
1388
+ if (entry.kind === KEYFRAMES) {
1389
+ stepKeyframes(state, at, rule, time, dt)
1390
+ return
1391
+ }
1392
+ // The loops' spring step: only the part of this step past the delay moves it.
1393
+ const delay = state.delays[at]
1394
+ const goal = state.targets[at]
1395
+ const simDt = Math.max(0, Math.min(dt, time - delay))
1396
+ let position = state.positions[at]
1397
+ let speed = state.velocities[at]
1398
+ if (simDt > 0) {
1399
+ const m = Spring.matrixFor(entry.spring, simDt)
1400
+ const d = position - goal
1401
+ position = goal + m.dd * d + m.dv * speed
1402
+ speed = m.vd * d + m.vv * speed
1403
+ }
1404
+ let settled = simDt > 0 && Math.abs(speed) <= state.restSpeeds[at] && Math.abs(position - goal) <= state.restDeltas[at]
1405
+ if (entry.kind === TIMED) settled = time - delay >= entry.spring.duration
1406
+ if (settled) {
1407
+ position = goal
1408
+ speed = 0
1409
+ }
1410
+ state.positions[at] = position
1411
+ state.velocities[at] = speed
1412
+ }
1413
+
1414
+ /** A key played backwards by `dt`: its value where its Playhead went back to; at its start, at rest there. */
1415
+ // Per frame, per key of a change played backwards: rare, so out of line.
1416
+ const stepBack = <S>(state: State<S>, at: number, rule: number, dt: number): boolean => {
1417
+ const time = Math.max(0, state.elapsed[at] + dt)
1418
+ state.elapsed[at] = time
1419
+ valueAt(state, at, rule, time, true)
1420
+ if (time > 0) return false
1421
+ state.positions[at] = state.origins[at]
1422
+ state.velocities[at] = 0
1423
+ return true
1424
+ }
1425
+
1426
+ /** Whether `animation` still moves the key at its `i`th: on its entry, toward its target. */
1427
+ const holds = <S>(animation: AnimationState<S>, i: number): boolean => {
1428
+ const at = animation.ats[i]
1429
+ return animation.state.rules[at] === animation.rules[i] && animation.state.targets[at] === animation.goals[i]
1430
+ }
1431
+
1432
+ /** It stops playing: its entries step at the frame's pace again, and the table may let them go. */
1433
+ const finish = <S>(animation: AnimationState<S>): void => {
1434
+ if (!animation.playing) return
1435
+ animation.playing = false
1436
+ const { state } = animation
1437
+ state.animations.delete(animation)
1438
+ Arr.forEach(animation.held, (rule) => {
1439
+ state.drivers[rule] = undefined
1440
+ release(state, rule)
1441
+ })
1442
+ }
1443
+
1444
+ /** Whether the key at `animation`'s `i`th is at rest at its target, past its delay. */
1445
+ // Once a step, per key of a playing change: plain reads.
1446
+ const keyAtRest = <S>(animation: AnimationState<S>, i: number): boolean => {
1447
+ const { state } = animation
1448
+ const at = animation.ats[i]
1449
+ return state.velocities[at] === 0 && state.positions[at] === animation.goals[i] && state.elapsed[at] >= state.delays[at]
1450
+ }
1451
+
1452
+ /** The members `animation` moves nothing of, told they landed, once, at its first play (`onMemberLanded`). */
1453
+ const tellIdle = <S>(animation: AnimationState<S>): void => {
1454
+ if (animation.idleTold) return
1455
+ animation.idleTold = true
1456
+ const tell = animation.options.onMemberLanded
1457
+ if (Predicate.isUndefined(tell)) return
1458
+ Arr.forEach(animation.idle, (slot) => tell(slot))
1459
+ }
1460
+
1461
+ /**
1462
+ * Each member `animation` moves told, once, as every key of it it still moves has landed (`onMemberLanded`):
1463
+ * at its target, past its delay. One whose keys a later change took all is never told.
1464
+ */
1465
+ // Once a step, per key of a playing change that tells its members: counted loops with plain reads.
1466
+ const tellMembers = <S>(animation: AnimationState<S>, tell: (slot: number) => void): void => {
1467
+ const { state, firsts, told, ats } = animation
1468
+ const n = told.length
1469
+ for (let r = 0; r < n; r++) {
1470
+ if (told[r] === 1) continue
1471
+ let kept = false
1472
+ let atRest = true
1473
+ for (let i = firsts[r]; i < firsts[r + 1]; i++) {
1474
+ if (!holds(animation, i)) continue
1475
+ kept = true
1476
+ if (!keyAtRest(animation, i)) {
1477
+ atRest = false
1478
+ break
1479
+ }
1480
+ }
1481
+ if (!kept || !atRest) continue
1482
+ told[r] = 1
1483
+ tell(slotAt(state, ats[firsts[r]]))
1484
+ }
1485
+ }
1486
+
1487
+ /**
1488
+ * Whether `animation` has landed, once a step while it plays: every key it still moves at its target,
1489
+ * past its delay; or, played backwards, back at its start. It ends then. A key a later change took keeps
1490
+ * it from landing (#433's latest-wins, as a ward's): it ends unheard, once the keys it kept are at rest.
1491
+ */
1492
+ const checkLanding = <S>(animation: AnimationState<S>): void => {
1493
+ const { state, options } = animation
1494
+ const backwards = options.head.speed < 0
1495
+ const tell = options.onMemberLanded
1496
+ if (Predicate.isNotUndefined(tell) && !backwards) tellMembers(animation, tell)
1497
+ const count = animation.ats.length
1498
+ let atRest = true
1499
+ let held = 0
1500
+ // Once a step, per key of a playing change: a counted loop with plain reads.
1501
+ for (let i = 0; i < count; i++) {
1502
+ if (!holds(animation, i)) continue
1503
+ held++
1504
+ if (backwards) continue
1505
+ if (!keyAtRest(animation, i)) atRest = false
1506
+ }
1507
+ if (held > 0 && backwards && animation.time > 0) return
1508
+ if (!atRest) return
1509
+ // Played back to its start, each key it still moves rests there, its target with it: a later step of the
1510
+ // member, for a change of another key, leaves it there.
1511
+ if (backwards) {
1512
+ for (let i = 0; i < count; i++) {
1513
+ if (!holds(animation, i)) continue
1514
+ const at = animation.ats[i]
1515
+ state.targets[at] = state.origins[at]
1516
+ }
1517
+ }
1518
+ finish(animation)
1519
+ if (held < count) return
1520
+ UndefinedOr.map(options.onLanded, (told) => told())
1521
+ }
1522
+
1523
+ /** A driven change's transition for a member's key, before its copy: its function's, or its own or `default`, else the key's own. */
1524
+ const animationBagsOf = <S>(state: State<S>, given: RetargetOptions["transition"]): ((slot: number, k: number) => Transition) => {
1525
+ if (Predicate.isFunction(given)) return given
1526
+ // The Batch's own entries are transitions: `make`'s.
1527
+ const own = Arr.map(state.ownRules, (rule) => UndefinedOr.getOrThrow(state.bags[rule]) as Transition)
1528
+ if (Predicate.isUndefined(given)) return (_, k) => own[k]
1529
+ const bags = Arr.map(bagsOf(state, given), (bag, k) => UndefinedOr.match(bag, { onUndefined: () => own[k], onDefined: identity }))
1530
+ return (_, k) => bags[k]
1531
+ }
1532
+
1533
+ /**
1534
+ * A change of `slots`' members toward `targetOf(slot, k)`, driven by `options.head`: nothing moves until
1535
+ * it's played. Its controls are `play`, `stop`, `cancel` and `durationOf`.
1536
+ *
1537
+ * @example
1538
+ * const head = Playback.make()
1539
+ * const shuffle = Batch.animate(grid, slots, (slot, k) => cellOf(slot)[k], { head, transition: { type: "spring" } })
1540
+ * Batch.play(shuffle)
1541
+ */
1542
+ export const animate: {
1543
+ (slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options: AnimateOptions): <S>(self: Batch<S>) => Animation
1544
+ <S>(self: Batch<S>, slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options: AnimateOptions): Animation
1545
+ } = dual(isBatch, <S>(self: Batch<S>, slots: ReadonlyArray<number>, targetOf: (slot: number, k: number) => number, options: AnimateOptions): Animation => {
1546
+ const state = stateOf(self)
1547
+ if (Predicate.isNotUndefined(options.delay)) checked(Delay, options.delay, "delay")
1548
+ const bagOf = animationBagsOf(state, options.transition)
1549
+ // A copy of each transition it runs, made once: most members' keys give the bag the last one gave.
1550
+ const copies = new Map<Transition, Transition>()
1551
+ let lastGiven: Transition | undefined = undefined
1552
+ let lastCopy: Transition | undefined = undefined
1553
+ const bag = (slot: number, k: number): Transition => {
1554
+ const given = bagOf(slot, k)
1555
+ if (given === lastGiven) return lastCopy as Transition
1556
+ let made = copies.get(given)
1557
+ if (Predicate.isUndefined(made)) {
1558
+ made = { ...given } as Transition
1559
+ copies.set(given, made)
1560
+ }
1561
+ lastGiven = given
1562
+ lastCopy = made
1563
+ return made
1564
+ }
1565
+ return animationFor(state, options, slots, { bag, targetOf, keyframesOf: undefined })
1566
+ })
1567
+
1568
+ /** A driven change, unplayed: worked out at its first play, toward targets or through keyframes. */
1569
+ const animationFor = <S>(
1570
+ state: State<S>,
1571
+ options: AnimateOptions,
1572
+ slots: ReadonlyArray<number>,
1573
+ moves: Pick<AnimationState<S>, "bag" | "targetOf" | "keyframesOf">,
1574
+ ): Animation => {
1575
+ const animation: AnimationState<S> = {
1576
+ state,
1577
+ options,
1578
+ slots,
1579
+ ...moves,
1580
+ ats: new Int32Array(0),
1581
+ starts: new Float64Array(0),
1582
+ speeds: new Float64Array(0),
1583
+ goals: new Float64Array(0),
1584
+ waits: new Float64Array(0),
1585
+ rules: new Uint16Array(0),
1586
+ held: [],
1587
+ started: false,
1588
+ playing: false,
1589
+ duration: undefined,
1590
+ time: 0,
1591
+ frame: 0,
1592
+ dt: 0,
1593
+ landing: false,
1594
+ tracks: [],
1595
+ indexAt: new Int32Array(0),
1596
+ firsts: new Int32Array(0),
1597
+ told: new Uint8Array(0),
1598
+ idle: [],
1599
+ idleTold: false,
1600
+ }
1601
+ return Object.assign(Object.create(AnimationProto), animation)
1602
+ }
1603
+
1604
+ /** A `keyframes` change's transition for a key: never read, its tracks run its keys. */
1605
+ const UNREAD_TRANSITION: Transition = { type: "tween" }
1606
+ const NO_BAG = (): Transition => UNREAD_TRANSITION
1607
+
1608
+ /** A `keyframes` change's target for a key: never read, its tracks end its keys. */
1609
+ const NO_TARGET = (): number => Number.NaN
1610
+
1611
+ /**
1612
+ * A change of `slots`' members through each key's own keyframes, `keyframesOf(slot, k)` (`undefined`
1613
+ * for a key it leaves), driven by `options.head`: each key as `Machine.keyframes` would run its stops,
1614
+ * frame for frame. Nothing moves until it's played; its controls are `animate`'s. A Sequence's Segment
1615
+ * of a Batch, its members' stops placed over the whole sequence, runs on it.
1616
+ *
1617
+ * @example
1618
+ * const head = Playback.make()
1619
+ * const wave = Batch.keyframes(grid, slots, (slot) => ({ stops: [Number.NaN, -20, 0], transition: { duration: 0.6, delay: slot * 0.05 } }), { head })
1620
+ * Batch.play(wave)
1621
+ */
1622
+ // #665, Q36: one entry of its own, every key it moves on it, each key's track by its index.
1623
+ export const keyframes: {
1624
+ (slots: ReadonlyArray<number>, keyframesOf: (slot: number, k: number) => Keyframes | undefined, options: KeyframesOptions): <S>(self: Batch<S>) => Animation
1625
+ <S>(self: Batch<S>, slots: ReadonlyArray<number>, keyframesOf: (slot: number, k: number) => Keyframes | undefined, options: KeyframesOptions): Animation
1626
+ } = dual(isBatch, <S>(self: Batch<S>, slots: ReadonlyArray<number>, keyframesOf: (slot: number, k: number) => Keyframes | undefined, options: KeyframesOptions): Animation => {
1627
+ return animationFor(stateOf(self), options, slots, { bag: NO_BAG, targetOf: NO_TARGET, keyframesOf })
1628
+ })
1629
+
1630
+ /** A key's keyframes resolved at its first play: its stops, each `NaN` the stop before, the first `current`; `undefined` for none. */
1631
+ // Once a play, per key: statements.
1632
+ const trackOf = (keyframes: Keyframes, current: number): Track | undefined => {
1633
+ const given = keyframes.stops
1634
+ if (given.length === 0) return undefined
1635
+ const resolved = resolveKeyframes(keyframes.transition)
1636
+ // One stop holds, as `Machine.keyframes`' does: it's there twice.
1637
+ const stops = new Float64Array(Math.max(2, given.length))
1638
+ let before = current
1639
+ for (let i = 0; i < given.length; i++) {
1640
+ let stop = given[i]
1641
+ if (Number.isNaN(stop)) stop = before
1642
+ stops[i] = stop
1643
+ before = stop
1644
+ }
1645
+ if (given.length === 1) stops[1] = stops[0]
1646
+ const run = resolved.run
1647
+ return {
1648
+ stops,
1649
+ stopTimes: stopTimesOf(stops.length, resolved.times, run.tween.duration),
1650
+ eases: resolved.eases,
1651
+ run,
1652
+ reverse: resolved.reverse,
1653
+ delay: resolved.delay,
1654
+ end: resolved.delay + run.total,
1655
+ }
1656
+ }
1657
+
1658
+ /** {@link trackValue}'s pass, written in place: read right after, never across a call. */
1659
+ // Module state (#460, Q7): per-frame scratch, written and read within one key's step, never across one.
1660
+ const TRACK_PASS: Pass = { within: 0, reversed: false, flipped: false }
1661
+
1662
+ /** A track's value `time` seconds from its start, as `Machine.keyframes`' Frame then: its first stop through its delay. */
1663
+ // Per frame, per key of a keyframes change: as `Machine.keyframes`' step, its delay held first (`Machine.delay`).
1664
+ const trackValue = (track: Track, time: number): number => {
1665
+ passAt(Math.max(0, time - track.delay), track.run, track.reverse, TRACK_PASS)
1666
+ return keyframeAt(track.stops, track.stopTimes, track.eases, TRACK_PASS, track.run.tween.duration)
1667
+ }
1668
+
1669
+ /** Where a track ends: its value at its end, or, for one that never ends, its last stop, which it never rests on. */
1670
+ const trackGoal = (track: Track): number => {
1671
+ if (Number.isFinite(track.end)) return trackValue(track, track.end)
1672
+ return track.stops[track.stops.length - 1]
1673
+ }
1674
+
1675
+ /** The key at `at`'s track, in the keyframes change driving its entry `rule`; `undefined` once that change has ended. */
1676
+ const trackAt = <S>(state: State<S>, at: number, rule: number): Track | undefined => {
1677
+ const driver = state.drivers[rule]
1678
+ if (Predicate.isUndefined(driver)) return undefined
1679
+ return driver.tracks[driver.indexAt[at]]
1680
+ }
1681
+
1682
+ /** The key at `at`'s keyframes `time` seconds in: its value, its speed over the frame before, and whether it has ended. */
1683
+ // At a play and played backwards: out of line.
1684
+ const keyframesAt = <S>(state: State<S>, at: number, rule: number, time: number): boolean => {
1685
+ const track = trackAt(state, at, rule)
1686
+ if (Predicate.isUndefined(track)) return true
1687
+ const value = trackValue(track, time)
1688
+ const before = trackValue(track, Math.max(0, time - FRAME))
1689
+ const landed = time >= track.end
1690
+ state.positions[at] = value
1691
+ state.velocities[at] = (value - before) / FRAME
1692
+ if (landed) state.velocities[at] = 0
1693
+ return landed
1694
+ }
1695
+
1696
+ /**
1697
+ * A keyframes key's step to `time`, by `dt`, written in place: whether it has ended. Its speed is its
1698
+ * move over the step. One whose change has ended rests where it is, its target.
1699
+ */
1700
+ // Per frame, per key of a keyframes change.
1701
+ const stepKeyframes = <S>(state: State<S>, at: number, rule: number, time: number, dt: number): boolean => {
1702
+ const track = trackAt(state, at, rule)
1703
+ if (Predicate.isUndefined(track)) {
1704
+ state.positions[at] = state.targets[at]
1705
+ state.velocities[at] = 0
1706
+ return true
1707
+ }
1708
+ const next = trackValue(track, time)
1709
+ const landed = time >= track.end
1710
+ if (landed) state.velocities[at] = 0
1711
+ if (!landed && dt > 0) state.velocities[at] = (next - state.positions[at]) / dt
1712
+ state.positions[at] = next
1713
+ return landed
1714
+ }
1715
+
1716
+ /** Its change worked out, once, at its first play: the keys it moves, where each starts, its target and its wait. */
1717
+ const startOf = <S>(animation: AnimationState<S>): void => {
1718
+ if (Predicate.isNotUndefined(animation.keyframesOf)) return keyframesStartOf(animation, animation.keyframesOf)
1719
+ const { state, slots, targetOf, options } = animation
1720
+ const { stride, flags, positions, velocities, targets } = state
1721
+ const from = options.from
1722
+ const given = slots.length
1723
+ const most = given * stride
1724
+ const ats = new Int32Array(most)
1725
+ const starts = new Float64Array(most)
1726
+ const speeds = new Float64Array(most)
1727
+ const goals = new Float64Array(most)
1728
+ // Each mover's first key in `ats`, by rank, and one past the last mover's.
1729
+ const firsts = new Int32Array(given + 1)
1730
+ const driven = state.animations.size > 0
1731
+ let count = 0
1732
+ let n = 0
1733
+ const idle: Array<number> = []
1734
+ // Per member per key, once an animation, as a change's (ADR-0025, *Amendment (#665)*): counted loops
1735
+ // over its typed arrays. A slot given twice moves once.
1736
+ for (let g = 0; g < given; g++) {
1737
+ const slot = slots[g]
1738
+ const flag = flags[slot]
1739
+ if ((flag & LIVE) === 0) continue
1740
+ if ((flag & COUNTED) !== 0) continue
1741
+ const first = count
1742
+ for (let k = 0; k < stride; k++) {
1743
+ const at = slot * stride + k
1744
+ const target = targetOf(slot, k)
1745
+ if (Number.isNaN(target)) continue
1746
+ let start = positions[at]
1747
+ let speed = velocities[at]
1748
+ if (driven && heldAt(state, at)) speed = 0
1749
+ let jumps = false
1750
+ if (Predicate.isNotUndefined(from)) {
1751
+ const stop = from(slot, k)
1752
+ if (!Number.isNaN(stop)) {
1753
+ start = stop
1754
+ speed = 0
1755
+ jumps = true
1756
+ }
1757
+ }
1758
+ if (!jumps && target === targets[at]) continue
1759
+ ats[count] = at
1760
+ starts[count] = start
1761
+ speeds[count] = speed
1762
+ goals[count] = target
1763
+ count++
1764
+ }
1765
+ if (count === first) {
1766
+ // Counted too, so a slot given twice is idle once.
1767
+ flags[slot] = flag | COUNTED
1768
+ idle.push(slot)
1769
+ continue
1770
+ }
1771
+ flags[slot] = flag | COUNTED
1772
+ firsts[n] = first
1773
+ n++
1774
+ }
1775
+ firsts[n] = count
1776
+ // Each mover's keys wait by its rank among the movers.
1777
+ const delayOf = delayOfChange(options.delay)
1778
+ const waits = new Float64Array(count)
1779
+ for (let rank = 0; rank < n; rank++) {
1780
+ const slot = slotAt(state, ats[firsts[rank]])
1781
+ flags[slot] = flags[slot] & ~COUNTED
1782
+ const wait = delayOf(rank, n)
1783
+ for (let i = firsts[rank]; i < firsts[rank + 1]; i++) waits[i] = wait
1784
+ }
1785
+ animation.ats = ats.slice(0, count)
1786
+ animation.starts = starts.slice(0, count)
1787
+ animation.speeds = speeds.slice(0, count)
1788
+ animation.goals = goals.slice(0, count)
1789
+ animation.waits = waits
1790
+ animation.rules = new Uint16Array(count)
1791
+ animation.firsts = firsts.slice(0, n + 1)
1792
+ animation.told = new Uint8Array(n)
1793
+ for (let s = 0; s < idle.length; s++) flags[idle[s]] = flags[idle[s]] & ~COUNTED
1794
+ animation.idle = idle
1795
+ animation.started = true
1796
+ }
1797
+
1798
+ /**
1799
+ * A keyframes change worked out, once, at its first play: each key it moves, its track, where it starts
1800
+ * and ends, and its end as its wait, so it lands no sooner.
1801
+ */
1802
+ const keyframesStartOf = <S>(animation: AnimationState<S>, keyframesOf: (slot: number, k: number) => Keyframes | undefined): void => {
1803
+ const { state, slots } = animation
1804
+ const { stride, flags, positions } = state
1805
+ const given = slots.length
1806
+ const most = given * stride
1807
+ const ats = new Int32Array(most)
1808
+ const starts = new Float64Array(most)
1809
+ const goals = new Float64Array(most)
1810
+ const ends = new Float64Array(most)
1811
+ const counted = new Int32Array(given)
1812
+ const indexAt = new Int32Array(state.used * stride)
1813
+ const tracks: Array<Track> = []
1814
+ let count = 0
1815
+ let n = 0
1816
+ // Per member per key, once an animation, as a change's: counted loops. A slot given twice moves once.
1817
+ for (let g = 0; g < given; g++) {
1818
+ const slot = slots[g]
1819
+ const flag = flags[slot]
1820
+ if ((flag & LIVE) === 0) continue
1821
+ if ((flag & COUNTED) !== 0) continue
1822
+ flags[slot] = flag | COUNTED
1823
+ counted[n] = slot
1824
+ n++
1825
+ for (let k = 0; k < stride; k++) {
1826
+ const at = slot * stride + k
1827
+ const keyframes = keyframesOf(slot, k)
1828
+ if (Predicate.isUndefined(keyframes)) continue
1829
+ const track = trackOf(keyframes, positions[at])
1830
+ if (Predicate.isUndefined(track)) continue
1831
+ ats[count] = at
1832
+ starts[count] = trackValue(track, 0)
1833
+ goals[count] = trackGoal(track)
1834
+ ends[count] = track.end
1835
+ indexAt[at] = count
1836
+ tracks.push(track)
1837
+ count++
1838
+ }
1839
+ }
1840
+ for (let c = 0; c < n; c++) flags[counted[c]] = flags[counted[c]] & ~COUNTED
1841
+ animation.ats = ats.slice(0, count)
1842
+ animation.starts = starts.slice(0, count)
1843
+ animation.speeds = new Float64Array(count)
1844
+ animation.goals = goals.slice(0, count)
1845
+ animation.waits = ends.slice(0, count)
1846
+ animation.rules = new Uint16Array(count)
1847
+ animation.tracks = tracks
1848
+ animation.indexAt = indexAt
1849
+ animation.started = true
1850
+ }
1851
+
1852
+ /** A keyframes change's entry: every key it moves is on it, its own, so its Playhead reaches them alone. */
1853
+ const KEYFRAMES_ENTRY: Entry = { kind: KEYFRAMES, delay: 0, spring: NO_SPRING, tween: NO_TWEEN }
1854
+
1855
+ /** `animation`'s rule for each key it moves: its own keyframes entry, or each key's transition's. */
1856
+ // Once a play, per key it moves.
1857
+ const playRules = <S>(animation: AnimationState<S>): void => {
1858
+ const { state } = animation
1859
+ const count = animation.ats.length
1860
+ if (Predicate.isNotUndefined(animation.keyframesOf)) {
1861
+ let rule = state.ruleByBag.get(animation)
1862
+ if (Predicate.isUndefined(rule)) rule = entryRuleOf(state, animation, KEYFRAMES_ENTRY)
1863
+ animation.rules.fill(rule)
1864
+ return
1865
+ }
1866
+ for (let i = 0; i < count; i++) {
1867
+ const at = animation.ats[i]
1868
+ const slot = slotAt(state, at)
1869
+ animation.rules[i] = ruleFor(state, animation.bag(slot, at - slot * state.stride))
1870
+ }
1871
+ }
1872
+
1873
+ /**
1874
+ * Plays `animation` from its Playhead's time: from its start at 0, its change worked out then, and from
1875
+ * wherever a seek put the time, every key it moves taken again there. It returns how many members it
1876
+ * sets off from rest. One that moves nothing lands at once, as an element's call with no key does.
1877
+ */
1878
+ export const play = (self: Animation): number => {
1879
+ const animation = animationOf(self)
1880
+ const { state, options } = animation
1881
+ if (!animation.started) startOf(animation)
1882
+ finish(animation)
1883
+ tellIdle(animation)
1884
+ const count = animation.ats.length
1885
+ if (count === 0) {
1886
+ UndefinedOr.map(options.onLanded, (told) => told())
1887
+ return 0
1888
+ }
1889
+ const time = options.head.time
1890
+ animation.playing = true
1891
+ animation.time = time
1892
+ animation.landing = time > 0
1893
+ state.animations.add(animation)
1894
+ // Once a play, per key it moves: each key's entry, then each entry held once for it and driven by it.
1895
+ playRules(animation)
1896
+ animation.held = Arr.dedupe(Arr.fromIterable(animation.rules))
1897
+ Arr.forEach(animation.held, (rule) => {
1898
+ hold(state, rule)
1899
+ state.drivers[rule] = animation
1900
+ })
1901
+ let setOff = 0
1902
+ for (let i = 0; i < count; i++) {
1903
+ const at = animation.ats[i]
1904
+ const rule = animation.rules[i]
1905
+ turn(state, at, rule, animation.goals[i], animation.starts[i], animation.speeds[i], animation.waits[i])
1906
+ state.elapsed[at] = time
1907
+ valueAt(state, at, rule, time, true)
1908
+ setOff += moving(state, slotAt(state, at))
1909
+ }
1910
+ return setOff
1911
+ }
1912
+
1913
+ /** The member at `slot` moving in the ruled list, so the next step draws it and rests it: 1 when that sets it off from rest. */
1914
+ const moving = <S>(state: State<S>, slot: number): number => {
1915
+ const flag = state.flags[slot]
1916
+ if ((flag & IN_RULED) !== 0) return 0
1917
+ state.flags[slot] = (flag & ~IN_PLAIN) | IN_RULED
1918
+ state.ruledList[state.ruledCount] = slot
1919
+ state.ruledCount = state.ruledCount + 1
1920
+ if ((flag & IN_PLAIN) !== 0) return 0
1921
+ return 1
1922
+ }
1923
+
1924
+ /** The key at `at` put at rest at `value`, drawn there at the next step and resting there, a tween's too. */
1925
+ const restAt = <S>(state: State<S>, at: number, value: number): void => {
1926
+ state.positions[at] = value
1927
+ state.targets[at] = value
1928
+ state.origins[at] = value
1929
+ state.velocities[at] = 0
1930
+ // Past any delay and duration: its next step lands it where it is.
1931
+ state.elapsed[at] = Number.POSITIVE_INFINITY
1932
+ moving(state, slotAt(state, at))
1933
+ }
1934
+
1935
+ /** Ends `animation` where it is: the keys it moves stay there, at rest. */
1936
+ export const stop = (self: Animation): void => {
1937
+ const animation = animationOf(self)
1938
+ if (!animation.playing) return
1939
+ const { state } = animation
1940
+ // Once a stop, per key it moves: one a later change took stays that change's.
1941
+ for (let i = 0; i < animation.ats.length; i++) {
1942
+ if (!holds(animation, i)) continue
1943
+ const at = animation.ats[i]
1944
+ restAt(state, at, state.positions[at])
1945
+ }
1946
+ finish(animation)
1947
+ }
1948
+
1949
+ /** Ends `animation`, and puts the keys it moved back where it started them, at rest. */
1950
+ export const cancel = (self: Animation): void => {
1951
+ const animation = animationOf(self)
1952
+ const { state } = animation
1953
+ // Once a cancel, per key it moved: one a later change took stays that change's.
1954
+ for (let i = 0; i < animation.ats.length; i++) {
1955
+ if (state.targets[animation.ats[i]] !== animation.goals[i]) continue
1956
+ restAt(state, animation.ats[i], animation.starts[i])
1957
+ }
1958
+ finish(animation)
1959
+ }
1960
+
1961
+ /**
1962
+ * How long a key runs, stepped at 60 Hz: the frames until its time, summed as its steps sum it, less
1963
+ * `after`, reaches `seconds`. A tween or keyframes ends at its end from its start, as `Machine.durationOf`
1964
+ * steps one; a spring set by its duration, its duration past its delay, as its step reads it. `Infinity`
1965
+ * for one not done by `Machine.MAX_DURATION`.
1966
+ */
1967
+ // 105 frames sum to 1.7499999999999987: a key ending at 1.75 lands at the 106th, where rounding to frames said 105.
1968
+ const framesUntil = (seconds: number, after = 0): number => {
1969
+ const most = Math.ceil(Machine.MAX_DURATION / FRAME)
1970
+ let time = 0
1971
+ // Once a duration, per distinct end: a counted loop.
1972
+ for (let f = 0; f <= most; f++) {
1973
+ if (time - after >= seconds) return f * FRAME
1974
+ time += FRAME
1975
+ }
1976
+ return Number.POSITIVE_INFINITY
1977
+ }
1978
+
1979
+ /**
1980
+ * How long `animation` runs, in seconds: its longest key's, a spring's until it rests, stepped from its
1981
+ * start at 60 Hz as `Machine.durationOf` steps a machine. Worked out once.
1982
+ */
1983
+ // Stepped here, not through `Machine.durationOf`, which would build a machine for each member's key.
1984
+ export const durationOf = (self: Animation): number => {
1985
+ const animation = animationOf(self)
1986
+ if (Predicate.isNotUndefined(animation.duration)) return animation.duration
1987
+ const { state } = animation
1988
+ if (!animation.started) startOf(animation)
1989
+ const most = Math.ceil(Machine.MAX_DURATION / FRAME)
1990
+ let longest = 0
1991
+ // Keyframes: each key's end, its wait; a sequence's keys share theirs.
1992
+ if (Predicate.isNotUndefined(animation.keyframesOf)) {
1993
+ const known = new Map<number, number>()
1994
+ for (let i = 0; i < animation.waits.length; i++) {
1995
+ const end = animation.waits[i]
1996
+ let seconds = known.get(end)
1997
+ if (Predicate.isUndefined(seconds)) {
1998
+ seconds = framesUntil(end)
1999
+ known.set(end, seconds)
2000
+ }
2001
+ longest = Math.max(longest, seconds)
2002
+ }
2003
+ animation.duration = longest
2004
+ return longest
2005
+ }
2006
+ // Once an animation, per key: a counted loop to its rest.
2007
+ for (let i = 0; i < animation.ats.length; i++) {
2008
+ const at = animation.ats[i]
2009
+ const slot = slotAt(state, at)
2010
+ const entry = entryFor(animation.bag(slot, at - slot * state.stride))
2011
+ const delay = entry.delay + animation.waits[i]
2012
+ const goal = animation.goals[i]
2013
+ const distance = goal - animation.starts[i]
2014
+ if (entry.kind === TWEEN) {
2015
+ longest = Math.max(longest, framesUntil(delay + entry.tween.duration))
2016
+ continue
2017
+ }
2018
+ if (entry.kind === TIMED) {
2019
+ longest = Math.max(longest, framesUntil(entry.spring.duration, delay))
2020
+ continue
2021
+ }
2022
+ const restDelta = Spring.restDeltaFor(entry.spring, distance)
2023
+ const restSpeed = Spring.restSpeedFor(entry.spring, distance)
2024
+ let position = animation.starts[i]
2025
+ let speed = animation.speeds[i]
2026
+ let time = 0
2027
+ let steps = most
2028
+ for (let f = 1; f <= most; f++) {
2029
+ time += FRAME
2030
+ const simDt = Math.max(0, Math.min(FRAME, time - delay))
2031
+ if (simDt > 0) {
2032
+ const m = Spring.matrixFor(entry.spring, simDt)
2033
+ const d = position - goal
2034
+ position = goal + m.dd * d + m.dv * speed
2035
+ speed = m.vd * d + m.vv * speed
2036
+ if (Math.abs(speed) <= restSpeed && Math.abs(position - goal) <= restDelta) {
2037
+ steps = f
2038
+ break
2039
+ }
2040
+ }
2041
+ }
2042
+ longest = Math.max(longest, steps * FRAME)
2043
+ }
2044
+ animation.duration = longest
2045
+ return longest
2046
+ }
2047
+
2048
+ /** A sink that keeps nothing: a Batch's run writes as it steps. */
2049
+ const ignore = (): undefined => undefined
2050
+
2051
+ /** `self`'s run numbered `id`: a step each tick, until nothing moves. */
2052
+ const machineOf = <S>(self: Batch<S>, id: number): Machine.Machine<Frame.Frame<number>> => {
2053
+ const state = stateOf(self)
2054
+ return Machine.make({
2055
+ settles: true,
2056
+ span: { name: "wardic.batch", attributes: { keys: state.stride } },
2057
+ start: () => {
2058
+ const frame = { value: 0, done: false }
2059
+ // Per frame (ADR-0025): the step, and its count of members moving.
2060
+ return (dt) => {
2061
+ const done = step(self, dt)
2062
+ frame.value = state.plainCount + state.ruledCount
2063
+ if (!done) return frame
2064
+ frame.done = true
2065
+ // Marked ended in the step that rests, so a change later in the same tick starts the next run.
2066
+ if (state.running === id) state.running = 0
2067
+ return frame
2068
+ }
2069
+ },
2070
+ })
2071
+ }
2072
+
2073
+ /**
2074
+ * Runs `self` on the Frame loop while any member moves, from the next tick: each tick steps every
2075
+ * moving member and writes it. It succeeds once nothing moves. While one runs, another does nothing,
2076
+ * so a binding calls it after each change.
2077
+ *
2078
+ * @example
2079
+ * Batch.retarget(grid, slots, targetOf)
2080
+ * runtime.runFork(Batch.run(grid))
2081
+ */
2082
+ // One run, not a fiber per member (ADR-0069, decision 10). Its span is `wardic.batch`.
2083
+ export const run = <S>(self: Batch<S>): Effect.Effect<void, never, FrameLoop.FrameLoop> =>
2084
+ Effect.suspend(() => {
2085
+ const state = stateOf(self)
2086
+ if (state.running !== 0) return Effect.void
2087
+ if (state.plainCount + state.ruledCount === 0) return Effect.void
2088
+ const id = state.runs + 1
2089
+ state.runs = id
2090
+ state.running = id
2091
+ return Effect.ensuring(
2092
+ Effect.asVoid(Machine.run(machineOf(self, id), ignore)),
2093
+ Effect.sync(() => {
2094
+ if (state.running === id) state.running = 0
2095
+ }),
2096
+ )
2097
+ })
2098
+
2099
+ /** `key`'s index among `state`'s keys, or a throw naming it. */
2100
+ const keyAt = <S>(state: State<S>, key: string): number => {
2101
+ const k = state.indexOfKey[key]
2102
+ if (Predicate.isNotUndefined(k)) return k
2103
+ throw new Machine.OptionError({ message: `Expected one of the Batch's keys, got ${JSON.stringify(key)}\n at ["key"]` })
2104
+ }
2105
+
2106
+ /** A member's value for `key` now. */
2107
+ // Per frame: a sink may read it for every member.
2108
+ export const get = <S>(self: Batch<S>, slot: number, key: string): number => {
2109
+ const state = stateOf(self)
2110
+ return state.positions[slot * state.stride + keyAt(state, key)]
2111
+ }
2112
+
2113
+ /** A member's target for `key` now: where a change last turned it, toward which it moves or rests. */
2114
+ // At a change, per key of a member a driver holds (#665's PR 4): whether the change moves it.
2115
+ export const target = <S>(self: Batch<S>, slot: number, key: string): number => {
2116
+ const state = stateOf(self)
2117
+ return state.targets[slot * state.stride + keyAt(state, key)]
2118
+ }
2119
+
2120
+ /** A member's velocity for `key` now, per second: what an animation that takes the key over starts with. */
2121
+ // Per frame, as `get`.
2122
+ export const velocity = <S>(self: Batch<S>, slot: number, key: string): number => {
2123
+ const state = stateOf(self)
2124
+ const at = slot * state.stride + keyAt(state, key)
2125
+ // Held by a paused Playhead, it reads 0 (#464).
2126
+ if (state.animations.size > 0 && heldAt(state, at)) return 0
2127
+ return state.velocities[at]
2128
+ }