Turn any SVG into a professional 60 fps animation. A Claude Code skill that brings anything drawn to life: live faces, full-body acting and whole scenes, in React Native and SwiftUI.
Swift
Acting, interface motion and reference-video tools, with a reveal demo
Eder Rosa0abc55a4a8bb
diff --git a/MOTION.md b/MOTION.mdindex 60dddb3..e540b1f 100644--- a/MOTION.md+++ b/MOTION.md@@ -22,10 +22,19 @@9. **The layout never moves:** motion lives inside the drawing.10. **Reduced motion:** loops freeze on a good frame 0, and one-shots show their final frame.11. **Nothing runs unseen:** pause off screen, when hidden and in the background.+12. **Enough frames:** anything under ~100 ms flickers at 30 fps; render and export at 60 when you can. Blinks close in ~110 ms and reopen in ~190 ms.+13. **Interface rules:**+ - frequency decides how much (often seen = barely moves; rare moments get the delight);+ - every motion has a purpose;+ - shared elements travel, never teleport;+ - interface moves stay under 300 ms;+ - exits are faster than entrances;+ - nothing appears from scale 0;+ - interruptions continue from the current value.### The engine- **Clocks:** a loop clock for idle life, a one-shot clock for a scene that tells an action. One per character, group or scene.-- **Tracks:** keyframes `[ms, value, 'out'?]` read with `track(t, keys)`. The last key equals the first.+- **Tracks:** keyframes `[ms, value, 'out'?]` read with `track(t, keys)`. The last key equals the first. `track` stops at every key, so use it for one move (a blink, a lid). For acting (a chain of poses), use `flow(t, keys)`, which passes through the keys without stopping and never overshoots.- **Helpers:**- `wave` (−1 to 1), for sway and breathing;- `loop` (0 to 1), for drift and falling;@@ -42,6 +51,8 @@| Subject | Recipe ||---|---|| Character | breathing 1–2 units over 3–5 s; a blink every 3–4 s; pupils glide; head tilt 3–6° |+| Waiting to be tapped | a jiggle every ~270 ms: squash 2%, widen 2%, the bulge trading sides |+| Floating figure | rises in from 30% of its height below, drifts 5% down and up, leaves rising || Tail, hair, ears | rotation around the root, phase delayed along the chain, 4–10° || Plant | sway 1.5–4° around the base over 3–6 s; leaves on seeded phases || Cloth, flag | a wave that travels along the length, growing away from the fixed edge |@@ -56,6 +67,27 @@| Icon, logo | plays once on appear, then rests || Chart | a one-shot draw-on, with bars staggered 40–80 ms |+### Acting (a whole character)+- **Every channel:** key pose (`flow`) + idle (`wave`s, never off while on stage) + follow-through (the parent read 90–140 ms earlier) + accents (a `wave` inside a `seg` window).+- **Arms:** an upper arm and a forearm share a round elbow; the forearm points at shoulder angle + elbow bend.+- **Head turns:** slide the face toward the turn (eyes 10, nose 13 in a 100-wide head) and the ears the other way. Blink on the turn.+- **Weight:** the hips shift and carry the upper body, and the legs angle to keep the feet under it.+- **Landing:** hover, then fall with gravity and stretch; squash hard (0.8) on contact and keep the volume (`width = 1 / height^0.6`).+- **In the air:** limp feet (toes down, one knee folded, trading slowly). The shadow stays on the floor and scales with the height.+- **Props:** enter from off screen already moving and roll by distance / radius. The eyes follow them. A kick hits at the middle of the swing; the prop leaves as a throw, spinning, with a short squash.+- **Asymmetry:** the arms never mirror each other.+- **Camera:** a view from a little above is a whole build, not a tweak: the head is 40–50% of the height, the torso is short and narrower than the head, the legs are short, the feet are round from above, and the shadow is a wide oval with the feet in its lower half. Keep it in one `build` object. A flat view keeps a thin pill shadow.+- **Framing:** on a phone, as big as the screen allows, with the feet low.++### From a reference video+- Contact sheets at the full frame rate (`tools/sheet.sh`).+- Measure motion with numbers (`tools/track_edges.py`): a 2% jiggle or a 5% float doesn't show to the eye.+- Sample colors from pixels (`tools/sample_colors.py`).+- Go part by part: feet, shadow, hands, head.+- Compare proportions as ratios of one unit (head widths). "Stretched" means a ratio is far off.+- Compare your render with the reference at the same moments.+- Don't publish a copy of someone else's art.+### Performance- Everything is a function of one clock's time.- Draw many items in one SVG or `Canvas`.@@ -68,7 +100,7 @@3. Pick one main action and two or three idle loops.4. Split the art into layers at their pivots.5. Put the numbers in tokens.-6. Check frame 0, the final frames and the loop seams.+6. Check frame 0, the final frames and the loop seams. For a character, look at a contact sheet of every 4th frame of your own render.7. Run the checks.8. Hand off: what moves, and what hasn't been seen on a real device.diff --git a/README.md b/README.mdindex 4568cd6..0099a9e 100644--- a/README.md+++ b/README.md@@ -4,20 +4,29 @@<sub>Rendered from `demo/DemoScene.swift` with the SwiftUI templates in this repo: one clock, an 8-second loop. [MP4 version](demo/demo.mp4).</sub>-A Claude Code skill for bringing anything drawn to life: characters and creatures, plants, cloth, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. The motion is calm and believable; it never teleports and never bounces.+A Claude Code skill for bringing anything drawn to life: characters and creatures, plants, cloth, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. The motion is calm and believable, and it never teleports. Characters can act: land, gesture, shift their weight, turn their head, float and play with props, without ever freezing between poses.-It comes with a small motion engine and templates for React Native (`react-native-svg` + `react-native-reanimated`) and SwiftUI (`TimelineView` + `Canvas`, iOS 17+ / macOS 14+), and the method works the same on the web.+It comes with:+- a small motion engine and templates for React Native (`react-native-svg` + `react-native-reanimated`) and SwiftUI (`TimelineView` + `Canvas`, iOS 17+ / macOS 14+);+- tools that measure a reference video frame by frame;+- an offline renderer that turns scenes into MP4 and GIF, in a phone frame too.++The method works the same on the web.## What's inside| File | What it is ||---|---|-| `SKILL.md` | The skill: principles, the engine, recipes for every kind of subject, characters in depth, scenes that tell an action, performance pitfalls, platforms and a workflow. |+| `SKILL.md` | The skill: principles, the engine, recipes for every kind of subject, faces, full-body acting, scenes that tell an action, pitfalls, platforms, working from a reference video, and a workflow. || `MOTION.md` | A notes file to copy into your project. Part 1 is the method in short form; Part 2 is where your project's specifics go (where the code is, the owner's rules, rig limits, how changes are checked). The skill reads it first. |-| `templates/react-native/motion.ts` | The engine: loop and one-shot clocks, keyframe `track`, `seg`, `wave`, `loop`, `bell`, `seeded` and the curves. |+| `templates/react-native/motion.ts` | The engine: loop and one-shot clocks, keyframe `track`, `flow` (smooth acting through key poses), `seg`, `wave`, `loop`, `bell`, `seeded` and the curves. || `templates/react-native/liveFace.tsx` | A live face on top of the engine: `LiveEye`, `LiveMouth`, `Choreo`. You give it the eye geometry and colours. |-| `templates/swiftui/Motion.swift` | The same engine in SwiftUI: `LoopClock`, `OneShotClock`, `track`, `seg`, `wave`, `loop`, `bell`, `seeded`, and the `travel` and `open` animations. |+| `templates/swiftui/Motion.swift` | The same engine in SwiftUI: `LoopClock`, `OneShotClock`, `track`, `flow`, `seg`, `wave`, `loop`, `bell`, `seeded`, and the `travel` and `open` animations. || `templates/swiftui/LiveFace.swift` | The same live face, drawn into a `Canvas`: `drawLiveEye`, `drawLiveMouth`, `Choreo`. |+| `tools/sheet.sh` | Contact sheets of a video at its full frame rate, to study timing (or to check your own render). |+| `tools/track_edges.py` | Measures a subject's edges frame by frame, so you can see motion too small for the eye (a 2% jiggle, a float, a sway). |+| `tools/sample_colors.py` | Reads exact colours from a video frame. |+| `demo/` | Three scenes, a phone frame (`PhoneMockup.swift`) and the renderer (`render.swift`). |## Install@@ -29,7 +38,7 @@ git clone https://github.com/rossark0/rossark-motion-skill ~/.claude/skills/rossFor one project only, clone it into that project's `.claude/skills/rossark-motion-skill` instead.-Then, in Claude Code, ask it to animate something ("make this plant sway", "bring the mascot to life", "animate the onboarding illustrations"), or type `/rossark-motion-skill`.+Then, in Claude Code, ask it to animate something ("make this plant sway", "bring the mascot to life", "make it move like this video"), or type `/rossark-motion-skill`.## First time in a project@@ -39,11 +48,11 @@ Then, in Claude Code, ask it to animate something ("make this plant sway", "brin## The idea in one paragraph-Every moving thing reads a clock. A loop clock gives idle life; a one-shot clock tells a small story when a scene appears. Parts are layers that rotate around their real pivots, trailing parts lag behind, and repeated things never move in sync. Amplitudes stay small, the curves are strong and nothing bounces. Characters get live eyes: pupils glide and lids blink over plain eye whites. Everything stops on a good frame when the user asks for reduced motion, and nothing runs off screen.+Every moving thing reads a clock. A loop clock gives idle life; a one-shot clock tells a small story when a scene appears. Parts are layers that rotate around their real pivots, trailing parts lag behind, and repeated things never move in sync. Characters get live eyes, and when they act, every channel is a smooth path through key poses, plus idle life that never stops, plus follow-through. Amplitudes stay small and the curves are strong. Everything stops on a good frame when the user asks for reduced motion, and nothing runs off screen.## The demos-Both are drawn with `templates/swiftui/`, on one clock each, in seamless 8-second loops.+All three are drawn with `templates/swiftui/`, each on one clock, in seamless loops.**Room** (`demo/DemoScene.swift`, at the top of this page):- a creature that breathes, with ears that follow through and live eyes that look, blink and smile;@@ -62,13 +71,27 @@ Both are drawn with `templates/swiftui/`, on one clock each, in seamless 8-secon[MP4 version](demo/orbit.mp4).+**Reveal** (`demo/RevealScene.swift`), full-body acting in a phone frame:++++- a mystery silhouette floats in, its feet hanging limp, its shadow breathing with the height;+- the kid hovers, falls with gravity, squashes on landing and keeps the volume;+- poses flow into each other with `flow`; idle life never stops; the head and forearms follow through;+- elbows bend, the head turns by sliding the face (2.5D), and the weight shifts from leg to leg;+- a ball rolls in from off screen, the eyes follow it, the kick hits at the middle of the swing, and the ball flies off spinning;+- a toy-like build seen from a little above: a big head, a short torso, round shoes and a wide oval shadow.++[MP4 version](demo/reveal.mp4), square and ready to post.+To render them again on macOS 14+:```bashswiftc -parse-as-library -target arm64-apple-macos14 \templates/swiftui/Motion.swift templates/swiftui/LiveFace.swift demo/*.swift -o /tmp/render-demo-/tmp/render-demo room /tmp/frames # or: orbit-ffmpeg -framerate 30 -i /tmp/frames/%04d.png -c:v libx264 -pix_fmt yuv420p -crf 20 demo/demo.mp4+/tmp/render-demo room /tmp/frames # or: orbit, reveal+/tmp/render-demo reveal /tmp/frames phone fps=60 # inside a phone frame, on a square page, at 60 fps+ffmpeg -framerate 60 -i /tmp/frames/%04d.png -c:v libx264 -pix_fmt yuv420p -crf 20 demo/reveal.mp4```## Licensediff --git a/SKILL.md b/SKILL.mdindex 52349a6..b1d0dac 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: rossark-motion-skill-description: Bring anything drawn to life with calm, believable motion. It covers characters and creatures (gliding pupils, blinks, breathing, head tilts), plants, fabric, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. Use it whenever someone asks to animate an illustration, an icon, a mascot or a scene, to make something "feel alive", to add idle motion, or to turn a static drawing into a living one. Comes with a small motion engine and templates for React Native (react-native-svg + Reanimated) and SwiftUI (TimelineView + Canvas); the method also works on the web.+description: Bring anything drawn to life with calm, believable motion. It covers characters and creatures (gliding pupils, blinks, breathing, head tilts), full-body acting (landing, waving, leaning, levitating, kicking a ball), plants, fabric, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. Use it whenever someone asks to animate an illustration, an icon, a mascot or a scene, to make something "feel alive", to add idle motion, to turn a static drawing into a living one, or to recreate the motion of a reference video. Comes with a small motion engine and templates for React Native (react-native-svg + Reanimated) and SwiftUI (TimelineView + Canvas), tools that measure a reference video frame by frame, and offline rendering to video, in a phone frame too. The method also works on the web.---# rossark-motion-skill: bring anything to life@@ -41,6 +41,7 @@ These hold for anything you animate.- Loops freeze at frame 0, which must be a good drawing.- One-shot scenes show their final frame, which must read on its own.11. **Nothing runs unseen.** Off screen, hidden or in the background, every clock is paused.+12. **Give every move enough frames.** At 30 fps, anything shorter than about 100 ms is two or three frames and flickers. Make fast moves (blinks, contact, snaps) last long enough, and render or export at 60 fps when the platform allows.## 2. The engine@@ -55,6 +56,8 @@ Copy it into the project, unless the project's notes name its own.- `useOneShotClock(duration, play, reduced)` / `OneShotClock` plays once and holds, for a scene that tells an action.- Use one clock per character, object group or scene, never one per tiny part.- **Tracks.** Keyframes `[ms, value, 'out'?]` read with `track(t, keys)`. Each segment eases in and out, or eases out when marked `'out'`. The last key equals the first, so a loop never jumps.+ - `track` stops at every key, which is right for ONE move (a blink, a lid, a door).+ - For acting, a chain of poses (a body, arms, a head turn), use `flow(t, keys)` with keys `[ms, value]`. It passes through every key with a continuous speed and never overshoots one. With `track`, the character stops dead at each pose and reads as a robot (section 5).- **Shaping helpers:**- `wave(t, period, phase)` gives a smooth -1 to 1, for sway, bob and breathing;- `loop(t, period, phase)` gives 0 to 1 progress, for drift and falling;@@ -86,9 +89,11 @@ Numbers are in drawing units (the artwork's own coordinate system) and milliseco| **Machines, gears, fans, clocks** | mechanism | Gears rotate linearly at speeds set by their tooth ratio. A clock hand steps once a second with ease-out; the colon blinks every 0.5 s. A fan spins steadily || **Phone, alarm, notification** | buzz | Bursts of ±3° (4 cycles in about 0.45 s), then a pause; vibration ticks show only during the burst. A notification slides in with ease-out and stays || **Vehicles** | ride | The body bobs 0.5–1 unit; wheels rotate linearly; scenery passes in parallax `loop`s. Never shake the whole frame |+| **Something waiting to be tapped** (a box, a gift, a card) | a jiggle | It never sits still while it waits: a quick, small squash-and-widen pulse (1.5–3%) on a 200–350 ms beat, with the bulge moving to one side and then the other (about 1% of its width). Stop it during the tap's anticipation, and bring it back once the object is at rest again |+| **Floating, levitating** | a float | It rises in from well below (a quarter to a third of its height) and slows, drifts a few percent of its height down and back, and leaves rising as it fades. Its feet hang limp and its shadow breathes with the height (section 5) || **Icon, logo** | a moment | Play once on appear (a draw-on, a small turn, a blink), then rest. No endless loops on UI chrome. A press is a 0.97 scale on the button, not inside the drawing || **Chart, diagram** | draw-on | One-shot: lines draw with a stroke-dash offset, bars grow from their base with ease-out and a small stagger (40–80 ms), and numbers count up with ease-out. Final frame = the data |-| **Scene** | a story | One one-shot action when the scene appears (section 5), then the idle loops of whatever is in it |+| **Scene** | a story | One one-shot action when the scene appears (section 6), then the idle loops of whatever is in it |## 4. Characters in depth@@ -109,7 +114,7 @@ A `Choreo` holds the tracks:The recipe for one loop of 6 to 9 s:- **Gaze:** a resting gaze, plus one or two glances at something in the scene. Glide there in about 500 ms and hold for at least 1 s.-- **Blinks:** one every 3 to 4 s. Close in about 90 ms, hold up to 60 ms, reopen in about 150 ms with `'out'`. Now and then, a double blink.+- **Blinks:** one every 3 to 4 s. Close in about 110 ms, hold 30–50 ms, and reopen in about 190 ms with `'out'`: reopening is slower than closing. Let the lower lid rise about 15% to meet the upper one, so the eye closes near its middle. Blink on head turns. Now and then, a double blink. A shorter blink (a 70 ms close) is only two frames at 30 fps and reads as a flicker.- **The loop closes:** the last key equals the first.| Feeling | Gaze | Lid | Extra |@@ -128,7 +133,112 @@ The recipe for one loop of 6 to 9 s:- **Cropped by an edge:** draw a few units below the crop, so the cut never shows when the character rises.- **Creatures without a face rig:** breathing, ear and tail follow-through, and an occasional whole-head turn still make them feel alive.-## 5. Scenes that tell an action+## 5. Acting: a character that feels alive++Section 4 makes a face alive. This section is for a whole character, or a creature, that performs: arrives, lands, gestures, shifts its weight, reacts, plays with something. A character can hit every pose and still read as a robot. What makes it alive is how it moves between the poses, and the fact that it never fully stops.++**The rules:**++1. **Poses flow; they don't stop.** Read every acting channel with `flow`, never `track`. `track` drops the speed to zero at each key, so the character freezes at every pose. To hold a pose, repeat its value in the keys; the idle layer keeps the hold moving.+2. **Never a frozen frame (moving holds).** While the character is on screen, every channel carries a small idle layer, even in a "still" pose. Use periods that divide the loop, and give each part its own:+ - breathing: the body's height ±1–1.5% over 2–3 s;+ - limbs: a few degrees of sway on two different periods, with the left and right sides out of phase;+ - joints (elbows, knees, wrists): a few degrees;+ - head tilt: ±2° over 4–5 s;+ - weight: a little sideways drift over 4–5 s;+ - head turn: a hint, about 5% of a full turn.+3. **Layer every channel.** Final value = key pose (`flow`) + idle (`wave`s) + follow-through (a delayed copy of the parent) + accents (a `wave` switched on by a `seg` window: a hand waving, wings flapping, a tail wagging).+4. **Follow-through by delay, not by springs.** A child part reads its parent a moment earlier, 60–150 ms, at 0.3–0.6 of its strength:+ - **Counter-motion:** `head(t) = own(t) − 0.45 × lean(t − 110 ms)`. The head rights itself a beat after the body leans.+ - **Trailing:** `joint(t) += 0.45 × (parent(t − 90 ms) − parent(t))`. When the parent swings, the child lags and then catches up, with no overshoot. Forearms, hands, tails, ears and hair all work this way.+5. **Bend the limbs.** A limb is two segments that share one round joint, driven by two angles: the root's angle `a` and the joint's bend `e`. For an arm, `a` is the shoulder's outward angle (0 hangs down) and the forearm points at `a + e`. Straight limbs only swing like pendulums; the joint is where the acting happens. Keep both segments about the same length. Starting angles for common arm gestures:++ | Gesture | a | e | Note |+ |---|---|---|---|+ | wave | 60° | +110° | forearm up beside the head, waving ±10–15° every 0.6–0.9 s |+ | hand on the hip | 30° | −95° | the hand goes behind the body and the joint breaks the silhouette |+ | fist pump, cheer | 55° | +60° | |+ | arms flung for balance | 80–120° | about 0 | |+ | arms up in a V | 150° | 0 | a raised straight limb can stretch about 30% (cartoon reach) |++6. **Turn without new drawings (2.5D).** A `yaw` from −1 to 1 slides each part by its depth:+ - what sticks out the most (a nose, a beak, a snout) slides the most, about 13% of the head's width;+ - the eyes and mouth slide about 10%;+ - the outline doesn't move;+ - parts at the back (ears, back hair) slide the other way, about 9%, so the far one tucks behind the head;+ - prints and stripes on the chest slide 8–12% of the torso's width, clipped to it.++ The pupils lead the turn. Blink on a head turn, as people do.+7. **Shift the weight.** The hips slide sideways and carry everything above them. The legs rotate from the hips so the feet stay planted: the angle is about the shift divided by the leg's length, in radians. The leg that carries no weight lifts out a little.+8. **Land like a body.**+ - **Air time:** hover a moment, then fall with gravity, `lift = top × (1 − k²)`, stretching 5–10%. Right before contact, the arms go up.+ - **Contact:** squash 15–20%, snap the arms out, recover with one small overshoot, then settle.+ - **A hop:** crouch 5–10%, stretch 5–10%, a parabola up and down, then the same squash.+9. **Keep the volume.** When the height scales by `sy`, the width scales by `1 / sy^0.6`.+10. **Break the symmetry.** Left and right never mirror each other. Give them different angles, phases and bends. A symmetric pose reads as a mannequin.+11. **In the air, the feet hang.** Anything held up by nothing hangs. That covers floating, levitating, hovering before a fall and being carried:+ - the legs fall limp and close together;+ - the toes point down, the foot turned 60–80° at the ankle;+ - one knee folds a little, so that leg reads shorter, and the two legs trade slowly;+ - the arms hang a little out and sway.++ Float rather than stand: rise in from well below and slow, drift a few percent of the body's height down and back, and leave rising as you fade. Flatten the feet just before they touch down.+12. **The shadow moves with the height.** The shadow stays on the floor, with a visible gap under anything in the air. Its size scales with the distance (for example `1 − height / 220` in the drawing's units), so it breathes as a body floats and grows as it falls. A shadow that never changes pins the body to the ground. Its shape follows the camera (rule 14): a thin pill for a flat view, a wide oval for a view from above.+13. **Props and contact.**+ - **Entry:** a prop enters already moving, from beyond the visible edge. In a device frame, that means beyond the screen's edge.+ - **Rolling:** a rolling prop turns by the distance over its radius (`angle = Δx / r`) and slows to a stop with ease-out.+ - **Eyes:** the eyes and head follow the prop, toward it as it comes and after it as it goes. Blink on the turn toward it.+ - **A strike (a kick, a hit, a swing):**+ - the weight goes onto the support side and the free limbs open for balance;+ - the striking limb winds up and stops at the top;+ - it swings through the prop at its fastest: contact at the middle of the swing, never at the end;+ - it follows through and comes back, with the opposite arm swinging against it.+ - **Launch:** a launched prop flies as a throw, `x = x0 + vx·s` and `y = y0 − vy·s + g·s²/2` (s in seconds), spinning. It squashes for 60–100 ms at contact (about 15% along the hit, 10% wider across it).+ - **Afterwards:** the character watches it go, then reacts.+14. **The camera angle is a build, not a tweak.** A flat side view keeps the drawing's own proportions and a thin pill shadow. A camera a little above the character (friendly and toy-like, common in games, avatars and reward screens) changes the whole build. Nudging a side-view body by a few percent doesn't get there: it just reads as stretched. In head widths:+ - the head is 40–50% of the total height;+ - the torso is short, about 0.6 head widths tall, and narrower than the head, tapering a little toward the waist;+ - the head sits right on the collar, with no neck showing;+ - the legs are short, a quarter of the height or less, and close together;+ - the arms hang to about the hips;+ - the feet are round, dark shapes seen from above, with their tops tucked under the sock or the trouser;+ - the floor shows, so the shadow is a wide oval (1.3–1.5 head widths, about a third as tall as wide). The feet stand in its lower half.++ Keep these numbers in one `build` object, so the whole body changes in one place. Compute where the feet touch the floor from them.+15. **Frame it for where it will be seen.** On a phone screen, make the character as big as the screen allows, with room for its widest pose and its highest jump, and set its feet in the lower part of the screen. A small figure lost in the middle of the screen reads as a placeholder.++**A shape for the code** (it works the same in React Native and SwiftUI):++```swift+struct Pose { var lift, sy, lean, shift, yaw, head: Double; var armL, armR: (a: Double, e: Double); var legL, legR: Double }++func pose(_ t: Double) -> Pose {+ let on = onScreen(t) ? 1.0 : 0.0 // idle only while visible+ let lean = flow(t, Act.lean) + 1.5 * wave(t, period: 4500) * on+ let head = flow(t, Act.head) - 0.45 * flow(t - 110, Act.lean) // follow-through+ func arm(_ ka: FlowKeys, _ ke: FlowKeys, _ ph: Double) -> (a: Double, e: Double) {+ let a = flow(t, ka) + (4 * wave(t, period: 3000, phase: ph) + 2 * wave(t, period: 1800, phase: ph + 0.3)) * on+ let e = flow(t, ke) + 5 * wave(t, period: 2250, phase: ph + 0.6) * on + 0.45 * (flow(t - 90, ka) - flow(t, ka))+ return (a, e)+ }+ // ...+}+```++Keep the key poses together as data (an `Act` enum or object), one array per channel, so "hold the wave longer" means editing one row. `demo/RevealScene.swift` is a full worked example.++**Before calling it alive, check:**+- [ ] Nothing is frozen while the character is on screen, even in a held pose.+- [ ] There is no moment where every part stops at once.+- [ ] The head and the outer parts of the limbs arrive after the body.+- [ ] Left and right don't mirror each other.+- [ ] The weight moves from one side to the other at least once.+- [ ] The head turns at least once, and the character blinks on the turn.+- [ ] Landings squash and keep the volume.+- [ ] Anything in the air has hanging feet and a shadow that changes with its height.+- [ ] Every prop enters from off screen already moving, and the eyes follow it.++## 6. Scenes that tell an actionSome scenes tell a small story: the phone buzzes, she picks it up, the alarm stops. Here's how to build one.@@ -138,7 +248,54 @@ Some scenes tell a small story: the phone buzzes, she picks it up, the alarm sto4. **The end:** the scene holds on its final frame and only the idle loops keep running.5. **A carousel of scenes:** the one leaving finishes its exit before the next one starts (or crossfades over it, never through an empty or dark frame). Only the scene on screen runs.-## 6. Performance and pitfalls+## 7. Motion in an interface++Illustrations live inside an interface, and the interface has its own rules. These follow Emil Kowalski's design-engineering rules and Benji Taylor's "Family values" (simplicity, fluidity, delight). Where this skill already agrees with them (never teleport, strong curves, transform-only, reduced motion, stagger), it says so in the sections above. This section adds the rest.++1. **Frequency decides how much.** The more often people see something, the less it should move:++ | How often | What it gets |+ |---|---|+ | Hundreds of times a day (shortcuts, typing, a list scroll) | no animation |+ | Tens of times a day (hovers, tab switches, toggles) | a minimal, fast change |+ | Now and then (sheets, toasts, a screen change) | a standard transition |+ | Rarely (onboarding, rewards, celebrations, empty states) | full delight: characters, scenes, a story |++ Delight is selective emphasis: spend it where people pass rarely, and keep frequent paths quiet.+2. **Every motion has a purpose.** It should do at least one of these:+ - show where something came from and where it goes;+ - show that a state changed;+ - confirm a touch;+ - explain how something works;+ - celebrate a rare moment.++ "It looks cool" isn't a purpose on a screen people see often.+3. **Continuity: fly, don't teleport.**+ - An element that exists on both screens travels or morphs between them. It is never removed and redrawn.+ - A transition moves in the direction of the action that caused it: the tab you tapped, the side you swiped.+ - A label that changes meaning morphs into the new one (Continue becomes Confirm). It doesn't swap.+4. **Durations.** These are for interface moves. Idle loops in an illustration run for seconds and are exempt.++ | Move | Duration |+ |---|---|+ | press feedback | 100–160 ms |+ | small popovers and tooltips | 125–200 ms |+ | menus | 150–250 ms |+ | sheets and modals | 200–500 ms |++ Keep interface moves under 300 ms when you can. Fast feels responsive.+5. **Curves.**+ - Entering or responding: a strong ease-out.+ - Moving on screen: a strong ease-in-out.+ - Constant motion: linear.+ - Never ease-in on something the user is waiting for. Ease-in is only for things falling away, like gravity in a drawing.+6. **Asymmetric timing.** Be slow where the user is deciding (a hold to confirm) and fast where the system answers (the release, a dismissal). An exit is usually quicker than the entrance. A blink closes faster than it opens.+7. **Nothing appears from nothing.** A shape enters from a scale of 0.9–0.97 with opacity, never from scale 0. Tiny sparkles and dots are the exception.+8. **Press feedback.** A pressable thing scales to about 0.97 on press and comes back. The drawing inside stays as it is.+9. **Interruptible.** If the user can act again mid-animation (tap again, swipe back), continue from the current value toward the new target. Never restart from zero, and never jump.+10. **Glitches cost trust.** A hairline seam, a dropped frame, a jump at a loop's seam or a flickering blink tells people the product isn't careful. Check at full resolution and at full frame rate before calling anything done.++## 8. Performance and pitfalls- **Clocks:** one clock per character, group or scene; everything else is a function of its time.- **Pausing:** pause clocks off screen, when hidden, in the background and with reduced motion. A loop running behind opacity 0 still costs.@@ -150,8 +307,12 @@ Some scenes tell a small story: the phone buzzes, she picks it up, the alarm sto- **Many items** (particles, leaves, stars): draw them in one SVG or one `Canvas`, computing each from the same clock, never one animated view each.- **Unique SVG ids:** clip paths are global to the screen.- **Canvas engines** (Skia, a big `Canvas`): they're heavier. Don't multiply them, and don't keep one running behind another.+- **Drawing traps that show up in motion:**+ - **A seam where two edges meet.** Whenever two anti-aliased edges land on the same line, a hairline shows there. That covers a cutout (an even-odd hole) ending on its shape's outline, and a clip edge on top of another edge. The hairline can cut straight across a face or an object. Draw the shape as ONE outline instead (an upside-down U around a face, not a cap with a hole), and zoom in on the result to check.+ - **Overlapping parts in one path.** A union built as several subpaths in one path can cancel where the directions differ (nonzero winding), punching holes. Fill each part on its own.+ - **A glasses ring around closed eyes.** Clip the lid to a shape 2 units larger than the eye white (section 4).-## 7. Platforms+## 9. Platforms| Piece | React Native | SwiftUI | Web ||---|---|---|---|@@ -195,13 +356,55 @@ function Flake({ i }: { i: number }) {}```-## 8. Workflow+## 10. Working from a reference video++When someone hands you a video and says "make it like this", watch it frame by frame. Don't work from one look at it. The tools are in `tools/` (ffmpeg plus Python's standard library; run Python with `-I`). Keep the downloaded video in a folder of its own.++1. **Read its frame rate and length:**+ ```bash+ ffprobe -v error -show_entries stream=width,height,r_frame_rate,duration -of compact ref.mp4+ ```+2. **Make contact sheets at the full frame rate**, cropped to the subject, a second or two per sheet, and read them:+ ```bash+ tools/sheet.sh ref.mp4 START DUR W:H:X:Y # every frame, 10 per row+ tools/sheet.sh ref.mp4 0 LENGTH iw:ih:0:0 8 2 poses.png # 2 a second: just the poses+ ```+ A 2-frames-per-second sheet shows the poses. Only the full frame rate shows the timing, the follow-through and the moving holds, and those are what make it feel alive.+3. **Measure the motion with numbers; don't trust your eyes.** Motion of 1–5% (a jiggle, a breath, a float, a sway) doesn't show on a contact sheet, and it is often exactly what makes the reference feel alive. Something that looks still may not be. Track the subject's edges frame by frame, at the source's frame rate, using the subject's own colors:+ ```bash+ python3 -I tools/track_edges.py ref.mp4 --start S --dur D --fps SOURCE_FPS \+ --crop X:Y:W:H --colors RRGGBB,RRGGBB --cols C1,C2,C3 --row R+ ```+ The top edge at a few columns shows bobbing, squash and tilt. The left and right edges on one row show widening, swaying and leaning. Read off the amplitude, as a percentage of the subject's size, and the period, then use those numbers.+4. **Write the beats as data:** each beat with its start and end in milliseconds, such as `{ enter: [300, 900], hold: [900, 1650], leave: [1650, 2350] }`.+5. **Go part by part.** For every part (the feet, the hands, the head, the eyes, the shadow, the props, the background), ask what the reference does with it, and make yours do it too. A part that does nothing while the rest moves reads as dead: feet standing flat under a floating body, a shadow that never changes, eyes that ignore what is happening.+6. **Measure the proportions as ratios of one unit.** Even when you draw your own character, measure the reference's build in head widths: the head's share of the total height, the torso's height and width, the leg length, the size of the feet and the shadow. Then compare them with yours. "It looks stretched" or "it looks off" almost always means one of these ratios is far from the reference's, not a few percent.+7. **Measure the drawing when it must match exactly.** Crop the subject, scale it 2x and lay a grid over it (`drawgrid=w=100:h=100`). Read every shape's corners and curves off the grid, in one unit system (the video's pixels work well).+8. **Sample the colors from pixels; don't guess:**+ ```bash+ python3 -I tools/sample_colors.py ref.mp4 --at SECONDS X1,Y1 X2,Y2+ ```+ For a lit or glowing state, sample that moment too, then blend between the two colors (never swap them).+9. **Compare side by side at the same moments.** Render your version at the same times, stack it under the reference (`vstack`) and look for differences in timing, amplitude and pose. Run `track_edges.py` on your own render too, and compare the numbers.+10. **Make it yours if it will be published.** Measuring and copying a drawing exactly is fine for a private test. A published demo, repo or product needs original characters and art: brand mascots and illustrations are trademarks and copyrighted.++**Checking without a device.** On macOS, render frames offline (SwiftUI `ImageRenderer` into PNGs, then `ffmpeg` into MP4 and GIF; see `demo/render.swift`). Read contact sheets of your own frames before showing anything. When you crop them, use the PNG's pixel size: with `renderer.scale = 2`, a 720-point scene is 1440 pixels wide.++**Showing it in a device frame.** Give the scene a `height` and place its stage inside it: backgrounds and skies fill the whole height, and the action stays where you put it. Scale it to the screen inside the frame (`demo/PhoneMockup.swift`), and frame for the screen, not for the source: make the subject as big as the screen allows, with room for its widest pose and its highest jump, and set it where the eye expects it (feet in the lower part of the screen, not floating in the middle). Use a dark status bar on light screens and a white one on colored screens. Anything that enters "from off screen" must start beyond the device's screen edge, not just the scene's.++**Exporting for social posts.** Render the frames at 2x and at 60 fps (`render-demo ... fps=60`), then scale them down with a good filter. Check each platform's current limits first. For X: square takes the most room in the feed, and uploads are capped at 1920×1200 (or 1200×1900).+```bash+ffmpeg -framerate 60 -i frames/%04d.png -vf "scale=1080:1080:flags=lanczos,format=yuv420p" \+ -c:v libx264 -profile:v high -level 4.2 -preset slow -crf 18 -r 60 -movflags +faststart post.mp4+```++## 11. Workflow-1. **Read** the project notes (section 0) and the header comments of the art file; decisions recorded there are law.+1. **Read** the project notes (section 0) and the header comments of the art file; decisions recorded there are law. With a reference video, study it first (section 10).2. **List** what could live in the drawing: the main subject, its parts and pivots, repeated items, light, the background.3. **Pick** ONE main action and two or three idle loops. Cut the rest.4. **Split** the art into layers at their pivots, without changing how it looks at frame 0.5. **Tune** by putting every number in a token object at the top of the file, so "slower", "smaller" or "less" is a one-line change.-6. **Check** frame 0 (reduced motion), the final frame of one-shots, and that every loop closes without a jump.+6. **Check** frame 0 (reduced motion), the final frame of one-shots, and that every loop closes without a jump. For a character, run the "alive" checklist in section 5, and look at a contact sheet of every 4th frame of your own render.7. **Run** the project's type check, lint and tests.8. **Hand off** in plain words: what moves, what was left still on purpose, and what hasn't been seen on a real device yet.diff --git a/demo/PhoneMockup.swift b/demo/PhoneMockup.swiftnew file mode 100644index 0000000..c0270c8--- /dev/null+++ b/demo/PhoneMockup.swift@@ -0,0 +1,70 @@+// PhoneMockup.swift: an iPhone around a scene, on a white page, for the demo videos.+import SwiftUI++struct PhoneMockup<Screen: View>: View {+ static var size: CGSize { CGSize(width: 1080, height: 1080) }+ /// The screen in points; the scene is scaled to its width and fills its height.+ static var screen: CGSize { CGSize(width: 434, height: 940) }++ /// Dark status bar text on a light screen, white on a dark or coloured one.+ let darkStatus: Bool+ @ViewBuilder let content: Screen++ private let bezel = 12.0+ private let bodyRadius = 70.0+ private let screenRadius = 58.0+ private let island = CGSize(width: 128, height: 37)++ var body: some View {+ let s = Self.screen+ let phone = CGSize(width: s.width + bezel * 2, height: s.height + bezel * 2)+ ZStack {+ Color.white+ ZStack {+ // Side buttons: action and volume on the left, power on the right.+ ForEach(Array([(-1.0, 168.0, 34.0), (-1.0, 236.0, 64.0), (-1.0, 314.0, 64.0), (1.0, 260.0, 104.0)].enumerated()), id: \.offset) { _, b in+ Capsule()+ .fill(Color(hex: 0x2C2C30))+ .frame(width: 7, height: b.2)+ .offset(x: b.0 * (phone.width / 2 + 1), y: b.1 + b.2 / 2 - phone.height / 2)+ }+ RoundedRectangle(cornerRadius: bodyRadius, style: .continuous)+ .fill(Color(hex: 0x111113))+ .overlay(RoundedRectangle(cornerRadius: bodyRadius, style: .continuous)+ .strokeBorder(Color(hex: 0x4A4A4F), lineWidth: 3))+ .frame(width: phone.width, height: phone.height)+ .shadow(color: .black.opacity(0.16), radius: 28, x: 20, y: 26)+ content+ .frame(width: s.width, height: s.height, alignment: .topLeading)+ .clipShape(RoundedRectangle(cornerRadius: screenRadius, style: .continuous))+ statusBar+ .frame(width: s.width, height: s.height, alignment: .top)+ }+ }+ .frame(width: Self.size.width, height: Self.size.height)+ }++ /// 9:41, the Dynamic Island, signal, wifi and battery.+ private var statusBar: some View {+ let ear = (Self.screen.width - island.width) / 2+ return ZStack {+ Capsule().fill(Color.black).frame(width: island.width, height: island.height)+ HStack(spacing: 0) {+ Text("9:41")+ .font(.system(size: 17, weight: .semibold))+ .frame(width: ear)+ Spacer(minLength: 0)+ HStack(spacing: 6) {+ Image(systemName: "cellularbars")+ Image(systemName: "wifi")+ Image(systemName: "battery.100")+ }+ .font(.system(size: 14, weight: .semibold))+ .frame(width: ear)+ }+ .foregroundStyle(darkStatus ? Color.black : Color.white)+ }+ .frame(width: Self.screen.width, height: island.height)+ .padding(.top, 12)+ }+}diff --git a/demo/RevealScene.swift b/demo/RevealScene.swiftnew file mode 100644index 0000000..c830f6c--- /dev/null+++ b/demo/RevealScene.swift@@ -0,0 +1,624 @@+// RevealScene.swift: a reward reveal, and the demo of SKILL.md section 5 (acting).+// A mystery silhouette floats in with a swirl and sparkles, its feet dangling, and leaves+// rising. A kid in a new team kit appears in the air, hovers, falls and squashes on landing. A+// ball rolls in from the right; the kid kicks it away and watches it go, turns to the viewer and+// waves hello, shuffles, grins and hops. One clock, a 9-second loop. Every acting channel is a+// `flow` of key poses plus idle life plus follow-through, so nothing ever freezes. The build is+// a toy-like avatar seen from a little above (see `build`). Render it at 60 fps.+//+// The kid follows duolingo-character-style for its shapes: a 100-wide tombstone head centred on+// (0, 0) with y growing down, pill eyes with no brows, capsule arms whose shoulders hide behind+// the torso, circle hands, flat colours from the guide's palette.+import SwiftUI++struct RevealScene: View {+ let t: Double+ /// Taller than the scene (a phone screen): the scene stays in the middle, the sky fills the rest.+ var height = 720.0+ /// Where the 720-tall stage starts inside that height; centred when nil.+ var stageTop: Double? = nil+ private var top: Double { stageTop ?? (height - Self.size.height) / 2 }+ static let size = CGSize(width: 720, height: 720)+ static let loopMs = 9000.0++ private enum Ink {+ static let bg = Color.white+ static let skyTop = Color(hex: 0x84D8FF)+ static let skyMid = Color(hex: 0xDDF4FF)+ static let cloud = Color(hex: 0xB5E6FF)+ static let floor = Color(hex: 0xD3ECFA)+ static let mystery = Color(hex: 0x84D8FF)+ static let mysteryMark = Color(hex: 0xDDF4FF)+ static let swirl = Color(hex: 0xBBF2FF)+ static let spark = Color(hex: 0x84D8FF)+ static let skin = Color(hex: 0xF5B092)+ static let feature = Color(hex: 0xD97856)+ static let hair = Color(hex: 0x4A2C1C)+ static let top = Color(hex: 0xFF4B4B)+ static let topShade = Color(hex: 0xEA2B2B)+ static let shorts = Color(hex: 0x1453A3)+ static let shoe = Color(hex: 0x33333B)+ static let white = Color.white+ static let pupil = Color(hex: 0x3C3C3C)+ static let mouth = Color(hex: 0xB03A3A)+ static let tongue = Color(hex: 0xF15A5A)+ static let ballShade = Color(hex: 0xD2E4E8)+ }++ // MARK: - Tokens++ /// Where the feet stand on screen, and kid units (head = 100 wide) to screen points.+ private let feet = CGPoint(x: 360, y: 620)+ private let kidScale = 1.45+ /// The build, seen from a little above, like a toy: the head is almost half the height, the+ /// torso is short and narrower than the head, the legs are short, the feet are round dark+ /// shoes under the socks, and the shadow is a wide oval because the floor shows. The feet+ /// stand in the lower half of the shadow.+ private let build = (torsoTop: 50.0, torsoBottom: 112.0, shoulders: 42.0, waist: 38.0, hip: 22.0, hipY: 132.0,+ shoeBottom: 62.0, shadow: 140.0, shadowRatio: 0.32, shadowUp: 7.0)+ /// The kid's frame: the head centre is (0, 0); the soles are this far below it.+ private var floorY: Double { build.hipY + build.shoeBottom }+ /// Arms: shoulder (inside the torso), capsule thickness, hand radius, upper arm and forearm+ /// (similar lengths, one shared round elbow), and how much further a raised straight arm reaches.+ private let arm = (x: 34.0, y: 66.0, w: 26.0, hand: 13.0, upper: 30.0, fore: 28.0, reach: 12.0)+ /// The beats of the loop, in ms.+ private let beat = (mysteryIn: 250.0, swirl: 500.0, mysteryOut: 2100.0, drop: 2450.0, fall: 2850.0,+ land: 3060.0, hop: 7560.0, hopEnd: 7940.0, out: 8500.0, gone: 8900.0)+ private let jump = (hover: 104.0, top: 116.0, hop: 28.0)++ private static let ink = FaceInk(white: .white, pupil: Ink.pupil, skin: Ink.skin, line: Ink.feature, lineWidth: 5)+ /// Blinks land on the head turns, as people do.+ private static let lid = blinks([3550, 4850, 5900, 8420])+ private static let cheek: Keys = [Key(0, 0), Key(7480, 0), Key(7580, 1, out: true), Key(8180, 1), Key(8340, 0), Key(loopMs, 0)]+ /// The open mouth's depth: wide on arrival and for the grin, a small open smile at rest.+ private static let mouth: Keys = [+ Key(0, 22), Key(2450, 22), Key(3060, 16), Key(3300, 14), Key(3600, 11), Key(4050, 9), Key(4150, 18), Key(4400, 20),+ Key(4600, 14), Key(4900, 16), Key(5100, 20), Key(6300, 18), Key(6700, 12),+ Key(7480, 10), Key(7580, 22, out: true), Key(8180, 22), Key(8360, 11), Key(8900, 11), Key(loopMs, 22),+ ]++ private static func blinks(_ at: [Double]) -> Keys {+ var keys = [Key(0, 0)]+ // Close in 110 ms, hold 40, reopen in 190 with ease-out: enough frames to read as one smooth+ // motion (a 70 ms close is two frames at 30 fps and flickers).+ for b in at { keys += [Key(b, 0), Key(b + 110, 1), Key(b + 150, 1), Key(b + 340, 0, out: true)] }+ return keys + [Key(loopMs, 0)]+ }++ var body: some View {+ Canvas { ctx, _ in+ ctx.fill(Path(CGRect(x: 0, y: 0, width: Self.size.width, height: height)), with: .color(Ink.bg))+ drawSky(ctx)+ var stage = ctx+ stage.translateBy(x: 0, y: top)+ drawMystery(stage)+ drawKidOnStage(stage)+ }+ .frame(width: Self.size.width, height: height)+ }++ // MARK: - Acting: smooth channels through key poses, plus idle life and follow-through++ /// One arm: `a` the upper arm's outward angle (0 hangs down), `e` the elbow bend+ /// (the forearm points at a + e; positive folds it up and out, negative in toward the body).+ private struct Arm { var a = 12.0, e = 0.0 }++ private struct Pose {+ var lift = 0.0, sx = 1.0, sy = 1.0, lean = 0.0+ /// The weight moving over one leg (hip shift), and the turn of head and chest, -1 to 1.+ var shift = 0.0, yaw = 0.0, head = 0.0+ var armL = Arm(), armR = Arm()+ /// Legs: outward angle in degrees.+ var legL = 3.0, legR = 3.0+ /// Levitating, 0 to 1: the legs hang limp, the toes point down, one knee folds a little.+ /// `pedal` (-1 to 1) slowly trades which leg is folded.+ var float = 0.0, pedal = 0.0+ /// The right foot's toe pointing through a kick, in degrees.+ var toeR = 0.0+ }++ /// The key poses: hover and fall, land, the ball rolls in and gets kicked, the kid watches it+ /// go, turns to the viewer and waves hello, shuffles, then the grin and the hop.+ private enum Act {+ static let sy: FlowKeys = [(0, 1), (2450, 1), (2850, 1), (2980, 1.1), (3060, 1.06), (3120, 0.8), (3220, 1.03),+ (3360, 1), (7440, 1), (7530, 0.9), (7600, 1.08), (7880, 1.02), (7950, 0.88),+ (8040, 1.03), (8160, 1), (9000, 1)]+ static let lean: FlowKeys = [(0, 0), (2450, 0), (2850, -2), (3060, 0), (3400, 0), (3850, -2), (4050, -4), (4150, -9),+ (4300, -5), (4550, 0), (5000, -3), (5500, 2), (6000, -2), (6400, 2), (6800, 0), (9000, 0)]+ static let shift: FlowKeys = [(0, 0), (3060, 0), (3350, 0), (3800, -4), (4050, -10), (4250, -8), (4550, 0),+ (5200, -4), (6300, -4), (6800, 0), (9000, 0)]+ static let yaw: FlowKeys = [(0, 0), (3350, 0), (3600, 0.45), (4050, 0.3), (4200, 0.55), (4600, 0.5), (4900, 0),+ (5100, 0.15), (6300, 0.2), (6700, 0), (9000, 0)]+ static let head: FlowKeys = [(0, 0), (2450, -4), (3060, 0), (3400, 0), (3600, 6), (4050, 3), (4200, -6), (4600, -4),+ (4900, 0), (5100, 6), (6300, 4), (6700, 0), (7480, 0), (7620, 6), (8180, 2), (8360, 0),+ (9000, 0)]+ /// The eyes follow the ball: down to it as it rolls in, up after it once it is kicked, then+ /// back to the viewer for the hello.+ static let lookY: FlowKeys = [(0, -3), (3060, -3), (3400, 0), (3450, 0), (3650, 4), (4100, 4), (4250, -5), (4600, -4),+ (4850, 0), (8900, 0), (9000, -3)]+ static let lookX: FlowKeys = [(0, 0), (3450, 0), (3650, 3), (4100, 2), (4250, 5), (4600, 4), (4850, 0), (9000, 0)]+ /// The kick, added to the right leg: wind up across, stop at the top, swing out fast+ /// through the ball at 4100, follow through, come back down.+ static let kick: FlowKeys = [(0, 0), (3850, 0), (4050, -20), (4100, 22), (4160, 58), (4250, 52), (4500, 0), (9000, 0)]+ /// The kicking foot points its toe through the swing (degrees).+ static let toe: FlowKeys = [(0, 0), (3950, 0), (4100, 40), (4250, 35), (4500, 0), (9000, 0)]+ static let armRa: FlowKeys = [(0, 110), (2450, 110), (2850, 125), (2960, 150), (3060, 92), (3150, 84), (3300, 76),+ (3850, 22), (4050, 40), (4150, 18), (4300, 30), (4600, 20), (4900, 40), (5100, 62),+ (6300, 62), (6600, 30), (7000, 14), (7480, 14), (7620, 55), (8180, 42), (8360, 14),+ (8900, 14), (9000, 110)]+ static let armRe: FlowKeys = [(0, 0), (2450, 0), (3060, 0), (3300, 10), (3850, 10), (4050, 20), (4150, 30), (4300, 15),+ (4600, 10), (4900, 40), (5100, 108), (6300, 110), (6600, 30), (7000, 10), (7480, 10),+ (7620, 60), (8180, 40), (8360, 10), (8900, 10), (9000, 0)]+ static let armLa: FlowKeys = [(0, 110), (2450, 110), (2850, 125), (2960, 150), (3060, 92), (3150, 84), (3300, 78),+ (3850, 30), (4050, 55), (4150, 85), (4300, 60), (4600, 20), (5100, 20), (6300, 22),+ (6600, 18), (7000, 14), (7480, 14), (7620, 55), (8180, 42), (8360, 14), (8900, 14),+ (9000, 110)]+ static let armLe: FlowKeys = [(0, 0), (2450, 0), (3060, 0), (3300, 12), (3850, 10), (4050, 15), (4150, 25), (4300, 15),+ (4600, 10), (5100, -15), (6300, -18), (6600, 8), (7000, 10), (7480, 10), (7620, 60),+ (8180, 40), (8360, 10), (8900, 10), (9000, 0)]+ }++ private func pose(_ t: Double) -> Pose {+ var p = Pose()+ // Idle life runs the whole time the kid is on stage: never a frozen frame.+ let on = t >= beat.drop && t < beat.gone ? 1.0 : 0.0+ // Height: hovers with the legs dangling, falls with gravity, the hop.+ if t >= beat.drop && t < beat.fall {+ p.lift = jump.hover + (jump.top - jump.hover) * easeOut.value(at: (t - beat.drop) / (beat.fall - beat.drop))+ } else if t >= beat.fall && t < beat.land {+ let k = (t - beat.fall) / (beat.land - beat.fall)+ p.lift = jump.top * (1 - k * k)+ } else if t >= beat.hop && t < beat.hopEnd {+ let k = (t - beat.hop) / (beat.hopEnd - beat.hop)+ p.lift = jump.hop * 4 * k * (1 - k)+ }+ // Squash and stretch keep the volume; breathing on top.+ let s = flow(t, Act.sy)+ p.sx = 1 / pow(s, 0.6)+ p.sy = s * (1 + 0.014 * wave(t, period: 2250) * on)+ let swaying = seg(t, 5100, 5300) * (1 - seg(t, 6100, 6300))+ p.lean = flow(t, Act.lean) + (1.5 * wave(t, period: 4500, phase: 0.2) + 2.5 * wave(t, period: 1500) * swaying) * on+ p.shift = 0.6 * flow(t, Act.shift) + 1.2 * wave(t, period: 4500) * on+ p.yaw = flow(t, Act.yaw) + 0.06 * wave(t, period: 3000, phase: 0.1) * on+ // The head follows the body a beat later and the other way, on top of its own acting.+ p.head = flow(t, Act.head) - 0.45 * flow(t - 110, Act.lean) + 2 * wave(t, period: 4500, phase: 0.6) * on+ // Arms: the key poses, a small sway that never stops, flapping in the air, and a forearm+ // that trails the upper arm when it swings (follow-through).+ let flap = 8 * wave(t, period: 450) * (t >= beat.drop && t < beat.fall ? 1 : 0)+ func arm(_ ka: FlowKeys, _ ke: FlowKeys, phase: Double) -> Arm {+ let sway = 4 * wave(t, period: 3000, phase: phase) + 2 * wave(t, period: 1800, phase: phase + 0.3)+ let a = flow(t, ka) + sway * on + flap+ let trail = 0.45 * (flow(t - 90, ka) - flow(t, ka))+ let e = flow(t, ke) + 5 * wave(t, period: 2250, phase: phase + 0.6) * on + trail+ return Arm(a: a, e: e)+ }+ p.armR = arm(Act.armRa, Act.armRe, phase: 0)+ p.armR.e += 14 * wave(t, period: 750) * seg(t, 5100, 5250) * (1 - seg(t, 6150, 6300))+ p.armL = arm(Act.armLa, Act.armLe, phase: 0.5)+ // Legs: dangle in the air, splay on the squash, a little shuffle, the free leg on the weight shift.+ let air = t >= beat.drop && t < beat.land ? 1 - seg(t, beat.land - 80, beat.land) : 0+ let splay = max(0, 1 - s) * 50+ p.legR = 3 + air * (5 + 7 * wave(t, period: 600)) + splay + 9 * bell((t - 6650) / 260) + flow(t, Act.kick)+ p.toeR = flow(t, Act.toe)+ p.legL = 3 + air * (5 + 7 * wave(t, period: 600, phase: 0.35)) + splay + 9 * bell((t - 6870) / 260)+ + max(0, p.shift) * 0.9+ // Hanging in the air the feet dangle; they flatten just before touching down.+ p.float = t >= beat.drop && t < beat.land ? 1 - seg(t, beat.land - 160, beat.land - 20) : 0+ p.pedal = wave(t, period: 600)+ return p+ }++ // MARK: - Sky: fades in behind the kid, with drifting clouds and twinkles++ private func drawSky(_ ctx: GraphicsContext) {+ let on = seg(t, 2500, 3000) * (1 - seg(t, beat.out, 8950, easeOut: false))+ guard on > 0 else { return }+ var s = ctx+ s.opacity = on+ // The gradient reaches white just above the feet, whatever the screen's height.+ let dy = top+ s.fill(Path(CGRect(x: 0, y: 0, width: Self.size.width, height: height)),+ with: .linearGradient(Gradient(stops: [.init(color: Ink.skyTop, location: 0),+ .init(color: Ink.skyMid, location: (dy + 360) / height),+ .init(color: Ink.bg, location: (dy + 576) / height)]),+ startPoint: .zero, endPoint: CGPoint(x: 0, y: height)))+ let clouds: [(x: Double, y: Double, r: Double)] = [+ (-10, 300, 96), (66, 236, 62), (-4, 176, 58), (730, 340, 104), (654, 276, 66), (706, 196, 56),+ ]+ for (i, c) in clouds.enumerated() {+ let dx = 8 * wave(t, period: Self.loopMs, phase: Double(i) * 0.17)+ s.fill(Path(ellipseIn: CGRect(x: c.x + dx - c.r, y: c.y - c.r, width: c.r * 2, height: c.r * 2)), with: .color(Ink.cloud))+ }+ let stars: [(x: Double, y: Double, r: Double)] = [+ (150, 190, 10), (580, 230, 9), (230, 90, 7), (480, 120, 11), (90, 330, 8), (640, 360, 7), (330, 60, 6),+ ]+ for (i, st) in stars.enumerated() {+ let p = loop(t, period: 1800, phase: seeded(i, salt: 2)) / 0.45+ guard p < 1 else { continue }+ var g = s+ g.translateBy(x: st.x, y: st.y)+ g.scaleBy(x: bell(p), y: bell(p))+ g.fill(fourPointStar(r: st.r), with: .color(Ink.white))+ }+ }++ // MARK: - The mystery: a silhouette with a question mark, a swirl and sparkles++ private func drawMystery(_ ctx: GraphicsContext) {+ guard t < beat.drop else { return }+ let inK = seg(t, beat.mysteryIn, beat.mysteryIn + 450)+ let outK = seg(t, beat.mysteryOut, beat.mysteryOut + 250, easeOut: false)+ let on = inK * (1 - outK)+ let scale = (0.92 + 0.08 * inK) * kidScale+ // It floats, measured on the reference: rises in from 30% of its height below and slows,+ // drifts down 5% and back up, and leaves rising while it fades.+ // `hover` is the height of the feet above the floor; the shadow shrinks as it rises.+ let hover = 70 - flow(t, [(beat.mysteryIn, 120), (900, 0), (1650, 18), (2350, -60)])+ let shadowK = 1 - min(1, max(0, hover) / 220)++ drawMysterySparks(ctx)+ var shade = ctx+ shade.opacity = on+ let mw = build.shadow * kidScale * shadowK+ shade.fill(Path(ellipseIn: CGRect(x: feet.x - mw / 2, y: feet.y - build.shadowUp * kidScale - mw * build.shadowRatio / 2,+ width: mw, height: mw * build.shadowRatio)), with: .color(Ink.floor))+ drawSwirl(ctx, front: false)+ var m = ctx+ m.opacity = on+ m.translateBy(x: feet.x, y: feet.y - hover)+ m.scaleBy(x: scale, y: scale)+ m.translateBy(x: 0, y: -floorY)+ var levitating = Pose()+ levitating.float = 1+ levitating.pedal = wave(t, period: 2400)+ levitating.legL = -2 + 3 * wave(t, period: 1800, phase: 0.2)+ levitating.legR = -2 + 3 * wave(t, period: 1800, phase: 0.55)+ levitating.armL = Arm(a: 16 + 3 * wave(t, period: 2400, phase: 0.1), e: 6)+ levitating.armR = Arm(a: 16 + 3 * wave(t, period: 2400, phase: 0.6), e: 6)+ drawKid(m, pose: levitating, flat: Ink.mystery)+ m.draw(Text("?").font(.system(size: 46, weight: .heavy, design: .rounded)).foregroundColor(Ink.mysteryMark),+ at: CGPoint(x: 0, y: 82))+ drawSwirl(ctx, front: true)+ }++ /// A ring that spirals up around the silhouette once, its back half behind it.+ private func drawSwirl(_ ctx: GraphicsContext, front: Bool) {+ let p = (t - beat.swirl) / 700+ guard p > 0, p < 1 else { return }+ let head = -Double.pi / 2 + p * 2 * .pi * 1.15+ let cy = feet.y - 70 - (30 + 160 * easeOut.value(at: p)) * kidScale+ let tilt = -12.0 * .pi / 180+ var g = ctx+ g.opacity = bell(p)+ let n = 16+ for i in 0..<n {+ let a0 = head - 2.0 + 2.0 * Double(i) / Double(n)+ let a1 = head - 2.0 + 2.0 * Double(i + 1) / Double(n)+ guard (sin((a0 + a1) / 2) > 0) == front else { continue }+ var piece = Path()+ for (j, a) in [a0, a1].enumerated() {+ let lx = 105 * kidScale * cos(a), ly = 24 * kidScale * sin(a)+ let pt = CGPoint(x: feet.x + lx * cos(tilt) - ly * sin(tilt), y: cy + lx * sin(tilt) + ly * cos(tilt))+ if j == 0 { piece.move(to: pt) } else { piece.addLine(to: pt) }+ }+ g.stroke(piece, with: .color(Ink.swirl), style: StrokeStyle(lineWidth: 3 + 9 * Double(i) / Double(n), lineCap: .round))+ }+ }++ /// A burst outward as the silhouette arrives, then a few twinkles while it waits.+ private func drawMysterySparks(_ ctx: GraphicsContext) {+ let center = CGPoint(x: feet.x, y: feet.y - 70 - 120 * kidScale)+ for i in 0..<16 {+ let burst = i < 10+ let start = burst ? 560 + seeded(i, salt: 2) * 350 : 1200 + seeded(i, salt: 4) * 800+ let p = (t - start) / 700+ guard p > 0, p < 1 else { continue }+ let a = seeded(i, salt: 1) * 2 * .pi+ let r = (95 + seeded(i, salt: 3) * 45 + (burst ? 35 * easeOut.value(at: p) : 0)) * kidScale+ var g = ctx+ g.translateBy(x: center.x + cos(a) * r, y: center.y + sin(a) * r * 1.3)+ g.scaleBy(x: bell(p), y: bell(p))+ switch i % 3 {+ case 0: g.fill(fourPointStar(r: 10 + seeded(i, salt: 5) * 8), with: .color(Ink.spark))+ case 1: g.fill(Path(ellipseIn: CGRect(x: -5, y: -5, width: 10, height: 10)), with: .color(Ink.spark))+ default:+ g.rotate(by: .radians(a + .pi / 2))+ g.fill(pill(cx: 0, cy: 0, w: 8, h: 24), with: .color(Ink.spark))+ }+ }+ }++ // MARK: - The kid on stage: drops in, lands, acts, grins, leaves++ private func drawKidOnStage(_ ctx: GraphicsContext) {+ guard t >= beat.drop, t < beat.gone else { return }+ let appear = seg(t, beat.drop, beat.drop + 120)+ let leave = seg(t, beat.out, beat.gone, easeOut: false)+ let p = pose(t)+ let ground = 1 - min(1, p.lift / 250)++ var shade = ctx+ shade.opacity = appear * (1 - leave)+ let sw = build.shadow * kidScale * ground * p.sx+ shade.fill(Path(ellipseIn: CGRect(x: feet.x + p.shift * 0.4 * kidScale - sw / 2,+ y: feet.y - build.shadowUp * kidScale - sw * build.shadowRatio / 2,+ width: sw, height: sw * build.shadowRatio)), with: .color(Ink.floor))++ var k = ctx+ k.opacity = appear * (1 - leave)+ k.translateBy(x: feet.x, y: feet.y - p.lift)+ k.rotate(by: .degrees(p.lean))+ let s = (0.94 + 0.06 * appear) * (1 - 0.03 * leave) * kidScale+ k.scaleBy(x: p.sx * s, y: p.sy * s)+ k.translateBy(x: 0, y: -floorY)+ drawKid(k, pose: p, flat: nil)+ drawBall(ctx)+ }++ // MARK: - The ball: rolls in from off the right edge, gets kicked, flies off spinning++ /// Radius, where it starts (off screen, even inside the phone) and stops by the right foot+ /// (stage units), when it enters, arrives and is kicked, the launch speed (units a second),+ /// gravity and spin (radians a second).+ private let ball = (r: 36.0, startX: 810.0, stopX: 440.0, enter: 3350.0, arrive: 4000.0, kick: 4100.0,+ vx: 900.0, vy: 760.0, g: 1500.0, spin: 16.0)++ private func drawBall(_ ctx: GraphicsContext) {+ guard t >= ball.enter, t < ball.kick + 700 else { return }+ let ground = feet.y - ball.r+ var x = ball.stopX, y = ground, angle = 0.0, sx = 1.0, sy = 1.0+ if t < ball.kick {+ // Rolling: it comes in already moving and slows to a stop by the foot. A ball that+ // rolls without slipping turns by the distance over its radius.+ let k = min(1, (t - ball.enter) / (ball.arrive - ball.enter))+ x = ball.startX + (ball.stopX - ball.startX) * easeOut.value(at: k)+ angle = (x - ball.startX) / ball.r+ } else {+ // Kicked: a throw (a straight line plus gravity), spinning, squashed for a moment at contact.+ let s = (t - ball.kick) / 1000+ x = ball.stopX + ball.vx * s+ y = ground - ball.vy * s + ball.g * s * s / 2+ angle = (ball.stopX - ball.startX) / ball.r + ball.spin * s+ let contact = 1 - seg(t, ball.kick, ball.kick + 90)+ sx = 1 - 0.16 * contact+ sy = 1 + 0.12 * contact+ }+ // Its shadow stays on the floor and shrinks as the ball rises.+ let low = 1 - min(1, (ground - y) / 160)+ if low > 0 {+ let bw = ball.r * 2.2 * low+ ctx.fill(Path(ellipseIn: CGRect(x: x - bw / 2, y: feet.y - bw * build.shadowRatio / 2, width: bw, height: bw * build.shadowRatio)),+ with: .color(Ink.floor))+ }+ var b = ctx+ b.translateBy(x: x, y: y)+ b.scaleBy(x: sx, y: sy)+ let disc = Path(ellipseIn: CGRect(x: -ball.r, y: -ball.r, width: ball.r * 2, height: ball.r * 2))+ // One shade step on the side away from the light; it stays put while the ball turns.+ b.fill(disc, with: .color(Ink.ballShade))+ var lit = b+ lit.clip(to: disc)+ lit.fill(Path(ellipseIn: CGRect(x: -ball.r * 1.14, y: -ball.r * 1.14, width: ball.r * 1.9, height: ball.r * 1.9)),+ with: .color(Ink.white))+ // The patches turn with the ball: a rounded pentagon in the middle, five more cut by the edge.+ var skin = b+ skin.clip(to: disc)+ skin.rotate(by: .radians(angle))+ skin.fill(pentagon(center: .zero, radius: ball.r * 0.36, turn: 0), with: .color(Ink.pupil))+ for i in 0..<5 {+ let a = Double(i) / 5 * 2 * .pi - .pi / 2+ skin.fill(pentagon(center: CGPoint(x: cos(a) * ball.r, y: sin(a) * ball.r), radius: ball.r * 0.34, turn: a + .pi),+ with: .color(Ink.pupil))+ }+ }++ private func pentagon(center: CGPoint, radius: Double, turn: Double) -> Path {+ roundedPolygon((0..<5).map { i in+ let a = turn + Double(i) / 5 * 2 * .pi - .pi / 2+ return CGPoint(x: center.x + cos(a) * radius, y: center.y + sin(a) * radius)+ }, r: radius * 0.25)+ }++ // MARK: - The kid, in the head frame. `flat` paints every part one colour with no face.++ private func drawKid(_ c: GraphicsContext, pose: Pose, flat: Color?) {+ func paint(_ g: GraphicsContext, _ path: Path, _ color: Color, eo: Bool = false) {+ g.fill(path, with: .color(flat ?? color), style: FillStyle(eoFill: eo))+ }+ func capsules(_ g: GraphicsContext, _ pts: [CGPoint], _ w: Double, _ color: Color) {+ var p = Path()+ p.addLines(pts)+ g.stroke(p, with: .color(flat ?? color), style: StrokeStyle(lineWidth: w, lineCap: .round, lineJoin: .round))+ }+ let yaw = pose.yaw++ // Short legs hang from the hips, which carry the weight shift; the feet stay under the body.+ // Seen from above, each foot is a round dark shoe, its top tucked under the sock.+ for (side, angle) in [(-1.0, pose.legL), (1.0, pose.legR)] {+ var leg = c+ leg.translateBy(x: side * build.hip + pose.shift, y: build.hipY)+ leg.rotate(by: .degrees(-side * angle + pose.shift))+ // Levitating, one knee folds a little (that leg reads shorter) and the foot hangs: the+ // shoe gets narrower and longer, toes down.+ let tuck = pose.float * 8 * (0.5 + 0.5 * side * pose.pedal)+ var shoe = leg+ shoe.translateBy(x: 0, y: 46 - tuck)+ shoe.rotate(by: .degrees(side > 0 ? pose.toeR : 0))+ shoe.scaleBy(x: 1 - 0.3 * pose.float, y: 1 + 0.35 * pose.float)+ paint(shoe, Path(roundedRect: CGRect(x: -15 + side * 2, y: -4, width: 30, height: 20), cornerRadius: 10), Ink.shoe)+ capsules(leg, [.zero, CGPoint(x: 0, y: 24 - tuck)], 20, Ink.skin)+ paint(leg, Path(roundedRect: CGRect(x: -12.5, y: 16 - tuck, width: 25, height: 33), cornerRadius: 9), Ink.top)+ paint(leg, Path(CGRect(x: -12.5, y: 21 - tuck, width: 25, height: 5)), Ink.white)+ }++ // Everything above the legs rides on the hips.+ var up = c+ up.translateBy(x: pose.shift, y: 0)+ paint(up, Path(roundedRect: CGRect(x: -40, y: 104, width: 80, height: 34), cornerRadius: 12), Ink.shorts)++ // Arms behind the torso, so the shoulder never shows: upper arm and forearm share one round+ // elbow, the hand is a circle, a short wide sleeve caps the shoulder.+ for (side, limb) in [(-1.0, pose.armL), (1.0, pose.armR)] {+ let a = limb.a * .pi / 180, f = (limb.a + limb.e) * .pi / 180+ let straight = min(1, max(0, 1 - abs(limb.e) / 40))+ let reach = arm.reach * min(1, max(0, (limb.a - 100) / 50)) * straight+ let from = CGPoint(x: side * arm.x, y: arm.y)+ let elbow = CGPoint(x: from.x + side * sin(a) * arm.upper, y: from.y + cos(a) * arm.upper)+ let uf = CGPoint(x: side * sin(f), y: cos(f))+ let hand = CGPoint(x: elbow.x + uf.x * (arm.fore + reach), y: elbow.y + uf.y * (arm.fore + reach))+ capsules(up, [from, elbow, CGPoint(x: hand.x - uf.x * 8, y: hand.y - uf.y * 8)], arm.w, Ink.skin)+ paint(up, Path(ellipseIn: CGRect(x: hand.x - arm.hand, y: hand.y - arm.hand, width: arm.hand * 2, height: arm.hand * 2)), Ink.skin)+ capsules(up, [from, CGPoint(x: from.x + side * sin(a) * 16, y: from.y + cos(a) * 16)], arm.w + 10, Ink.top)+ }++ // The jersey: short, narrowing a little toward the waist; the head sits right on the collar.+ // Turning slides the stripes, collar and crest.+ let torso = roundedPolygon([CGPoint(x: -build.shoulders, y: build.torsoTop), CGPoint(x: build.shoulders, y: build.torsoTop),+ CGPoint(x: build.waist, y: build.torsoBottom), CGPoint(x: -build.waist, y: build.torsoBottom)], r: 18)+ paint(up, torso, Ink.top)+ if flat == nil {+ var chest = up+ chest.clip(to: torso)+ for x in [-24.0, -5.0, 14.0] {+ chest.fill(Path(CGRect(x: x + 5 * yaw, y: build.torsoTop, width: 10, height: build.torsoBottom - build.torsoTop)),+ with: .color(Ink.topShade))+ }+ chest.fill(pill(cx: 4 * yaw, cy: build.torsoTop + 3, w: 30, h: 10), with: .color(Ink.topShade))+ chest.fill(Path(ellipseIn: CGRect(x: 13 + 7 * yaw, y: 60, width: 12, height: 12)), with: .color(Ink.white))+ }++ // Head, tilting where it meets the collar. Turning slides the face one way and the ears the+ // other; the far ear tucks behind the head.+ var h = up+ h.translateBy(x: 0, y: 56)+ h.rotate(by: .degrees(pose.head))+ h.translateBy(x: 0, y: -56)+ for side in [-1.0, 1.0] {+ paint(h, Path(ellipseIn: CGRect(x: side * 50 - 9 * yaw - 11, y: -9, width: 22, height: 22)), Ink.skin)+ }+ paint(h, tomb(cx: 0, top: -66, w: 100, h: 122, r: 26), Ink.skin)+ if flat == nil { drawFace(h, yaw: yaw) }+ // Hair: a cap down to above the ears and one quiff. The cap is ONE outline (an upside-down U+ // around the face), never a shape with a hole cut in it: any cutout edge that lands on+ // another edge leaves an anti-aliased hairline, here straight across the eyes.+ paint(h, hairCap(window: -39 + 9 * yaw), Ink.hair)+ let q = 5 * yaw+ paint(h, roundedTriangle(CGPoint(x: -30 + q, y: -70), CGPoint(x: 34 + q, y: -104), CGPoint(x: 48 + q, y: -58), r: 12), Ink.hair)+ }++ private func drawFace(_ h: GraphicsContext, yaw: Double) {+ // The lower lid rises a little to meet the upper one, so the eye closes nearer its middle.+ let lid = track(t, Self.lid)+ let face = Choreo(period: Self.loopMs, lookX: [Key(0, 5 * yaw + flow(t, Act.lookX))], lookY: [Key(0, flow(t, Act.lookY))],+ lid: [Key(0, lid)], cheek: [Key(0, max(track(t, Self.cheek), 0.18 * lid))], mouth: Self.mouth)+ let dx = 10 * yaw+ for side in [-1.0, 1.0] {+ h.fill(pill(cx: side * 19.5 + dx, cy: -8, w: 30, h: 40), with: .color(Ink.white))+ drawLiveEye(h, side: side,+ eye: EyeGeometry(cx: side * 19.5 + dx, cy: -8, w: 30, h: 40, pupilW: 13, pupilH: 20, pupilTop: 7, shine: 2.8),+ ink: Self.ink, choreo: face, t: t)+ }+ // The nose sticks out, so it slides a little further than the eyes.+ let nx = 13 * yaw+ h.fill(pill(cx: 2 + nx, cy: -2, w: 8, h: 22), with: .color(Ink.feature))+ h.fill(Path(ellipseIn: CGRect(x: -4.5 + nx, y: 2.5, width: 13, height: 13)), with: .color(Ink.feature))+ drawLiveMouth(h, x0: -16 + dx, x1: 18 + dx, top: 24, tilt: 6, mouth: Ink.mouth, tongue: Ink.tongue, teeth: Ink.white,+ choreo: face, t: t)+ }++ // MARK: - The style's shapes++ /// A tombstone: a half-circle top, straight sides, bottom corners of radius r.+ /// When h <= w/2 it is a cap: an arc cut flat at the bottom.+ private func tomb(cx: Double, top: Double, w: Double, h: Double, r: Double) -> Path {+ let R = w / 2, yb = top + h+ var p = Path()+ if h <= R {+ let half = (R * R - (R - h) * (R - h)).squareRoot()+ let a = asin((R - h) / R)+ p.move(to: CGPoint(x: cx - half, y: yb))+ p.addArc(center: CGPoint(x: cx, y: top + R), radius: R, startAngle: .radians(.pi + a), endAngle: .radians(-a), clockwise: false)+ p.closeSubpath()+ return p+ }+ let q = min(r, R, h - R)+ p.move(to: CGPoint(x: cx - R, y: top + R))+ p.addArc(center: CGPoint(x: cx, y: top + R), radius: R, startAngle: .degrees(180), endAngle: .degrees(0), clockwise: false)+ p.addLine(to: CGPoint(x: cx + R, y: yb - q))+ p.addQuadCurve(to: CGPoint(x: cx + R - q, y: yb), control: CGPoint(x: cx + R, y: yb))+ p.addLine(to: CGPoint(x: cx - R + q, y: yb))+ p.addQuadCurve(to: CGPoint(x: cx - R, y: yb - q), control: CGPoint(x: cx - R, y: yb))+ p.closeSubpath()+ return p+ }++ /// The hair cap as one outline: a half-circle top, sideburns down to above the ears, and the+ /// face's opening (rounded at the top) starting at `window` and 78 wide.+ private func hairCap(window x0: Double) -> Path {+ let R = 55.0, cy = -19.0, bottom = -10.0, q = 8.0, top = -42.0, w = 78.0, r = 18.0+ var p = Path()+ p.move(to: CGPoint(x: -R, y: cy))+ p.addArc(center: CGPoint(x: 0, y: cy), radius: R, startAngle: .degrees(180), endAngle: .degrees(0), clockwise: false)+ p.addLine(to: CGPoint(x: R, y: bottom - q))+ p.addQuadCurve(to: CGPoint(x: R - q, y: bottom), control: CGPoint(x: R, y: bottom))+ p.addLine(to: CGPoint(x: x0 + w, y: bottom))+ p.addLine(to: CGPoint(x: x0 + w, y: top + r))+ p.addQuadCurve(to: CGPoint(x: x0 + w - r, y: top), control: CGPoint(x: x0 + w, y: top))+ p.addLine(to: CGPoint(x: x0 + r, y: top))+ p.addQuadCurve(to: CGPoint(x: x0, y: top + r), control: CGPoint(x: x0, y: top))+ p.addLine(to: CGPoint(x: x0, y: bottom))+ p.addLine(to: CGPoint(x: -R + q, y: bottom))+ p.addQuadCurve(to: CGPoint(x: -R, y: bottom - q), control: CGPoint(x: -R, y: bottom))+ p.closeSubpath()+ return p+ }++ /// A rectangle with only its top corners rounded.+ private func topRound(x: Double, y: Double, w: Double, h: Double, r: Double) -> Path {+ let q = min(r, w / 2, h)+ var p = Path()+ p.move(to: CGPoint(x: x, y: y + h))+ p.addLine(to: CGPoint(x: x, y: y + q))+ p.addQuadCurve(to: CGPoint(x: x + q, y: y), control: CGPoint(x: x, y: y))+ p.addLine(to: CGPoint(x: x + w - q, y: y))+ p.addQuadCurve(to: CGPoint(x: x + w, y: y + q), control: CGPoint(x: x + w, y: y))+ p.addLine(to: CGPoint(x: x + w, y: y + h))+ p.closeSubpath()+ return p+ }++ /// The rounded triangle with corners a, b, c and corner radius r.+ private func roundedTriangle(_ a: CGPoint, _ b: CGPoint, _ c: CGPoint, r: Double) -> Path {+ roundedPolygon([a, b, c], r: r)+ }++ /// A polygon with every corner rounded (radius r).+ private func roundedPolygon(_ pts: [CGPoint], r: Double) -> Path {+ let n = pts.count+ var p = Path()+ for i in 0..<n {+ let pt = pts[i], prev = pts[(i + n - 1) % n], next = pts[(i + 1) % n]+ func toward(_ q: CGPoint) -> CGPoint {+ let dx = q.x - pt.x, dy = q.y - pt.y, l = max(0.001, (dx * dx + dy * dy).squareRoot())+ return CGPoint(x: pt.x + dx / l * r, y: pt.y + dy / l * r)+ }+ let s = toward(prev), e = toward(next)+ if i == 0 { p.move(to: s) } else { p.addLine(to: s) }+ p.addQuadCurve(to: e, control: pt)+ }+ p.closeSubpath()+ return p+ }++ /// A soft four-point star centred on (0, 0).+ private func fourPointStar(r: CGFloat) -> Path {+ var p = Path()+ let w = r * 0.32+ p.move(to: CGPoint(x: 0, y: -r))+ p.addQuadCurve(to: CGPoint(x: r, y: 0), control: CGPoint(x: w, y: -w))+ p.addQuadCurve(to: CGPoint(x: 0, y: r), control: CGPoint(x: w, y: w))+ p.addQuadCurve(to: CGPoint(x: -r, y: 0), control: CGPoint(x: -w, y: w))+ p.addQuadCurve(to: CGPoint(x: 0, y: -r), control: CGPoint(x: -w, y: -w))+ return p+ }+}diff --git a/demo/render.swift b/demo/render.swiftindex 6e1cc1f..9652de1 100644--- a/demo/render.swift+++ b/demo/render.swift@@ -2,28 +2,55 @@//// swiftc -parse-as-library -target arm64-apple-macos14 \// templates/swiftui/Motion.swift templates/swiftui/LiveFace.swift demo/*.swift -o /tmp/render-demo-// /tmp/render-demo room /tmp/frames # or: orbit+// /tmp/render-demo room /tmp/frames # or: orbit, reveal+// /tmp/render-demo reveal /tmp/frames phone # inside an iPhone, on a square page+// /tmp/render-demo reveal /tmp/frames phone fps=60 # smoother, for posting+// /tmp/render-demo reveal /tmp/frames phone 0 40 # only these frames (to check before a full render)// ffmpeg -framerate 30 -i /tmp/frames/%04d.png -c:v libx264 -pix_fmt yuv420p -crf 20 demo/demo.mp4import Foundationimport ImageIOimport SwiftUIimport UniformTypeIdentifiers+@MainActor+func scene(_ name: String, _ t: Double, phone: Bool) -> (view: AnyView, loopMs: Double) {+ switch name {+ case "orbit":+ return (AnyView(OrbitScene(t: t)), OrbitScene.loopMs)+ case "reveal":+ guard phone else { return (AnyView(RevealScene(t: t)), RevealScene.loopMs) }+ // The 720-wide scene, as big as the screen allows, with the feet at 73% of the screen.+ let screen = PhoneMockup<EmptyView>.screen+ let k = screen.width / 720 * 1.85+ return (AnyView(PhoneMockup(darkStatus: true) {+ RevealScene(t: t, height: screen.height / k, stageTop: screen.height * 0.73 / k - 620)+ .scaleEffect(k, anchor: .topLeading)+ .offset(x: -(720 * k - screen.width) / 2)+ }), RevealScene.loopMs)+ default:+ return (AnyView(DemoScene(t: t)), DemoScene.loopMs)+ }+}+@mainstruct RenderDemo {@MainActorstatic func main() throws {- let args = CommandLine.arguments- let scene = args.count > 1 ? args[1] : "room"- let out = URL(fileURLWithPath: args.count > 2 ? args[2] : "frames")+ var args = Array(CommandLine.arguments.dropFirst())+ let name = args.isEmpty ? "room" : args.removeFirst()+ let out = URL(fileURLWithPath: args.isEmpty ? "frames" : args.removeFirst())+ let phone = args.first == "phone"+ if phone { args.removeFirst() }+ var fps = 30.0+ if let i = args.firstIndex(where: { $0.hasPrefix("fps=") }) {+ fps = Double(args.remove(at: i).dropFirst(4)) ?? 30+ }try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)- let fps = 30.0- let loopMs = scene == "orbit" ? OrbitScene.loopMs : DemoScene.loopMs- let frames = Int(loopMs / 1000 * fps)- for f in 0..<frames {- let t = Double(f) / fps * 1000- let content: AnyView = scene == "orbit" ? AnyView(OrbitScene(t: t)) : AnyView(DemoScene(t: t))- let renderer = ImageRenderer(content: content)+ let loopMs = scene(name, 0, phone: phone).loopMs+ let picks = args.compactMap { Int($0) }+ let frames = picks.isEmpty ? Array(0..<Int(loopMs / 1000 * fps)) : picks+ for f in frames {+ let renderer = ImageRenderer(content: scene(name, Double(f) / fps * 1000, phone: phone).view)renderer.scale = 2guard let image = renderer.cgImage else { throw CocoaError(.fileWriteUnknown) }let url = out.appendingPathComponent(String(format: "%04d.png", f))@@ -33,6 +60,6 @@ struct RenderDemo {CGImageDestinationAddImage(dest, image, nil)CGImageDestinationFinalize(dest)}- print("rendered \(frames) frames of \(scene) to \(out.path)")+ print("rendered \(frames.count) frames of \(name) to \(out.path)")}}diff --git a/demo/reveal.gif b/demo/reveal.gifnew file mode 100644index 0000000..76a654aBinary files /dev/null and b/demo/reveal.gif differdiff --git a/demo/reveal.mp4 b/demo/reveal.mp4new file mode 100644index 0000000..e67bf52Binary files /dev/null and b/demo/reveal.mp4 differdiff --git a/templates/react-native/motion.ts b/templates/react-native/motion.tsindex bc20965..94f0f2b 100644--- a/templates/react-native/motion.ts+++ b/templates/react-native/motion.ts@@ -36,6 +36,49 @@ export function track(t: number, keys: Keys): number {return keys[keys.length - 1][1];}+/** A key pose for `flow`: time (ms) and value, sorted by time. */+export type FlowKey = readonly [number, number];++/**+ * A smooth track through key poses, for acting (a body, arms, a head turn).+ * `track` eases in and out of EVERY key, so the motion stops at each one: fine for one+ * move (a blink, a lid), but a chain of poses then reads as stop-and-go, like a robot.+ * `flow` passes through the keys with a continuous speed and never overshoots one+ * (a monotone cubic). Repeat a value to hold, and layer idle life on top of the hold.+ */+export function flow(t: number, k: readonly FlowKey[]): number {+ 'worklet';+ const n = k.length;+ if (t <= k[0][0]) return k[0][1];+ if (t >= k[n - 1][0]) return k[n - 1][1];+ let i = 0;+ while (k[i + 1][0] < t) i++;+ function slope(j: number): number {+ return (k[j + 1][1] - k[j][1]) / (k[j + 1][0] - k[j][0]);+ }+ function tangent(j: number): number {+ if (j === 0 || j === n - 1) return 0;+ const a = slope(j - 1);+ const b = slope(j);+ if (a * b <= 0) return 0;+ const h0 = k[j][0] - k[j - 1][0];+ const h1 = k[j + 1][0] - k[j][0];+ const w0 = 2 * h1 + h0;+ const w1 = h1 + 2 * h0;+ return (w0 + w1) / (w0 / a + w1 / b);+ }+ const h = k[i + 1][0] - k[i][0];+ const s = (t - k[i][0]) / h;+ const s2 = s * s;+ const s3 = s2 * s;+ return (+ (2 * s3 - 3 * s2 + 1) * k[i][1] ++ (s3 - 2 * s2 + s) * h * tangent(i) ++ (-2 * s3 + 3 * s2) * k[i + 1][1] ++ (s3 - s2) * h * tangent(i + 1)+ );+}+/** 0 → 1 inside the window [a, b] of a clock (eased), 0 before it, 1 after. One beat of a scene. */export function seg(t: number, a: number, b: number, curve: 'out' | 'inOut' = 'out'): number {'worklet';diff --git a/templates/swiftui/Motion.swift b/templates/swiftui/Motion.swiftindex 5bf0dde..83b14ae 100644--- a/templates/swiftui/Motion.swift+++ b/templates/swiftui/Motion.swift@@ -51,6 +51,36 @@ public func track(_ t: Double, _ keys: Keys) -> Double {return keys[keys.count - 1].value}+/// Key poses for `flow`: (ms, value), sorted by time.+public typealias FlowKeys = [(Double, Double)]++/// A smooth track through key poses, for acting (a body, arms, a head turn).+/// `track` eases in and out of EVERY key, so the motion stops at each one: fine for one move+/// (a blink, a lid), but a chain of poses then reads as stop-and-go, like a robot. `flow` passes+/// through the keys with a continuous speed and never overshoots one (a monotone cubic).+/// Repeat a value to hold, and layer idle life on top of the hold.+public func flow(_ t: Double, _ k: FlowKeys) -> Double {+ let n = k.count+ if t <= k[0].0 { return k[0].1 }+ if t >= k[n - 1].0 { return k[n - 1].1 }+ var i = 0+ while k[i + 1].0 < t { i += 1 }+ func slope(_ j: Int) -> Double { (k[j + 1].1 - k[j].1) / (k[j + 1].0 - k[j].0) }+ func tangent(_ j: Int) -> Double {+ guard j > 0, j < n - 1 else { return 0 }+ let a = slope(j - 1), b = slope(j)+ guard a * b > 0 else { return 0 }+ let h0 = k[j].0 - k[j - 1].0, h1 = k[j + 1].0 - k[j].0+ let w0 = 2 * h1 + h0, w1 = h1 + 2 * h0+ return (w0 + w1) / (w0 / a + w1 / b)+ }+ let h = k[i + 1].0 - k[i].0+ let s = (t - k[i].0) / h+ let s2 = s * s, s3 = s2 * s+ return (2 * s3 - 3 * s2 + 1) * k[i].1 + (s3 - 2 * s2 + s) * h * tangent(i)+ + (-2 * s3 + 3 * s2) * k[i + 1].1 + (s3 - s2) * h * tangent(i + 1)+}+/// 0 → 1 inside the window [a, b] of a clock (eased), 0 before it, 1 after. One beat of a scene.public func seg(_ t: Double, _ a: Double, _ b: Double, easeOut useEaseOut: Bool = true) -> Double {if t <= a { return 0 }diff --git a/tools/sample_colors.py b/tools/sample_colors.pynew file mode 100755index 0000000..552eb9a--- /dev/null+++ b/tools/sample_colors.py@@ -0,0 +1,37 @@+#!/usr/bin/env python3+"""Read exact colours from a frame of a reference video instead of guessing them.++ python3 -I tools/sample_colors.py ref.mp4 --at 1.0 900,1065 1075,915 1080,1090++Prints each point (in video pixels) and its hex colour. For a lit or glowing state, sample+that moment too, then blend between the two colours in code (never swap one for the other).+Needs ffmpeg; Python standard library only.+"""+import argparse+import subprocess+++def main():+ ap = argparse.ArgumentParser(description="Sample hex colours at points of one video frame.")+ ap.add_argument("video")+ ap.add_argument("--at", default="0", help="seconds")+ ap.add_argument("points", nargs="+", help="x,y in video pixels")+ a = ap.parse_args()++ probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",+ "stream=width,height", "-of", "csv=p=0", a.video],+ capture_output=True, text=True, check=True).stdout.strip()+ w, h = map(int, probe.split(",")[:2])+ raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", a.at, "-i", a.video, "-frames:v", "1",+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout+ for p in a.points:+ x, y = map(int, p.split(","))+ if not (0 <= x < w and 0 <= y < h):+ print(f"{x},{y} outside the {w}x{h} frame")+ continue+ i = (y * w + x) * 3+ print(f"{x},{y} #{raw[i]:02X}{raw[i + 1]:02X}{raw[i + 2]:02X}")+++if __name__ == "__main__":+ main()diff --git a/tools/sheet.sh b/tools/sheet.shnew file mode 100755index 0000000..8b711a6--- /dev/null+++ b/tools/sheet.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+# sheet.sh: a contact sheet of a video, to study its timing frame by frame (or check your own render).+#+# tools/sheet.sh VIDEO START DUR CROP [PER_ROW] [FPS] [OUT]+#+# tools/sheet.sh ref.mp4 2.1 2 700:760:730:330 # every frame at the source's rate, 10 per row+# tools/sheet.sh ref.mp4 0 5 640:600:760:700 16 10 # 10 frames a second, 16 per row+# tools/sheet.sh ref.mp4 0 16 iw:ih:0:0 8 2 poses.png # the whole frame, 2 a second: the poses+#+# A sheet at 2 frames a second shows the poses. Only the full frame rate shows the timing, the+# follow-through and the moving holds. Tiny motion (a 2% squash) won't show at all: measure it+# with tools/track_edges.py.+set -euo pipefail+video=$1 start=$2 dur=$3 crop=$4 per_row=${5:-10} fps=${6:-} out=${7:-sheet.png}+if [[ -z "$fps" ]]; then+ fps=$(ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 "$video" | awk -F/ '{ printf "%g", $1 / ($2 ? $2 : 1) }')+fi+frames=$(awk -v d="$dur" -v f="$fps" 'BEGIN { n = d * f; printf "%d", (n == int(n)) ? n : int(n) + 1 }')+rows=$(( (frames + per_row - 1) / per_row ))+ffmpeg -v error -y -ss "$start" -t "$dur" -i "$video" \+ -vf "fps=$fps,crop=$crop,scale=200:-2,tile=${per_row}x${rows}" -frames:v 1 "$out"+echo "$out: $frames frames at $fps fps, $per_row per row"diff --git a/tools/track_edges.py b/tools/track_edges.pynew file mode 100755index 0000000..95ad123--- /dev/null+++ b/tools/track_edges.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Measure how something moves in a reference video, frame by frame.++Small motion (a 2% squash, a 5-pixel sway, a float of 5% of a body's height) is invisible on a+contact sheet, and it is exactly what makes the reference feel alive. This prints, for every+frame, where the subject's edges are:+ - the top edge at a few columns: does it bob, squash or tilt?+ - the left and right edges on one row: does it widen, sway or lean?++The subject is every pixel close to one of the given colours; a run of several such pixels is+needed, so sparkles and anti-aliased edges don't count. Needs ffmpeg; Python standard library only.++Examples:+ # an object that might be jiggling while it waits: read it at the source's frame rate+ python3 -I tools/track_edges.py ref.mp4 --start 0 --dur 1.2 --fps 60 \\+ --crop X:Y:W:H --colors RRGGBB,RRGGBB,RRGGBB --cols 110,320,530 --row 300++ # a figure floating in: where is its top, frame by frame?+ python3 -I tools/track_edges.py ref.mp4 --start 0 --dur 2.2 --fps 15 \\+ --crop X:Y:W:H --colors RRGGBB --tol 60 --cols 60,190,320+"""+import argparse+import subprocess+++def hex_rgb(h):+ h = h.strip().lstrip("#")+ return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))+++def main():+ ap = argparse.ArgumentParser(description="Track a subject's edges in a video, frame by frame.")+ ap.add_argument("video")+ ap.add_argument("--start", default="0", help="seconds")+ ap.add_argument("--dur", default="2", help="seconds")+ ap.add_argument("--fps", default="60", help="read at this rate (use the source's rate for timing)")+ ap.add_argument("--crop", required=True, help="x:y:w:h in video pixels")+ ap.add_argument("--colors", required=True, help="comma-separated hex colours of the subject")+ ap.add_argument("--tol", type=float, default=40, help="colour distance that still counts (0-441)")+ ap.add_argument("--cols", default="", help="columns, inside the crop, to read the top edge at")+ ap.add_argument("--row", type=int, default=-1, help="row, inside the crop, to read the left/right edges at")+ ap.add_argument("--run", type=int, default=6, help="pixels in a row needed to count as the subject")+ a = ap.parse_args()++ x, y, w, h = map(int, a.crop.split(":"))+ targets = [hex_rgb(c) for c in a.colors.split(",")]+ cols = [int(c) for c in a.cols.split(",") if c]+ cmd = ["ffmpeg", "-v", "error", "-ss", a.start, "-t", a.dur, "-i", a.video,+ "-vf", f"fps={a.fps},crop={w}:{h}:{x}:{y}", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]+ raw = subprocess.run(cmd, capture_output=True, check=True).stdout+ size = w * h * 3+ tol2 = a.tol ** 2++ def hit(o, px, py):+ i = o + (py * w + px) * 3+ r, g, b = raw[i], raw[i + 1], raw[i + 2]+ return any((r - tr) ** 2 + (g - tg) ** 2 + (b - tb) ** 2 <= tol2 for tr, tg, tb in targets)++ def first(o, coords):+ run = 0+ for k, (px, py) in enumerate(coords):+ if hit(o, px, py):+ run += 1+ if run >= a.run:+ return k - a.run + 1+ else:+ run = 0+ return None++ def cell(v, width):+ return f"{'-' if v is None else v:>{width}}"++ head = "frame ms " + " ".join(f"top@{c:<5}" for c in cols)+ if a.row >= 0:+ head += " left right width"+ print(head)+ for f in range(len(raw) // size):+ o = f * size+ line = f"{f:5d} {round(f * 1000 / float(a.fps)):6d} "+ line += " ".join(cell(first(o, [(c, yy) for yy in range(h)]), 9) for c in cols)+ if a.row >= 0:+ left = first(o, [(xx, a.row) for xx in range(w)])+ back = first(o, [(xx, a.row) for xx in range(w - 1, -1, -1)])+ right = None if back is None else w - 1 - back+ width = None if left is None or right is None else right - left+ line += f" {cell(left, 6)} {cell(right, 6)} {cell(width, 6)}"+ print(line)+++if __name__ == "__main__":+ main()