skia-motion-runtime 0.0.0-stage → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE.md +62 -0
- package/package.json +44 -4
- package/runtime/asset-draw.ts +262 -0
- package/runtime/asset-image.ts +64 -0
- package/runtime/asset-layout.ts +22 -0
- package/runtime/asset-mesh.ts +37 -0
- package/runtime/asset.ts +410 -0
- package/runtime/index.ts +7 -0
- package/runtime/machine-schema.d.ts +6 -0
- package/runtime/machine-schema.js +384 -0
- package/runtime/mobile.tsx +158 -0
- package/runtime/useMachine.ts +206 -0
- package/runtime/version.ts +37 -0
- package/templates/motion/face.ts +118 -0
- package/templates/motion/machine.ts +647 -0
- package/templates/motion/motion.ts +215 -0
- package/README.md +0 -3
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
// machine.ts: the skac.machine/1 core (skac docs machine), an engine file like motion.ts. It imports only the motion
|
|
2
|
+
// engine's curves, so it runs the same in Node (the CLI's checks), in Remotion and on the app's UI thread. Every
|
|
3
|
+
// function is a worklet. The app imports it through skia-motion-agentic-cli/runtime, never as a copy.
|
|
4
|
+
// Define each worklet helper before its callers. Babel initializes worklets with factory calls that capture their dependencies immediately.
|
|
5
|
+
//
|
|
6
|
+
// One pure function does the work: advance(compiled, snapshot, toMs, writes, clock) -> snapshot. The CLI replays a
|
|
7
|
+
// log through it from the start; the app advances it each frame from the last frame's snapshot. Because a value can
|
|
8
|
+
// change only at a write (the app's or an action's), every condition changes only at a write, an exit-time crossing
|
|
9
|
+
// or a mix's end, and advance jumps from one such instant to the next. Splitting a run into frames therefore gives
|
|
10
|
+
// the same snapshot as running it whole.
|
|
11
|
+
import { EASE_IN, EASE_IN_OUT, EASE_OUT } from './motion';
|
|
12
|
+
|
|
13
|
+
export const SCHEMA = 'skac.machine/1';
|
|
14
|
+
/** Rive's cap, kept: one layer changes state at most this often in one instant. */
|
|
15
|
+
export const MAX_CHANGES = 100;
|
|
16
|
+
|
|
17
|
+
export type Literal = boolean | number | string;
|
|
18
|
+
export type PartBox = { x: number; y: number; w: number; h: number; rot?: number };
|
|
19
|
+
export type Pose = { channels: Record<string, number>; parts?: Record<string, PartBox> };
|
|
20
|
+
export type Clip = { ms: number; reducedAt?: number; play: (localMs: number) => Pose };
|
|
21
|
+
export type Clips = Record<string, Clip>;
|
|
22
|
+
/** A value write at `at` ms of machine time. A trigger is written with `to: true`. */
|
|
23
|
+
/** A write of `to` into `value` at machine time `at`; `hit` marks the machine's own (a hit area's action), which may write an out-value. */
|
|
24
|
+
export type Write = { at: number; value: string; to: Literal; hit?: boolean };
|
|
25
|
+
/** The reading of a named clock, in ms. The CLI simulates it from machine time; the app reads its shared value. */
|
|
26
|
+
export type ClockRead = (name: string, t: number) => number;
|
|
27
|
+
export type StateEntry = { layer: string; state: string; at: number };
|
|
28
|
+
|
|
29
|
+
type Condition = readonly Literal[];
|
|
30
|
+
type Action = { set?: string; to?: Literal; fire?: string };
|
|
31
|
+
// The CLI validates literal choices and tuple shapes. JSON imports widen those to strings and arrays.
|
|
32
|
+
export type Machine = {
|
|
33
|
+
schema: string;
|
|
34
|
+
values?: Record<string, { type: string; default?: Literal; options?: readonly string[]; bind?: string }>;
|
|
35
|
+
clocks?: Record<string, { wrap_ms?: number; step_hz: number }>;
|
|
36
|
+
layers: readonly {
|
|
37
|
+
name: string;
|
|
38
|
+
entry: string | readonly { to: string; when?: readonly Condition[] }[];
|
|
39
|
+
clock?: string;
|
|
40
|
+
states: Record<string, {
|
|
41
|
+
clip?: string; loop?: string; speed?: number; reason?: string;
|
|
42
|
+
blend?: { by: string; keys: readonly (readonly (number | string)[])[] }; on_enter?: readonly Action[]; on_exit?: readonly Action[];
|
|
43
|
+
} | undefined>;
|
|
44
|
+
transitions?: readonly {
|
|
45
|
+
from: string; to: string; when?: readonly Condition[]; exit_at?: number; duration_ms?: number;
|
|
46
|
+
ease?: string; on_start?: readonly Action[]; on_end?: readonly Action[];
|
|
47
|
+
}[];
|
|
48
|
+
}[];
|
|
49
|
+
hits?: readonly { part: string; on: string; set?: string; to?: Literal; fire?: string }[];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Compiled forms: names resolved to indices once, on load.
|
|
53
|
+
const OP = { '==': 0, '!=': 1, '<': 2, '<=': 3, '>': 4, '>=': 5 } as const;
|
|
54
|
+
const TRIGGER_OP = 6;
|
|
55
|
+
const LOOP = { once: 0, loop: 1, pingpong: 2 } as const;
|
|
56
|
+
const EASE = { linear: 0, out: 1, inOut: 2, in: 3 } as const;
|
|
57
|
+
const EXIT = -2;
|
|
58
|
+
const ANY = -1;
|
|
59
|
+
|
|
60
|
+
/** [value index, op, operand value index or -1, literal operand] */
|
|
61
|
+
type CCond = [number, number, number, Literal];
|
|
62
|
+
/** [value index, operand value index or -1, literal, fire] */
|
|
63
|
+
type CAction = [number, number, Literal, boolean];
|
|
64
|
+
type CState = {
|
|
65
|
+
name: string; clip: string; keys: [number, string][] | null; by: number; loop: number; speed: number; ms: number;
|
|
66
|
+
enter: CAction[]; exit: CAction[]; reason: string;
|
|
67
|
+
};
|
|
68
|
+
type CTrans = { from: number; to: number; when: CCond[]; triggers: number[]; exitAt: number; dur: number; ease: number; start: CAction[]; end: CAction[] };
|
|
69
|
+
type CLayer = {
|
|
70
|
+
name: string; clock: string; wrap: number; states: CState[]; entry: { to: number; when: CCond[] }[];
|
|
71
|
+
trans: CTrans[]; any: number[]; byState: number[][];
|
|
72
|
+
};
|
|
73
|
+
export type Compiled = {
|
|
74
|
+
values: { name: string; type: string; def: Literal; bind: string; options: readonly string[] }[];
|
|
75
|
+
index: Record<string, number>;
|
|
76
|
+
layers: CLayer[];
|
|
77
|
+
hits: { part: string; on: string; action: CAction }[];
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** One layer's place: its state (or EXIT, holding `heldS` at `held` with blend input `heldBy`), when it entered, and any mix running. */
|
|
81
|
+
export type LayerSnap = {
|
|
82
|
+
s: number; at: number; cAt: number; held: number; heldS: number; heldBy: number;
|
|
83
|
+
mixFrom: number; mixAt: number; mixCAt: number; mixStart: number; mixEnd: number; mixTr: number;
|
|
84
|
+
};
|
|
85
|
+
/** Everything the machine knows at `t`: values and each layer. Plain numbers, so it copies to the UI thread. */
|
|
86
|
+
export type Snapshot = { t: number; vals: Literal[]; layers: LayerSnap[] };
|
|
87
|
+
|
|
88
|
+
function clipOf(clips: Clips, name: string): Clip {
|
|
89
|
+
'worklet';
|
|
90
|
+
const c = clips[name];
|
|
91
|
+
if (!c) throw new Error(`skac runtime: no clip named "${name}"`);
|
|
92
|
+
return c;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Resolve a machine (already judged by `skac <Name> --machine`) against its clips. Throws on a schema it cannot read. */
|
|
96
|
+
export function compile(m: Machine, clips: Clips): Compiled {
|
|
97
|
+
'worklet';
|
|
98
|
+
if (m.schema !== SCHEMA) throw new Error(`skac runtime reads ${SCHEMA}, not ${String(m.schema)}: update skia-motion-agentic-cli`);
|
|
99
|
+
const values: Compiled['values'] = [];
|
|
100
|
+
const index: Record<string, number> = {};
|
|
101
|
+
for (const name of Object.keys(m.values ?? {})) {
|
|
102
|
+
const v = m.values![name]!;
|
|
103
|
+
index[name] = values.length;
|
|
104
|
+
const def: Literal = v.default !== undefined ? v.default : v.type === 'number' ? 0 : v.type === 'enum' ? v.options![0]! : false;
|
|
105
|
+
values.push({ name, type: v.type, def, bind: v.bind ?? 'in', options: v.options ?? [] });
|
|
106
|
+
}
|
|
107
|
+
// A string operand names a value unless it is an option of the enum it is compared with or written to.
|
|
108
|
+
const ref = (x: Literal, owner: string): number =>
|
|
109
|
+
(typeof x === 'string' && index[x] !== undefined && !(m.values?.[owner]?.options ?? []).includes(x) ? index[x]! : -1);
|
|
110
|
+
const conds = (when: readonly Condition[] | undefined): CCond[] =>
|
|
111
|
+
(when ?? []).map(([name, op, rhs]): CCond => {
|
|
112
|
+
const owner = name as string;
|
|
113
|
+
return op === undefined ? [index[owner]!, TRIGGER_OP, -1, true]
|
|
114
|
+
: [index[owner]!, OP[op as keyof typeof OP], ref(rhs!, owner), rhs!];
|
|
115
|
+
});
|
|
116
|
+
const acts = (list: readonly Action[] | undefined): CAction[] =>
|
|
117
|
+
(list ?? []).map((a) => (a.fire !== undefined
|
|
118
|
+
? [index[a.fire]!, -1, true, true] as CAction
|
|
119
|
+
: [index[a.set!]!, ref(a.to!, a.set!), a.to!, false] as CAction));
|
|
120
|
+
const layers: CLayer[] = m.layers.map((L) => {
|
|
121
|
+
const names = Object.keys(L.states);
|
|
122
|
+
const at = (n: string) => (n === 'exit' ? EXIT : n === '*' ? ANY : names.indexOf(n));
|
|
123
|
+
const states: CState[] = names.map((n) => {
|
|
124
|
+
const s = L.states[n]!;
|
|
125
|
+
const keys = s.blend ? s.blend.keys.map((k) => [k[0], k[1]] as [number, string]) : null;
|
|
126
|
+
const lengths = keys ? keys.map((k) => clipOf(clips, k[1]).ms) : [s.clip ? clipOf(clips, s.clip).ms : 0];
|
|
127
|
+
return {
|
|
128
|
+
name: n, clip: s.clip ?? '', keys, by: s.blend ? index[s.blend.by]! : -1, loop: LOOP[(s.loop ?? 'once') as keyof typeof LOOP], speed: s.speed ?? 1,
|
|
129
|
+
ms: Math.max(...lengths), enter: acts(s.on_enter), exit: acts(s.on_exit), reason: s.reason ?? '',
|
|
130
|
+
};
|
|
131
|
+
});
|
|
132
|
+
const trans: CTrans[] = (L.transitions ?? []).map((t) => {
|
|
133
|
+
const when = conds(t.when);
|
|
134
|
+
return {
|
|
135
|
+
from: at(t.from), to: at(t.to), when, triggers: when.filter((c) => c[1] === TRIGGER_OP).map((c) => c[0]),
|
|
136
|
+
exitAt: t.exit_at ?? -1, dur: t.duration_ms ?? 0, ease: EASE[(t.ease ?? 'linear') as keyof typeof EASE], start: acts(t.on_start), end: acts(t.on_end),
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
const entry = typeof L.entry === 'string' ? [{ to: at(L.entry), when: [] as CCond[] }] : L.entry.map((e) => ({ to: at(e.to), when: conds(e.when) }));
|
|
140
|
+
const clock = L.clock ?? '';
|
|
141
|
+
return {
|
|
142
|
+
name: L.name, clock, wrap: clock ? m.clocks![clock]!.wrap_ms ?? 0 : 0, states, entry, trans,
|
|
143
|
+
any: trans.map((t, i) => (t.from === ANY ? i : -1)).filter((i) => i >= 0),
|
|
144
|
+
byState: states.map((_, si) => trans.map((t, i) => (t.from === si ? i : -1)).filter((i) => i >= 0)),
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
const hits = (m.hits ?? []).map((h) => ({
|
|
148
|
+
part: h.part, on: h.on,
|
|
149
|
+
action: (h.fire !== undefined ? [index[h.fire]!, -1, true, true] : [index[h.set!]!, ref(h.to!, h.set!), h.to!, false]) as CAction,
|
|
150
|
+
}));
|
|
151
|
+
return { values, index, layers, hits };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The machine before its first instant: defaults set, no layer entered. advance(…, 0, …) enters them. */
|
|
155
|
+
export function start(c: Compiled): Snapshot {
|
|
156
|
+
'worklet';
|
|
157
|
+
return {
|
|
158
|
+
t: -1,
|
|
159
|
+
vals: c.values.map((v) => (v.type === 'trigger' ? false : v.def)),
|
|
160
|
+
layers: c.layers.map(() => ({ s: -1, at: 0, cAt: 0, held: 0, heldS: -1, heldBy: 0, mixFrom: -1, mixAt: 0, mixCAt: 0, mixStart: 0, mixEnd: 0, mixTr: -1 })),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function copy(s: Snapshot): Snapshot {
|
|
165
|
+
'worklet';
|
|
166
|
+
return { t: s.t, vals: s.vals.slice(), layers: s.layers.map((l) => ({ ...l })) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function holds(c: CCond, vals: Literal[], used: number[]): boolean {
|
|
170
|
+
'worklet';
|
|
171
|
+
const a = vals[c[0]]!;
|
|
172
|
+
if (c[1] === TRIGGER_OP) return a === true && used.indexOf(c[0]) < 0;
|
|
173
|
+
const b = c[2] >= 0 ? vals[c[2]]! : c[3];
|
|
174
|
+
switch (c[1]) {
|
|
175
|
+
case 0: return a === b;
|
|
176
|
+
case 1: return a !== b;
|
|
177
|
+
case 2: return (a as number) < (b as number);
|
|
178
|
+
case 3: return (a as number) <= (b as number);
|
|
179
|
+
case 4: return (a as number) > (b as number);
|
|
180
|
+
default: return (a as number) >= (b as number);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function allHold(when: CCond[], vals: Literal[], used: number[]): boolean {
|
|
185
|
+
'worklet';
|
|
186
|
+
for (const c of when) if (!holds(c, vals, used)) return false;
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function run(actions: CAction[], vals: Literal[]): void {
|
|
191
|
+
'worklet';
|
|
192
|
+
for (const a of actions) vals[a[0]] = a[3] ? true : a[1] >= 0 ? vals[a[1]]! : a[2];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** When the exit time of transition `tr` falls for layer `l`, in machine ms; -1 when it has none. Frame-clock layers only. */
|
|
196
|
+
function exitTime(L: CLayer, l: LayerSnap, tr: CTrans): number {
|
|
197
|
+
'worklet';
|
|
198
|
+
if (tr.exitAt < 0 || l.s < 0) return -1;
|
|
199
|
+
const st = L.states[l.s]!;
|
|
200
|
+
return l.at + (tr.exitAt * st.ms) / st.speed;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function sinceEntry(L: CLayer, at: number, cAt: number, t: number, clock: ClockRead): number {
|
|
204
|
+
'worklet';
|
|
205
|
+
if (!L.clock) return Math.max(0, t - at);
|
|
206
|
+
const d = clock(L.clock, t) - cAt;
|
|
207
|
+
return L.wrap > 0 ? ((d % L.wrap) + L.wrap) % L.wrap : Math.max(0, d);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A layer's time inside its current state, in clip ms before looping: frame time, or its named clock since entry. */
|
|
211
|
+
function localMs(L: CLayer, l: LayerSnap, t: number, clock: ClockRead): number {
|
|
212
|
+
'worklet';
|
|
213
|
+
const st = L.states[l.s]!;
|
|
214
|
+
return sinceEntry(L, l.at, l.cAt, t, clock) * st.speed;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Enter state `to` of layer `li` at `t` from its current one, through transition `tr` (or none, on entry). */
|
|
218
|
+
function enter(c: Compiled, s: Snapshot, li: number, to: number, tr: CTrans | null, t: number, clock: ClockRead, entries?: StateEntry[]): void {
|
|
219
|
+
'worklet';
|
|
220
|
+
const L = c.layers[li]!;
|
|
221
|
+
const l = s.layers[li]!;
|
|
222
|
+
const from = l.s;
|
|
223
|
+
if (from >= 0) run(L.states[from]!.exit, s.vals);
|
|
224
|
+
if (tr) run(tr.start, s.vals);
|
|
225
|
+
const reading = L.clock ? clock(L.clock, t) : 0;
|
|
226
|
+
if (to === EXIT) {
|
|
227
|
+
l.held = from >= 0 ? localMs(L, l, t, clock) : 0;
|
|
228
|
+
l.heldS = from;
|
|
229
|
+
const by = from >= 0 ? L.states[from]!.by : -1;
|
|
230
|
+
l.heldBy = by >= 0 ? (s.vals[by] as number) : 0;
|
|
231
|
+
l.s = EXIT;
|
|
232
|
+
l.mixTr = -1;
|
|
233
|
+
if (tr) run(tr.end, s.vals);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (tr && tr.dur > 0 && from >= 0) {
|
|
237
|
+
l.mixFrom = from; l.mixAt = l.at; l.mixCAt = l.cAt; l.mixStart = t; l.mixEnd = t + tr.dur;
|
|
238
|
+
l.mixTr = L.trans.indexOf(tr);
|
|
239
|
+
} else {
|
|
240
|
+
l.mixTr = -1;
|
|
241
|
+
}
|
|
242
|
+
l.s = to; l.at = t; l.cAt = reading;
|
|
243
|
+
if (entries) entries.push({ layer: L.name, state: L.states[to]!.name, at: t });
|
|
244
|
+
run(L.states[to]!.enter, s.vals);
|
|
245
|
+
if (tr && l.mixTr < 0) run(tr.end, s.vals);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Try layer `li`'s transitions at `t`, Any State first, then the current state's. True when one fired. */
|
|
249
|
+
function step(c: Compiled, s: Snapshot, li: number, t: number, clock: ClockRead, used: number[], entries?: StateEntry[]): boolean {
|
|
250
|
+
'worklet';
|
|
251
|
+
const L = c.layers[li]!;
|
|
252
|
+
const l = s.layers[li]!;
|
|
253
|
+
if (l.s < 0) return false; // exited, or not entered yet
|
|
254
|
+
if (l.mixTr >= 0) return false; // Rive's default: no exit during a transition
|
|
255
|
+
const lists = [L.any, L.byState[l.s]!];
|
|
256
|
+
for (const list of lists) {
|
|
257
|
+
for (const i of list) {
|
|
258
|
+
const tr = L.trans[i]!;
|
|
259
|
+
if (tr.from === ANY && tr.to === l.s) continue;
|
|
260
|
+
if (tr.exitAt >= 0 && t < exitTime(L, l, tr)) continue;
|
|
261
|
+
if (!allHold(tr.when, s.vals, used)) continue;
|
|
262
|
+
for (const v of tr.triggers) used.push(v);
|
|
263
|
+
enter(c, s, li, tr.to, tr, t, clock, entries);
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Why an outside write (the app's set or fire, a CLI event) of `to` into `name` is refused, or '' when the machine takes it:
|
|
272
|
+
* the value must exist, be an in or both value, and `to` must fit its type (a trigger takes true).
|
|
273
|
+
*/
|
|
274
|
+
export function writeProblem(c: Compiled, name: string, to: Literal): string {
|
|
275
|
+
'worklet';
|
|
276
|
+
const i = c.index[name];
|
|
277
|
+
if (i === undefined) return `the machine has no value "${name}"`;
|
|
278
|
+
const v = c.values[i]!;
|
|
279
|
+
if (v.bind === 'out') return `"${name}" is an out-value: the machine writes it, the app reads it`;
|
|
280
|
+
const fits = v.type === 'trigger' ? to === true
|
|
281
|
+
: v.type === 'boolean' ? typeof to === 'boolean'
|
|
282
|
+
: v.type === 'number' ? typeof to === 'number' && Number.isFinite(to)
|
|
283
|
+
: typeof to === 'string' && v.options.includes(to);
|
|
284
|
+
if (fits) return '';
|
|
285
|
+
const wanted = v.type === 'trigger' ? 'a fire (true)' : v.type === 'enum' ? `one of ${v.options.join(', ')}` : `a ${v.type}`;
|
|
286
|
+
return `"${name}" takes ${wanted}, not ${JSON.stringify(to)}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Everything due at instant `t`: its writes, ending mixes, entry at 0, then every layer's transitions until none fires. */
|
|
290
|
+
function instant(c: Compiled, s: Snapshot, t: number, writes: Write[], clock: ClockRead, entries?: StateEntry[]): void {
|
|
291
|
+
'worklet';
|
|
292
|
+
for (const w of writes) {
|
|
293
|
+
const i = c.index[w.value];
|
|
294
|
+
if (i === undefined || (!w.hit && writeProblem(c, w.value, w.to))) continue; // the hook and the rig refuse these first
|
|
295
|
+
s.vals[i] = c.values[i]!.type === 'trigger' ? true : w.to;
|
|
296
|
+
}
|
|
297
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
298
|
+
const l = s.layers[li]!;
|
|
299
|
+
if (l.mixTr >= 0 && l.mixEnd <= t) {
|
|
300
|
+
const tr = c.layers[li]!.trans[l.mixTr]!;
|
|
301
|
+
l.mixTr = -1;
|
|
302
|
+
run(tr.end, s.vals);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (s.t < 0) {
|
|
306
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
307
|
+
const branch = c.layers[li]!.entry.find((e) => allHold(e.when, s.vals, [])) ?? c.layers[li]!.entry[c.layers[li]!.entry.length - 1]!;
|
|
308
|
+
enter(c, s, li, branch.to, null, t, clock);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const used: number[][] = c.layers.map(() => []);
|
|
312
|
+
const changes = c.layers.map(() => 0);
|
|
313
|
+
let changed = true;
|
|
314
|
+
while (changed) {
|
|
315
|
+
changed = false;
|
|
316
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
317
|
+
if (changes[li]! >= MAX_CHANGES) continue;
|
|
318
|
+
if (step(c, s, li, t, clock, used[li]!, entries)) {
|
|
319
|
+
changes[li]! += 1;
|
|
320
|
+
changed = true;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
for (let i = 0; i < c.values.length; i++) if (c.values[i]!.type === 'trigger') s.vals[i] = false;
|
|
325
|
+
s.t = t;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** The next instant after `s.t` at which something is due without a write: an exit time or a mix's end. */
|
|
329
|
+
function nextDue(c: Compiled, s: Snapshot): number {
|
|
330
|
+
'worklet';
|
|
331
|
+
let next = Infinity;
|
|
332
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
333
|
+
const L = c.layers[li]!;
|
|
334
|
+
const l = s.layers[li]!;
|
|
335
|
+
if (l.s < 0) continue;
|
|
336
|
+
if (l.mixTr >= 0) { if (l.mixEnd > s.t) next = Math.min(next, l.mixEnd); continue; }
|
|
337
|
+
if (L.clock) continue; // exit times are refused on named-clock layers
|
|
338
|
+
for (const list of [L.any, L.byState[l.s]!]) {
|
|
339
|
+
for (const i of list) {
|
|
340
|
+
const e = exitTime(L, l, L.trans[i]!);
|
|
341
|
+
if (e > s.t) next = Math.min(next, e);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return next;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* The machine at `toMs`, from `s`, with `writes` applied at their times (those after `s.t` and at or before `toMs`;
|
|
350
|
+
* a write before 0 applies at 0). Pure: `s` is not changed.
|
|
351
|
+
*/
|
|
352
|
+
export function advance(c: Compiled, s: Snapshot, toMs: number, writes: Write[], clock: ClockRead, entries?: StateEntry[]): Snapshot {
|
|
353
|
+
'worklet';
|
|
354
|
+
const out = copy(s);
|
|
355
|
+
const due = writes
|
|
356
|
+
.map((w, i) => ({ w, i, at: Math.max(0, w.at) }))
|
|
357
|
+
.filter((x) => x.at > out.t && x.at <= toMs)
|
|
358
|
+
.sort((a, b) => a.at - b.at || a.i - b.i);
|
|
359
|
+
let k = 0;
|
|
360
|
+
if (out.t < 0 && toMs >= 0) {
|
|
361
|
+
const atZero: Write[] = [];
|
|
362
|
+
while (k < due.length && due[k]!.at === 0) atZero.push(due[k++]!.w);
|
|
363
|
+
instant(c, out, 0, atZero, clock);
|
|
364
|
+
}
|
|
365
|
+
for (let guard = 0; guard < 100000; guard++) {
|
|
366
|
+
if (out.t < 0) break;
|
|
367
|
+
const nextWrite = k < due.length ? due[k]!.at : Infinity;
|
|
368
|
+
const t = Math.min(nextWrite, nextDue(c, out));
|
|
369
|
+
if (!(t <= toMs)) break;
|
|
370
|
+
const now: Write[] = [];
|
|
371
|
+
while (k < due.length && due[k]!.at === t) now.push(due[k++]!.w);
|
|
372
|
+
instant(c, out, t, now, clock, entries);
|
|
373
|
+
}
|
|
374
|
+
if (out.t >= 0) out.t = Math.max(out.t, toMs);
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** A clip's own time for a state's loop mode; under reduced motion a once-clip shows its end and a loop its start. */
|
|
379
|
+
function clipTime(loop: number, ms: number, local: number, reduced: boolean, reducedAt?: number): number {
|
|
380
|
+
'worklet';
|
|
381
|
+
if (ms === 0) return 0;
|
|
382
|
+
if (reduced) return reducedAt ?? (loop === 0 ? ms : 0);
|
|
383
|
+
if (loop === 0) return Math.min(local, ms);
|
|
384
|
+
if (loop === 1) return local % ms;
|
|
385
|
+
const p = local % (2 * ms);
|
|
386
|
+
return p <= ms ? p : 2 * ms - p;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function lerpPose(a: Pose, b: Pose, w: number): Pose {
|
|
390
|
+
'worklet';
|
|
391
|
+
const channels: Record<string, number> = { ...a.channels };
|
|
392
|
+
for (const k of Object.keys(b.channels)) {
|
|
393
|
+
const bv = b.channels[k]!;
|
|
394
|
+
const av = a.channels[k];
|
|
395
|
+
channels[k] = av === undefined ? bv : av + (bv - av) * w;
|
|
396
|
+
}
|
|
397
|
+
let parts: Record<string, PartBox> | undefined;
|
|
398
|
+
if (a.parts || b.parts) {
|
|
399
|
+
parts = { ...(a.parts ?? {}) };
|
|
400
|
+
for (const k of Object.keys(b.parts ?? {})) {
|
|
401
|
+
const bp = b.parts![k]!;
|
|
402
|
+
const ap = a.parts?.[k];
|
|
403
|
+
if (ap === undefined) { parts[k] = bp; continue; }
|
|
404
|
+
const box: PartBox = { x: ap.x + (bp.x - ap.x) * w, y: ap.y + (bp.y - ap.y) * w, w: ap.w + (bp.w - ap.w) * w, h: ap.h + (bp.h - ap.h) * w };
|
|
405
|
+
// rot only when a side has it, so a part keeps the same fields on every frame.
|
|
406
|
+
if (ap.rot !== undefined || bp.rot !== undefined) box.rot = (ap.rot ?? 0) + ((bp.rot ?? 0) - (ap.rot ?? 0)) * w;
|
|
407
|
+
parts[k] = box;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return parts ? { channels, parts } : { channels };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** State `si`'s pose `local` ms in: its clip, or its 1D blend at the current value. */
|
|
414
|
+
function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips: Clips, reduced: boolean): Pose {
|
|
415
|
+
'worklet';
|
|
416
|
+
const st = L.states[si]!;
|
|
417
|
+
if (!st.keys) {
|
|
418
|
+
if (!st.clip) return { channels: {} };
|
|
419
|
+
const clip = clipOf(clips, st.clip);
|
|
420
|
+
return clip.play(clipTime(st.loop, clip.ms, local, reduced, clip.reducedAt));
|
|
421
|
+
}
|
|
422
|
+
const v = vals[st.by] as number;
|
|
423
|
+
const keys = st.keys;
|
|
424
|
+
const at = (k: [number, string]) => {
|
|
425
|
+
const clip = clipOf(clips, k[1]);
|
|
426
|
+
return clip.play(clipTime(st.loop, clip.ms, local, reduced, clip.reducedAt));
|
|
427
|
+
};
|
|
428
|
+
if (v <= keys[0]![0]) return at(keys[0]!);
|
|
429
|
+
for (let i = 1; i < keys.length; i++) {
|
|
430
|
+
if (v <= keys[i]![0]) {
|
|
431
|
+
const a = keys[i - 1]!;
|
|
432
|
+
const b = keys[i]!;
|
|
433
|
+
return lerpPose(at(a), at(b), (v - a[0]) / (b[0] - a[0]));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return at(keys[keys.length - 1]!);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function ease(kind: number, p: number): number {
|
|
440
|
+
'worklet';
|
|
441
|
+
const q = Math.min(1, Math.max(0, p));
|
|
442
|
+
if (kind === 1) return EASE_OUT(q);
|
|
443
|
+
if (kind === 2) return EASE_IN_OUT(q);
|
|
444
|
+
if (kind === 3) return EASE_IN(q);
|
|
445
|
+
return q;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* What the machine draws at `t` (at or after `s.t`, before the next instant): every layer's pose, mixes applied, a later
|
|
450
|
+
* layer's channel or part over an earlier one's.
|
|
451
|
+
*/
|
|
452
|
+
export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: ClockRead, reduced = false): Pose {
|
|
453
|
+
'worklet';
|
|
454
|
+
const channels: Record<string, number> = {};
|
|
455
|
+
let parts: Record<string, PartBox> | undefined;
|
|
456
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
457
|
+
const L = c.layers[li]!;
|
|
458
|
+
const l = s.layers[li]!;
|
|
459
|
+
let p: Pose;
|
|
460
|
+
if (l.s === EXIT) {
|
|
461
|
+
if (l.heldS < 0) continue;
|
|
462
|
+
// An exited layer holds its pose: a blend keeps the input it had when the layer exited.
|
|
463
|
+
const by = L.states[l.heldS]!.by;
|
|
464
|
+
let vals = s.vals;
|
|
465
|
+
if (by >= 0) { vals = s.vals.slice(); vals[by] = l.heldBy; }
|
|
466
|
+
p = statePose(L, l.heldS, l.held, vals, clips, reduced);
|
|
467
|
+
} else if (l.s < 0) {
|
|
468
|
+
continue;
|
|
469
|
+
} else {
|
|
470
|
+
p = statePose(L, l.s, localMs(L, l, t, clock), s.vals, clips, reduced);
|
|
471
|
+
if (l.mixTr >= 0 && t < l.mixEnd && !reduced) {
|
|
472
|
+
const from = L.states[l.mixFrom]!;
|
|
473
|
+
const fromPose = statePose(L, l.mixFrom, sinceEntry(L, l.mixAt, l.mixCAt, t, clock) * from.speed, s.vals, clips, reduced);
|
|
474
|
+
const tr = L.trans[l.mixTr]!;
|
|
475
|
+
p = lerpPose(fromPose, p, ease(tr.ease, (t - l.mixStart) / (l.mixEnd - l.mixStart)));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
for (const k of Object.keys(p.channels)) channels[k] = p.channels[k]!;
|
|
479
|
+
if (p.parts) parts = { ...(parts ?? {}), ...p.parts };
|
|
480
|
+
}
|
|
481
|
+
return parts ? { channels, parts } : { channels };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Whether the machine at `s` can change what it draws without a write. `frame` is false when every frame-clock layer
|
|
486
|
+
* rests (no mix, no exit time it could take, a still pose), so the app may stop its frame callback; layers on a named
|
|
487
|
+
* clock follow that clock instead and are listed in `clocked` while their pose moves with it.
|
|
488
|
+
*/
|
|
489
|
+
export function settled(c: Compiled, s: Snapshot, clock: ClockRead, reduced = false): { frame: boolean; awake: string[]; clocked: string[] } {
|
|
490
|
+
'worklet';
|
|
491
|
+
const awake: string[] = [];
|
|
492
|
+
const clocked: string[] = [];
|
|
493
|
+
for (let li = 0; li < c.layers.length; li++) {
|
|
494
|
+
const L = c.layers[li]!;
|
|
495
|
+
const l = s.layers[li]!;
|
|
496
|
+
if (l.s === EXIT) continue;
|
|
497
|
+
if (l.s < 0) { awake.push(L.name); continue; }
|
|
498
|
+
const st = L.states[l.s]!;
|
|
499
|
+
const moving = !reduced && st.loop !== 0 && st.ms > 0;
|
|
500
|
+
// A once-clip can start over at its entry phase on a wrapping clock.
|
|
501
|
+
// A mix and its on_end run on machine time, whatever clock the clips read.
|
|
502
|
+
if (L.clock && l.mixTr >= 0 && s.t < l.mixEnd) { awake.push(L.name); continue; }
|
|
503
|
+
if (L.clock) { if (!reduced && st.ms > 0 && (moving || L.wrap > 0 || localMs(L, l, s.t, clock) < st.ms)) clocked.push(L.name); continue; }
|
|
504
|
+
let busy = l.mixTr >= 0 && s.t < l.mixEnd;
|
|
505
|
+
if (!busy && moving) busy = true;
|
|
506
|
+
if (!busy && !reduced && st.ms > 0 && s.t < l.at + st.ms / st.speed) busy = true; // a once-clip still playing
|
|
507
|
+
if (!busy) {
|
|
508
|
+
for (const list of [L.any, L.byState[l.s]!]) {
|
|
509
|
+
for (const i of list) {
|
|
510
|
+
const tr = L.trans[i]!;
|
|
511
|
+
if (tr.exitAt >= 0 && exitTime(L, l, tr) > s.t && allHold(tr.when, s.vals, [])) busy = true;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (busy) awake.push(L.name);
|
|
516
|
+
}
|
|
517
|
+
return { frame: awake.length === 0, awake, clocked };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** The name of the first hit area whose part box (rotated about its centre, radians) holds the point, or ''. */
|
|
521
|
+
export function hitTest(c: Compiled, p: Pose, x: number, y: number): string {
|
|
522
|
+
'worklet';
|
|
523
|
+
for (const h of c.hits) {
|
|
524
|
+
const b = p.parts?.[h.part];
|
|
525
|
+
if (!b) continue;
|
|
526
|
+
const cx = b.x + b.w / 2;
|
|
527
|
+
const cy = b.y + b.h / 2;
|
|
528
|
+
const r = -(b.rot ?? 0);
|
|
529
|
+
const dx = (x - cx) * Math.cos(r) - (y - cy) * Math.sin(r);
|
|
530
|
+
const dy = (x - cx) * Math.sin(r) + (y - cy) * Math.cos(r);
|
|
531
|
+
if (Math.abs(dx) <= b.w / 2 && Math.abs(dy) <= b.h / 2) return h.part;
|
|
532
|
+
}
|
|
533
|
+
return '';
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** The writes a hit on `part` makes at `at`: its trigger, or its value set. */
|
|
537
|
+
export function hitWrites(c: Compiled, part: string, at: number, vals: Literal[]): Write[] {
|
|
538
|
+
'worklet';
|
|
539
|
+
const out: Write[] = [];
|
|
540
|
+
for (const h of c.hits) {
|
|
541
|
+
if (h.part !== part) continue;
|
|
542
|
+
const a = h.action;
|
|
543
|
+
out.push({ at, value: c.values[a[0]]!.name, to: a[3] ? true : a[1] >= 0 ? vals[a[1]]! : a[2], hit: true });
|
|
544
|
+
}
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** A named clock as the CLI simulates it: stepped at its rate from machine time 0, wrapping at its length. */
|
|
549
|
+
export function simulatedClock(m: Machine): ClockRead {
|
|
550
|
+
'worklet';
|
|
551
|
+
return (name: string, t: number) => {
|
|
552
|
+
'worklet';
|
|
553
|
+
const k = m.clocks?.[name];
|
|
554
|
+
if (!k) return t;
|
|
555
|
+
// Whole steps first, then ms: n * 1000 / hz is exact at every whole second, where floor(t / step) * step is not.
|
|
556
|
+
const n = Math.floor((Math.max(0, t) * k.step_hz) / 1000 + 1e-9);
|
|
557
|
+
const stepped = (n * 1000) / k.step_hz;
|
|
558
|
+
return k.wrap_ms ? stepped % k.wrap_ms : stepped;
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** An event a composition takes (seconds): a trigger `{name, at}`, a write `{name, to, at}`, or a hit `{pointer, x, y, at}`. */
|
|
563
|
+
export type MachineEvent = { name?: string; to?: Literal; pointer?: 'tap' | 'down' | 'up'; x?: number; y?: number; at: number };
|
|
564
|
+
export type MachineRig = ((ms: number, events?: MachineEvent[]) => Pose) & {
|
|
565
|
+
/** Each layer's state, the values, and what keeps the machine awake, at `ms`. For `--trace` and the settle rule. */
|
|
566
|
+
inspect: (ms: number, events?: MachineEvent[]) => {
|
|
567
|
+
states: Record<string, string>; values: Record<string, Literal>; awake: string[]; clocked: string[];
|
|
568
|
+
reasons: Record<string, string>; writes_ms: number[];
|
|
569
|
+
};
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* A rig(ms, events) for the CLI and Remotion: the machine replayed from its start to `ms` with the events as writes,
|
|
574
|
+
* named clocks simulated. A pointer event hit-tests the part boxes drawn at its instant and makes that hit's writes.
|
|
575
|
+
*/
|
|
576
|
+
// It runs on the JS thread (the CLI's rig); the directive keeps every engine export a worklet, as --export checks.
|
|
577
|
+
export function machineRig(m: Machine, clips: Clips, defaults: MachineEvent[] = []): MachineRig {
|
|
578
|
+
'worklet';
|
|
579
|
+
const c = compile(m, clips);
|
|
580
|
+
const clock = simulatedClock(m);
|
|
581
|
+
const wrappedMotion = new Map<string, boolean>();
|
|
582
|
+
const movesOnWrap = (L: CLayer, si: number, vals: Literal[]) => {
|
|
583
|
+
const st = L.states[si]!;
|
|
584
|
+
const end = Math.min(L.wrap * st.speed, st.ms);
|
|
585
|
+
if (!Number.isFinite(end)) return true;
|
|
586
|
+
const key = JSON.stringify([L.name, si, vals[st.by]]);
|
|
587
|
+
const cached = wrappedMotion.get(key);
|
|
588
|
+
if (cached !== undefined) return cached;
|
|
589
|
+
// Sample the effective pose at 120 Hz, including the phase endpoint. Bound the work for very long clips.
|
|
590
|
+
const keyAt = (ms: number) => JSON.stringify(statePose(L, si, ms, vals, clips, false));
|
|
591
|
+
const first = keyAt(0);
|
|
592
|
+
const steps = Math.min(12000, Math.ceil(end * 120 / 1000));
|
|
593
|
+
let moving = keyAt(end) !== first;
|
|
594
|
+
for (let i = 1; !moving && i < steps; i++) moving = keyAt(end * (i / steps)) !== first;
|
|
595
|
+
wrappedMotion.set(key, moving);
|
|
596
|
+
return moving;
|
|
597
|
+
};
|
|
598
|
+
const writesOf = (events: MachineEvent[]): Write[] => {
|
|
599
|
+
const writes: Write[] = [];
|
|
600
|
+
const sorted = events.map((e, i) => ({ e, i })).sort((a, b) => a.e.at - b.e.at || a.i - b.i);
|
|
601
|
+
for (const { e } of sorted) {
|
|
602
|
+
const at = e.at * 1000;
|
|
603
|
+
if (e.pointer) {
|
|
604
|
+
if (e.pointer !== 'tap') continue; // down and up hit areas wait for a runtime gesture model (M2)
|
|
605
|
+
const s = advance(c, start(c), at, writes, clock);
|
|
606
|
+
const part = hitTest(c, pose(c, clips, s, at, clock), e.x ?? 0, e.y ?? 0);
|
|
607
|
+
if (part) writes.push(...hitWrites(c, part, at, s.vals));
|
|
608
|
+
} else if (e.name !== undefined) {
|
|
609
|
+
const to = e.to ?? true;
|
|
610
|
+
const problem = writeProblem(c, e.name, to);
|
|
611
|
+
if (problem) throw new Error(`event ${e.name}${e.to === undefined ? '' : `=${String(e.to)}`}@${e.at}: ${problem}`);
|
|
612
|
+
writes.push({ at, value: e.name, to });
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return writes;
|
|
616
|
+
};
|
|
617
|
+
const at = (ms: number, events: MachineEvent[]) => {
|
|
618
|
+
const writes = writesOf(events);
|
|
619
|
+
return { writes, s: advance(c, start(c), ms, writes, clock) };
|
|
620
|
+
};
|
|
621
|
+
const rig = ((ms: number, events: MachineEvent[] = defaults) => {
|
|
622
|
+
const { s } = at(ms, events);
|
|
623
|
+
return pose(c, clips, s, ms, clock);
|
|
624
|
+
}) as MachineRig;
|
|
625
|
+
rig.inspect = (ms: number, events: MachineEvent[] = defaults) => {
|
|
626
|
+
const { s, writes } = at(ms, events);
|
|
627
|
+
const states: Record<string, string> = {};
|
|
628
|
+
const reasons: Record<string, string> = {};
|
|
629
|
+
c.layers.forEach((L, li) => {
|
|
630
|
+
const l = s.layers[li]!;
|
|
631
|
+
states[L.name] = l.s === EXIT ? 'exit' : l.s < 0 ? '' : L.states[l.s]!.name;
|
|
632
|
+
reasons[L.name] = l.s >= 0 ? L.states[l.s]!.reason : '';
|
|
633
|
+
});
|
|
634
|
+
const values: Record<string, Literal> = {};
|
|
635
|
+
c.values.forEach((v, i) => { values[v.name] = s.vals[i]!; });
|
|
636
|
+
const z = settled(c, s, clock);
|
|
637
|
+
const clocked = z.clocked.filter((name) => {
|
|
638
|
+
const li = c.layers.findIndex((L) => L.name === name);
|
|
639
|
+
const L = c.layers[li]!;
|
|
640
|
+
const si = s.layers[li]!.s;
|
|
641
|
+
return !L.wrap || L.states[si]!.loop !== LOOP.once || movesOnWrap(L, si, s.vals);
|
|
642
|
+
});
|
|
643
|
+
// Only writes applied by `ms` count: a write after it has not happened yet at this sample.
|
|
644
|
+
return { states, values, awake: z.awake, clocked, reasons, writes_ms: writes.filter((w) => w.at <= ms).map((w) => w.at) };
|
|
645
|
+
};
|
|
646
|
+
return rig;
|
|
647
|
+
}
|