⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
reanimate
Clone a section, widget, page or animation from any reference (a live website URL, a screen recording, an mp4/mov/webm, a gif, a Lottie file, a prototype export) frame by frame into the user's own codebase, then record the clone and verify it against the reference frame by frame, iterating until timing, easing, sequence and layout match. Use whenever the user wants to clone, copy, replicate, recreate, reverse-engineer, port or "steal" a hero, section, widget, marquee, carousel, hover effect, page transition, loader, scroll animation or interaction from a site or video, says "make it look/feel/move like this", "same animation as", "match this exactly", or hands over a gif/video and asks to build it, including when they also want to add their own content, colours or extra features on top, or only want part of the reference (one section, one widget, a few seconds). Covers canvas, WebGL, WebGPU and three.js / 3D scenes (shaders, particles, globes, glTF models) as well as CSS and JS motion. Pixel-level matching of fonts, colours and spacing is done only when they ask for it.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
A lot of good ideas start on someone else's site. Ask an agent to rebuild one from a link or a screenshot and it makes one pass, calls it done, and misses. It can't see the motion or tell how far off it is.
reanimate records the original, rebuilds it in your code, then records the copy the same way and compares the two. Each round shows what's still off, so the agent keeps going until the numbers match. You end up with a close starting point to make your own.
Install
npx skills add NiazMorshed2007/reanimate -g
The skills CLI asks which agents to set up; add -a claude-code to skip the question. Then, in Claude Code, say what you want, where it is and where it should go:
/reanimate the hero entrance on https://example.com, into components/Hero.tsx
/reanimate this loader, 0:03 to 0:05 of ~/Downloads/loader.mov
/reanimate the card hover in this gif, match it exactly
/reanimate the logo marquee from https://example.com, with our logos and pause on hover
Needs Bun 1.1 or later, on macOS or Linux (Windows is untested). The first run installs a static ffmpeg into the skill's folder and Playwright's Chromium into Playwright's usual cache, about 250 MB together. No API keys. Other agents that read SKILL.md can install it too, but it has only been tested with Claude Code.
How it works
- Record. It films the reference in a headless browser at a fixed viewport and frame rate: a video, numbered frames, every CSS and Web Animations API animation it finds, and the position of chosen elements on every frame. For canvas and WebGL it also traces the GPU calls (shaders, uniforms, draw calls, the three.js scene) on a virtual clock that makes every capture identical.
- Spec. One row per element per property: start, duration, from → to, easing, stagger. A row with a "?" means the frames haven't been read yet.
- Build. It writes the animation with what your project already uses: CSS, Framer Motion, GSAP, three.js.
- Verify. It films the copy the same way, compares timing, easing and pixels, and makes side-by-side sheets.
- Repeat. It fixes the biggest difference and films again, usually 2 to 5 rounds. Whatever still doesn't match after 5 is listed in its report, with the reason.
By default it matches the motion and leaves the look to you. Ask for more or less:
| Say | Level | Must match |
|---|---|---|
| "clone this animation" | Moves the same (default) | trigger, order, stagger, timing within 80 ms, easing family, distance |
| "match it exactly", "pixel-perfect" | Looks the same | all of the above, plus fonts, sizes, colours, spacing and assets; ≤ 2 % mean pixel mismatch |
| "clone X and add Y" | Yours on top | the cloned parts at one of the levels above; your additions kept separate |
Examples
Six animations from vercel.com, nextjs.org and turborepo.com, three cards from the stripe.com homepage, the integrations visual from workos.com/atlas, the feature cards from clerk.com, the demo under the liveblocks.io/comments hero, the cube in the resend.com hero and React Bits Pro's Fading Stars, each cloned by its own agent running this skill, most in 30 to 90 minutes. The site runs the ones you can hover or drag live in the page, and shows the others next to a recording of the original.
| Clone | Built with | Measured against the original |
|---|---|---|
| Vercel Toolbar (vercel.com/products/previews): a toolbar among seven tags; hover a button and its tag takes its colour while the others blur | HTML, SVG, CSS | 417 of 417 frames identical; every change on the same frame |
| Drop to deploy (vercel.com): the hero triangle, lit by the pointer; drag a file over the page and it turns into a prism | WebGL2, Web Workers | 785 of 803 frames byte-identical, the rest within 1 level |
| Fluid ocean (vercel.com/fluid): 262,144 dots rolling like a sea behind the hero | WebGPU, Web Workers | 0 px differ over 12 s, light and dark |
| Inspect every run (vercel.com/workflow): a dashboard playing one run of a workflow | HTML, SVG | all six bars 0 px off; every step on time (0 ms) |
| Speedometer (turborepo.com): a needle that revs into the red under the pointer, and a counter rolling up | SVG, springs | 0 px differ while hovering, light and dark |
| Feature cards (nextjs.org): image frames lit by the pointer, streaks streaming into a page, a component tree | canvas, SVG | every animated value identical on every frame |
| Agentic commerce: a chat over a 10,000-point particle ring | three.js, CSS | chat timing within 43 ms, layout within 0.05 px |
| Card issuing: a Visa card that tilts toward the pointer | three.js, Web Workers | 0.03 % of pixels differ at rest; tilt within 0.4 px |
| Stablecoins and crypto: a dotted globe with flying payments | three.js, Web Workers | globe pose exact; arcs and labels within stripe.com's own spread |
| Connected to all your tools (workos.com): a robot reaching out to a dome of app icons | HTML, SVG, WebGPU | 0.05 % of pixels differ; each link within 10 ms |
| Feature cards (clerk.com): passcodes, magic links, a radar, a laptop opening and more, each playing on hover | HTML, SVG, canvas, WebGL2 | each card's motion within 40 ms; under 0.6 % of pixels differ |
| Comments in any app (liveblocks.io): an app window switching between five apps, its comment panel gliding to each | HTML, SVG, springs | every change on time (0 ms); panel within 0.7 px; 0.55 % of pixels differ |
| Hero cube (resend.com): a dark Rubik's cube turning, its slices making half-turns | three.js | every rotation exact over 25 s; 0.11 % of pixels differ |
| Fading stars (pro.reactbits.dev): violet stars rising in a fan, surging with the pointer | WebGL2 | 0 px differ at rest; 0.014 % during a click burst |
// HOW IT'S BUILT
// FILES
20 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/reanimate/SKILL.md11 KB6d2b044db816upstream ↗
--- name: reanimate description: Clone a section, widget, page or animation from any reference (a live website URL, a screen recording, an mp4/mov/webm, a gif, a Lottie file, a prototype export) frame by frame into the user's own codebase, then record the clone and verify it against the reference frame by frame, iterating until timing, easing, sequence and layout match. Use whenever the user wants to clone, copy, replicate, recreate, reverse-engineer, port or "steal" a hero, section, widget, marquee, carousel, hover effect, page transition, loader, scroll animation or interaction from a site or video, says "make it look/feel/move like this", "same animation as", "match this exactly", or hands over a gif/video and asks to build it, including when they also want to add their own content, colours or extra features on top, or only want part of the reference (one section, one widget, a few seconds). Covers canvas, WebGL, WebGPU and three.js / 3D scenes (shaders, particles, globes, glTF models) as well as CSS and JS motion. Pixel-level matching of fonts, colours and spacing is done only when they ask for it. --- # reanimate Rebuild what the user points at so that it moves the way the reference moves, prove it with a frame-by-frame comparison, and keep going until the comparison passes. The deliverable is code in the user's project plus evidence (numbers and side-by-side sheets), never "it looks about right". ## What "done" means Pick the fidelity level from the user's words and state it in the first message; it decides what you verify. | Level | When | Must match | May differ | |---|---|---|---| | **motion-faithful** (default) | "clone this animation", "make ours feel like theirs", "same hero as X but our copy" | trigger, sequence and order, stagger, timing of every step (±80 ms), easing family, direction and distance of movement relative to the element size, layout proportions | copy, colours, fonts, images, brand details | | **pixel-faithful** | "match it exactly", "pixel-perfect", "details should match", "1:1" | everything above plus fonts, sizes, colours, spacing, radii, shadows, assets; mean frame mismatch ≤ 2 % | nothing the user did not ask to change | | **mixed** | "clone X and add Y", "like theirs but with our pricing tiers" | the cloned parts at one of the levels above | the additions, which you describe and show but verify only for not breaking the cloned motion | The user can narrow the target to one section, one widget, one page, or a time range of a video ("the first 3 seconds", "0:12 to 0:15"). Clone exactly that; do not pull in the rest of the page. ## Workflow Everything below lives in `.reanimate/<name>/` inside the user's project (add it to `.gitignore` unless they want the evidence committed). Keep each round's artefacts; they are the proof. ### 0. Scope Write three lines at the top of `.reanimate/<name>/spec.md` before any capture: - **Target**: what to clone, as precisely as the user said it (URL + selector / time range / "the toggle in the gif"). - **Destination**: where the code goes and in what stack (read `package.json`, existing components and the animation library already in use; match it rather than introducing a new one). - **Fidelity**: motion-faithful, pixel-faithful or mixed, plus the list of additions for mixed. Infer what you can from the request and the repo. Ask only when two readings lead to different work (for instance "the hero" on a page with two candidate sections). When a reference is a login-walled page or a YouTube/Loom link you cannot download here, ask the user for a screen recording and continue with everything else meanwhile. ### 1. Setup `<skill>` below is the directory this SKILL.md lives in. Scripts need [Bun](https://bun.sh); the first run downloads Playwright's Chromium and a static ffmpeg (about 250 MB). ```bash bash <skill>/scripts/setup.sh # installs playwright, ffmpeg, pixelmatch once; prints "ready" ``` All scripts are run with `bun <skill>/scripts/<name>.ts --help`. They are deterministic and share one rule: capture the reference and the clone with the **same** viewport, selector crop, trigger, duration and fps, otherwise the comparison measures your setup instead of your work. ### 2. Capture the reference Read `references/capture.md` for the recipe for your source type. In short: - **Website**: `capture.ts --url … --out ref --selector <section> --trigger load|scroll|hover|click|none --duration … --track "<moving elements>"`. You get `video.webm`, `frames/`, `inspect.json` (declared animations, keyframes, computed styles, fonts, detected libraries) and `track.json` (per animation frame position, size, opacity, transform of each tracked element). For CSS/WAAPI motion `inspect.json` often contains the exact durations, delays and easings: use them, it beats estimating. - **Video or gif**: `frames.ts --in file --out ref/frames --fps 10..30 --start … --end … --crop …`. Probe first with `--probe`, then view a few frames to find the crop of the widget you are cloning. - **Canvas, WebGL, WebGPU, 3D** (`inspect.json › canvases` shows one, or the page uses three.js, Pixi, Babylon, Spline…): add `--clock virtual --gl --assets` to the capture and read `gl/summary.md` (`gl.ts summary <out>`). You get the shader sources, every constant uniform, the scene graph, the render passes, the textures and models, and each animated uniform or object property as a channel in `gl-track.json`. The virtual clock makes every frame exact and every capture identical, random particles included. Read `references/webgl.md`. - **Lottie / Rive / prototype export**: the file is the spec; read it, do not re-derive it from pixels. Then build labelled sheets and look at them: `sheet.ts filmstrip --frames ref/frames --out ref/sheets`. Read every sheet with the image viewer. This is the frame-by-frame inspection the user asked for; do not skip it or sample only the first sheet. ### 3. Write the motion spec Fill `spec.md` using the template in `references/analysis.md`. One row per element per property: trigger, start time, duration, delay or stagger, from → to, easing, notes. Get the numbers from, in order of preference: `inspect.json` animations and keyframes → `easing.ts` on `track.json`, or on `gl-track.json --channel` for canvas → reading frames (first frame where it changes, last frame where it changes, overshoot or not). Also note the static facts the motion depends on: element sizes and positions, z-order, overflow clipping, transform origins, and for pixel-faithful work fonts, colours, spacing and assets. The spec is the contract between the reference and the clone. Every row becomes a check in step 5. If a row has a "?" you have not finished reading the frames. ### 4. Build Implement in the user's stack following `references/implementation.md` (easing tables, stagger math, scroll and hover triggers, reduced motion). Keep the DOM structure close to the reference's role structure so the tracked selectors have equivalents. For mixed work, put additions in clearly separate components or blocks and mention them in `spec.md` under "Additions". Give the clone a way to be captured the same way as the reference: a route or a static page that renders the component at the reference viewport with the same trigger. A dev server is fine (`capture.ts --url http://localhost:5173/…`); a standalone HTML file also works. ### 5. Verify, fix, repeat Capture the clone with the exact command used for the reference, changing only `--url` and `--out clone-N`, then: ```bash bun <skill>/scripts/compare.ts --ref ref/frames --clone clone-N/frames --out compare-N bun <skill>/scripts/sheet.ts compare --ref ref/frames --clone clone-N/frames --diff compare-N/diff --out compare-N/sheets --every 2 bun <skill>/scripts/easing.ts --track clone-N/track.json --selector "<el>" --prop <translateY|opacity|…> --compare-track ref/track.json ``` For canvas work, also run `gl.ts compare --ref ref --clone clone-N`, which checks canvas settings, draw structure and every animated channel. Read `references/verify.md` for how to read the report, the pass criteria for each fidelity level and the fixes that each kind of failure usually needs. Look at the compare sheets yourself, every round; the numbers tell you that something is off, the sheets tell you what. Loop until every spec row passes. Each round: change the smallest thing the evidence points at, re-capture, re-compare. Expect 2 to 5 rounds. If after 5 rounds a row still fails, stop and report it with its numbers and the reason (missing font, a shader or model the user may not copy, a physics spring you approximated), do not quietly lower the threshold or drop the row. ### 6. Report The final message must stand alone: - Fidelity level and what was cloned, what was added. - Where the code is (files) and how to trigger the motion. - A short table of the last compare round: timing error, mean mismatch, easing match per key element, pass/fail. - Paths to the final compare sheets, embedded as images when the environment shows them. - Residual deviations, each with a number and a reason. ## Pitfalls that waste rounds - Different viewport or crop between reference and clone: fix the capture before touching code. - Judging from the first frame and the last frame only: the easing lives in the middle frames; read the sheets. - Fonts: a different fallback font changes every frame's pixels. For pixel-faithful work load the same font (from `inspect.json` fonts) before judging mismatch; for motion-faithful work ignore text pixels and read the timing columns. - Reference recorded on a loaded page vs clone captured cold: use `--wait-before`, or `--trigger none` with a `--pre-js` that restarts the animation, so both start from rest. - Scroll-driven motion: it is a function of scroll position, not time. Capture both with the same `--scroll-steps` and `--scroll-ms`, and compare per scroll position (the track's `scrollY`), not per second. - JS libraries (GSAP, Framer Motion springs): `--playback-rate` does not slow them. Use `track.json` and `easing.ts` (it reports overshoot and "spring-like") and tune spring parameters by the overshoot and settle time. - Videos of someone else's screen have a cursor, a browser chrome and compression noise: crop them out and raise `--pixel-threshold` a little (0.15) rather than chasing noise. - Canvas and WebGL captured on the real clock: frames drop in software GL and random content differs on every load, so the comparison measures the machine. Capture both sides with `--clock virtual` and the same `--seed`. - Rebuilding a shader from screenshots: the trace already has its source and every constant. Read `gl/shaders/` and the fixed uniforms before writing GLSL.skills/reanimate/scripts/bun.lock4.8 KB4761a33116b0upstream ↗
{ "lockfileVersion": 2, "configVersion": 1, "workspaces": { "": { "name": "reanimate-scripts", "dependencies": { "ffmpeg-static": "^5.2.0", "pixelmatch": "^8.0.0", "playwright": "1.64.1", "pngjs": "^7.0.0", }, }, }, "packages": { "@derhuerst/http-basic": ["@derhuerst/[email protected]", "", { "dependencies": { "caseless": "^0.12.0", "concat-stream": "^2.0.0", "http-response-object": "^3.0.1", "parse-cache-control": "^1.0.1" } }, "sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw=="], "@types/node": ["@types/[email protected]", "", {}, "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw=="], "agent-base": ["[email protected]", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], "buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "caseless": ["[email protected]", "", {}, "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw=="], "concat-stream": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.0.2", "typedarray": "^0.0.6" } }, "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A=="], "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], "ffmpeg-static": ["[email protected]", "", { "dependencies": { "@derhuerst/http-basic": "^8.2.0", "env-paths": "^2.2.0", "https-proxy-agent": "^5.0.0", "progress": "^2.0.3" } }, "sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg=="], "http-response-object": ["[email protected]", "", { "dependencies": { "@types/node": "^10.0.3" } }, "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA=="], "https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="], "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "parse-cache-control": ["[email protected]", "", {}, "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg=="], "pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-cIqOLfh5k52us715qf3B3+kTOxZv+WDv77HN7xokLScYQGYQHi4m/ynoDIPpvF2LvCyUJGyvzY64i0QCXtzu1g=="], "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA=="], "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="], "pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="], "progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="], "readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], "string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], "typedarray": ["[email protected]", "", {}, "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="], "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], } }skills/reanimate/scripts/capture.ts39 KBd5b002c3157cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/reanimate/scripts/compare.ts12 KBc2fe7eae3e59upstream ↗
// Compare the clone's frames against the reference's, frame by frame. // Produces per-frame mismatch (pixel diff), an "activity curve" (how much changes between consecutive // frames, which captures timing and easing regardless of colours or copy), diff images, and a report. // Usage: bun compare.ts --ref <frames dir> --clone <frames dir> --out <dir> [--auto-align] [--threshold 0.05] import { PNG } from "pngjs"; import pixelmatch from "pixelmatch"; import { join } from "node:path"; import { existsSync, readFileSync, writeFileSync, unlinkSync, readdirSync } from "node:fs"; import { abs, ensureDir, ffmpeg, listFrames, num, parseArgs, parseRect, readJson, usage, writeJson, pad } from "./lib.ts"; const HELP = ` compare.ts — frame-by-frame comparison of clone vs reference. bun compare.ts --ref <dir> --clone <dir> --out <dir> [options] --auto-align find the clone frame offset (±--max-shift) that best matches the reference start, default on --offset K fixed offset instead (clone frame = ref frame + K) --max-shift N search range for auto-align, default 15 frames --region x,y,w,h only compare this region (in reference pixel coordinates) --pixel-threshold T pixelmatch colour sensitivity 0..1, default 0.1 (raise to ignore anti-aliasing/noise) --threshold T pass if mean mismatch ≤ T (fraction of pixels), default 0.05; use 0.01-0.02 for pixel fidelity --motion-threshold T pass if activity-curve timing error ≤ T seconds, default 0.08 --fps N frames per second (default: frames.json beside --ref or next to it, else 25) --blur R box-blur both sets by R px before comparing: particles, noise and grain that are placed differently but have the same density, colour and motion stop counting as mismatch (try 4-8). Reports both the sharp and the blurred mismatch. --no-diffs skip writing diff PNGs Output in <out>/: report.json, report.md, diff/NNNN.png (red = differing pixels) Both frame sets must share fps and be clipped to the same region; the clone is rescaled to the reference size if needed. `; const a = parseArgs(process.argv.slice(2)); if (a.help || !a.ref || !a.clone || !a.out) usage(HELP); const refDir = abs(String(a.ref)), cloneDir = abs(String(a.clone)), out = ensureDir(abs(String(a.out))); // frames.ts writes frames.json beside the frames, capture.ts one level up const framesJson = [join(refDir, "frames.json"), join(refDir, "..", "frames.json")].find((p) => existsSync(p)); const fps = num(a.fps, framesJson ? Number(readJson(framesJson).fps) || 25 : 25); const pixelThreshold = num(a["pixel-threshold"], 0.1); const threshold = num(a.threshold, 0.05); const motionThreshold = num(a["motion-threshold"], 0.08); const region = parseRect(a.region); const wantDiffs = !a["no-diffs"]; const blurR = num(a.blur, 0); // Captures made with different settings measure the setup, not the clone. capture.json sits next to frames/. const capOf = (dir: string) => { const p = join(dir, "..", "capture.json"); return existsSync(p) ? readJson(p) : null; }; const capRef = capOf(refDir), capClone = capOf(cloneDir); const setupWarnings: string[] = []; if (capRef && capClone) { const same = (k: string, f = (c: any) => JSON.stringify(c[k] ?? null)) => { if (f(capRef) !== f(capClone)) setupWarnings.push(`${k}: reference ${f(capRef)}, clone ${f(capClone)}`); }; for (const k of ["viewport", "scale", "fps", "trigger", "duration", "preRoll", "clock", "seed", "gpu", "rafHz", "rate"]) same(k); if (capRef.renderer && capClone.renderer && capRef.renderer !== capClone.renderer) setupWarnings.push(`renderer: reference "${capRef.renderer}", clone "${capClone.renderer}"`); for (const w of setupWarnings) console.error(`warning: captures differ in ${w}`); } const refFiles = listFrames(refDir); let cloneFiles = listFrames(cloneDir); if (!refFiles.length || !cloneFiles.length) throw new Error("no frames found"); const readPng = (p: string) => PNG.sync.read(readFileSync(p)); const ref0 = readPng(refFiles[0]); const c0 = readPng(cloneFiles[0]); // rescale the clone set once if sizes differ (keeps the comparison honest, but prefer capturing at the same size) if (c0.width !== ref0.width || c0.height !== ref0.height) { const scaled = ensureDir(join(out, ".clone-scaled")); for (const f of readdirSync(scaled)) unlinkSync(join(scaled, f)); console.error(`clone frames are ${c0.width}x${c0.height}, reference ${ref0.width}x${ref0.height}: rescaling clone`); cloneFiles.forEach((p, i) => ffmpeg(["-y", "-i", p, "-vf", `scale=${ref0.width}:${ref0.height}:flags=lanczos`, join(scaled, `${pad(i)}.png`)], { quiet: true })); cloneFiles = listFrames(scaled); } const W = ref0.width, H = ref0.height; function crop(img: PNG): PNG { if (!region) return img; const o = new PNG({ width: region.width, height: region.height }); PNG.bitblt(img, o, region.x, region.y, region.width, region.height, 0, 0); return o; } // separable box blur, two passes ≈ gaussian; RGBA in place function blur(img: PNG, r: number): PNG { if (r <= 0) return img; const { width: w, height: h } = img; const src = new Float32Array(img.data), tmp = new Float32Array(src.length); const pass = (from: Float32Array, to: Float32Array, horizontal: boolean) => { const n = horizontal ? w : h, m = horizontal ? h : w; for (let j = 0; j < m; j++) for (let c = 0; c < 4; c++) { let acc = 0, cnt = 0; const idx = (i: number) => ((horizontal ? j * w + i : i * w + j) << 2) + c; for (let i = 0; i <= Math.min(r, n - 1); i++) { acc += from[idx(i)]; cnt++; } for (let i = 0; i < n; i++) { to[idx(i)] = acc / cnt; const add = i + r + 1, rem = i - r; if (add < n) { acc += from[idx(add)]; cnt++; } if (rem >= 0) { acc -= from[idx(rem)]; cnt--; } } } }; pass(src, tmp, true); pass(tmp, src, false); pass(src, tmp, true); pass(tmp, src, false); const o = new PNG({ width: w, height: h }); for (let i = 0; i < src.length; i++) o.data[i] = Math.round(src[i]); return o; } function mismatch(aP: PNG, bP: PNG, diff?: PNG): number { const n = pixelmatch(aP.data, bP.data, diff?.data, aP.width, aP.height, { threshold: pixelThreshold, includeAA: false }); return n / (aP.width * aP.height); } // cache decoded + cropped frames (frames are small after clipping; fine for a few hundred) const refSharp = refFiles.map((p) => crop(readPng(p))); const cloneSharp = cloneFiles.map((p) => crop(readPng(p))); const refImgs = blurR ? refSharp.map((p) => blur(p, blurR)) : refSharp; const cloneImgs = blurR ? cloneSharp.map((p) => blur(p, blurR)) : cloneSharp; // ---- activity curve: change between consecutive frames, per set ---- function activity(imgs: PNG[]): number[] { const out: number[] = [0]; for (let i = 1; i < imgs.length; i++) out.push(mismatch(imgs[i - 1], imgs[i])); return out; } const refAct = activity(refSharp), cloneAct = activity(cloneSharp); // timing reads sharp frames, even with --blur function motionWindow(act: number[], floor = 0.002) { // first and last frame where something visibly changes let first = -1, last = -1; act.forEach((v, i) => { if (v > floor) { if (first < 0) first = i; last = i; } }); const peak = act.indexOf(Math.max(...act)); return { first, last, peak, durationS: first < 0 ? 0 : (last - first + 1) / fps }; } // ---- alignment ---- let offset = a.offset !== undefined ? num(a.offset, 0) : 0; if (a.offset === undefined && !(a["auto-align"] === "false")) { const maxShift = num(a["max-shift"], 15); const probeN = Math.min(10, refImgs.length); let best = Infinity; for (let k = -maxShift; k <= maxShift; k++) { let sum = 0, n = 0; for (let i = 0; i < probeN; i++) { const j = i + k; if (j < 0 || j >= cloneImgs.length) continue; sum += mismatch(refImgs[i], cloneImgs[j]); n++; } if (n >= Math.min(5, probeN) && sum / n < best) { best = sum / n; offset = k; } } } // ---- per-frame mismatch + diffs ---- const diffDir = wantDiffs ? ensureDir(join(out, "diff")) : undefined; if (diffDir) for (const f of readdirSync(diffDir)) if (f.endsWith(".png")) unlinkSync(join(diffDir, f)); const frames: { i: number; t: number; cloneIndex: number | null; mismatch: number | null }[] = []; for (let i = 0; i < refImgs.length; i++) { const j = i + offset; if (j < 0 || j >= cloneImgs.length) { frames.push({ i, t: +(i / fps).toFixed(3), cloneIndex: null, mismatch: null }); continue; } const diff = diffDir ? new PNG({ width: refImgs[i].width, height: refImgs[i].height }) : undefined; const m = mismatch(refImgs[i], cloneImgs[j], diff); if (diff && diffDir) writeFileSync(join(diffDir, `${pad(i)}.png`), PNG.sync.write(diff)); frames.push({ i, t: +(i / fps).toFixed(3), cloneIndex: j, mismatch: +m.toFixed(4), ...(blurR ? { sharpMismatch: +mismatch(refSharp[i], cloneSharp[j]).toFixed(4) } : {}) }); } const compared = frames.filter((f) => f.mismatch !== null) as { i: number; t: number; mismatch: number; sharpMismatch?: number }[]; const sharpMean = blurR ? compared.reduce((s, f) => s + (f.sharpMismatch ?? 0), 0) / Math.max(1, compared.length) : null; const mean = compared.reduce((s, f) => s + f.mismatch, 0) / Math.max(1, compared.length); const worst = [...compared].sort((x, y) => y.mismatch - x.mismatch).slice(0, 5); const refWin = motionWindow(refAct), cloneWin = motionWindow(cloneAct.slice(Math.max(0, offset))); const timingError = { startS: +((cloneWin.first - refWin.first) / fps).toFixed(3), endS: +((cloneWin.last - refWin.last) / fps).toFixed(3), peakS: +((cloneWin.peak - refWin.peak) / fps).toFixed(3), durationS: +(cloneWin.durationS - refWin.durationS).toFixed(3), }; const maxTimingErr = Math.max(Math.abs(timingError.startS), Math.abs(timingError.endS), Math.abs(timingError.durationS)); const pass = { pixels: mean <= threshold, timing: maxTimingErr <= motionThreshold }; const report = { fps, size: [W, H], region, offset, threshold, motionThreshold, pixelThreshold, blur: blurR || undefined, sharpMeanMismatch: sharpMean === null ? undefined : +sharpMean.toFixed(4), setupWarnings, frames: frames.length, compared: compared.length, meanMismatch: +mean.toFixed(4), maxMismatch: worst[0]?.mismatch ?? 0, worstFrames: worst, motion: { reference: refWin, clone: cloneWin, timingError }, activity: { reference: refAct.map((v) => +v.toFixed(4)), clone: cloneAct.map((v) => +v.toFixed(4)) }, pass, frameDetails: frames, }; writeJson(join(out, "report.json"), report); const bar = (v: number) => "█".repeat(Math.min(40, Math.round(v * 400))) || "·"; const md = [ `# compare: ${refDir} vs ${cloneDir}`, ``, `- frames compared: ${compared.length}/${frames.length} at ${fps} fps, clone offset ${offset}`, ...setupWarnings.map((w) => `- **warning, captures differ in ${w}**: re-capture with the same settings before reading the numbers`), `- mean mismatch${blurR ? ` (blurred ${blurR} px)` : ""}: **${(mean * 100).toFixed(2)}%** (threshold ${(threshold * 100).toFixed(1)}%) → ${pass.pixels ? "PASS" : "FAIL"}${sharpMean !== null ? `; sharp: ${(sharpMean * 100).toFixed(2)}%` : ""}`, `- motion window — reference: frames ${refWin.first}–${refWin.last} (${refWin.durationS.toFixed(2)}s, peak #${refWin.peak}); clone: ${cloneWin.first}–${cloneWin.last} (${cloneWin.durationS.toFixed(2)}s, peak #${cloneWin.peak})`, `- timing error (clone − ref): start ${timingError.startS}s, end ${timingError.endS}s, duration ${timingError.durationS}s, peak ${timingError.peakS}s → ${pass.timing ? "PASS" : "FAIL"} (limit ${motionThreshold}s)`, `- worst frames: ${worst.map((w) => `#${w.i} (${(w.mismatch * 100).toFixed(1)}% @ ${w.t}s)`).join(", ")}`, ``, `## activity per frame (how much changed since the previous frame)`, ``, "```", `frame t(s) reference clone`, ...frames.map((f) => `${String(f.i).padStart(5)} ${f.t.toFixed(2).padStart(6)} ${bar(refAct[f.i]).padEnd(40)} ${f.cloneIndex === null ? "" : bar(cloneAct[f.cloneIndex])}`), "```", ``, `Diff images: ${diffDir ?? "(skipped)"} — red pixels differ. Build labelled sheets with sheet.ts compare.`, ].join("\n"); writeFileSync(join(out, "report.md"), md + "\n"); console.log(md);skills/reanimate/scripts/easing.ts9.2 KB31c8d6d6a19dupstream ↗
// Fit a recorded motion curve to known easings and report duration, delay and overshoot. // Input: a track.json from capture.ts (choose selector + property) or a plain JSON array of [t_ms, value]. // Usage: bun easing.ts --track <track.json> --selector ".hero h1" --prop y // bun easing.ts --series '[[0,0],[100,12],[200,40],...]' import { readJson, parseArgs, usage, num } from "./lib.ts"; const HELP = ` easing.ts — which easing is this? bun easing.ts --track <track.json> --selector <css> --prop <x|y|w|h|opacity|scale|translateX|translateY|rotate> [--from-ms T --to-ms T] bun easing.ts --series '[[t_ms, value], ...]' bun easing.ts --track <track.json> --selector <css> --prop y --compare-track <other.json> # also diffs two tracks bun easing.ts --track <gl-track.json> --channel <key> [--compare-track <other gl-track.json> --compare-channel <key>] # a uniform, camera, object or material value from capture.ts --gl (key or its unique ending, e.g. uHover) Prints: start/end values, delay (first change), duration (first → last change), overshoot, and the best-fitting named easings with their RMSE. Use the top match as the CSS/Framer/GSAP easing in the clone, then re-run on the clone's track to confirm the curve matches. `; const a = parseArgs(process.argv.slice(2)); if (a.help || (!a.track && !a.series)) usage(HELP); function matrixPart(transform: string): { tx: number; ty: number; sx: number; sy: number; rot: number } { if (!transform || transform === "none") return { tx: 0, ty: 0, sx: 1, sy: 1, rot: 0 }; const m = transform.match(/matrix(3d)?\(([^)]+)\)/); if (!m) return { tx: 0, ty: 0, sx: 1, sy: 1, rot: 0 }; const v = m[2].split(",").map(Number); if (m[1]) return { tx: v[12], ty: v[13], sx: Math.hypot(v[0], v[1]), sy: Math.hypot(v[4], v[5]), rot: (Math.atan2(v[1], v[0]) * 180) / Math.PI }; return { tx: v[4], ty: v[5], sx: Math.hypot(v[0], v[1]), sy: Math.hypot(v[2], v[3]), rot: (Math.atan2(v[1], v[0]) * 180) / Math.PI }; } // gl-track.json channels: exact key, or a unique key ending in ".<name>" / "<name>" function resolveChannel(t: any, name: string): string { if (t.channels[name]) return name; const keys = Object.keys(t.channels).filter((k) => k.endsWith("." + name) || k.endsWith(name)); if (keys.length === 1) return keys[0]; throw new Error(keys.length ? `channel "${name}" is ambiguous: ${keys.slice(0, 12).join(", ")}` : `no animated channel "${name}" (bun gl.ts channels <dir> lists them; constants are in gl/gl.json)`); } function seriesFromTrack(path: string, selector: string, prop: string, channel?: string): [number, number][] { const t = readJson(path); const outS: [number, number][] = []; if (t.kind === "gl-track") { if (!channel) throw new Error("this is a gl-track.json: pass --channel <key>"); const k = resolveChannel(t, channel); for (const s of t.samples) if (s.v[k] !== undefined) outS.push([s.t, s.v[k]]); return outS; } for (const s of t.samples) { const e = s.els?.[selector]; if (!e) continue; const mp = matrixPart(e.transform); const v: Record<string, number> = { x: e.x, y: e.y, w: e.w, h: e.h, opacity: e.opacity, translateX: mp.tx, translateY: mp.ty, scale: mp.sx, scaleX: mp.sx, scaleY: mp.sy, rotate: mp.rot }; if (!(prop in v)) throw new Error(`unknown prop ${prop}; use one of ${Object.keys(v).join(", ")}`); outS.push([s.t, v[prop]]); } return outS; } let series: [number, number][] = a.series ? JSON.parse(String(a.series)) : seriesFromTrack(String(a.track), String(a.selector), String(a.prop || "y"), a.channel ? String(a.channel) : undefined); const fromMs = num(a["from-ms"], -Infinity), toMs = num(a["to-ms"], Infinity); series = series.filter(([t]) => t >= fromMs && t <= toMs); if (series.length < 4) { console.log("not enough samples (element missing from track, or window too narrow)"); process.exit(1); } // bezier easings (CSS cubic-bezier) and a few others, sampled numerically const bez = (x1: number, y1: number, x2: number, y2: number) => (t: number) => { // solve x(u)=t for u by bisection, return y(u) let lo = 0, hi = 1, u = t; for (let i = 0; i < 30; i++) { u = (lo + hi) / 2; const x = 3 * (1 - u) ** 2 * u * x1 + 3 * (1 - u) * u ** 2 * x2 + u ** 3; if (x < t) lo = u; else hi = u; } return 3 * (1 - u) ** 2 * u * y1 + 3 * (1 - u) * u ** 2 * y2 + u ** 3; }; const EASINGS: Record<string, (t: number) => number> = { "linear": (t) => t, "ease": bez(0.25, 0.1, 0.25, 1), "ease-in": bez(0.42, 0, 1, 1), "ease-out": bez(0, 0, 0.58, 1), "ease-in-out": bez(0.42, 0, 0.58, 1), "cubic-bezier(0.4,0,0.2,1) material standard": bez(0.4, 0, 0.2, 1), "cubic-bezier(0.2,0,0,1) material emphasized": bez(0.2, 0, 0, 1), "cubic-bezier(0.16,1,0.3,1) easeOutExpo": bez(0.16, 1, 0.3, 1), "cubic-bezier(0.22,1,0.36,1) easeOutQuint": bez(0.22, 1, 0.36, 1), "cubic-bezier(0.33,1,0.68,1) easeOutCubic": bez(0.33, 1, 0.68, 1), "cubic-bezier(0.25,1,0.5,1) easeOutQuart": bez(0.25, 1, 0.5, 1), "cubic-bezier(0.5,1,0.89,1) easeOutQuad": bez(0.5, 1, 0.89, 1), "cubic-bezier(0.65,0,0.35,1) easeInOutCubic": bez(0.65, 0, 0.35, 1), "cubic-bezier(0.83,0,0.17,1) easeInOutQuint": bez(0.83, 0, 0.17, 1), "cubic-bezier(0.87,0,0.13,1) easeInOutExpo": bez(0.87, 0, 0.13, 1), "cubic-bezier(0.76,0,0.24,1) easeInOutQuart": bez(0.76, 0, 0.24, 1), "cubic-bezier(0.45,0,0.55,1) easeInOutQuad": bez(0.45, 0, 0.55, 1), "cubic-bezier(0.32,0,0.67,0) easeInCubic": bez(0.32, 0, 0.67, 0), "cubic-bezier(0.7,0,0.84,0) easeInExpo": bez(0.7, 0, 0.84, 0), "cubic-bezier(0.34,1.56,0.64,1) easeOutBack": bez(0.34, 1.56, 0.64, 1), "cubic-bezier(0.68,-0.6,0.32,1.6) easeInOutBack": bez(0.68, -0.6, 0.32, 1.6), "cubic-bezier(0.19,1,0.22,1) 'expo' (common in landing pages)": bez(0.19, 1, 0.22, 1), "cubic-bezier(0.77,0,0.175,1) 'power3.inOut' (gsap)": bez(0.77, 0, 0.175, 1), "cubic-bezier(0.075,0.82,0.165,1) easeOutCirc": bez(0.075, 0.82, 0.165, 1), "cubic-bezier(0.23,1,0.32,1) ease-out-quint variant": bez(0.23, 1, 0.32, 1), }; const t0 = series[0][0]; const start = series[0][1], end = series[series.length - 1][1]; const range = end - start; const eps = Math.max(Math.abs(range) * 0.01, 0.002); let firstChange = series.findIndex(([, v]) => Math.abs(v - start) > eps); let lastChange = series.length - 1; for (let i = series.length - 1; i > 0; i--) if (Math.abs(series[i][1] - end) > eps) { lastChange = Math.min(series.length - 1, i + 1); break; } if (firstChange < 1) firstChange = 1; const delayMs = series[firstChange - 1][0] - t0; const durMs = series[lastChange][0] - series[firstChange - 1][0]; const extremes = series.map(([, v]) => v); const overshoot = range === 0 ? 0 : Math.max(0, (Math.max(...extremes.map((v) => (v - start) * Math.sign(range))) - Math.abs(range)) / Math.abs(range)); // Fit each easing with the duration as a free parameter (1x..2x the visible duration): expo-style curves have // long tails that fall under the 1% change floor, so the declared duration is often longer than the visible one. const fits: { name: string; rmse: number; durationMs: number }[] = []; if (Math.abs(range) > 0 && durMs > 0) { const base = series[firstChange - 1][0]; const raw = series.slice(firstChange - 1).map(([t, v]) => [t - base, (v - start) / range] as [number, number]); for (const [name, fn] of Object.entries(EASINGS)) { let best = { rmse: Infinity, durationMs: durMs }; for (let k = 1; k <= 2.0001; k += 0.05) { const d = durMs * k; const pts = raw.filter(([t]) => t <= d * 1.05); const err = Math.sqrt(pts.reduce((s, [t, y]) => s + (fn(Math.min(1, Math.max(0, t / d))) - y) ** 2, 0) / pts.length); if (err < best.rmse) best = { rmse: err, durationMs: Math.round(d) }; } fits.push({ name, rmse: +best.rmse.toFixed(4), durationMs: best.durationMs }); } fits.sort((x, y) => x.rmse - y.rmse); } const result = { samples: series.length, start: +start.toFixed(3), end: +end.toFixed(3), change: +range.toFixed(3), delayMs: +delayMs.toFixed(0), visibleDurationMs: +durMs.toFixed(0), overshootPct: +(overshoot * 100).toFixed(1), verdict: overshoot > 0.02 ? "spring-like / back easing (overshoots)" : fits[0] ? `${fits[0].name} over ~${fits[0].durationMs}ms${fits[0].rmse < 0.03 ? " (good fit)" : fits[0].rmse < 0.08 ? " (approximate)" : " (poor fit: maybe multi-step, spring, or scroll-linked)"}` : "no motion", note: "visibleDurationMs = time until within 1% of the final value; durationMs in bestFits is the fitted declared duration", bestFits: fits.slice(0, 5), }; if (a["compare-track"]) { const other = seriesFromTrack(String(a["compare-track"]), String(a.selector), String(a.prop || "y"), a["compare-channel"] ? String(a["compare-channel"]) : a.channel ? String(a.channel) : undefined); // both tracks have t=0 at their trigger, so compare at the same t (not from each track's first sample) const at = (s: [number, number][], t: number) => { let best = s[0]; for (const p of s) if (Math.abs(p[0] - t) < Math.abs(best[0] - t)) best = p; return best[1]; }; const diffs = series.map(([t, v]) => +(at(other, t) - v).toFixed(2)); (result as any).compare = { otherSamples: other.length, maxAbsDiff: Math.max(...diffs.map(Math.abs)), meanAbsDiff: +(diffs.reduce((s, d) => s + Math.abs(d), 0) / diffs.length).toFixed(2), sampledDiffs: diffs.filter((_, i) => i % Math.ceil(diffs.length / 20) === 0) }; } console.log(JSON.stringify(result, null, 2));skills/reanimate/scripts/frames.ts3.0 KB1c74b902d1edupstream ↗
// Turn a video or gif (reference recording, screen capture, exported prototype) into numbered PNG frames. // Usage: bun frames.ts --in <file> --out <dir> [--fps 10] [--start 0:03] [--end 0:08] [--crop x,y,w,h] [--width 800] import { join } from "node:path"; import { readdirSync, unlinkSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { abs, ensureDir, ffmpeg, ffmpegPath, num, parseArgs, parseRect, parseTime, usage, writeJson } from "./lib.ts"; const HELP = ` frames.ts — extract frames from a video or gif. bun frames.ts --in <file.mp4|.mov|.webm|.gif> --out <dir> [options] --fps N frames per second to keep, default 10 (use 25-30 for fast motion, 5 for long slow sequences) --start T start time: "0:03", "3.5", "1500ms". default 0 --end T end time (same formats). default: end of file --crop x,y,w,h crop in source pixels (find values on a full frame first) --width W downscale frames to this width (keeps aspect). default: source size --probe only print the source's duration, size and fps, extract nothing Writes <out>/NNNN.png and <out>/frames.json (fps, count, start, source size). Frame i is at reference time start + i/fps. `; const a = parseArgs(process.argv.slice(2)); if (a.help || !a.in || (!a.out && !a.probe)) usage(HELP); const input = abs(String(a.in)); // probe with ffmpeg itself (no ffprobe in ffmpeg-static) const probe = spawnSync(ffmpegPath(), ["-hide_banner", "-i", input], { encoding: "utf8" }).stderr; const dur = probe.match(/Duration:\s*(\d+):(\d+):([\d.]+)/); const durationS = dur ? Number(dur[1]) * 3600 + Number(dur[2]) * 60 + Number(dur[3]) : undefined; const vid = probe.match(/Video:.*?(\d{2,5})x(\d{2,5})/); const srcFps = probe.match(/([\d.]+) fps/); const info = { input, durationS, width: vid ? Number(vid[1]) : undefined, height: vid ? Number(vid[2]) : undefined, sourceFps: srcFps ? Number(srcFps[1]) : undefined }; if (a.probe) { console.log(JSON.stringify(info, null, 2)); process.exit(0); } const out = ensureDir(abs(String(a.out))); for (const f of readdirSync(out)) if (f.endsWith(".png")) unlinkSync(join(out, f)); const fps = num(a.fps, 10); const start = parseTime(a.start) ?? 0; const end = parseTime(a.end); const crop = parseRect(a.crop); const width = a.width ? num(a.width, 0) : 0; const vf = [`fps=${fps}`]; if (crop) vf.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`); if (width) vf.push(`scale=${width}:-2`); const args = ["-y", "-ss", String(start), "-i", input]; if (end !== undefined) args.push("-t", String(end - start)); args.push("-vf", vf.join(","), "-vsync", "0", join(out, "%04d.png")); ffmpeg(args, { quiet: true }); const count = readdirSync(out).filter((f) => f.endsWith(".png")).length; const meta = { ...info, fps, count, start, end, crop, outWidth: width || undefined, note: "frame i (1-based file name) is at t = start + (i-1)/fps seconds of the source" }; writeJson(join(out, "frames.json"), meta); console.log(JSON.stringify(meta, null, 2));skills/reanimate/scripts/gl.ts28 KB31a6df64583aupstream ↗
// Read what capture.ts --gl recorded from a canvas: WebGL / WebGPU / canvas 2D calls and the three.js scene. // capture.ts calls writeGlArtifacts() to turn the raw in-page trace into files; the CLI reads them back. // // Usage: bun gl.ts summary <capture dir> // bun gl.ts channels <capture dir> [--grep RE] [--series KEY] // bun gl.ts compare --ref <capture dir> --clone <capture dir> [--map "refName=cloneName,…"] import { existsSync, readFileSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { abs, ensureDir, num, parseArgs, readJson, usage, writeJson } from "./lib.ts"; const slug = (s: string) => s.replace(/\(([^)]*)\)/g, "$1").replace(/[^\w-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48); const suffix = (n: number, k: number) => (n === 1 ? "" : n <= 4 ? "." + "xyzw"[k] : `[${k}]`); const r4 = (v: number) => +v.toPrecision(5); type Channel = { source: "uniform" | "scene" | "webgpu"; program?: string; uniform?: string; min: number; max: number; firstChangeMs: number | null; lastChangeMs: number | null; kind: string; perSecond?: number; periodMs?: number }; // What a channel does over the capture: constant, a clock (uniform time), a transition between two rests, // an oscillation, or several steps. The kind decides how it is cloned (drive by time, ease, loop). function classify(ts: number[], vs: number[]): Pick<Channel, "min" | "max" | "firstChangeMs" | "lastChangeMs" | "kind" | "perSecond" | "periodMs"> { const min = Math.min(...vs), max = Math.max(...vs), range = max - min; const base = { min: r4(min), max: r4(max) }; if (!(range > 1e-7)) return { ...base, firstChangeMs: null, lastChangeMs: null, kind: "constant" }; const eps = range * 0.002; let first = -1, last = -1, ups = 0, downs = 0, turns = 0, prevSign = 0; for (let i = 1; i < vs.length; i++) { const d = vs[i] - vs[i - 1]; if (Math.abs(d) <= eps) continue; if (first < 0) first = i - 1; last = i; const s = Math.sign(d); if (s > 0) ups++; else downs++; if (prevSign && s !== prevSign) turns++; prevSign = s; } const firstChangeMs = Math.round(ts[first + 1]), lastChangeMs = Math.round(ts[last]); // first sample that moved, sample where it settled const moving = ups + downs; const span = ts[ts.length - 1] - ts[0]; if (turns === 0) { // monotonic: a clock if it moves through the whole capture at a constant rate const n = vs.length, mt = ts.reduce((s, t) => s + t, 0) / n, mv = vs.reduce((s, v) => s + v, 0) / n; let sxy = 0, sxx = 0, syy = 0; for (let i = 0; i < n; i++) { sxy += (ts[i] - mt) * (vs[i] - mv); sxx += (ts[i] - mt) ** 2; syy += (vs[i] - mv) ** 2; } const r2 = sxx && syy ? (sxy * sxy) / (sxx * syy) : 0; if (r2 > 0.995 && lastChangeMs - firstChangeMs > span * 0.8) return { ...base, firstChangeMs, lastChangeMs, kind: "clock", perSecond: r4((sxy / sxx) * 1000) }; return { ...base, firstChangeMs, lastChangeMs, kind: "transition" }; } if (turns >= 3) { // period from the mean distance between same-direction turning points const peaks: number[] = []; for (let i = 1; i < vs.length - 1; i++) if (vs[i] > vs[i - 1] + eps / 2 && vs[i] >= vs[i + 1]) peaks.push(ts[i]); const periodMs = peaks.length >= 2 ? Math.round((peaks[peaks.length - 1] - peaks[0]) / (peaks.length - 1)) : undefined; return { ...base, firstChangeMs, lastChangeMs, kind: moving > vs.length * 0.6 ? "oscillation" : "steps", periodMs }; } return { ...base, firstChangeMs, lastChangeMs, kind: "there-and-back" }; } // ---------- capture.ts → files ---------- export function writeGlArtifacts(out: string, d: any, t0: number, rate: number) { const dir = join(out, "gl"); rmSync(dir, { recursive: true, force: true }); rmSync(join(out, "three"), { recursive: true, force: true }); ensureDir(dir); const t = (pageMs: number) => +((pageMs - t0) * rate).toFixed(1); const progKey = new Map<string, string>(); for (const p of d.programs) progKey.set(p.id, p.id + (p.label ? ":" + slug(p.label) : "")); // shaders const shaderDir = ensureDir(join(dir, "shaders")); for (const p of d.programs) { const base = progKey.get(p.id)!.replace(":", "-"); p.files = {}; if (p.vs) { writeFileSync(join(shaderDir, base + ".vert"), p.vs); p.files.vs = `gl/shaders/${base}.vert`; } if (p.fs) { writeFileSync(join(shaderDir, base + ".frag"), p.fs); p.files.fs = `gl/shaders/${base}.frag`; } delete p.vs; delete p.fs; } for (const m of d.gpu?.modules ?? []) { if (!m.code) continue; const f = `${m.id}${m.label ? "-" + slug(m.label) : ""}.wgsl`; writeFileSync(join(shaderDir, f), m.code); m.file = `gl/shaders/${f}`; delete m.code; } // buffer dumps and canvas textures for (const [id, dump] of Object.entries<any>(d.dumps ?? {})) { const f = `${id}.${dump.type.replace(/Array$/, "")}.bin`; writeFileSync(join(ensureDir(join(dir, "buffers")), f), Buffer.from(dump.base64, "base64")); const b = d.buffers.find((x: any) => x.id === id); if (b) b.file = `gl/buffers/${f}`; } delete d.dumps; for (const tx of d.textures) { const url: string | undefined = tx.src?.dataUrl; if (!url) continue; writeFileSync(join(ensureDir(join(dir, "textures")), `${tx.id}.png`), Buffer.from(url.split(",")[1], "base64")); tx.src.file = `gl/textures/${tx.id}.png`; delete tx.src.dataUrl; } // three.js scenes in three's own JSON format (ObjectLoader.parse() loads them back) if (d.three) for (const s of d.three.scenes) { if (s._json) { writeFileSync(join(ensureDir(join(out, "three")), `scene-${s.index}.json`), s._json); s.file = `three/scene-${s.index}.json`; delete s._json; } } // ---------- channels ---------- const frames: any[] = d.frameData; type Raw = { ts: number[]; vs: number[] }; const raw = new Map<string, Raw>(); const put = (key: string, tm: number, v: number) => { let r = raw.get(key); if (!r) raw.set(key, (r = { ts: [], vs: [] })); r.ts.push(tm); r.vs.push(v); }; const meta = new Map<string, Partial<Channel>>(); // uniforms: deltas per (program, n-th draw of it in the frame), replayed into values per frame const state = new Map<string, Record<string, number[]>>(); const perOrd = new Map<string, Map<number, Raw>>(); // "prog|uniform|k" → ord → series for (const f of frames) { const tm = t(f.t); for (const [key, delta] of Object.entries<any>(f.u ?? {})) state.set(key, { ...(state.get(key) ?? {}), ...delta }); for (const [pid, count] of Object.entries<number>(f.pc ?? {})) { for (let ord = 0; ord < count; ord++) { const vals = state.get(`${pid}#${ord}`); if (!vals) continue; for (const [name, v] of Object.entries(vals)) { if (v.length > 16) continue; v.forEach((x, k) => { const id = `${pid}|${name}|${k}|${v.length}`; let m = perOrd.get(id); if (!m) perOrd.set(id, (m = new Map())); let r = m.get(ord); if (!r) m.set(ord, (r = { ts: [], vs: [] })); r.ts.push(tm); r.vs.push(x); }); } } } } for (const [id, m] of perOrd) { const [pid, name, k, n] = id.split("|"); const series = [...m.entries()].sort((x, y) => x[0] - y[0]); const same = series.every(([, r]) => r.vs.length === series[0][1].vs.length && r.vs.every((v, i) => v === series[0][1].vs[i])); for (const [ord, r] of same ? series.slice(0, 1) : series) { const key = `${progKey.get(pid) ?? pid}${same ? "" : "#" + ord}.${name}${suffix(+n, +k)}`; raw.set(key, r); meta.set(key, { source: "uniform", program: pid, uniform: name }); } } // scene graphs (three.js, pixi, playcanvas, babylon, ogl): deltas of camera / object / material values per render const sg: Record<string, number> = {}; for (const f of frames) { if (!f.sg || !f.tr) continue; Object.assign(sg, f.sg); const tm = t(f.t); for (const [key, v] of Object.entries(sg)) { put(key, tm, v); if (!meta.has(key)) meta.set(key, { source: "scene" }); } } // WebGPU uniform buffer writes const gw: Record<string, number[]> = {}; for (const f of frames) { if (!f.gw || !Object.keys(f.gw).length) continue; Object.assign(gw, f.gw); const tm = t(f.t); for (const [key, v] of Object.entries(gw)) v.forEach((x, k) => { const ck = `gpu:${key}[${k}]`; put(ck, tm, x); if (!meta.has(ck)) meta.set(ck, { source: "webgpu" }); }); } const channels: Record<string, Channel> = {}; const constants: Record<string, number> = {}; for (const [key, r] of raw) { const c = classify(r.ts, r.vs); if (c.kind === "constant") { if (meta.get(key)?.source !== "scene" || Object.keys(constants).length < 2000) constants[key] = r.vs[0]; continue; } channels[key] = { ...(meta.get(key) as any), ...c }; } // samples: one per frame that drew something, values carried forward between draws const keys = Object.keys(channels); const idx = new Map(keys.map((k) => [k, 0])); const samples: any[] = []; const times = [...new Set(keys.flatMap((k) => raw.get(k)!.ts))].sort((x, y) => x - y); const cur: Record<string, number> = {}; for (const tm of times) { for (const k of keys) { const r = raw.get(k)!; let i = idx.get(k)!; while (i < r.ts.length && r.ts[i] <= tm) { cur[k] = r.vs[i]; i++; } idx.set(k, i); } samples.push({ t: tm, v: { ...cur } }); } writeJson(join(out, "gl-track.json"), { kind: "gl-track", note: "t in ms, 0 = trigger. One sample per rendered frame; v holds every channel that changes during the capture (constants are in gl/gl.json). Fit one with: easing.ts --track gl-track.json --channel <key>", channels, samples, }); // ---------- passes: what one frame draws, in order, per canvas ---------- const drawn = frames.filter((f) => f.d?.length); const passes: any[] = []; const canvasOf = new Map(d.contexts.map((c: any) => [c.id, c.canvas])); const ctxIds = [...new Set(drawn.flatMap((f) => f.d.map((x: any) => x.c ?? "webgpu")))]; for (const cid of ctxIds) { const rep = [...drawn].reverse().find((f) => f.d.some((x: any) => (x.c ?? "webgpu") === cid)); if (!rep) continue; for (const dr of rep.d.filter((x: any) => (x.c ?? "webgpu") === cid)) { const fb = dr.fb && d.framebuffers.find((x: any) => x.id === dr.fb); const target = `${cid} ${canvasOf.get(cid) ?? ""} → ` + (dr.gpu ? "webgpu" : dr.fb ? `framebuffer ${dr.fb}${fb?.color ? " → texture " + fb.color : ""}` : "screen"); let p = passes[passes.length - 1]; if (!p || p.target !== target) passes.push((p = { target, draws: [] })); const last = p.draws[p.draws.length - 1]; const label = dr.gpu ? dr.gpu : `${progKey.get(dr.p) ?? dr.p} ${dr.m} ${dr.n}${dr.i ? " ×" + dr.i + " instances" : ""}${dr.tx ? " samples " + dr.tx.filter(Boolean).join(",") : ""} [${dr.st}]`; if (last && last.label === label) last.times++; else p.draws.push({ label, times: 1 }); } } const drawCounts = drawn.map((f) => f.d.length + (f.more || 0)); const avgDraws = drawCounts.length ? +(drawCounts.reduce((s, n) => s + n, 0) / drawCounts.length).toFixed(1) : 0; writeJson(join(dir, "draws.json"), { note: "per frame: every draw call (p program, m primitive, n vertices, i instances, fb target framebuffer, tx bound textures by unit, st state), clears, three.js render calls", frames: frames.map((f) => ({ t: t(f.t), draws: f.d, more: f.more || undefined, clears: f.cl?.length ? f.cl : undefined, three: f.tr, canvas2d: f.c2 ? Object.fromEntries(Object.entries<any>(f.c2).map(([k, v]) => [k, { n: v.n, calls: v.calls }])) : undefined })) }); // canvas 2D call logs from sampled frames const logs: Record<string, string[]> = {}; for (const f of frames) for (const [cid, v] of Object.entries<any>(f.c2 ?? {})) if (v.log) (logs[cid] = logs[cid] ?? []).push(`--- frame t=${t(f.t)}ms (${v.n} calls)`, ...v.log); for (const [cid, lines] of Object.entries(logs)) writeFileSync(join(dir, `canvas2d-${cid}.txt`), lines.join("\n") + "\n"); // ---------- gl.json ---------- const animatedBy = new Map<string, string[]>(); for (const [k, c] of Object.entries(channels)) if (c.program) animatedBy.set(c.program + "|" + c.uniform, [...(animatedBy.get(c.program + "|" + c.uniform) ?? []), k]); for (const p of d.programs) { p.key = progKey.get(p.id); p.drawsPerFrame = drawn.length ? +(p.draws / drawn.length).toFixed(2) : 0; for (const u of p.uniforms) { const ch = animatedBy.get(p.id + "|" + u.name); if (ch) u.animated = ch; } } const glJson = { note: "static side of the GPU scene; animated values are channels in ../gl-track.json; shader sources in shaders/", renderer: d.contexts.find((c: any) => c.renderer)?.renderer ?? (d.gpu?.adapter ? `WebGPU ${[d.gpu.adapter.vendor, d.gpu.adapter.architecture, d.gpu.adapter.description].filter(Boolean).join(" ")}` : null), contexts: d.contexts, three: d.three, engines: d.engines && Object.keys(d.engines).length ? d.engines : undefined, workers: d.workers, frames: frames.length, drawCallsPerFrame: avgDraws, passes, programs: d.programs, textures: d.textures, buffers: d.buffers, framebuffers: d.framebuffers, webgpu: d.gpu && (d.gpu.modules.length || d.gpu.pipelines.length) ? d.gpu : undefined, canvas2d: Object.keys(logs).length ? Object.keys(logs).map((c) => `gl/canvas2d-${c}.txt`) : undefined, constants, errors: d.errors?.length ? d.errors : undefined, }; writeJson(join(dir, "gl.json"), glJson); const sum = summarize(out); writeFileSync(join(dir, "summary.md"), sum + "\n"); return { contexts: d.contexts.map((c: any) => `${c.id} ${c.type} ${c.canvas}`), programs: d.programs.length, drawCallsPerFrame: avgDraws, animatedChannels: keys.length, three: d.three?.revision ?? undefined, summary: join(dir, "summary.md") }; } // ---------- summary ---------- export function summarize(dirIn: string): string { const dir = abs(dirIn); const g = readJson(join(dir, "gl", "gl.json")); const track = existsSync(join(dir, "gl-track.json")) ? readJson(join(dir, "gl-track.json")) : { channels: {} }; const L: string[] = []; L.push(`# GPU trace: ${dir}`, ""); L.push(`renderer: ${g.renderer ?? "?"} · ${g.frames} frames traced · ${g.drawCallsPerFrame} draw calls per frame`, ""); L.push("## Canvases"); for (const c of g.contexts) L.push(`- ${c.id} ${c.type} on ${c.canvas}: ${c.size ? c.size.join("×") : "?"} px${c.cssRect ? `, css ${c.cssRect[2]}×${c.cssRect[3]} at ${c.cssRect[0]},${c.cssRect[1]} (pixel ratio ${c.pixelRatio})` : ""}${c.attributes ? `, antialias ${c.attributes.antialias}, alpha ${c.attributes.alpha}, premultipliedAlpha ${c.attributes.premultipliedAlpha}, preserveDrawingBuffer ${c.attributes.preserveDrawingBuffer}` : ""}`); if (g.three) { L.push("", `## three.js r${g.three.revision ?? "?"}`); for (const r of g.three.renderers) L.push(`- ${r.kind} on ${r.canvas}: pixelRatio ${r.pixelRatio}, size ${r.size?.join("×")}, outputColorSpace ${r.outputColorSpace ?? r.outputEncoding}, toneMapping ${r.toneMapping} (exposure ${r.toneMappingExposure}), clear ${JSON.stringify(r.clearColor)} α${r.clearAlpha}, autoClear ${r.autoClear}`); for (const s of g.three.scenes) { L.push(`- scene ${s.index}${s.name ? ` "${s.name}"` : ""}: ${s.objects} objects${s.file ? `, full JSON in ${s.file} (THREE.ObjectLoader)` : ""}`); for (const o of s.tree.slice(0, 40)) { if (o.key === "scene") continue; const geo = o.geometry ? ` ${o.geometry.type}${o.geometry.parameters ? JSON.stringify(o.geometry.parameters) : ""} ${o.geometry.vertices ?? "?"} verts` : ""; const mat = o.material ? " · " + o.material.map((m: any) => `${m.type}${m.name ? ` "${m.name}"` : ""}${m.transparent ? " transparent" : ""}${m.blending !== 1 && m.blending !== undefined ? ` blending=${m.blending}` : ""}${m.uniforms ? ` uniforms[${m.uniforms.join(",")}]` : ""}`).join(", ") : ""; L.push(` ${" ".repeat(o.depth)}- ${o.key} ${o.type}${geo}${mat} pos ${JSON.stringify(o.position)} rot ${JSON.stringify(o.rotation)}${o.visible ? "" : " (hidden)"}`); } if (s.tree.length > 40) L.push(` … ${s.tree.length - 40} more in gl/gl.json`); } for (const m of g.three.mixers ?? []) for (const act of m.actions) L.push(`- AnimationMixer on ${m.root}: clip "${act.clip}" ${act.duration?.toFixed?.(3)} s, ${act.tracks?.length} tracks (${act.tracks?.slice(0, 6).map((x: any) => `${x.name} ${x.keys} keys ${x.interpolation === 2300 ? "discrete" : x.interpolation === 2301 ? "linear" : x.interpolation === 2302 ? "smooth" : ""}`).join(", ")}…), ${act.running ? "running" : "stopped"}, timeScale ${act.timeScale}, loop ${act.loop === 2201 ? "repeat" : act.loop === 2200 ? "once" : act.loop === 2202 ? "pingpong" : act.loop}; keyframes in gl/gl.json › three.mixers`); if (g.three.loads?.length) L.push(`- loaded through three.js loaders: ${g.three.loads.map((x: any) => `${x.loader} ${x.url}`).join(", ")}`); } if (g.engines && Object.keys(g.engines).length) L.push("", "## Other engines", ...Object.entries<any>(g.engines).map(([k, v]) => `- ${k}: ${v.map((e: any) => `${e.kind}${e.version ? " v" + e.version : ""}`).join(", ")}; scene values are \`${k}:…\` channels`)); L.push("", "## Programs (shaders in gl/shaders/)"); for (const p of g.programs) { if (!p.draws) continue; L.push(`- **${p.key}**: ${p.drawsPerFrame}/frame, ${p.modes.join("/")} up to ${p.maxCount} verts${p.maxInstances ? ` × ${p.maxInstances} instances` : ""}, ${p.state}${p.files?.fs ? ` (${p.files.vs}, ${p.files.fs})` : ""}`); if (p.three?.length) L.push(` - three.js: ${p.three.join("; ")}`); const anim = p.uniforms.filter((u: any) => u.animated).map((u: any) => u.name); const fixed = p.uniforms.filter((u: any) => !u.animated && u.value !== undefined && !/^(sampler|isampler|usampler)/.test(u.type ?? "") && (u.value?.length ?? 0) <= 4).map((u: any) => `${u.name}=${u.value.length === 1 ? u.value[0] : "[" + u.value.join(",") + "]"}`); if (anim.length) L.push(` - animated: ${anim.join(", ")}`); if (fixed.length) L.push(` - fixed: ${fixed.slice(0, 24).join(", ")}${fixed.length > 24 ? " …" : ""}`); if (p.layout?.length) L.push(` - attributes: ${p.layout.map((x: any) => x.constant ? `${x.name}(constant)` : `${x.name} ${x.size}×${x.type} buf ${x.buffer}${x.divisor ? " per-instance" : ""}`).join(", ")}`); } const unused = g.programs.filter((p: any) => !p.draws).length; if (unused) L.push(`- (${unused} programs compiled but not drawn during the capture)`); if (g.passes?.length) { L.push("", "## One frame per canvas, in draw order (render target: draws)"); for (const p of g.passes) L.push(`- ${p.target}: ${p.draws.map((x: any) => x.label + (x.times > 1 ? ` ×${x.times}` : "")).join("; ")}`); } const tex = g.textures.filter((t: any) => t.src && t.src.kind !== "empty" && t.src.kind !== "storage" && !(t.w === 1 && t.h === 1)); if (tex.length) { L.push("", "## Textures with content"); for (const t of tex.slice(0, 30)) L.push(`- ${t.id} ${t.w}×${t.h} ${t.src.kind}${t.src.url ? " " + t.src.url : ""}${t.src.file ? " → " + t.src.file : ""}${t.uploads > 1 ? ` (${t.uploads} uploads: updated while running)` : ""}`); } if (g.webgpu) L.push("", `## WebGPU`, `- ${g.webgpu.modules.length} shader modules (WGSL in gl/shaders/), ${g.webgpu.pipelines.length} pipelines`); if (g.canvas2d) L.push("", "## Canvas 2D", ...g.canvas2d.map((f: string) => `- call log of sampled frames: ${f}`)); const ch = Object.entries<any>(track.channels); if (ch.length) { L.push("", `## Animated channels (${ch.length}; fit any of them with easing.ts --track gl-track.json --channel KEY)`); const order = ["transition", "there-and-back", "oscillation", "steps", "clock"]; const shown = ch.sort((x, y) => order.indexOf(x[1].kind) - order.indexOf(y[1].kind) || (x[1].firstChangeMs ?? 0) - (y[1].firstChangeMs ?? 0)); for (const [k, c] of shown.slice(0, 60)) L.push(`- ${k}: ${c.kind}${c.kind === "clock" ? ` (+${c.perSecond}/s)` : ""}${c.periodMs ? ` period ~${c.periodMs} ms` : ""}, ${c.min} → ${c.max}, changes ${c.firstChangeMs}–${c.lastChangeMs} ms`); if (shown.length > 60) L.push(`- … ${shown.length - 60} more: bun gl.ts channels ${dirIn}`); } if (g.errors?.length) L.push("", "## Tracer notes", ...g.errors.map((e: string) => `- ${e}`)); return L.join("\n"); } // ---------- compare ---------- function compareCaptures(refDir: string, cloneDir: string, map: Record<string, string>, timingLimit: number, grep: RegExp | null) { const R = readJson(join(refDir, "gl", "gl.json")), C = readJson(join(cloneDir, "gl", "gl.json")); const rt = readJson(join(refDir, "gl-track.json")), ct = readJson(join(cloneDir, "gl-track.json")); const L: string[] = [`# GPU compare: ${refDir} vs ${cloneDir}`, ""]; // canvases matched by element (tag, id, classes), the probe canvases libraries make (300×150, not in the page) left out const ctx = (g: any) => g.contexts.filter((c: any) => /webgl|webgpu/.test(c.type) && c.cssRect && c.cssRect[2] > 0); const fmt = (c: any) => c ? `${c.type} ${c.size?.join("×")} px (ratio ${c.pixelRatio}), antialias ${c.attributes?.antialias}, alpha ${c.attributes?.alpha}, premultipliedAlpha ${c.attributes?.premultipliedAlpha}` : "—"; L.push("## Canvases", "| canvas | reference | clone |", "|---|---|---|"); const cc = ctx(C); for (const r of ctx(R)) { const c = cc.find((x: any) => x.canvas === r.canvas); L.push(`| ${r.canvas} | ${fmt(r)} | ${fmt(c)}${c && fmt(c) !== fmt(r) ? " **differs**" : ""} |`); } for (const c of cc) if (!ctx(R).some((r: any) => r.canvas === c.canvas)) L.push(`| ${c.canvas} | — | ${fmt(c)} |`); if (R.three || C.three) { const f = (g: any) => g.three ? g.three.renderers.map((r: any) => `${r.canvas}: r${g.three.revision} ${r.outputColorSpace ?? r.outputEncoding}, toneMapping ${r.toneMapping}, pixelRatio ${r.pixelRatio}, clear ${JSON.stringify(r.clearColor)} α${r.clearAlpha}`).join("<br>") : "—"; L.push(`| three.js renderers | ${f(R)} | ${f(C)} |`); } // structure: drawn programs grouped by what they draw (primitive, vertex count, instances, blend/depth state) const sig = (g: any) => { const m = new Map<string, number>(); for (const p of g.programs.filter((p: any) => p.draws)) { const k = `${p.modes.join("/")} ${p.maxCount}${p.maxInstances ? " ×" + p.maxInstances : ""} [${p.state}]`; m.set(k, +((m.get(k) ?? 0) + p.drawsPerFrame).toFixed(2)); } return m; }; const rs = sig(R), cs = sig(C); L.push("", "## Draw structure (draw calls per traced frame, by primitive · vertices · state)", "", "| draws | reference | clone |", "|---|---|---|"); for (const k of [...new Set([...rs.keys(), ...cs.keys()])].sort()) L.push(`| ${k} | ${rs.get(k) ?? "—"} | ${cs.get(k) ?? "—"}${!rs.has(k) || !cs.has(k) ? " **only in one**" : ""} |`); L.push("", `draw calls per frame: ${R.drawCallsPerFrame} vs ${C.drawCallsPerFrame}. A different rate for the same draw usually means a different render cadence (every frame vs every other frame).`); // channels matched by uniform / property name (prefixes differ between builds), or by --map const tail = (k: string) => k.replace(/^(w\d+\.)?p\d+(:[\w-]+)?(#\d+)?\./, "").replace(/^(\w+):s\d+\//, "$1:").replace(/#\d+/g, ""); const cIndex = new Map<string, string[]>(); for (const k of Object.keys(ct.channels)) cIndex.set(tail(k), [...(cIndex.get(tail(k)) ?? []), k]); const series = (tr: any, k: string) => tr.samples.filter((s: any) => s.v[k] !== undefined).map((s: any) => [s.t, s.v[k]] as [number, number]); const at = (s: [number, number][], tm: number) => { let best = s[0]; for (const p of s) if (Math.abs(p[0] - tm) < Math.abs(best[0] - tm)) best = p; return best[1]; }; const rows: string[] = []; let fails = 0; // several clone channels can share a name (every Group has a rotation.x): take the one that moves most alike const likeness = (r: any, c: any) => (c.kind === r.kind ? 0 : 1000) + Math.abs((c.firstChangeMs ?? 0) - (r.firstChangeMs ?? 0)) + Math.abs((c.lastChangeMs ?? 0) - (r.lastChangeMs ?? 0)) + 1000 * (Math.abs(c.min - r.min) + Math.abs(c.max - r.max)) / Math.max(1e-9, Math.abs(r.max - r.min)); const taken = new Set<string>(); for (const [rk, r] of Object.entries<any>(rt.channels)) { if (r.kind === "clock" || (grep && !grep.test(rk))) continue; const wanted = map[tail(rk)] ?? tail(rk); const ck = (cIndex.get(wanted) ?? []).filter((k) => !taken.has(k)).sort((x, y) => likeness(r, ct.channels[x]) - likeness(r, ct.channels[y]))[0]; if (ck) taken.add(ck); if (!ck) { rows.push(`| ${rk} | ${r.kind} ${r.min}→${r.max} ${r.firstChangeMs}–${r.lastChangeMs} ms | (no channel named ${wanted}) | | missing |`); fails++; continue; } const c = ct.channels[ck]; const ds = r.firstChangeMs !== null && c.firstChangeMs !== null ? c.firstChangeMs - r.firstChangeMs : NaN; const de = r.lastChangeMs !== null && c.lastChangeMs !== null ? c.lastChangeMs - r.lastChangeMs : NaN; const span = Math.max(1e-9, r.max - r.min); const rsr = series(rt, rk), csr = series(ct, ck); const diffs = rsr.map(([tm, v]) => Math.abs(at(csr, tm) - v) / span); const mean = diffs.reduce((s, x) => s + x, 0) / Math.max(1, diffs.length); const ok = Math.abs(ds) <= timingLimit && Math.abs(de) <= timingLimit && mean <= 0.05 && c.kind === r.kind; if (!ok) fails++; rows.push(`| ${rk} | ${r.kind} ${r.min}→${r.max} ${r.firstChangeMs}–${r.lastChangeMs} ms | ${ck}: ${c.kind} ${c.min}→${c.max} ${c.firstChangeMs}–${c.lastChangeMs} ms | start ${ds >= 0 ? "+" : ""}${ds} ms, end ${de >= 0 ? "+" : ""}${de} ms, mean |Δ| ${(mean * 100).toFixed(1)} % of range | ${ok ? "pass" : "FAIL"} |`); } L.push("", `## Animated channels (${rows.length} in the reference; uniform time "clock" channels are skipped)`, "", "| reference | | clone | timing and value error | result |", "|---|---|---|---|---|", ...rows); L.push("", `pass: start/end within ${timingLimit} ms, same kind, mean value error ≤ 5 % of the reference range. ${fails} of ${rows.length} failing.`); return { md: L.join("\n"), fails }; } if (import.meta.main) { const HELP = ` gl.ts — read a GPU trace written by capture.ts --gl. bun gl.ts summary <capture dir> canvases, three.js scene, programs, passes, textures, animated channels bun gl.ts channels <capture dir> [--grep RE] [--series KEY] list channels (kind, range, change window) or print one as [[t, v], …] bun gl.ts compare --ref <dir> --clone <dir> [--grep RE] [--map "uHover=u_hover,…"] [--timing 80] [--out report.md] canvas settings, draw structure and every animated channel, ref vs clone `; const a = parseArgs(process.argv.slice(2)); const cmd = a._[0]; if (a.help || !cmd) usage(HELP); if (cmd === "summary") { const dir = String(a._[1] ?? a.in ?? ""); if (!existsSync(join(dir, "gl", "gl.json"))) throw new Error(`no gl/gl.json in ${dir}: capture with --gl first`); console.log(summarize(dir)); } else if (cmd === "channels") { const dir = String(a._[1] ?? a.in ?? ""); const tr = readJson(join(dir, "gl-track.json")); if (a.series) { const k = String(a.series); const keys = Object.keys(tr.channels).filter((x) => x === k || x.endsWith("." + k) || x.endsWith(k)); if (keys.length !== 1) throw new Error(keys.length ? `ambiguous: ${keys.join(", ")}` : `no channel ${k}`); console.log(JSON.stringify(tr.samples.filter((s: any) => s.v[keys[0]] !== undefined).map((s: any) => [s.t, s.v[keys[0]]]))); } else { const re = a.grep ? new RegExp(String(a.grep), "i") : null; for (const [k, c] of Object.entries<any>(tr.channels)) if (!re || re.test(k)) console.log(`${k}\t${c.kind}\t${c.min} → ${c.max}\t${c.firstChangeMs}–${c.lastChangeMs} ms${c.perSecond ? `\t+${c.perSecond}/s` : ""}${c.periodMs ? `\tperiod ${c.periodMs} ms` : ""}`); } } else if (cmd === "compare") { if (!a.ref || !a.clone) usage(HELP); const map: Record<string, string> = {}; for (const pair of String(a.map ?? "").split(",").filter(Boolean)) { const [x, y] = pair.split("="); map[x.trim()] = y.trim(); } const { md, fails } = compareCaptures(abs(String(a.ref)), abs(String(a.clone)), map, num(a.timing, 80), a.grep ? new RegExp(String(a.grep)) : null); if (a.out) writeFileSync(abs(String(a.out)), md + "\n"); console.log(md); process.exitCode = fails ? 1 : 0; } else usage(HELP); }skills/reanimate/scripts/inpage/clock.js11 KBfd12f10de919upstream ↗
// Virtual clock, injected before any page script (capture.ts --clock virtual, --seed). // // Seeded Math.random: the same seed gives the same particles, arcs and noise on every capture. // Virtual time: performance.now, Date, timers, requestAnimationFrame, requestIdleCallback, // document.timeline.currentTime, Event.timeStamp and every CSS / Web Animations API animation follow // one clock that the capturer advances by hand. A frame then takes as long as it takes to render (software // GL, a slow machine) and the page still sees a steady 60 Hz, so frame k is always the state at t = k / fps. // // Free mode (before freeze) passes timers and frames through to the browser, with bookkeeping, so the // page loads normally. freeze() takes the pending timers and frames over; advance(ms) then runs them in // time order, ticking rAF every 1000 / rafHz ms and yielding to the event loop between callbacks so // promise chains and MessageChannel schedulers (React) keep up. (function (CFG) { const w = self; // also runs in workers (seed only) if (w.__mcClock) return; if (CFG.seed !== null && CFG.seed !== undefined) { // mulberry32 let s = CFG.seed >>> 0 || 1; Math.random = function random() { s = (s + 0x6d2b79f5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } if (!CFG.virtual) { w.__mcClock = { virtual: false, seed: CFG.seed }; return; } const N = { setTimeout: w.setTimeout.bind(w), clearTimeout: w.clearTimeout.bind(w), raf: w.requestAnimationFrame.bind(w), caf: w.cancelAnimationFrame.bind(w), perfNow: performance.now.bind(performance), dateNow: Date.now, Date: Date, }; const tsDesc = Object.getOwnPropertyDescriptor(Event.prototype, "timeStamp"); const tlDesc = w.AnimationTimeline && Object.getOwnPropertyDescriptor(AnimationTimeline.prototype, "currentTime"); const st = { frozen: false, now: 0, dateOffset: N.dateNow() - N.perfNow(), nextId: 1, seq: 0, nesting: 0, timers: new Map(), rafs: new Map(), tick: 1000 / (CFG.rafHz || 60), nextTick: 0, anims: new Map(), frames: 0, startedAt: null, keeper: 0, hist: [], }; const now = () => (st.frozen ? st.now : N.perfNow()); function call(cb, args) { try { if (typeof cb === "string") (0, eval)(cb); else if (typeof cb === "function") cb.apply(w, args); } catch (e) { N.setTimeout(() => { throw e; }); } } // ---------- timers ---------- function arm(t) { t.native = N.setTimeout(() => { if (st.timers.get(t.id) === t && !st.frozen) fire(t); }, Math.max(0, t.due - N.perfNow())); } function addTimer(cb, delay, args, interval) { const id = st.nextId++; const nesting = st.nesting + 1; let d = Math.max(0, Number(delay) || 0); if (nesting > 5 || interval) d = Math.max(d, nesting > 5 ? 4 : 1); // browsers clamp nested timers to 4 ms const t = { id, cb, args, delay: d, interval, due: now() + d, seq: st.seq++, nesting, native: null }; st.timers.set(id, t); if (!st.frozen) arm(t); return id; } function fire(t) { if (t.interval) { t.due = (st.frozen ? t.due : N.perfNow()) + t.delay; t.seq = st.seq++; if (!st.frozen) arm(t); } else st.timers.delete(t.id); const prev = st.nesting; st.nesting = t.nesting; call(t.cb, t.args); st.nesting = prev; } function clearTimer(id) { const t = st.timers.get(id); if (!t) return; if (t.native !== null) N.clearTimeout(t.native); st.timers.delete(id); } w.setTimeout = function setTimeout(cb, delay, ...args) { return addTimer(cb, delay, args, false); }; w.setInterval = function setInterval(cb, delay, ...args) { return addTimer(cb, delay, args, true); }; w.clearTimeout = function clearTimeout(id) { clearTimer(id); }; w.clearInterval = function clearInterval(id) { clearTimer(id); }; w.requestIdleCallback = function requestIdleCallback(cb, opts) { return addTimer(() => cb({ didTimeout: false, timeRemaining: () => 10 }), Math.min(50, (opts && opts.timeout) || 1), [], false); }; w.cancelIdleCallback = function cancelIdleCallback(id) { clearTimer(id); }; // ---------- animation frames ---------- w.requestAnimationFrame = function requestAnimationFrame(cb) { const id = st.nextId++; const r = { cb, native: null }; if (!st.frozen) r.native = N.raf((ts) => { if (st.rafs.get(id) === r) { st.rafs.delete(id); call(cb, [ts]); } }); st.rafs.set(id, r); return id; }; w.cancelAnimationFrame = function cancelAnimationFrame(id) { const r = st.rafs.get(id); if (!r) return; if (r.native !== null) N.caf(r.native); st.rafs.delete(id); }; function runFrame(ts) { st.frames++; syncAnims(); syncVideos(); const due = [...st.rafs.entries()]; st.rafs.clear(); // callbacks registered while these run belong to the next frame for (const [, r] of due) call(r.cb, [ts]); } // ---------- CSS animations, transitions and WAAPI ---------- // Each running animation on the document timeline is paused when first seen and then seeked to // base + (virtual now − first seen) · playbackRate. Finite ones are finish()ed at their end so // `finished` promises and finish events still fire (motion / Framer Motion wait on them). function syncAnims() { let list; try { list = document.getAnimations(); } catch { return; } for (const a of list) { if (a.timeline && a.timeline !== document.timeline) continue; // scroll / view timelines follow scroll let rec = st.anims.get(a); if (!rec || a.playState === "running") { if (!rec && a.playState !== "running") continue; // paused or finished by the page rec = { base: a.currentTime || 0, v0: st.now }; st.anims.set(a, rec); try { a.pause(); } catch { continue; } } if (!st.frozen) continue; const rate = a.playbackRate || 1; const t = rec.base + (st.now - rec.v0) * rate; let end = Infinity; try { end = a.effect ? a.effect.getComputedTiming().endTime : Infinity; } catch {} if ((rate > 0 && t >= end) || (rate < 0 && t <= 0)) { st.anims.delete(a); try { a.finish(); } catch {} continue; } try { a.currentTime = t; } catch {} } } // <video> plays on the decoder's real clock: pause each playing video when first seen and seek it with // the virtual clock; busy() holds the frame until the seek has landed. const videos = new Map(); function syncVideos() { let list; try { list = document.querySelectorAll("video"); } catch { return; } for (const v of list) { let rec = videos.get(v); if (!rec) { if (v.paused) continue; rec = { base: v.currentTime, v0: st.now }; videos.set(v, rec); try { v.pause(); } catch {} } if (!st.frozen) continue; let t = rec.base + ((st.now - rec.v0) / 1000) * (v.playbackRate || 1); if (v.loop && v.duration > 0) t %= v.duration; else if (v.duration > 0) t = Math.min(t, v.duration); if (Math.abs(v.currentTime - t) > 0.001) try { v.currentTime = t; } catch {} } } // While frozen but not stepping (page load for --trigger load), keep catching new animations so // they start from ~0 instead of running on the real clock. function keeper() { if (!st.frozen) return; syncAnims(); st.keeper = N.raf(keeper); } // ---------- time sources ---------- performance.now = function now_() { return now(); }; function VDate(...a) { if (!new.target) return new N.Date(st.dateOffset + now()).toString(); return a.length ? new N.Date(...a) : new N.Date(st.frozen ? st.dateOffset + st.now : N.dateNow()); } VDate.prototype = N.Date.prototype; VDate.now = () => (st.frozen ? Math.round(st.dateOffset + st.now) : N.dateNow()); VDate.parse = N.Date.parse; VDate.UTC = N.Date.UTC; Object.defineProperty(VDate.prototype, "constructor", { value: VDate, writable: true, configurable: true }); w.Date = VDate; if (tsDesc && tsDesc.get) { Object.defineProperty(Event.prototype, "timeStamp", { configurable: true, get() { return st.frozen ? st.now : tsDesc.get.call(this); } }); } if (tlDesc && tlDesc.get) { Object.defineProperty(AnimationTimeline.prototype, "currentTime", { configurable: true, get() { return st.frozen && this === document.timeline ? st.now : tlDesc.get.call(this); } }); } // ---------- workers ---------- // A worker answers on its own (real) clock. The capturer waits for posted-but-unanswered messages // before each frame, the same way it waits for the network, so a worker reply always lands on the // same virtual frame. A worker that never answers stops counting after 2 s. const pending = new Map(); if (w.Worker) { const W = w.Worker; const post = W.prototype.postMessage; W.prototype.postMessage = function () { if (!this.__mcSilent) pending.set(this, N.perfNow()); if (!this.__mcListening) { this.__mcListening = true; this.addEventListener("message", () => pending.delete(this)); this.addEventListener("error", () => pending.delete(this)); } return post.apply(this, arguments); }; } function busy() { let n = 0; for (const v of videos.keys()) if (v.seeking) n++; for (const [wk, t] of pending) { if (N.perfNow() - t > 2000) { wk.__mcSilent = true; pending.delete(wk); } else n++; } return n; } // ---------- control ---------- const mc = new MessageChannel(); const waiting = []; mc.port1.onmessage = () => { const r = waiting.shift(); if (r) r(); }; const yieldTask = () => new Promise((r) => { waiting.push(r); mc.port2.postMessage(0); }); function freeze() { if (st.frozen) return st.now; st.now = N.perfNow(); st.frozen = true; st.nextTick = st.now + st.tick; for (const t of st.timers.values()) if (t.native !== null) { N.clearTimeout(t.native); t.native = null; } for (const r of st.rafs.values()) if (r.native !== null) { N.caf(r.native); r.native = null; } syncAnims(); keeper(); return st.now; } async function advance(ms) { if (!st.frozen) freeze(); if (st.startedAt === null) st.startedAt = st.now; N.caf(st.keeper); const target = st.now + Math.max(0, ms); for (let guard = 0; guard < 200000; guard++) { let next = null; for (const t of st.timers.values()) if (!next || t.due < next.due || (t.due === next.due && t.seq < next.seq)) next = t; const nextAt = Math.min(next ? next.due : Infinity, st.nextTick); if (nextAt > target) break; if (next && next.due <= st.nextTick) { st.now = Math.max(st.now, next.due); fire(next); } else { st.now = st.nextTick; st.nextTick += st.tick; runFrame(st.now); } await yieldTask(); } st.now = target; syncAnims(); syncVideos(); keeper(); if (st.hist.length < 20000) st.hist.push([N.perfNow(), st.now]); return st.now; } w.__mcClock = { virtual: true, seed: CFG.seed, freeze, advance, busy, history: () => st.hist, // [real performance.now, virtual now] after each advance, to place worker events now: () => now(), state: () => ({ frozen: st.frozen, now: st.now, timers: st.timers.size, rafs: st.rafs.size, frames: st.frames, animations: st.anims.size }), }; if (CFG.freezeAtStart) freeze(); })skills/reanimate/scripts/inpage/gl-hooks.js46 KB16e2a7687270upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/reanimate/scripts/lib.ts3.4 KB7cad35798e07upstream ↗
// Shared helpers for the reanimate scripts. Bun + TypeScript, no build step. import { mkdirSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; export const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url)); export function ffmpegPath(): string { const p = join(SCRIPTS_DIR, "node_modules", "ffmpeg-static", "ffmpeg"); if (!existsSync(p)) throw new Error(`ffmpeg not installed, run ${join(SCRIPTS_DIR, "setup.sh")}`); return p; } export function ffmpeg(args: string[], opts: { quiet?: boolean } = {}): string { const r = spawnSync(ffmpegPath(), ["-hide_banner", "-loglevel", opts.quiet ? "error" : "warning", ...args], { encoding: "utf8", maxBuffer: 64 << 20 }); if (r.status !== 0) throw new Error(`ffmpeg failed (${r.status}): ${r.stderr}`); return r.stderr; } /** Minimal argv parser: --key value, --flag, --key=value. Returns { _: positionals, ...flags }. */ export function parseArgs(argv: string[], defaults: Record<string, any> = {}): Record<string, any> { const out: Record<string, any> = { _: [], ...defaults }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (!a.startsWith("--")) { out._.push(a); continue; } const eq = a.indexOf("="); if (eq > 0) { out[a.slice(2, eq)] = a.slice(eq + 1); continue; } const key = a.slice(2); const next = argv[i + 1]; if (next === undefined || next.startsWith("--")) out[key] = true; else { out[key] = next; i++; } } return out; } export function usage(text: string): never { console.log(text.trim() + "\n"); process.exit(0); } export function ensureDir(p: string): string { mkdirSync(p, { recursive: true }); return p; } export function num(v: any, fallback: number): number { if (v === undefined || v === true) return fallback; const n = Number(v); return Number.isFinite(n) ? n : fallback; } /** "1:23.5" | "83.5" | "83.5s" | "1500ms" -> seconds */ export function parseTime(v: any): number | undefined { if (v === undefined || v === true) return undefined; const s = String(v).trim(); if (s.endsWith("ms")) return Number(s.slice(0, -2)) / 1000; if (s.includes(":")) { const [m, sec] = s.split(":"); return Number(m) * 60 + Number(sec); } return Number(s.replace(/s$/, "")); } export function parseSize(v: any, fallback: { width: number; height: number }) { if (!v || v === true) return fallback; const m = String(v).match(/^(\d+)x(\d+)$/); if (!m) throw new Error(`bad size "${v}", expected WxH`); return { width: Number(m[1]), height: Number(m[2]) }; } export function parseRect(v: any): { x: number; y: number; width: number; height: number } | undefined { if (!v || v === true) return undefined; const p = String(v).split(",").map(Number); if (p.length !== 4 || p.some((n) => !Number.isFinite(n))) throw new Error(`bad rect "${v}", expected x,y,w,h`); return { x: p[0], y: p[1], width: p[2], height: p[3] }; } export function listFrames(dir: string): string[] { return readdirSync(dir).filter((f) => /\.png$/i.test(f)).sort().map((f) => join(dir, f)); } export function readJson<T = any>(p: string): T { return JSON.parse(readFileSync(p, "utf8")); } export function writeJson(p: string, v: any) { writeFileSync(p, JSON.stringify(v, null, 2) + "\n"); } export function abs(p: string) { return resolve(p); } export const pad = (n: number, w = 4) => String(n).padStart(w, "0");skills/reanimate/scripts/package.json207 B8913c2b8841fupstream ↗
{ "name": "reanimate-scripts", "private": true, "type": "module", "dependencies": { "ffmpeg-static": "^5.2.0", "pixelmatch": "^8.0.0", "playwright": "1.64.1", "pngjs": "^7.0.0" } }skills/reanimate/scripts/setup.sh818 Bf05fe0cc9ab1upstream ↗
#!/usr/bin/env bash # Installs the script dependencies once (bun) and checks that Chromium and ffmpeg are usable. # Safe to re-run; it is a no-op when everything is already in place. set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$HERE" if ! command -v bun >/dev/null; then echo "bun is required (https://bun.sh)"; exit 1; fi if [ ! -d node_modules/playwright ] || [ ! -x node_modules/ffmpeg-static/ffmpeg ]; then bun install --silent fi if ! bun -e 'const {chromium}=await import("playwright"); const b=await chromium.launch(); await b.close(); console.log("chromium ok")' 2>/dev/null; then echo "Chromium missing for this Playwright version, installing it..." bunx playwright install chromium fi node_modules/ffmpeg-static/ffmpeg -hide_banner -version | head -1 echo "ready: $HERE"skills/reanimate/scripts/sheet.ts6.2 KBc6b0eae6ac51upstream ↗
// Lay frames out on labelled contact sheets so a whole motion can be read in one image. // Two modes: // filmstrip: one directory of frames → sheet-NN.png with the timestamp under each frame // compare: reference frames vs clone frames (and diffs from compare.ts) side by side, one row per frame // Rendered with Chromium (HTML + screenshot), so labels work without ffmpeg drawtext. import { chromium } from "playwright"; import { join, basename } from "node:path"; import { existsSync, readFileSync } from "node:fs"; import { abs, ensureDir, listFrames, num, pad, parseArgs, readJson, usage } from "./lib.ts"; const HELP = ` sheet.ts — labelled contact sheets. bun sheet.ts filmstrip --frames <dir> --out <dir> [--fps N] [--cols 6] [--per-sheet 24] [--width 240] [--every K] [--from I --to J] bun sheet.ts compare --ref <dir> --clone <dir> --out <dir> [--diff <dir>] [--fps N] [--per-sheet 8] [--width 420] [--every K] [--offset K] --fps used for the time labels (default: fps from frames.json next to the frames, else 25) --every K show every K-th frame (default 1) --from/--to frame index range (0-based, inclusive) --offset K compare: clone frame = ref frame + K (take it from compare.ts report.json alignment) Writes <out>/sheet-01.png, sheet-02.png … and prints their paths. Read them with the image viewer. `; const a = parseArgs(process.argv.slice(2)); const mode = a._[0]; if (a.help || !mode || !a.out) usage(HELP); const out = ensureDir(abs(String(a.out))); // frames.ts writes frames.json beside the frames, capture.ts one level up function fpsOf(dir: string, fallback: number) { for (const j of [join(dir, "frames.json"), join(dir, "..", "frames.json")]) { if (existsSync(j)) { const m = readJson(j); if (m.fps) return Number(m.fps); } } return fallback; } const label = (i: number, fps: number) => `#${i} ${(i / fps).toFixed(2)}s`; // data URIs: a page built with setContent has no file:// access const fileUrl = (p: string) => "data:image/png;base64," + readFileSync(p).toString("base64"); type Sheet = { html: string; name: string }; const sheets: Sheet[] = []; const css = `body{margin:0;background:#111;color:#ddd;font:12px/1.3 ui-monospace,Menlo,monospace;padding:10px} .grid{display:grid;gap:10px}.cell{display:flex;flex-direction:column;gap:3px;align-items:center} .cell img{display:block;background:#000;outline:1px solid #333}.cap{color:#9ad}.hdr{margin:0 0 8px;color:#fff;font-weight:600} .row{display:grid;gap:8px;align-items:start;margin-bottom:10px}.row img{display:block;background:#000;outline:1px solid #333} .colhdr{display:grid;gap:8px;color:#9ad;margin-bottom:4px}`; if (mode === "filmstrip") { if (!a.frames) usage(HELP); const dir = abs(String(a.frames)); const fps = num(a.fps, fpsOf(dir, 25)); const every = num(a.every, 1), cols = num(a.cols, 6), per = num(a["per-sheet"], 24), width = num(a.width, 240); let frames = listFrames(dir).map((p, i) => ({ p, i })); const from = num(a.from, 0), to = num(a.to, frames.length - 1); frames = frames.filter((f) => f.i >= from && f.i <= to && (f.i - from) % every === 0); for (let s = 0; s * per < frames.length; s++) { const chunk = frames.slice(s * per, (s + 1) * per); const cells = chunk.map((f) => `<div class="cell"><img src="${fileUrl(f.p)}" style="width:${width}px"><div class="cap">${label(f.i, fps)}</div></div>`).join(""); sheets.push({ name: `sheet-${String(s + 1).padStart(2, "0")}.png`, html: `<style>${css}</style><p class="hdr">${basename(dir)} · frames ${chunk[0].i}–${chunk[chunk.length - 1].i} · ${fps} fps</p><div class="grid" style="grid-template-columns:repeat(${cols},max-content)">${cells}</div>` }); } } else if (mode === "compare") { if (!a.ref || !a.clone) usage(HELP); const refDir = abs(String(a.ref)), cloneDir = abs(String(a.clone)); const diffDir = a.diff ? abs(String(a.diff)) : undefined; const fps = num(a.fps, fpsOf(refDir, 25)); const every = num(a.every, 1), per = num(a["per-sheet"], 8), width = num(a.width, 420), offset = num(a.offset, 0); const ref = listFrames(refDir), clone = listFrames(cloneDir); const hasDiffs = !!diffDir && listFrames(diffDir).length > 0; let report: any = null; if (diffDir && existsSync(join(diffDir, "..", "report.json"))) report = readJson(join(diffDir, "..", "report.json")); const n = Math.min(ref.length, clone.length - Math.max(0, offset)); const idx: number[] = []; const from = num(a.from, Math.max(0, -offset)), to = num(a.to, n - 1); for (let i = from; i <= to && i < n; i += every) idx.push(i); const ncol = hasDiffs ? 3 : 2; for (let s = 0; s * per < idx.length; s++) { const chunk = idx.slice(s * per, (s + 1) * per); const rows = chunk.map((i) => { const c = clone[i + offset]; // compare.ts names each diff after its reference frame and skips frames without a clone frame const d = hasDiffs ? join(diffDir!, `${pad(i)}.png`) : undefined; const mm = report?.frameDetails?.[i]?.mismatch ?? undefined; const cap = `${label(i, fps)}${mm !== undefined ? ` · mismatch ${(mm * 100).toFixed(1)}%` : ""}`; return `<div class="cap">${cap}</div><div class="row" style="grid-template-columns:repeat(${ncol},${width}px)"><img src="${fileUrl(ref[i])}" style="width:${width}px"><img src="${c ? fileUrl(c) : ""}" style="width:${width}px">${d && existsSync(d) ? `<img src="${fileUrl(d)}" style="width:${width}px">` : ""}</div>`; }).join(""); sheets.push({ name: `compare-${String(s + 1).padStart(2, "0")}.png`, html: `<style>${css}</style><p class="hdr">reference vs clone${hasDiffs ? " vs diff" : ""} · ${fps} fps · clone offset ${offset}</p><div class="colhdr" style="grid-template-columns:repeat(${ncol},${width}px)"><div>reference</div><div>clone</div>${hasDiffs ? "<div>diff (red = differs)</div>" : ""}</div>${rows}` }); } } else usage(HELP); const browser = await chromium.launch(); const page = await browser.newPage({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1 }); const paths: string[] = []; for (const s of sheets) { await page.setContent(s.html, { waitUntil: "load" }); const p = join(out, s.name); await page.screenshot({ path: p, fullPage: true }); paths.push(p); } await browser.close(); console.log(paths.join("\n") || "no frames selected");skills/reanimate/references/analysis.md6.5 KB94d4a3e87419upstream ↗
# Reading frames and writing the motion spec The spec turns "I watched it" into rows you can check. Write it before building; update it when verification teaches you something; it is the first thing to show the user when they ask "does it match?". ## spec.md template ```markdown # <name> motion spec Target: <url + selector | file + time range> Viewport: 1440x900 Fps: 25 Destination: <path/Component.tsx> (<stack: React + Framer Motion | CSS | GSAP …>) Fidelity: motion-faithful | pixel-faithful | mixed (additions: …) Reference capture: .reanimate/<name>/ref (command: …) ## Structure (static) | element | role / selector (ref → clone) | box at rest (x,y,w,h) | notes (overflow, z-index, origin, clip) | ## Timeline (t=0 is the trigger) | # | element | property | from → to | start ms | duration ms | easing | stagger / repeat | source | | 1 | h1 | opacity | 0 → 1 | 200 | 700 | cubic-bezier(.16,1,.3,1) | – | inspect.json | | 2 | h1 | translateY | 40px → 0 | 200 | 700 | same | – | inspect.json | | 2b | canvas card | three:Card.rotation.x | 0 → 0.26 rad | 30 | 630 | ease-in-out (lag 0.004/ms) | follows pointer | gl-track.json + easing.ts --channel | | 3 | p | opacity, translateY | 0→1, 30px→0 | 400 | 700 | same | +200 ms after h1 | track.json + easing.ts | | 4 | .cta | opacity, translateY | 0→1, 24px→0 | 600 | 600 | same | +200 ms | frames #15–#30 | Trigger: load | enters viewport (threshold ~25 %) | hover | click | scroll-linked (0–600px) | loop every N ms Total length: <ms> Last visible change: <ms> ## Style facts needed for the motion (and everything, if pixel-faithful) fonts, sizes, colours, radii, shadows, gaps, assets (with URLs or where copied) ## Additions (mixed only) what is new, where it lives, how it is kept out of the compared region or why it does not affect timing ``` ## Where the numbers come from 1. **`inspect.json › animations`** (websites with CSS/WAAPI motion): `timing.delay`, `timing.duration`, per-keyframe `easing`, `iterations`, `direction`. Transitions show up as `CSSTransition` with `transitionProperty`. Copy them. 2. **`track.json` + `easing.ts`** (websites, any technology): per element and property, prints delay, visible duration, overshoot and the best-fitting named easing with its fitted duration. Run it for every moving element and property (`translateY`, `opacity`, `scale`, `x`, `w`…). Overshoot > 2 % means a spring or a back easing; note the overshoot percentage and the settle time, the implementation notes say how to map them. 3. **`gl-track.json` + `easing.ts --channel`** (canvas, WebGL, 3D, captured with `--gl`): uniforms and scene-graph values (camera, object transforms, material uniforms) per rendered frame. `gl.ts summary` lists the animated ones by kind (`clock`, `transition`, `there-and-back`, `oscillation`, `steps`) with their change windows, and the fixed uniforms are constants to copy as they are. See `references/webgl.md`. 4. **Frames** (videos, gifs, and canvas when there is no trace): for each element find the first frame where it changes and the last frame where it changes; `start = first/fps`, `duration = (last − first + 1)/fps`. Judge the easing from where the midpoint lands: if the element has covered more than half of its distance at a third of the duration it is an ease-out; less than a quarter, an ease-in; symmetric, ease-in-out; constant steps, linear. Overshoot past the final position then return: back/spring. `compare.ts` prints an activity curve per set that shows these shapes as bars even without a track. 5. **Staggers**: the gap between the start frames of siblings. Note whether it is a constant (each +80 ms), grows (ease on the stagger), or is per-character/per-word (text reveals). ## Patterns worth recognising Most landing-page motion is one of these; naming it saves rounds. | Pattern | Tell-tale frames | Typical numbers | |---|---|---| | fade-up stagger | siblings rise 16–48 px while fading, each one slightly later | 500–800 ms, ease-out-expo/quint, stagger 60–150 ms | | text reveal (lines, words, chars) | pieces appear in order, often clipped by their line box (`overflow: hidden` wrapper) | 600–1000 ms, per-piece stagger 20–50 ms | | clip/mask reveal | content uncovers along an edge, no fade | 800–1200 ms, ease-in-out, `clip-path: inset()` | | scale-in (modal, menu, card) | grows from 0.9–0.96 with a fade, transform-origin at the anchor | 150–250 ms, ease-out | | hover lift | card moves up 2–8 px, shadow grows | 150–300 ms, ease-out; reverse uses a shorter or same time | | marquee | continuous translateX of a duplicated row | linear, period 10–40 s, loops; measure the period, not the easing | | scroll-linked | changes only while scrolling, stops when you stop | ties to `scrollY` ranges; read `track.json` scrollY vs value | | pinned section | element stays fixed while the page scrolls past | track `y` stays constant for a scroll range | | parallax | layers move at different fractions of the scroll delta | ratios like 0.2 / 0.5 / 1 | | count-up / typewriter | numbers or characters change per frame | duration plus easing on the value | | spring | overshoots then settles, sometimes twice | stiffness/damping; see implementation notes | | loader / skeleton pulse | opacity or gradient position oscillates | period 1–2 s, ease-in-out, infinite alternate | | page transition | old view exits, new view enters, often with a shared element | 300–600 ms, exit shorter than enter | | shader clock | a canvas that never rests; a `clock` channel such as `u_time` | its rate (+1000/s = ms, +1/s = seconds) and the shader that uses it | | uniform tween | a `transition` channel on a uniform (`u_hover`, `u_progress`) | duration and easing like any tween; the shader maps 0→1 to pixels | | pointer lag (WebGL) | a value chasing the pointer, slower for longer moves | per-frame or per-ms rate `k`; `x += (target − x)·k` | | keyframed model (glTF) | an `AnimationMixer` in `gl.ts summary` | clip name, duration, loop, timeScale: play the same clip | ## How to read a sheet - Go row by row with the timestamp labels. Write down, per element, the frame it first moves and the frame it rests. Do this for every element, not just the biggest one. - Compare consecutive frames: a big jump early then small changes = ease-out; small then big = ease-in. - Look for things that are easy to miss: a backdrop that fades, a shadow that grows, letter-spacing that tightens, a blur that clears, a border that appears, an icon that rotates. They are part of the motion. - Note what does **not** move. A clone that animates an element the reference keeps still fails just as much.skills/reanimate/references/capture.md8.6 KB63582f3c1f9aupstream ↗
# Capturing a reference Goal: a numbered set of PNG frames of exactly the thing to clone, at a known fps, starting a little before the motion begins, plus whatever ground truth the source can give you (declared animations, tracked element positions). The same capture, later run on the clone, is the verification. ## Live website ```bash bun <skill>/scripts/capture.ts --url https://example.com --out .reanimate/<name>/ref \ --viewport 1440x900 --selector "section.hero" --trigger load --duration 3000 \ --track "section.hero h1, section.hero p, section.hero .cta" ``` Find the selector first: `capture.ts --no-video --selector body` dumps `inspect.json` with every node under the target, its rect and styles. Or open the page in any browser tool your agent has (a Playwright or Chrome DevTools MCP, the host app's preview) and read the accessibility tree. Prefer selectors by role or stable class names; generated class names (`css-1x2y3z`) change between loads on some sites, so pick a parent with a semantic tag or `id`. Triggers: | Motion starts when… | `--trigger` | Notes | |---|---|---| | the page loads | `load` | window starts at navigation; nothing else is needed | | the section scrolls into view | `scroll` | starts just below the fold and wheels the section in over `--scroll-ms` in `--scroll-steps` steps; same values on the clone | | the page reaches a scroll position | `scroll --scroll-to 1800` | scroll-linked (parallax, pinned) motion; compare by `scrollY` in `track.json` | | the pointer enters an element | `hover --target ".card"` | `--selector` is the crop, `--target` the element hovered; `--hover-at 0.2,0.8` picks the spot | | the pointer leaves (hover-out) | `leave --pre-hover ".card"` | hovers first for `--pre-hover-ms`, then moves to `--leave-to` | | something follows the pointer (glow, tilt, spotlight) | `move --target ".card" --path "0.1,0.1;0.9,0.1;0.9,0.9"` | `--path-ms` per leg; same path on the clone | | something is dragged (globe, carousel, slider, inertia/fling) | `drag --target ".globe" --path "0.3,0.5;0.7,0.5"` | button down at the first point, glide each leg in `--path-ms`, released while moving so fling velocity is non-zero | | something is clicked (menu, tab, accordion, toggle) | `click --target "button[aria-label=Menu]"` | add `--pre-js` to reach the state before the click | | never, it loops (marquee, idle loader, background) | `none` | capture 2 to 3 loop periods and measure the period from the activity curve | Useful options: - `--pre-js "document.querySelector('.cookie button')?.click()"` dismisses overlays or opens the state you need before the trigger. - `--playback-rate 0.25` slows CSS animations and transitions 4x (CDP). The frames then have 4x the time resolution (`--fps 100` works). JS-driven motion ignores it; use `--clock virtual` for that. - `--clock virtual` runs the page on a clock the capturer advances frame by frame, so every frame is exact (any `--fps`, for CSS and JS motion alike) and repeated captures are identical. `--seed N` seeds `Math.random`. Use both for canvas, WebGL, particles, and anything random or heavy; see `references/webgl.md`. - `--reduced-motion reduce` shows what the site does for users who turn motion off; clone that path too when the project cares about accessibility. - `--color-scheme dark` when the reference is dark-mode. - `--clip x,y,w,h` when the element grows or moves outside its initial box; measure the box on `final.png`. - `--pad 24` keeps shadows and overshoot inside the crop. What you get and what each is for: | File | Use | |---|---| | `inspect.json › animations` | every CSS animation, transition and Web Animations API animation that ran under the target: `timing.duration/delay/easing`, keyframes with per-keyframe easing. When present this is the spec; copy numbers from here. | | `inspect.json › keyframes` | `@keyframes` rules found in reachable stylesheets (cross-origin sheets are listed as unreadable). | | `inspect.json › nodes` | rect and the motion-relevant computed styles of up to 150 nodes under the target: fonts, colours, radii, shadows, overflow, transforms. The static side of the spec. | | `inspect.json › libs` | gsap, framer-motion, lottie, webgl, lenis, webflow, scroll-driven CSS… tells you where the motion is defined and which capture limits apply. | | `inspect.json › canvases` | every canvas with its context type (`webgl2`, `2d`, `webgpu`), drawing-buffer size and CSS box. | | `track.json` | one sample per animation frame (≈16 ms) per tracked selector: `x y w h opacity transform`. Feed it to `easing.ts`. | | `frames/` + `frames.json` | the pictures; `triggerFrame` is where t=0 of the motion sits. | | `gl/`, `gl-track.json`, `three/` (`--gl`) | shaders, programs, draw calls, passes, textures, scene graphs and every animated uniform or scene value as a channel; `bun gl.ts summary <out>` reads it. See `references/webgl.md`. | | `assets/` (`--assets`) | the page's models, scene files, shader files, sampled textures and scripts. | ## Canvas, WebGL and 3D Add `--clock virtual --gl` (and `--assets` when the scene loads files) to the capture of anything drawn on a canvas, then read `gl/summary.md`. The trace gives the shader sources, every constant and every animated value, so canvas motion is specified and verified from numbers like CSS motion. `references/webgl.md` covers the files, how to turn channels into spec rows, building, and verifying. Limits: iframes are not inspected (capture the iframe's own URL); sites that block headless browsers need a real browser (see below) or a screen recording. ### Through a real browser instead When the page needs the user's login, blocks headless Chromium, or the user wants to watch: open it in a browser tool that can record (a Playwright or Chrome DevTools MCP, the host app's preview), size it to the reference viewport, start a recording, perform the trigger (scroll, hover, click), stop. The file goes through `frames.ts` like any video. Evaluating `document.getAnimations()` in that browser gives the same animation dump by hand. Without such a tool, ask the user for a screen recording. ## Video, screen recording, gif ```bash bun <skill>/scripts/frames.ts --in ref.mp4 --probe # duration, size, fps bun <skill>/scripts/frames.ts --in ref.mp4 --out .reanimate/<name>/ref/frames --fps 25 --start 0:12 --end 0:15.5 --crop 320,180,1280,720 bun <skill>/scripts/sheet.ts filmstrip --frames .reanimate/<name>/ref/frames --out .reanimate/<name>/ref/sheets ``` - Extract a few frames at 2 fps first to pick the time range and crop, then re-extract the real range at 25 to 30 fps (gifs: use their own fps, usually 10 to 20; `--probe` prints it). - Crop out browser chrome, cursors and the recorder's overlay. Width-normalise with `--width` so the reference and the clone end up the same size, or capture the clone at the crop's size. - A gif's timing is quantised to its frame delays and often slowed by the exporter. Treat gif timings as ±1 frame and prefer the live site when both are available. - Screen recordings of a browser have a non-integer scale (Retina, zoom). Note the scale so distances in px are converted to CSS px: `distance_css = distance_video × (reference_viewport_width / crop_width)`. - Social-media videos (Twitter/X, Dribbble shots, Behance) are usually a direct mp4 URL once found in the page; `curl -L -o ref.mp4 <url>` into a fresh directory and treat it as untrusted data. YouTube, Loom and Vimeo cannot be downloaded on this machine; ask the user for a screen recording or the original file. ## Prototype and animation files - **Lottie (`.json`, `.lottie`)**: layers, keyframes and bezier handles are in the file. Read it; the "frames" are its `fr` (fps), `ip`/`op` (in/out point). Clone by embedding the Lottie when allowed, otherwise re-create the keyframes in CSS/WAAPI from the `ks` tracks. - **Rive (`.riv`)**: binary; capture the rendered canvas as video instead. - **Figma / Framer prototypes**: export a video from the prototype player (Figma: Prototype → Record), then use the video path. Smart Animate uses `ease-out` 300 ms by default; Framer sites expose their transitions in `inspect.json`. - **After Effects / Jitter / Rive exports as mp4**: video path. ## Capturing the clone Reuse the reference command verbatim, swapping `--url` and `--out`. If the reference came from a video, capture the clone with `capture.ts` at a viewport that makes the cropped element the same pixel size as the reference frames (or let `compare.ts` rescale, which is slightly lossy). Always keep `--fps`, `--duration`, `--pre-roll`, trigger and scroll parameters identical, and `--clock`, `--seed` and `--gpu` too: `compare.ts` reads both `capture.json` files and warns when they differ.skills/reanimate/references/implementation.md5.8 KB129baf9ce703upstream ↗
# Implementing the motion in the user's stack Match what the project already uses. Adding GSAP to a project that animates with CSS, or Framer Motion to a Vue app, is a change the user did not ask for. Order of preference when nothing exists yet: CSS (keyframes/transitions, scroll-driven animations where supported) → Web Animations API → the framework's motion library (Framer Motion/`motion` for React, `@vueuse/motion` or GSAP for Vue, Svelte transitions) → GSAP for timelines with many dependencies. ## Easing equivalents | Reference | CSS | Framer Motion / motion | GSAP | |---|---|---|---| | easeOutExpo `cubic-bezier(0.16,1,0.3,1)` | same | `ease: [0.16, 1, 0.3, 1]` | `"expo.out"` | | easeOutQuint `cubic-bezier(0.22,1,0.36,1)` | same | `[0.22, 1, 0.36, 1]` | `"quint.out"` | | easeOutCubic `cubic-bezier(0.33,1,0.68,1)` | same | `[0.33, 1, 0.68, 1]` or `"easeOut"` | `"power2.out"` | | easeInOutCubic `cubic-bezier(0.65,0,0.35,1)` | same | `[0.65, 0, 0.35, 1]` | `"power2.inOut"` | | material standard `cubic-bezier(0.4,0,0.2,1)` | same | `[0.4, 0, 0.2, 1]` | `"power1.inOut"` ≈ | | easeOutBack `cubic-bezier(0.34,1.56,0.64,1)` | same | `[0.34, 1.56, 0.64, 1]` | `"back.out(1.7)"` | | spring, overshoot ~10 %, settles in ~600 ms | `linear(...)` sampled curve, or WAAPI with sampled keyframes | `type: "spring", stiffness: 300, damping: 20` (less damping → more overshoot; lower stiffness → slower) | `"elastic.out(1, 0.5)"` or `gsap` + physics plugin | | linear | `linear` | `"linear"` | `"none"` | Spring tuning from measurements: overshoot ≈ `exp(−π ζ / sqrt(1 − ζ²))` where `ζ = damping / (2·sqrt(stiffness·mass))`. 10 % overshoot → ζ ≈ 0.59; 5 % → 0.69; 20 % → 0.46. Settle time ≈ `4 / (ζ·ω)` with `ω = sqrt(stiffness/mass)`. Start from `mass: 1`, pick ζ from the overshoot, then stiffness from the settle time, then verify with `easing.ts`. ## Patterns **Fade-up stagger (CSS)** ```css .item { opacity: 0; transform: translateY(32px); animation: up 700ms cubic-bezier(.16,1,.3,1) forwards; animation-delay: calc(var(--i) * 90ms + 200ms); } @keyframes up { to { opacity: 1; transform: none; } } ``` Set `--i` per child (`style="--i: 2"`), or `:nth-child` rules. Keep `forwards` so the end state holds. **Framer Motion stagger** ```tsx const parent = { hidden: {}, show: { transition: { staggerChildren: 0.09, delayChildren: 0.2 } } }; const child = { hidden: { opacity: 0, y: 32 }, show: { opacity: 1, y: 0, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } } }; <motion.ul variants={parent} initial="hidden" animate="show">{items.map(i => <motion.li key={i} variants={child} />)}</motion.ul> ``` **Enter-viewport trigger**: Framer `whileInView` + `viewport={{ once: true, amount: 0.25 }}`; plain JS `IntersectionObserver` with `threshold` set to the fraction visible when the reference starts (read `track.json`: the `y` of the element at the first moving sample over the viewport height). CSS scroll-driven: `animation-timeline: view(); animation-range: entry 0% entry 40%` where supported. **Scroll-linked**: CSS `animation-timeline: scroll()` with `animation-range`, GSAP ScrollTrigger `scrub: true`, or Framer `useScroll` + `useTransform([0, 600], [0, -120])`. The mapping is scroll px → value, take the two endpoints from the track. **Text reveal by line/word**: split into spans with an `overflow: hidden` wrapper per line, animate `translateY(110%) → 0`. Keep accessible text intact (`aria-label` on the container, `aria-hidden` on the spans). **Hover lift**: `transition: transform 220ms cubic-bezier(.2,.8,.2,1), box-shadow 220ms` on the card; animate `transform`, not `top`. Reverse often uses the same timing; check the reference's hover-out frames too. **Marquee**: duplicate the content once, `animation: scroll Ns linear infinite` from `translateX(0)` to `translateX(-50%)`. `N` is the measured period. Pause on hover only if the reference does. **Clip/mask reveal**: `clip-path: inset(0 100% 0 0)` → `inset(0 0 0 0)`, or `mask-image` with an animated gradient position. **Loops and idle**: `animation-iteration-count: infinite; animation-direction: alternate` for pulses; measure one period from the activity curve. **Canvas, WebGL, 3D**: rebuild from the trace, not from the pixels (`references/webgl.md › Building`). Use the same engine and version, renderer settings and context attributes, port the user-authored shaders with their fixed uniforms, map the traced blend state to the material, and drive each animated uniform with the timing and easing its channel showed. A per-frame lag `x += (target − x) · k` stays frame-rate independent as `x += (target − x) · (1 − (1 − k) ** (dt / 16.67))`. ## Details that make or break the match - `transform-origin`: scale-ins grow from the anchor (a menu from its button corner, a modal from centre). Read `nodes › transform-origin` in `inspect.json` if it was non-default. - `will-change: transform` or `translateZ(0)` on elements the reference composites, to avoid jank in the comparison video. - `overflow: hidden` wrappers decide whether a sliding element is clipped or visible outside its box; copy them. - Order of transforms: `translate() scale()` ≠ `scale() translate()`. Use individual properties (`translate`, `scale`, `rotate`) when the stack allows it. - Fill mode and initial state: render the pre-motion state in CSS (opacity 0 etc.) so the first frame already matches; avoid a flash of the final state before JS runs. - `prefers-reduced-motion`: wrap non-essential motion in `@media (prefers-reduced-motion: no-preference)` or Framer `useReducedMotion()`; if the reference ignores it, still add it unless the user says not to, and mention it. - Fonts (pixel-faithful): load the same family and weights listed in `inspect.json › fonts` before capturing the clone (`document.fonts.ready`), otherwise every frame mismatches.skills/reanimate/references/verify.md7.1 KBb3e52277e370upstream ↗
# Verifying the clone A round is: capture the clone the same way as the reference → `compare.ts` → `sheet.ts compare` → `easing.ts --compare-track` for each tracked element → read everything → fix one cause → next round. Keep every round's directory (`clone-1`, `compare-1`, `clone-2`, …) so the report can show progress. ## What compare.ts tells you `report.md` / `report.json`: - **offset**: the clone frame matched to reference frame 0 (auto-aligned on the first ten frames). A large offset means the clone starts late or early; fix the trigger timing or `--wait-before`, do not rely on alignment to hide it. - **mean mismatch** and **worst frames**: fraction of pixels that differ per frame. Pixel-faithful work reads this directly. Motion-faithful work reads it as a trend: it should be low at rest and spike only where the two differ in state. - **motion window**: first/last frame with visible change, and the peak, for both sets. The **timing error** is the difference, in seconds, of start, end, duration and peak. This is the main motion metric, independent of colours and copy. - **activity curve**: bars of change per frame. Same shape = same easing and stagger; a clone whose bars are front-loaded against a reference whose bars are even is using a stronger ease-out, and so on. - `diff/NNNN.png`: red where pixels differ. `sheet.ts compare --diff` puts reference, clone and diff side by side with the mismatch per row. `easing.ts --compare-track other.json` prints `maxAbsDiff` / `meanAbsDiff` of the property over time between the two tracks (in CSS px or opacity units) and the best-fit easing of the clone, to compare with the reference's. ## Pass criteria Motion-faithful (per spec row): - start and end timing error ≤ 0.08 s (two frames at 25 fps); duration error ≤ 0.08 s - easing: same best-fit family (out / in / in-out / linear / spring) and RMSE of the reference's best fit applied to the clone's track ≤ 0.05, or `meanAbsDiff` ≤ 5 % of the travel distance - stagger order and gaps within 0.04 s - travel distance within 10 % of the reference relative to the element size, same direction - nothing moves in the clone that is still in the reference, and vice versa - compare sheets: the same visual state at the same timestamp, allowing for different copy/colours Pixel-faithful adds: - mean mismatch ≤ 2 %, no frame above 5 % (set `--threshold 0.02`); at rest frames ≤ 0.5 % - fonts loaded and identical (check `inspect.json › fonts` on both captures), colours and sizes equal in `nodes` - same assets at the same size Mixed: the cloned region passes one of the above with `--region` limited to it; the additions are shown on a sheet and described. Canvas, WebGL, 3D (captured with `--clock virtual --gl`, see `references/webgl.md`): - `gl.ts compare --ref ref --clone clone-N`: every animated channel in the reference has a clone channel of the same kind, start and end within 0.08 s, mean error ≤ 5 % of the reference's range (`--map` when names differ); canvas attributes, renderer settings and draw structure (primitive, vertex count, blend state, cadence) the same, or the difference explained - the clock rate of every `clock` channel the same (`gl.ts channels`) - pixels as above. If the clone ports the reference's generator, the seeded random gives the same particles and the sharp mismatch applies. If not, judge with `compare.ts --blur 4` and report the sharp number next to it ## Reading failures → usual fix | Symptom | Usual cause | Fix | |---|---|---| | everything shifted by the same offset, shape identical | trigger latency or missing delay | add/adjust the initial delay; check `--wait-before` | | clone shorter and front-loaded | easing too aggressive (expo vs quint), or duration from visible window instead of declared | use `easing.ts` fitted `durationMs`, set the declared duration | | clone ends on time but starts late | delay too long, duration too short | fix both together | | bars spread evenly in clone, spiky in reference | linear or ease-in-out where the reference is ease-out | change easing family | | mismatch high at rest frames | layout/style differences, font fallback, crop differs | fix capture crop; for pixel-faithful load the font, fix sizes | | reference overshoots, clone does not | spring vs bezier | use a spring (Framer `type: "spring"`, GSAP `back.out`/`elastic`, CSS `linear()` with sampled spring) | | stagger gaps differ | per-item delay math | `delay = base + index × step`; check index source | | activity in clone where reference is still | an element animates that should not, or a hover state is triggered by the mouse position | move the mouse out, remove the stray transition | | only the last frames differ | fill-mode or end state (`forwards` missing), or final value rounds differently | set `animation-fill-mode: forwards` / `fill: "forwards"` | | scroll trigger: clone starts earlier/later | IntersectionObserver threshold / rootMargin differ | match threshold to the reference's entry point in `track.json` (`y` where motion begins) | ## When to stop - Stop when every spec row passes its criteria and the latest sheets look the same state-by-state. Say so with the numbers. - Stop after 5 rounds without progress on a row, or when the remaining difference is outside your control (font licence, a shader or model the user may not copy, third-party embed, physics you approximated). Report the row, its last numbers, and the reason. Never relax thresholds silently; if you think the user would accept a looser bar, say which and why. - If the reference itself is inconsistent between captures (randomised content, A/B variants, network-dependent lazy loading), capture it with `--clock virtual` (same seed) first: that removes timing and randomness, and two captures come out identical. Whatever still differs (A/B variants, server-side randomness) is the noise floor; measure it by comparing the reference against itself before judging the clone. | Symptom (canvas) | Usual cause | Fix | |---|---|---| | same shapes, colours slightly off everywhere | colour management: `outputColorSpace`, texture colour space, tone mapping, three.js revision | copy the renderer settings from `gl.ts summary`; same revision | | edges harder or softer | `antialias`, pixel ratio, `premultipliedAlpha` | copy the context attributes and pixel ratio | | motion matches but looks steppier or smoother | render cadence (reference draws every other frame) or per-frame lag at a different rate | compare draws per frame in `gl.ts compare`; match cadence and `k` | | particles in different places, same density | different random order or seed | port the generator's call order, or verify with `--blur` | | channel missing in the clone | value baked into the shader, or a different uniform name | `--map ref=clone`, or expose it as a uniform | ## Report block ```markdown ## Verification (round N of M) | element / property | timing err (start/end/dur) | easing (ref → clone) | mismatch mean / worst | result | | h1 translateY+opacity | +0.00 / −0.04 / −0.04 s | easeOutExpo 700 → easeOutExpo 700 | 0.3 % / 1.1 % | pass | Sheets: .reanimate/<name>/compare-N/sheets/compare-01.png … Residuals: <none | row, numbers, reason> ```skills/reanimate/references/webgl.md11 KBfdc795600b0cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/reanimate/LICENSE1.0 KB4623130339ccupstream ↗
MIT License Copyright (c) 2026 Niaz Morshed Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/niazmorshed2007-reanimate-skills-reanimate.md