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.
@@ -0,0 +1,206 @@
1
+ // useMachine.ts: play a skac.machine/1 scene in an app (skac docs app). Reanimated and Worklets only, never Skia: the
2
+ // exported index.tsx draws `pose` with the app's own Skia package.
3
+ //
4
+ // The machine's snapshot lives in a shared value and moves forward on the UI thread through the same advance() the
5
+ // CLI checks with. A frame callback runs only while a frame-clock layer is awake or a write waits; once the machine
6
+ // rests it switches itself off and the last pose stays. Layers on a named clock follow that clock's shared value
7
+ // through the pose reaction, so they step with the app's own clock and cost nothing between its steps.
8
+ import { useCallback, useEffect, useMemo } from 'react';
9
+ import { useAnimatedReaction, useFrameCallback, useReducedMotion, useSharedValue, type FrameInfo, type SharedValue } from 'react-native-reanimated';
10
+ import { scheduleOnRN, scheduleOnUI } from 'react-native-worklets';
11
+ import {
12
+ advance, compile, hitTest, hitWrites, pose as poseAt, settled, start, writeProblem,
13
+ type Clips, type ClockRead, type Literal, type Machine, type Pose, type Snapshot, type StateEntry, type Write,
14
+ } from '../templates/motion/machine';
15
+ import { assertRuntimeVersion } from './version';
16
+
17
+ declare const __DEV__: boolean;
18
+
19
+ /** Dev-only timing probe (skac docs app): frame timestamps, in ms, of the frame that applied a write and of the first frame that drew something different after it. */
20
+ export type MachineProbe = { onWrite?: (frameMs: number) => void; onChanged?: (frameMs: number) => void };
21
+
22
+ export type MachineOptions = {
23
+ /** false stops time and the frame callback (hidden, background, covered). Default true. */
24
+ live?: boolean;
25
+ /** Overrides the system's reduced-motion setting: once-clips show their end, loops their start. */
26
+ reduced?: boolean;
27
+ /** Named clocks the machine's layers read, as shared values in ms (Word Quran passes its ambient phase × 64000). */
28
+ clocks?: Record<string, SharedValue<number>>;
29
+ probe?: MachineProbe;
30
+ /** Entries after initialization, in machine order. Delivered on the React Native thread. */
31
+ onStateEntries?: (entries: StateEntry[]) => void;
32
+ /** The skac version that wrote the exported machine module. */
33
+ exportedBy?: string;
34
+ };
35
+
36
+ type Values<M extends Machine> = 'values' extends keyof M ? NonNullable<M['values']> : {};
37
+ type ValueName<V> = Extract<keyof V, string>;
38
+ type WritableName<V> = ValueName<{ [K in keyof V as V[K] extends { bind: 'out' } ? never : K]: V[K] }>;
39
+ type TriggerName<V> = string extends keyof V ? string : ValueName<{
40
+ [K in WritableName<V> as V[K] extends { type: 'trigger' } ? K : never]: V[K];
41
+ }>;
42
+ type WriteValue<V> = V extends { type: 'boolean' } ? boolean
43
+ : V extends { type: 'number' } ? number
44
+ : V extends { type: 'enum'; options: readonly (infer O extends string)[] } ? O
45
+ : V extends { type: 'trigger' } ? true : Literal;
46
+
47
+ export type MachineHandle<M extends Machine = Machine> = {
48
+ /** What to draw: channels and part boxes. Read it in a derived value or a Skia picture; it changes only when the drawing does. */
49
+ pose: SharedValue<Pose>;
50
+ /** Write a value from JavaScript; it applies at the next frame. */
51
+ set: <K extends WritableName<Values<M>>>(name: K, to: WriteValue<Values<M>[NoInfer<K>]>) => void;
52
+ /** Fire a trigger from JavaScript. */
53
+ fire: (name: TriggerName<Values<M>>) => void;
54
+ /** Write a value from the UI thread (a gesture worklet); it applies at the next frame. */
55
+ setOnUI: MachineHandle<M>['set'];
56
+ /** Tap the point (x, y) in pt from the UI thread: the first hit area under it makes its writes. Returns the part's name, or ''. */
57
+ tapOnUI: (x: number, y: number) => string;
58
+ /** A value as the machine holds it now, on the UI thread: how an out-value reaches an animated style. */
59
+ readOnUI: (name: ValueName<Values<M>>) => Literal | undefined;
60
+ };
61
+
62
+ function sameNumbers(left: Record<string, number | undefined>, right: Record<string, number | undefined>): boolean {
63
+ 'worklet';
64
+ if (left === right) return true;
65
+ let remaining = 0;
66
+ for (const key in left) {
67
+ if (!Object.hasOwn(left, key) || left[key] === undefined) continue;
68
+ if (!Object.hasOwn(right, key) || left[key] !== right[key]) return false;
69
+ remaining++;
70
+ }
71
+ for (const key in right) {
72
+ if (Object.hasOwn(right, key) && right[key] !== undefined) remaining--;
73
+ }
74
+ return remaining === 0;
75
+ }
76
+
77
+ function samePose(left: Pose, right: Pose): boolean {
78
+ 'worklet';
79
+ if (!sameNumbers(left.channels, right.channels)) return false;
80
+ const { parts: leftParts } = left;
81
+ const { parts: rightParts } = right;
82
+ if (leftParts === rightParts) return true;
83
+ if (!leftParts || !rightParts) return false;
84
+ let remaining = 0;
85
+ for (const name in leftParts) {
86
+ if (!Object.hasOwn(leftParts, name)) continue;
87
+ if (!Object.hasOwn(rightParts, name) || !sameNumbers(leftParts[name]!, rightParts[name]!)) return false;
88
+ remaining++;
89
+ }
90
+ for (const name in rightParts) {
91
+ if (Object.hasOwn(rightParts, name)) remaining--;
92
+ }
93
+ return remaining === 0;
94
+ }
95
+
96
+ /** Play `machine` with its `clips`. The machine and clips must be stable (module constants), as an exported scene's are. */
97
+ export function useMachine<const M extends Machine>(machine: M, clips: Clips, options: MachineOptions = {}): MachineHandle<M> {
98
+ if (__DEV__ && options.exportedBy !== undefined) assertRuntimeVersion(options.exportedBy);
99
+ const { live = true, clocks = {}, probe, onStateEntries } = options;
100
+ const systemReduced = useReducedMotion();
101
+ const reduced = options.reduced ?? systemReduced;
102
+ const compiled = useMemo(() => compile(machine, clips), [machine, clips]);
103
+ // The clocks its layers run on: the pose reads only these, and each must be passed, since a missing one would read
104
+ // machine time, which stops while the machine rests.
105
+ const clockNames = useMemo(() => [...new Set(compiled.layers.map((L) => L.clock).filter((n) => n))], [compiled]);
106
+ const missing = clockNames.filter((n) => !clocks[n]);
107
+ if (missing.length) throw new Error(`useMachine: layers run on clock${missing.length > 1 ? 's' : ''} ${missing.join(', ')}; pass clocks={{ ${missing.join(', ')} }} as shared values in ms`);
108
+
109
+ // The snapshot at machine time `ms`; writes wait in `pending` until the next frame stamps and applies them.
110
+ const read: ClockRead = (name: string, t: number) => {
111
+ 'worklet';
112
+ const clock = clocks[name];
113
+ return clock ? clock.value : t;
114
+ };
115
+ // Entered at mount, at machine time 0, with each named clock's reading now.
116
+ const first = useMemo(() => advance(compiled, start(compiled), 0, [], read), [compiled]); // eslint-disable-line react-hooks/exhaustive-deps
117
+ const ms = useSharedValue(0);
118
+ const snapshot = useSharedValue<Snapshot>(first);
119
+ const pending = useSharedValue<Write[]>([]);
120
+ const lastChannels = useSharedValue('');
121
+ const awaitingChange = useSharedValue(false);
122
+ const liveNow = useSharedValue(live);
123
+ const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced), [first]); // eslint-disable-line react-hooks/exhaustive-deps
124
+ const pose = useSharedValue<Pose>(firstPose);
125
+
126
+ useAnimatedReaction(
127
+ () => {
128
+ if (!liveNow.value) return undefined;
129
+ // Subscribe to the named clocks, including when the frame callback sleeps.
130
+ for (const n of clockNames) void clocks[n]!.value;
131
+ return poseAt(compiled, clips, snapshot.value, ms.value, read, reduced);
132
+ },
133
+ (next) => {
134
+ // The reaction subscribes only to the prepare inputs. Updating its output cannot wake it again.
135
+ if (next && !samePose(next, pose.value)) pose.value = next;
136
+ },
137
+ );
138
+
139
+ const tick = useCallback((frame: FrameInfo) => {
140
+ 'worklet';
141
+ const writes = pending.value;
142
+ // The first frame after a wake has no previous frame (dt 0); advance takes writes after the snapshot's time only,
143
+ // so writes waiting then are stamped a hair later, or they would be lost.
144
+ const dt = frame.timeSincePreviousFrame ?? 0;
145
+ const t = ms.value + (writes.length ? Math.max(dt, 0.001) : dt);
146
+ ms.value = t;
147
+ if (writes.length) {
148
+ pending.value = [];
149
+ if (probe?.onWrite) { scheduleOnRN(probe.onWrite, frame.timestamp); awaitingChange.value = true; }
150
+ }
151
+ const entries: StateEntry[] | undefined = onStateEntries ? [] : undefined;
152
+ const next = advance(compiled, snapshot.value, t, writes.map((w) => ({ ...w, at: t })), read, entries);
153
+ snapshot.value = next;
154
+ if (entries?.length && onStateEntries) scheduleOnRN(onStateEntries, entries);
155
+ if (probe?.onChanged) {
156
+ const key = JSON.stringify(poseAt(compiled, clips, next, t, read, reduced).channels);
157
+ if (key !== lastChannels.value) {
158
+ lastChannels.value = key;
159
+ if (awaitingChange.value) { awaitingChange.value = false; scheduleOnRN(probe.onChanged, frame.timestamp); }
160
+ }
161
+ }
162
+ if (pending.value.length === 0 && settled(compiled, next, read, reduced).frame) scheduleOnRN(sleep);
163
+ }, [compiled, clips, reduced, probe, onStateEntries]);
164
+
165
+ const frames = useFrameCallback(tick, false);
166
+ // The callback is switched from JavaScript only: switching it from a worklet makes a synchronous remote call that
167
+ // release builds refuse (found in Word Quran, 18 Oct 2026).
168
+ function sleep() {
169
+ frames.setActive(false);
170
+ }
171
+ // It reads `live` through its shared value: the tick holds an older copy of this function.
172
+ const wake = useCallback(() => { if (liveNow.value) frames.setActive(true); }, [frames, liveNow]);
173
+ useEffect(() => {
174
+ liveNow.value = live;
175
+ frames.setActive(live);
176
+ }, [frames, live, liveNow, reduced]);
177
+
178
+ const setOnUI = useCallback((name: string, to: Literal) => {
179
+ 'worklet';
180
+ pending.value = [...pending.value, { at: 0, value: name, to }];
181
+ scheduleOnRN(wake);
182
+ }, [pending, wake]);
183
+ const set = useCallback((name: string, to: Literal) => {
184
+ const problem = writeProblem(compiled, name, to);
185
+ if (problem) throw new Error(`useMachine set: ${problem}`);
186
+ // The UI worklet queues the wake after any sleep the tick has already queued on JavaScript.
187
+ scheduleOnUI(setOnUI, name, to);
188
+ }, [compiled, setOnUI]);
189
+ const fire = useCallback((name: string) => set(name, true), [set]);
190
+ const tapOnUI = useCallback((x: number, y: number) => {
191
+ 'worklet';
192
+ const part = hitTest(compiled, pose.value, x, y);
193
+ if (!part) return '';
194
+ const writes = hitWrites(compiled, part, 0, snapshot.value.vals);
195
+ pending.value = [...pending.value, ...writes];
196
+ scheduleOnRN(wake);
197
+ return part;
198
+ }, [compiled, pose, snapshot, pending, wake]);
199
+ const readOnUI = useCallback((name: string) => {
200
+ 'worklet';
201
+ const i = compiled.index[name];
202
+ return i === undefined ? undefined : snapshot.value.vals[i];
203
+ }, [compiled, snapshot]);
204
+
205
+ return { pose, set, fire, setOnUI, tapOnUI, readOnUI };
206
+ }
@@ -0,0 +1,37 @@
1
+ import packageJson from '../package.json';
2
+
3
+ export const runtimeVersion = packageJson.version;
4
+
5
+ function compareVersions(a: string, b: string): number {
6
+ const [aCore = '', ...aPre] = a.split('+')[0]!.split('-');
7
+ const [bCore = '', ...bPre] = b.split('+')[0]!.split('-');
8
+ const left = aCore.split('.').map(Number);
9
+ const right = bCore.split('.').map(Number);
10
+ for (let i = 0; i < 3; i++) {
11
+ const diff = left[i]! - right[i]!;
12
+ if (diff) return diff;
13
+ }
14
+ if (!aPre.length || !bPre.length) return Number(!aPre.length) - Number(!bPre.length);
15
+ const x = aPre.join('-').split('.');
16
+ const y = bPre.join('-').split('.');
17
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
18
+ const l = x[i]!;
19
+ const r = y[i]!;
20
+ if (l === r) continue;
21
+ const lNumeric = /^\d+$/.test(l);
22
+ const rNumeric = /^\d+$/.test(r);
23
+ if (lNumeric && rNumeric) return Number(l) - Number(r);
24
+ if (lNumeric !== rNumeric) return lNumeric ? -1 : 1;
25
+ return l < r ? -1 : 1;
26
+ }
27
+ return x.length - y.length;
28
+ }
29
+
30
+ export function assertRuntimeVersion(exportedBy: string): void {
31
+ if (compareVersions(runtimeVersion, exportedBy) < 0) {
32
+ const install = packageJson.name === 'skia-motion-runtime'
33
+ ? `Install the app runtime for ${exportedBy} or newer from ${packageJson.homepage}/releases.`
34
+ : `Install ${packageJson.name}@${exportedBy} or newer.`;
35
+ throw new Error(`This machine was exported by Skia Motion ${exportedBy}, but the installed runtime is ${runtimeVersion}. ${install}`);
36
+ }
37
+ }
@@ -0,0 +1,118 @@
1
+ // face.ts: the face as pure math, no React or Skia, so a rig file, a test or skac's checks can import it
2
+ // in plain Node. liveFace.tsx draws it. Adapted from rossark-motion-skill (MIT) and huashu-art-motion (MIT);
3
+ // see NOTICE.md and `skac docs motion/faces`. Every function here is a worklet in the app.
4
+ import { flow, track, type FlowKeys, type Key, type Keys } from './motion';
5
+
6
+ /**
7
+ * One character's face choreography. Missing channels rest at their default.
8
+ * lookX / lookY: eye offset in pt (flow). lid: upper lid 0 open .. 1 shut (track: one move).
9
+ * cheek: lower lid rising, 0..1; above 0.86 the happy arc shows (delight).
10
+ * squeeze: wind-up scrunch, 0..1, read with lid = 1; turns the closed line into a tight chevron.
11
+ * wide: shock, 0..1, eyes 1.0x -> 1.25x. smile: 0..1 rest smile (default 1).
12
+ * grin: open grin, 0..1. o: surprised O mouth, 0..1.
13
+ */
14
+ export type FaceChoreo = {
15
+ lookX?: FlowKeys;
16
+ lookY?: FlowKeys;
17
+ lid?: Keys;
18
+ cheek?: FlowKeys;
19
+ squeeze?: FlowKeys;
20
+ wide?: FlowKeys;
21
+ grin?: FlowKeys;
22
+ o?: FlowKeys;
23
+ };
24
+
25
+ export type FaceState = { lookX: number; lookY: number; lid: number; cheek: number; squeeze: number; wide: number; grin: number; o: number };
26
+
27
+ const clamp01 = (x: number) => {
28
+ 'worklet';
29
+ return Math.min(1, Math.max(0, x));
30
+ };
31
+
32
+ /** Every face channel at time t (ms). */
33
+ export function faceAt(t: number, c: FaceChoreo): FaceState {
34
+ 'worklet';
35
+ return {
36
+ lookX: c.lookX ? flow(t, c.lookX) : 0,
37
+ lookY: c.lookY ? flow(t, c.lookY) : 0,
38
+ lid: c.lid ? clamp01(track(t, c.lid)) : 0,
39
+ cheek: c.cheek ? clamp01(flow(t, c.cheek)) : 0,
40
+ squeeze: c.squeeze ? clamp01(flow(t, c.squeeze)) : 0,
41
+ wide: c.wide ? clamp01(flow(t, c.wide)) : 0,
42
+ grin: c.grin ? clamp01(flow(t, c.grin)) : 0,
43
+ o: c.o ? clamp01(flow(t, c.o)) : 0,
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Blink keys: close 110 ms, hold 40 ms, reopen 190 ms with 'out' (reopening is slower than closing).
49
+ * Never shorter: a 70 ms close is two frames at 30 fps and flickers (rossark §4, §1.12).
50
+ */
51
+ export function blinkKeys(starts: readonly number[], end: number): Key[] {
52
+ 'worklet';
53
+ const k: Key[] = [[0, 0]];
54
+ for (const s of starts) k.push([s, 0], [s + 110, 1], [s + 150, 1], [s + 340, 0, 'out']);
55
+ k.push([end, 0]);
56
+ return k;
57
+ }
58
+
59
+ /** Where one solid eye sits at rest (for example 14 x 20 pt black ovals, 44 pt apart). */
60
+ export type SolidEye = { cx: number; cy: number; w: number; h: number; shine: number };
61
+ export type FaceInk = { eye: string; shine: string; skin: string; mouth: string; tongue: string; line: number };
62
+
63
+ /** The eye's drawing at this instant: all strings and numbers, safe to derive on the UI thread. */
64
+ export function eyeGeometry(e: SolidEye, f: FaceState, side: -1 | 1) {
65
+ 'worklet';
66
+ const s = 1 + 0.25 * f.wide; // shock widens the eye to 1.25x (huashu toon.js shock 1.28)
67
+ const w = e.w * s;
68
+ const h = e.h * s;
69
+ const cx = e.cx + f.lookX;
70
+ const cy = e.cy + f.lookY;
71
+ const top = 0.85 * f.lid * (h + 2); // the upper lid travels 85 %...
72
+ const bottom = Math.min(1, 0.15 * f.lid + f.cheek) * (h + 2); // ...the lower lid rises 15 % to meet it (rossark §4)
73
+ const closed = clamp01((f.lid - 0.88) / 0.12);
74
+ const happy = clamp01((f.cheek - 0.86) / 0.14);
75
+ return {
76
+ eye: { x: cx - w / 2, y: cy - h / 2, w, h },
77
+ // the skin lids are clipped to a shape 1 pt larger all round than the eye: clipped to the exact
78
+ // eye, the anti-aliased edge leaks around a closed eye and reads as glasses (rossark §4, §8)
79
+ clip: { x: cx - w / 2 - 1, y: cy - h / 2 - 1, w: w + 2, h: h + 2 },
80
+ lidPath: `M${cx - w} ${cy - h / 2 - 1}h${2 * w}v${top}h${-2 * w}Z`,
81
+ cheekPath: `M${cx - w} ${cy + h / 2 + 1}h${2 * w}v${-bottom}h${-2 * w}Z`,
82
+ shine: { cx: cx + w * 0.2, cy: cy - h * 0.24, r: e.shine * (1 - 0.3 * f.wide), opacity: 1 - closed },
83
+ // a soft closed line, a tight wind-up chevron pointing at the nose, a happy arc
84
+ closedPath: `M${cx - 7} ${cy + 1}Q${cx} ${cy + 5} ${cx + 7} ${cy + 1}`,
85
+ closedOpacity: closed * (1 - f.squeeze),
86
+ squeezePath: `M${cx - side * 7} ${cy - 5}L${cx + side * 5} ${cy + 1}L${cx - side * 7} ${cy + 6}`,
87
+ squeezeOpacity: closed * f.squeeze,
88
+ happyPath: `M${cx - 7} ${cy + 3}Q${cx + side * 0.5} ${cy - 8} ${cx + 7} ${cy + 3}`,
89
+ happyOpacity: happy,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * The ONE mouth path. Two cubic halves between the corners: the top half's handles sit `top`
95
+ * below the corner line, the bottom half's `bot` below it, at `hx` of the half width.
96
+ * rest smile: w 22, top 6, bot 6 (zero area; the 3 pt stroke reads as the spec's arc, 4.5 pt deep)
97
+ * grin: w 26, top 3, bot 20 (open D, tongue shows)
98
+ * O: w 14, top -12, bot 12, hx 1 (an upright oval 14 x 18 pt: never smaller, see `skac docs motion/faces`)
99
+ * Channels blend these linearly, so the mouth morphs; it never swaps (huashu toon.js mouth set).
100
+ */
101
+ export function mouthGeometry(cx: number, y: number, f: FaceState) {
102
+ 'worklet';
103
+ const g = f.grin * (1 - f.o);
104
+ const o = f.o;
105
+ const r = 1 - g - o;
106
+ const w = 22 * r + 26 * g + 14 * o;
107
+ const top = 6 * r + 3 * g - 12 * o;
108
+ const bot = 6 * r + 20 * g + 12 * o;
109
+ const hx = 0.5 * (1 - o) + 1 * o;
110
+ const yc = y + 4 * o; // the O sits a little lower, centred where the smile's dip was
111
+ const a = (w / 2) * hx;
112
+ const path = `M${cx - w / 2} ${yc}C${cx - a} ${yc + top} ${cx + a} ${yc + top} ${cx + w / 2} ${yc}C${cx + a} ${yc + bot} ${cx - a} ${yc + bot} ${cx - w / 2} ${yc}Z`;
113
+ const open = Math.max(0, bot - Math.max(top, 0)) * 0.75; // visible depth of the opening
114
+ return {
115
+ path,
116
+ tongue: { x: cx - w * 0.28, y: yc + bot * 0.75 - open * 0.45, w: w * 0.56, h: open * 0.6, opacity: clamp01(open / 6) },
117
+ };
118
+ }