Skip to content

Text to motion graphics for Claude Code and Codex: write a brief, get a checked MP4. 30 art forms from claymation and paper cut-out to anime and pixel art, 2D explainers, Shorts, 3D products. Installs brief2motion for websites. MIT.

feat: 0.3.0 release candidate: setup for agents, Windows, 3D pack, formats, docs

Varun Pratap Bhardwajf40e36d4f4dd
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 8e81772..e2ace48 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -11,13 +11,27 @@
{
"name": "brief2mp4",
"source": "./plugin",
- "description": "Turn a written brief into a finished, checked MP4 motion graphic with HyperFrames, Three.js, Blender and ffmpeg.",
- "version": "0.2.0",
- "author": { "name": "Varun Pratap Bhardwaj" },
+ "description": "Turn a written brief into a finished, checked MP4 motion graphic: HyperFrames, Three.js, an optional 3D pack (CAD, materials, physics), Blender and ffmpeg. macOS, Windows, Linux.",
+ "version": "0.3.0",
+ "author": {
+ "name": "Varun Pratap Bhardwaj"
+ },
"homepage": "https://github.com/qualixar/brief2mp4",
"repository": "https://github.com/qualixar/brief2mp4",
"license": "MIT",
- "keywords": ["video", "motion-graphics", "hyperframes", "threejs", "blender", "ffmpeg", "skill"],
+ "keywords": [
+ "video",
+ "motion-graphics",
+ "hyperframes",
+ "threejs",
+ "blender",
+ "ffmpeg",
+ "3d",
+ "physics",
+ "agent-skills",
+ "text-to-video",
+ "skill"
+ ],
"category": "productivity"
}
]
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..9cf1745
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,9 @@
+* text=auto
+*.sh text eol=lf
+*.py text eol=lf
+*.js text eol=lf
+*.ps1 text eol=crlf
+*.png binary
+*.webp binary
+*.jpg binary
+*.glb binary
diff --git a/.github/ISSUE_TEMPLATE/brief-result.yml b/.github/ISSUE_TEMPLATE/brief-result.yml
new file mode 100644
index 0000000..aacce65
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/brief-result.yml
@@ -0,0 +1,26 @@
+name: Brief result
+description: The skill made a video that misses the brief
+labels: ["brief-result"]
+body:
+ - type: textarea
+ id: brief
+ attributes: { label: The brief, description: Paste it exactly as you sent it., render: markdown }
+ validations: { required: true }
+ - type: textarea
+ id: miss
+ attributes: { label: What was wrong, description: Which line of the brief was missed, and at what time in the video. }
+ validations: { required: true }
+ - type: input
+ id: app
+ attributes: { label: App and model, placeholder: "Claude Code, Opus / Codex, GPT" }
+ validations: { required: true }
+ - type: dropdown
+ id: os
+ attributes: { label: OS, options: [macOS, Windows, Linux, WSL] }
+ validations: { required: true }
+ - type: textarea
+ id: doctor
+ attributes: { label: Doctor output, description: "bash plugin/skills/brief2mp4/scripts/doctor.sh", render: text }
+ - type: textarea
+ id: report
+ attributes: { label: REPORT.md, description: The report the skill wrote, if any., render: markdown }
diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 0000000..a96fe5a
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,18 @@
+name: Bug
+description: A script, installer or the 3D pack fails
+labels: ["bug"]
+body:
+ - type: textarea
+ id: what
+ attributes: { label: What happened, description: The command you ran and the full error output., render: text }
+ validations: { required: true }
+ - type: dropdown
+ id: os
+ attributes: { label: OS, options: [macOS, Windows, Linux, WSL] }
+ validations: { required: true }
+ - type: input
+ id: version
+ attributes: { label: brief2mp4 version, placeholder: "cat VERSION" }
+ - type: textarea
+ id: doctor
+ attributes: { label: Doctor output, render: text }
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..7668207
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: true
+contact_links:
+ - name: Free guide (every brief and setting from the video)
+ url: https://qualixar.com/learn/guides/brief2mp4-guide
+ about: Read this before asking how to write a brief.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..f0c17e6
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,11 @@
+## What this changes
+
+## How I tested it
+- [ ] `bash tests/run_tests.sh` passes
+- [ ] `bash tests/run_tests.sh --slow` passes (if renders or the 3D pack changed)
+- [ ] OS tested on:
+
+## Checklist
+- [ ] SKILL.md and references updated if behaviour changed
+- [ ] CHANGELOG.md updated under an "Unreleased" heading
+- [ ] No personal paths, tokens or private names
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..3d0a467
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,59 @@
+name: test
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ install-and-test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ env:
+ CLAUDE_CONFIG_DIR: ${{ github.workspace }}/.tmp/claude
+ CODEX_HOME: ${{ github.workspace }}/.tmp/codex
+ B2M3D_HOME: ${{ github.workspace }}/.tmp/b2m3d
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ - uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ - name: Install ffmpeg
+ run: |
+ case "$RUNNER_OS" in
+ Linux) sudo apt-get update -q && sudo apt-get install -y -q ffmpeg ;;
+ macOS) brew install ffmpeg ;;
+ Windows) choco install ffmpeg -y --no-progress ;;
+ esac
+ ffmpeg -version | head -1
+
+ - name: Install the skill and the 3D pack (bash)
+ if: runner.os != 'Windows'
+ run: bash install.sh --with-3d=core,dev
+
+ - name: Install the skill and the 3D pack (PowerShell)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: ./install.ps1 -With3D core,dev
+
+ - name: Doctor
+ run: bash plugin/skills/brief2mp4/scripts/doctor.sh
+
+ - name: Detect 3D pack
+ run: bash plugin/skills/brief2mp4/scripts/detect_3d.sh
+
+ - name: Fast tests
+ run: bash tests/run_tests.sh
diff --git a/.gitignore b/.gitignore
index c9da8d3..e507f97 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,18 @@
-.DS_Store
-*.mp4
+*.egg-info/
*.mov
+*.mp4
+*.pyc
*.wav
-frames/
+.DS_Store
+.pytest_cache/
+.tmp/
+.venv/
+__pycache__/
checks/
-renders/
+frames/
node_modules/
-__pycache__/
-*.pyc
+renders/
+.tmp/
+venv/
+.venv/
+.pytest_cache/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..cb35d6a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,13 @@
+# AGENTS.md
+
+This repository is the brief2mp4 skill for Claude Code and Codex: a written video brief goes in, a checked `final.mp4` comes out.
+
+If the user asked you to install or set up brief2mp4, follow [SETUP.md](SETUP.md) step by step. It detects the operating system (macOS, Windows, Linux), installs what is missing with the user's permission, installs the skill, runs the doctor and does a two-minute first render.
+
+If the user asked you to make a video, the skill itself is in [plugin/skills/brief2mp4/SKILL.md](plugin/skills/brief2mp4/SKILL.md). Read it and follow it.
+
+If you are changing this repository:
+
+- Run `bash tests/run_tests.sh` before you finish (add `--slow` for the render tests).
+- Keep the skill self-contained: no personal paths, no network calls at render time, every script works from any folder.
+- The 3D pack (`plugin/skills/brief2mp4/3d/`) is optional. The skill must keep working when it is not installed.
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..8a42f2a
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,50 @@
+# Changelog
+
+All notable changes to brief2mp4. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
+
+## [0.3.0] - 2026-11-15
+
+### Added
+- **Optional 3D pack** (`plugin/skills/brief2mp4/3d/`): CAD and mesh models to GLB, material presets, deterministic Jolt physics bakes, shot JSON to a frame-seekable HyperFrames project, and a Blender hero-render route. Installs per component (`core`, `cad`, `blender`) with `install.sh --with-3d` or `install.ps1 -With3D`. The skill detects it and falls back to the Three.js template when it is missing.
+- **SETUP.md**: step-by-step instructions an agent follows to set up a machine on macOS, Windows or Linux, ending with a two-minute first render.
+- **Windows support**: `install.ps1` (PowerShell 5.1 and 7, optional winget install of Node, ffmpeg and Git), Git Bash guidance in the skill.
+- `scripts/doctor.sh` (with `--json`): checks every tool and prints the install command for this OS. `scripts/detect_3d.sh`. `scripts/bounds.py`: measures where content sits in a still and checks margins and safe zones, standard library only. `scripts/vendor_libs.sh`: pinned GSAP, three.js and fonts copied into a project. `sound_bed.sh --ticks` for click accents.
+- `references/formats.md`: beat sheets, tool routes and checks for 2D explainers, maths and algorithms, tutorial intros, stories and skits, vertical Shorts and Reels (with safe zones), data stories, product launches, logo stings, kinetic type and captions.
+- Examples 05 (a 20 s 2D explainer) and 06 (a 15 s vertical Short), each with a sample report from a real run.
+- `references/pipelines.md`: architecture diagram, route per beat, recipes for mixed pipelines.
+- `references/ecosystem.md`: 45+ open-source motion, 3D, capture and agent-skill repos with licences, when each beats the default, and how to bring its output in frame-exact.
+- Example 04: a 3D product brief (parts drop and settle, exploded view, title).
+- `docs/`: getting started (per OS, with a flow diagram), architecture (the loop, routing, determinism, the 3D pack) and a 3D walkthrough of example 04.
+- Tests (`tests/`, 46 including render tests) and CI on macOS, Ubuntu and Windows.
+- `AGENTS.md` and `CLAUDE.md` so an agent opened in a clone knows what to do; CONTRIBUTING, SECURITY, code of conduct, issue and PR templates.
+
+### Fixed (from an independent pre-release audit)
+- Windows: a `.gitattributes` keeps bash scripts on LF line endings, so they run under Git Bash after a Windows checkout.
+- The 3D pack installs its own copy into `~/.brief2mp4/3d/pack`, so moving or deleting the clone or plugin cache no longer breaks it; `detect_3d` now checks that the pack actually imports, and understands the Windows venv layout.
+- The 3D pack needs Python 3.12 or 3.13 (its pinned numpy and scipy do); docs and checks no longer claim 3.11. `B2M3D_PYTHON` picks a specific interpreter (for example from `uv` on Debian 12).
+- `install_3d.ps1 -Components core,cad` works when typed in a PowerShell window as well as with `-File`.
+- Text files in the 3D pack are read and written as UTF-8, so accented titles survive on Windows.
+- The Three.js template loads GSAP and three.js from `vendor/` (new `scripts/vendor_libs.sh`), so renders never touch the network.
+- `finish.sh` handles a silent soundtrack shorter than the video; `check_delivery.sh` no longer reports a dark designed background as black.
+- Uninstall: `install.sh --uninstall --uninstall-3d` (or `install.ps1 -Uninstall -Uninstall3D`, `install_3d.sh --uninstall`) removes the 3D pack, only if the installer created it. On Windows a junctioned skill folder is unlinked, never emptied.
+- Vertical safe zones in the formats guide and example 06 are now conservative (top 288, bottom 672, left 64, right 192 px at 1080x1920).
+- `references/formats.md`: MathJax (SVG) vs KaTeX (HTML), Manim's LaTeX requirement, word timing with `hyperframes transcribe`, and holds vs loops for Shorts.
+
+### Changed
+- `finish.sh` now normalises loudness in two passes behind a soft limiter. Single-pass normalisation undershot on short clips with sharp hits (example 04 measured -16.0 LUFS against -14; it now measures -14.2).
+- `install.sh` runs the doctor instead of its own checks, and accepts `--with-3d[=components]`.
+- SKILL.md: doctor first, OS notes, 3D routing, links to the new references.
+
+## [0.2.0] - 2026-11-14
+
+### Added
+- Claude Code and Codex plugin manifests and a marketplace entry; logo; README with the contest video and showcase.
+
+## [0.1.0] - 2026-11-14
+
+### Added
+- First release: the spec, build, self-check, fix, deliver loop; HyperFrames, Three.js and Blender references; `finish.sh`, `check_delivery.sh`, `contact_sheet.sh`, `sound_bed.sh`; three example briefs and a sample report.
+
+[0.3.0]: https://github.com/qualixar/brief2mp4/releases/tag/v0.3.0
+[0.2.0]: https://github.com/qualixar/brief2mp4/compare/4b17df4...fda69b5
+[0.1.0]: https://github.com/qualixar/brief2mp4/commit/4b17df4
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..63be4eb
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,3 @@
+# CLAUDE.md
+
+Read [AGENTS.md](AGENTS.md). It applies to Claude Code too: set up with [SETUP.md](SETUP.md), make videos with [plugin/skills/brief2mp4/SKILL.md](plugin/skills/brief2mp4/SKILL.md).
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..dca8a46
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,5 @@
+# Code of conduct
+
+This project follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). In short: be respectful, assume good faith, critique work rather than people, and keep discussion on the project.
+
+Report unacceptable behaviour privately through the repository owner's GitHub profile. Reports are handled confidentially.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..846bc3e
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,33 @@
+# Contributing to brief2mp4
+
+Thanks for helping. The most useful contributions are, in order: a brief that the skill got wrong (with the brief and what came out), a fix to a script or reference that makes the self-check catch more, and new example briefs with a passing report.
+
+## Report a bad result
+
+Open an issue with the **Brief result** template. Include the brief exactly as you sent it, your OS, the app and model (Claude Code or Codex), the doctor output (`bash plugin/skills/brief2mp4/scripts/doctor.sh`) and the `REPORT.md` the skill wrote. A still from `contact_sheet.sh` showing the miss helps most.
+
+## Change the code
+
+1. Fork, then branch from `main`.
+2. Make the change. Keep files under 800 lines and scripts working from any folder.
+3. Run the tests:
+ ```bash
+ bash tests/run_tests.sh # fast checks
+ bash tests/run_tests.sh --slow # also renders, needs Node 22+, ffmpeg and the 3D pack
+ ```
+4. If you changed the skill's behaviour, update `SKILL.md`, the matching reference and `CHANGELOG.md` under an "Unreleased" heading at the top (add it if it is not there).
+5. Open a pull request using the template.
+
+## Rules for the skill itself
+
+- **Determinism.** Every frame is a pure function of time. No wall clock, unseeded randomness or network at render time.
+- **Optional stays optional.** The skill must work with only Node and ffmpeg. Blender and the 3D pack are detected, never assumed.
+- **Cross-platform.** Scripts are bash and must run in macOS bash 3.2, Linux bash and Git Bash on Windows. Installers have a PowerShell twin.
+- **Licences.** Only add dependencies under MIT, Apache-2.0, BSD, Zlib or similar. GPL tools may be used as external programs (like Blender), never bundled.
+- **No personal data.** No absolute paths from your machine, tokens or private names in commits.
+
+## Example briefs
+
+A new example goes in `examples/NN-name/BRIEF.md`, in the format the README describes, with a "Done when" list. Add `SAMPLE-REPORT.md` from a real run if you can.
+
+By contributing you agree that your work is released under the MIT licence of this repository.
diff --git a/README.md b/README.md
index d9be047..c643d05 100644
--- a/README.md
+++ b/README.md
@@ -2,117 +2,177 @@
<img src="assets/banner.png" alt="brief2mp4: write a brief, get a checked MP4" width="100%">
</p>
+<h1 align="center">brief2mp4</h1>
+
+<p align="center"><b>Text to motion graphics for Claude Code and Codex. Write a video brief, get a finished MP4 that has been checked against every line of it.</b><br>2D explainers · maths animations · tutorials · Shorts and Reels · data stories · product launches · logo stings · kinetic type · 3D products</p>
+
<p align="center">
+ <a href="https://github.com/qualixar/brief2mp4/releases"><img alt="Release" src="https://img.shields.io/github/v/release/qualixar/brief2mp4?color=FF5A1F"></a>
+ <a href="https://github.com/qualixar/brief2mp4/actions/workflows/test.yml"><img alt="Tests" src="https://github.com/qualixar/brief2mp4/actions/workflows/test.yml/badge.svg"></a>
<a href="LICENSE"><img alt="MIT licence" src="https://img.shields.io/badge/licence-MIT-16130F"></a>
+ <img alt="macOS, Windows, Linux" src="https://img.shields.io/badge/macOS%20%7C%20Windows%20%7C%20Linux-supported-16130F">
<img alt="Claude Code plugin" src="https://img.shields.io/badge/Claude%20Code-plugin-FF5A1F">
<img alt="Codex plugin" src="https://img.shields.io/badge/Codex-plugin-FF5A1F">
- <img alt="Version 0.2.0" src="https://img.shields.io/badge/version-0.2.0-16130F">
</p>
-**brief2mp4 is a free skill for Claude Code and Codex. You paste a written video brief; the agent builds the video, renders it, measures the file, checks every line of your brief against real frames, fixes what fails, and hands you `final.mp4` with a report.**
+<p align="center">
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#what-it-makes">What it makes</a> ·
+ <a href="#how-it-works">How it works</a> ·
+ <a href="#the-3d-pack">3D pack</a> ·
+ <a href="#examples">Examples</a> ·
+ <a href="#write-a-brief">Write a brief</a> ·
+ <a href="docs/README.md">Docs</a> ·
+ <a href="#faq">FAQ</a>
+</p>
-It covers kinetic type and 2D motion (HyperFrames), stylised 3D (Three.js) and realistic product shots (Blender), and finishes every file with ffmpeg. Everything runs on your own machine.
+brief2mp4 is a free, MIT-licensed agent skill. You paste a written brief (length, size, exact words, what happens when). The agent writes a spec with a checkable "done when" list, routes each beat to the right tool (HyperFrames for type and 2D motion, Three.js for stylised 3D, an optional 3D pack for CAD models, materials and physics, Blender for photoreal shots), renders, finishes the file with ffmpeg, measures it, looks at real frames, fixes what misses and hands you `final.mp4` with a `REPORT.md` that shows the evidence for every line. Everything runs on your own machine.
<p align="center">
<a href="https://youtu.be/l9mEZQon6JM"><img src="assets/video-thumbnail.jpg" alt="Watch the video: Fable 5.2 vs Opus 5.5 vs GPT-6.1, who makes better motion graphics?" width="720"></a>
</p>
<p align="center">
- <b><a href="https://youtu.be/l9mEZQon6JM">▶ Watch the video</a></b> &nbsp;·&nbsp; <b><a href="https://drive.google.com/drive/folders/1yBmCb2h63Fp5yr_37LY46f8BSRa_3GiO?usp=sharing">All 11 contest films, untouched (Google Drive)</a></b> &nbsp;·&nbsp; <b><a href="https://qualixar.com/learn/guides/brief2mp4-guide">Free 13-page guide (PDF)</a></b>
+ <b><a href="https://youtu.be/l9mEZQon6JM">▶ Watch the video</a></b> &nbsp;·&nbsp; <b><a href="https://drive.google.com/drive/folders/1yBmCb2h63Fp5yr_37LY46f8BSRa_3GiO?usp=sharing">All 11 contest films, untouched</a></b> &nbsp;·&nbsp; <b><a href="https://qualixar.com/learn/guides/brief2mp4-guide">Free 13-page guide</a></b>
</p>
-## What Claude Code can make from a written brief
+## Quick start
-<p align="center">
- <img src="assets/r4-fable-four-worlds.webp" alt="Fable 5.2, Round 4: one camera move through a desert, an underwater city, neon rain and space" width="800">
-</p>
+**Fastest: let your agent set everything up.** Open Claude Code or Codex in any folder and send:
-Round 4 of the video: Fable 5.2 in Claude Code got a written brief for a 60-second film, one continuous camera move through four worlds with its own music, and delivered this. Excerpts above; the [full film and the other entries are on Google Drive](https://drive.google.com/drive/folders/1yBmCb2h63Fp5yr_37LY46f8BSRa_3GiO?usp=sharing), untouched, with checksums.
+> Set up brief2mp4 from https://github.com/qualixar/brief2mp4 by following its SETUP.md.
-That was a sealed contest run, made without this skill. brief2mp4 packages the same loop the brief demands (spec, build, measure, check every line, fix) so you can run it on your own briefs. The [guide](https://qualixar.com/learn/guides/brief2mp4-guide) has every brief, setting and result from the video.
+The agent detects your OS, asks before installing Node, ffmpeg (and Git Bash on Windows), installs the skill, runs the doctor and makes a 12-second test video so you know it works. [SETUP.md](SETUP.md) is the exact script it follows.
-**Proof the skill itself works:** example brief 01, pasted as written, came back as a 12.000 s, 1920x1080, 30 fps file that passed the delivery check. Its [report](examples/01-kinetic-type/SAMPLE-REPORT.md) lists every requirement with its evidence: which still shows which line, the measured headline height (126 px against a 120 px minimum), the text bounds and the loudness at each sound accent.
+**Or install it yourself:**
-## Install
+| You use | Run |
+|---|---|
+| Claude Code (plugin) | `/plugin marketplace add qualixar/brief2mp4` then `/plugin install brief2mp4@brief2mp4` |
+| Codex (plugin) | `codex plugin marketplace add qualixar/brief2mp4` then `codex plugin add brief2mp4@brief2mp4` |
+| macOS / Linux / WSL (both apps) | `git clone https://github.com/qualixar/brief2mp4.git && bash brief2mp4/install.sh` |
+| Windows PowerShell (both apps) | `git clone https://github.com/qualixar/brief2mp4.git; powershell -ExecutionPolicy Bypass -File .\brief2mp4\install.ps1 -InstallTools` |
-There are two ways in each app. Pick one per app; installing both ways gives you two copies of the same skill.
+Add the 3D pack with `--with-3d` (macOS/Linux) or `-With3D core` (Windows). Plugins install the skill only, so on a fresh machine also install the tools below. Start a new session after installing so the app loads the skill.
-### Claude Code
+**Then make a video.** In a folder for the video:
-As a plugin, inside Claude Code:
+> Use the brief2mp4 skill to make the video in this brief: *(paste your brief)*
-```
-/plugin marketplace add qualixar/brief2mp4
-/plugin install brief2mp4@brief2mp4
-```
+When it says it is done, send one follow-up:
-On Claude Code 2.1.275 or later this also works in one line: `/plugin install brief2mp4 --marketplace qualixar/brief2mp4`.
+> Check it against the brief.
-### Codex
+That makes the agent go back to your original brief line by line, show the evidence for each line, fix what falls short and render again. In our run of example 01 it caught headlines that cleared the 120 px minimum by only a few pixels, enlarged them and rendered again.
-As a plugin, in a terminal:
+### Requirements
-```bash
-codex plugin marketplace add qualixar/brief2mp4
-codex plugin add brief2mp4@brief2mp4
-```
+| Tool | Needed for | macOS | Windows | Ubuntu / Debian |
+|---|---|---|---|---|
+| Node.js 22+ | every video | `brew install node` | `winget install -e --id OpenJS.NodeJS.LTS` | [nodesource setup_22.x](https://github.com/nodesource/distributions) |
+| ffmpeg | every video | `brew install ffmpeg` | `winget install -e --id Gyan.FFmpeg` | `sudo apt install ffmpeg` |
+| Git Bash | Windows only (the scripts are bash) | | `winget install -e --id Git.Git` | |
+| Blender 4.2+ | photoreal shots (optional) | `brew install --cask blender` | `winget install -e --id BlenderFoundation.Blender` | [blender.org/download](https://www.blender.org/download) |
+| Python 3.12 or 3.13 | the 3D pack (optional) | `brew install [email protected]` | `winget install -e --id Python.Python.3.12` | Ubuntu 24.04: `sudo apt install python3 python3-venv` (Debian 12 ships 3.11: `uv python install 3.12`, then install with `B2M3D_PYTHON="$(uv python find 3.12)"`, see [uv](https://docs.astral.sh/uv/)) |
-The Codex desktop app reads the same settings, so the plugin shows up there too.
+Check a machine at any time with `bash plugin/skills/brief2mp4/scripts/doctor.sh`. It prints `ok` or the exact install command for each tool.
-### Both apps at once, with the script
+## What it makes
-```bash
-git clone https://github.com/qualixar/brief2mp4.git && bash brief2mp4/install.sh
-```
+<p align="center">
+ <img src="assets/r4-fable-four-worlds.webp" alt="Fable 5.2, Round 4: one camera move through a desert, an underwater city, neon rain and space" width="800">
+</p>
-This copies the skill into `~/.claude/skills/brief2mp4` and `~/.codex/skills/brief2mp4` and checks that Node, ffmpeg and Blender are on your machine. Use `--claude` or `--codex` for one app only.
+Round 4 of the video: Fable 5.2 in Claude Code got a written brief for a 60-second film, one continuous camera move through four worlds with its own music, and delivered this. That was a sealed contest run made without this skill; brief2mp4 packages the same loop (spec, build, measure, check every line, fix) so you can run it on your own briefs. The [full films](https://drive.google.com/drive/folders/1yBmCb2h63Fp5yr_37LY46f8BSRa_3GiO?usp=sharing) are untouched, with checksums.
-### No terminal
+| Format | What the skill does for it | Route |
+|---|---|---|
+| **2D explainers** (YouTube, courses) | hook, setup, three-step idea, example, takeaway; diagrams that draw on, labels word by word | HyperFrames |
+| **Maths and algorithms** | equations term by term, colour-coded to the picture; one transformation per beat | HyperFrames + KaTeX, or [Manim](https://github.com/ManimCommunity/manim) inserts |
+| **Tutorial intros and callouts** | title and chapter cards, callouts and zooms over your screen recording | HyperFrames + your recording |
+| **Stories and skits** | situation, want, obstacle, turn; timing pauses before the punchline; captions to the voice | HyperFrames, SVG, Lottie or Rive characters |
+| **YouTube Shorts, Reels, TikTok** | 9:16 safe zones, a hook in the first frame, a change every 2-4 s, loopable endings | HyperFrames |
+| **Data stories** | charts that draw from the baseline, numbers that count to the exact value | HyperFrames + SVG/D3 |
+| **Product launches** | problem, reveal, features, call to action; real UI recreated sharp | HyperFrames, 3D pack, Blender |
+| **Logo stings and titles** | build-up, resolve on the sound accent, hold | HyperFrames, 3D pack |
+| **Kinetic type and lyric videos** | words timed to measured audio, stress shown with scale and weight | HyperFrames |
+| **Stylised 3D** | planets, particles, abstract shapes, flying cameras | Three.js |
+| **3D products with physics** | parts that drop and settle, exploded views, turntables | 3D pack |
+| **Photoreal shots** | glass, metal, soft shadows | Blender |
-Paste this into Claude Code or Codex and let the agent do it:
+<p align="center">
+ <img src="assets/example05-explainer.png" alt="Example 05, a 2D explainer made by the skill: the hook question, the cache diagram mid-count at 626 ms, three labels, and the closing line Keep a copy close." width="49%">
+ <img src="assets/example06-short.png" alt="Example 06, a vertical Short made by the skill: four phone frames with the hook, rule one with an easing dot, rule three with a spinning dot, and Save this." width="49%">
+</p>
-> Clone https://github.com/qualixar/brief2mp4 into a temporary folder and run its install.sh.
+Examples 05 (a 20 s explainer) and 06 (a 15 s vertical Short), each made by running the skill on the brief as written: both passed `check_delivery.sh`, and their [sample](examples/05-2d-explainer/SAMPLE-REPORT.md) [reports](examples/06-vertical-short/SAMPLE-REPORT.md) list the evidence for every line, including the fixes the self-check forced.
-Whichever way you install, start a new session afterwards so the app loads the skill.
+Every format has a beat sheet, a route and its own checks in [references/formats.md](plugin/skills/brief2mp4/references/formats.md), which the agent reads when your brief names the kind of video.
-## Use it
+**Proof the skill works:** example brief 01, pasted as written, came back as a 12.000 s, 1920x1080, 30 fps file that passed the delivery check. Its [report](examples/01-kinetic-type/SAMPLE-REPORT.md) lists every requirement with its evidence: which still shows which line, the measured headline height (126 px against a 120 px minimum), the text bounds and the loudness at each sound accent.
-Open a folder for the video, start a session and send:
+## How it works
-> Use the brief2mp4 skill to make the video in this brief: *(paste your brief)*
+<p align="center">
+ <img src="assets/architecture.png" alt="How brief2mp4 works: 1 your brief, 2 SPEC.md, 3 route each beat to HyperFrames, Three.js, the optional 3D pack or Blender, 4 compose on one HyperFrames timeline, 5 finish with ffmpeg, 6 self-check by measuring the file and looking at stills, looping back to fix the worst miss up to three times, 7 deliver final.mp4 and REPORT.md" width="100%">
+</p>
-When it says it is done, send one follow-up:
-> Check it against the brief.
+1. **Spec.** Before any code the agent writes `SPEC.md`: size, frame rate, exact duration, codecs and loudness; every on-screen word copied exactly; the palette; a beat sheet with times; and a "done when" list with one checkable line per requirement.
+2. **Route and build.** Each beat goes to the tool that fits it, starting from templates that already render. HyperFrames is the spine where every layer meets on one timeline.
+3. **Self-check.** `check_delivery.sh` measures the file (PASS, WARN or FAIL). `contact_sheet.sh` pulls stills at the important moments, and the agent views them and marks every "done when" line met or not met, with evidence.
+4. **Fix.** Worst miss first, render again, up to three rounds.
+5. **Deliver.** `final.mp4` and a `REPORT.md` that says what was checked, how, and what is still open.
-The skill reads that as an instruction to go back to your original brief, line by line, show the evidence for each line, fix anything that falls short and render again. In our test of brief 01 this follow-up caught a real miss: the headlines cleared the 120 px minimum by only a few pixels, so it enlarged them and rendered again, and the delivery check still passed.
+| The beat needs | Tool | Licence |
+|---|---|---|
+| Type, layouts, UI, charts, 2D motion | [HyperFrames](https://github.com/heygen-com/hyperframes) (HTML, CSS and [GSAP](https://github.com/greensock/GSAP) to MP4) | Apache-2.0 |
+| Stylised 3D, particles, camera moves | [Three.js](https://github.com/mrdoob/three.js) inside HyperFrames, seeked by time | MIT |
+| CAD models, materials, physics, exploded views | the optional [3D pack](#the-3d-pack) | MIT and Apache-2.0 parts |
+| Realistic products, materials, soft light | [Blender](https://www.blender.org), scripted in Python, headless | GPL (external tool) |
+| Sound, joins, exact length, loudness, encoding | [ffmpeg](https://ffmpeg.org) | LGPL/GPL (external tool) |
-## How it works
+Mixed briefs, recipes for each mix and the architecture in detail: [docs/architecture.md](docs/architecture.md) for people, [references/pipelines.md](plugin/skills/brief2mp4/references/pipelines.md) for the agent.
-The skill gives the agent one loop and the scripts to run it.
+## The 3D pack
-1. **Spec.** Before any code it writes `SPEC.md`: size, frame rate, exact duration, codecs and loudness; every on-screen word copied exactly; the palette; a beat sheet with times; and a "done when" list with one checkable line per requirement.
-2. **Build.** It picks the tool that fits the brief and starts from a template that already renders.
-3. **Self-check.** It measures the file with `check_delivery.sh`, pulls stills at the important moments with `contact_sheet.sh`, looks at them, and marks every line of the list met or not met, with evidence.
-4. **Fix.** It fixes the worst miss first and renders again, for up to three rounds.
-5. **Deliver.** You get `final.mp4` and a `REPORT.md` that says what was checked, how, and what is still open.
+<p align="center">
+ <img src="assets/example04-3d-product.webp" alt="Example 04 rendered with the 3D pack: five parts of a small sensor drop and settle with real physics, open into an exploded view, and the title Everything inside. appears" width="720">
+</p>
-| The brief asks for | The skill uses |
-|---|---|
-| Type, layouts, UI, charts, 2D motion | [HyperFrames](https://github.com/heygen-com/hyperframes) (HTML, CSS and GSAP to MP4) |
-| Stylised 3D, particles, camera moves | [Three.js](https://threejs.org) inside HyperFrames, driven by the timeline so every frame renders the same way twice |
-| Realistic products, materials, soft light | [Blender](https://www.blender.org), scripted in Python and rendered without opening a window |
-| Sound, joins, exact length, loudness, encoding | [ffmpeg](https://ffmpeg.org) |
+Example 04, rendered by the 3D pack on a laptop: five parts drop and settle with baked rigid-body physics, open into an exploded view, and the title lands. 8 seconds of 1080p rendered in about 5 seconds; `check_delivery.sh` passes.
-## Example briefs
+An optional layer for briefs with 3D products. It turns a CAD or mesh spec into a GLB, applies material presets, bakes rigid-body physics once so every render frame is identical, writes a self-contained HyperFrames project from a short shot JSON, and renders photoreal hero shots through Blender. The skill detects it; without it, 3D beats use the Three.js template.
-| Brief | Tool | Length |
+| Component | What it adds | Built on |
|---|---|---|
-| [01 kinetic type](examples/01-kinetic-type/BRIEF.md): "Finish something today" | HyperFrames | 12 s |
-| [02 Three.js](examples/02-threejs-orbit/BRIEF.md): a low-poly planet, three moons, "ORBIT" | Three.js | 10 s |
-| [03 Blender](examples/03-blender-product/BRIEF.md): a smart-speaker turntable, "LISTEN." | Blender | 8 s |
+| `core` | models from mesh specs, material presets, physics bakes, GLB optimisation, shot JSON to HyperFrames | [three.js](https://github.com/mrdoob/three.js), [glTF-Transform](https://github.com/donmccurdy/glTF-Transform), [meshoptimizer](https://github.com/zeux/meshoptimizer), [Jolt Physics](https://github.com/jrouwe/JoltPhysics), [Manifold](https://github.com/elalish/manifold), [trimesh](https://github.com/mikedh/trimesh) |
+| `cad` | exact parametric parts: enclosures, gears, brackets | [CadQuery](https://github.com/CadQuery/cadquery) |
+| `blender` | photoreal hero renders on the GPU (Metal, OptiX, CUDA or CPU) | your installed [Blender](https://www.blender.org) |
+
+```bash
+bash install.sh --with-3d # core
+bash install.sh --with-3d=core,cad # core + CadQuery
+```
-## Write your own brief
+```powershell
+powershell -ExecutionPolicy Bypass -File .\install.ps1 -With3D core,cad
+```
+
+The brief does the asking. "Parts fall and settle" becomes a physics bake with a camera that frames the landing zone; "show what's inside" becomes an exploded view; "hero product" becomes a Blender render with a dramatic light rig. The full mapping, the shot JSON and the look rules are in [3d/README-3D.md](plugin/skills/brief2mp4/3d/README-3D.md).
+
+## Examples
+
+| # | Brief | Route | Length |
+|---|---|---|---|
+| 01 | [Kinetic type](examples/01-kinetic-type/BRIEF.md): "Finish something today" ([sample report](examples/01-kinetic-type/SAMPLE-REPORT.md)) | HyperFrames | 12 s |
+| 02 | [Three.js](examples/02-threejs-orbit/BRIEF.md): a low-poly planet, three moons, "ORBIT" | Three.js in HyperFrames | 10 s |
+| 03 | [Blender](examples/03-blender-product/BRIEF.md): a smart-speaker turntable, "LISTEN." | Blender | 8 s |
+| 04 | [3D product](examples/04-3d-product/BRIEF.md): parts drop and settle, explode, title | 3D pack | 8 s |
+| 05 | [2D explainer](examples/05-2d-explainer/BRIEF.md): "How a cache works" | HyperFrames | 20 s |
+| 06 | [Vertical Short](examples/06-vertical-short/BRIEF.md): "3 easing rules", 1080x1920 with safe zones | HyperFrames | 15 s |
+
+## Write a brief
The agent guesses less when the brief says more. A brief that works well has these parts:
@@ -128,61 +188,67 @@ Sound: a quiet bed with a low hit at 4.0 s.
Done when: every line is readable, nothing touches the frame edge, headlines are at least 100 px tall.
```
-The "done when" lines matter most, because they are what the self-check measures. The free guide at [qualixar.com/learn/guides/brief2mp4-guide](https://qualixar.com/learn/guides/brief2mp4-guide) goes through brief writing, each tool and the checks in more detail.
+The "done when" lines matter most, because they are what the self-check measures. The [free guide](https://qualixar.com/learn/guides/brief2mp4-guide) goes through brief writing, each tool and the checks in detail.
-## Requirements
+## How it compares
-- Claude Code or Codex, desktop app or command line.
-- Node.js 22 or newer and ffmpeg, for every brief.
-- Blender, only for Blender briefs (tested with 5.2; 4.2 or newer should work).
+brief2mp4 sits on top of the tools below rather than replacing them. The table compares scope as each project describes itself.
-HyperFrames runs through `npx`, so there is nothing else to install. The install script tells you what is missing.
+| | brief2mp4 | [HyperFrames skills](https://github.com/heygen-com/hyperframes) | [Remotion skills](https://github.com/remotion-dev/skills) | Prompting an agent with no skill |
+|---|---|---|---|---|
+| Input | a written brief | a request | a request in a Remotion project | a request |
+| Writes a spec with a checkable done-when list | yes | | | |
+| Routes beats across HyperFrames, Three.js, a 3D pack and Blender | yes | HyperFrames | Remotion | whatever the agent picks |
+| Measures the delivered file (duration, size, codecs, loudness) | yes, PASS/WARN/FAIL | | | |
+| Looks at frames and reports evidence per brief line | yes, `REPORT.md` | lint and preview | | |
+| Physics and CAD 3D | optional 3D pack | | | |
+| Licence | MIT | Apache-2.0 | see repo; Remotion has its own licence | |
-## FAQ
+They work well together: install the HyperFrames skills next to brief2mp4 for deeper HyperFrames know-how, and the agent uses both. For more than 45 other open-source motion, 3D, capture and agent-skill projects, with licences and how to bring each one into a brief2mp4 pipeline, see [references/ecosystem.md](plugin/skills/brief2mp4/references/ecosystem.md).
-**Does it cost anything?** The skill is free and MIT licensed. The agent runs on your own Claude Code or Codex plan, and the rendering happens on your machine.
+## FAQ
-**Which models has it been tested with?** Claude Code on Sonnet made brief 01 in 98 seconds, start to finish, with the delivery check passing. Stronger models handle harder briefs better, but the loop and the checks are the same for all of them.
+**Does it cost anything?** The skill is free and MIT licensed. The agent runs on your own Claude Code or Codex plan, and rendering happens on your machine.
-**Does it upload my files anywhere?** No. Rendering, checks and the report all stay in your project folder. The only network traffic is what the tools themselves fetch: HyperFrames and Three.js packages through npm, and any web fonts your brief names.
+**Which models has it been tested with?** Claude Code on Sonnet made briefs 01, 05 and 06 from the brief as written, each passing the delivery check (05 and 06 rendered in about 7 seconds each on an Apple M-series laptop). Stronger models handle harder briefs better, but the loop and the checks are the same for all of them.
-**What about music?** `sound_bed.sh` makes a quiet original placeholder so the file is never silent. For a real soundtrack, pass your own licensed track to `finish.sh --audio`.
+**Does it work on Windows?** Yes, with Git for Windows installed (`install.ps1 -InstallTools` does it), because the scripts are bash. CI runs the install, the doctor and the tests on Windows, macOS and Ubuntu on every change. Full renders are tested on macOS.
-**Can I use the scripts without an agent?** Yes. They are plain bash and ffmpeg. For example, from a clone of this repo:
+**Does it upload my files anywhere?** No. Rendering, checks and reports stay in your project folder. The only network traffic is what the tools fetch: npm and PyPI packages at install time and any web fonts your brief names.
-```bash
-bash plugin/skills/brief2mp4/scripts/check_delivery.sh my-video.mp4 --seconds 30
-```
+**What about music?** `sound_bed.sh` makes a quiet original placeholder so the file is never silent. For a real soundtrack, pass your own licensed track to `finish.sh --audio`.
-**Does it work on Windows or Linux?** It is tested on macOS. The scripts are bash and ffmpeg, so Linux should work. On Windows, use WSL; that is untested.
+**Can I use the scripts without an agent?** Yes. They are plain bash and ffmpeg, for example `bash plugin/skills/brief2mp4/scripts/check_delivery.sh my-video.mp4 --seconds 30`.
-**How do I update or remove it?** Claude Code plugin: `claude plugin update brief2mp4@brief2mp4`, or `claude plugin uninstall brief2mp4@brief2mp4`. Codex plugin: `codex plugin marketplace upgrade`, or `codex plugin remove brief2mp4@brief2mp4`. Script install: `git pull` then `bash install.sh` again, or `bash install.sh --uninstall`. The script only replaces or removes a folder it created; if you already had a `brief2mp4` folder in your skills, it is moved aside with a timestamp, never deleted.
+**How do I update or remove it?** Claude Code plugin: `claude plugin update brief2mp4@brief2mp4` or `claude plugin uninstall brief2mp4@brief2mp4`. Codex plugin: `codex plugin marketplace upgrade` or `codex plugin remove brief2mp4@brief2mp4`. Script install: `git pull` and run the installer again, or `install.sh --uninstall` / `install.ps1 -Uninstall`. The installers only replace or remove a folder they created; an existing `brief2mp4` folder is moved aside with a timestamp, never deleted.
## What is inside
```
+SETUP.md the setup script an agent follows (macOS, Windows, Linux)
+AGENTS.md, CLAUDE.md what an agent opened in this repo should do
+install.sh, install.ps1 install, update or remove for both apps; --with-3d / -With3D
.claude-plugin/marketplace.json marketplace entry, read by Claude Code and Codex
plugin/
.claude-plugin/plugin.json Claude Code plugin manifest
.codex-plugin/plugin.json Codex plugin manifest
skills/brief2mp4/
SKILL.md the loop the agent follows
- references/ HyperFrames, Three.js, Blender and ffmpeg notes
- scripts/
- finish.sh any render to a delivery MP4 (exact length, H.264/AAC, -14 LUFS)
- check_delivery.sh PASS, WARN or FAIL against the delivery spec
- contact_sheet.sh stills at chosen moments, plus a grid
- sound_bed.sh a quiet original placeholder soundtrack
- templates/
- SPEC.md the spec the agent fills in
- threejs/index.html a Three.js scene that renders frame by frame
- blender/scene.py a scripted Blender turntable
-examples/ three briefs and a sample report
-install.sh script install, update or removal for both apps
+ references/ formats, pipelines, ecosystem, hyperframes, threejs, blender, ffmpeg
+ scripts/ finish, check_delivery, contact_sheet, sound_bed, doctor, detect_3d
+ templates/ SPEC.md, a Three.js scene, a Blender turntable
+ 3d/ the optional 3D pack and its installers
+docs/ getting started, architecture, 3D walkthrough
+examples/ six briefs; 01, 04, 05 and 06 with sample reports or a worked build
+tests/ fast checks and render tests (bash tests/run_tests.sh [--slow])
```
+## Contributing
+
+Bad results are the most useful bug reports: open a **Brief result** issue with the brief, the app and model, and the `REPORT.md`. Code changes are welcome too; see [CONTRIBUTING.md](CONTRIBUTING.md). Security reports go through [SECURITY.md](SECURITY.md). Releases are listed in [CHANGELOG.md](CHANGELOG.md).
+
## Licence
-MIT. Use it, change it, ship videos with it. HyperFrames (Apache-2.0), Three.js (MIT), GSAP, Blender (GPL) and ffmpeg (LGPL/GPL) keep their own licences; this repo does not bundle them.
+MIT. Use it, change it, ship videos with it. HyperFrames (Apache-2.0), Three.js (MIT), GSAP (standard no-charge licence), Jolt (MIT), glTF-Transform (MIT), meshoptimizer (MIT), Manifold (Apache-2.0), CadQuery (Apache-2.0), trimesh (MIT), Blender (GPL) and ffmpeg (LGPL/GPL) keep their own licences; this repo does not bundle them.
Made by [Varun Pratap Bhardwaj](https://github.com/qualixar).
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..794c56b
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,17 @@
+# Security policy
+
+brief2mp4 is a skill: instructions, bash and PowerShell scripts, and an optional Python and Node 3D pack that run on your own machine. It makes no network calls of its own at render time. The installers download only from npm, PyPI and the official package managers (Homebrew, winget, apt).
+
+## What runs as code
+
+Two inputs are executed, by design: a 3D pack model spec (`b2m3d model spec.py`) is Python, and a HyperFrames composition is HTML and JavaScript run in headless Chrome. Treat both like any script: only build from specs and compositions you wrote or trust. A brief itself is plain text and is never executed.
+
+## Supported versions
+
+Only the latest release gets fixes.
+
+## Report a vulnerability
+
+Please do not open a public issue. Use GitHub's private reporting: **Security > Report a vulnerability** on this repository. Include the version, your OS, and steps to reproduce. You should get a reply within seven days.
+
+Things we treat as security issues: a script that writes or deletes outside the project folder or its own install folder, an installer that runs with elevated rights without saying so, any path that executes content from a brief, and dependency pins with known critical vulnerabilities.
diff --git a/SETUP.md b/SETUP.md
new file mode 100644
index 0000000..2b10f8e
--- /dev/null
+++ b/SETUP.md
@@ -0,0 +1,95 @@
+# SETUP.md: instructions for the agent
+
+You are Claude Code or Codex, and the user asked you to set up brief2mp4 on this machine. Follow these steps in order. Ask before installing anything system-wide, show each command before you run it, and stop on the first step you cannot finish, saying exactly what failed.
+
+The user can start this with one message:
+
+> Set up brief2mp4 from https://github.com/qualixar/brief2mp4 by following its SETUP.md.
+
+## Step 1. Find out where you are
+
+Run the probe for the shell you have and note the answers.
+
+macOS, Linux, WSL, Git Bash:
+
+```bash
+uname -s; uname -m
+for t in git node npm ffmpeg ffprobe python3 blender; do printf '%-8s ' "$t"; command -v "$t" || echo missing; done
+node -v 2>/dev/null; ffmpeg -version 2>/dev/null | head -1; python3 --version 2>/dev/null
+```
+
+Windows PowerShell:
+
+```powershell
+$PSVersionTable.PSVersion; [System.Environment]::Is64BitOperatingSystem
+foreach ($t in 'git','node','npm','ffmpeg','ffprobe','python','py','blender','winget') { $c = Get-Command $t -ErrorAction SilentlyContinue; "{0,-8} {1}" -f $t, $(if ($c) { $c.Source } else { 'missing' }) }
+```
+
+Decide the operating system: `Darwin` is macOS, `Linux` is Linux (WSL counts as Linux), PowerShell or `MINGW`/`MSYS` in `uname -s` is Windows.
+
+## Step 2. Install what is missing
+
+Required for every brief: **Node.js 22 or newer**, **ffmpeg** (with ffprobe) and **git**. On Windows also **Git for Windows**, because the skill's scripts are bash and Git Bash runs them. Optional: **Blender** (4.2 or newer, tested with 5.2) for realistic product shots, and **Python 3.12 or 3.13** for the 3D pack (its pinned numpy and scipy need 3.12+).
+
+Ask the user once, listing only what is missing, then run the matching commands.
+
+| Tool | macOS (Homebrew) | Windows (winget) | Ubuntu / Debian |
+|---|---|---|---|
+| Node.js 22+ | `brew install node` | `winget install -e --id OpenJS.NodeJS.LTS` | `curl -fsSL https://deb.nodesource.com/setup_22.x \| sudo -E bash - && sudo apt install -y nodejs` |
+| ffmpeg | `brew install ffmpeg` | `winget install -e --id Gyan.FFmpeg` | `sudo apt install -y ffmpeg` |
+| git / Git Bash | `xcode-select --install` | `winget install -e --id Git.Git` | `sudo apt install -y git` |
+| Blender (optional) | `brew install --cask blender` | `winget install -e --id BlenderFoundation.Blender` | download from https://www.blender.org/download (the apt version is often old) |
+| Python 3.12 (3D pack) | `brew install [email protected]` | `winget install -e --id Python.Python.3.12` | Ubuntu 24.04: `sudo apt install -y python3 python3-venv`; Debian 12 ships 3.11: `uv python install 3.12`, then run the 3D install with `B2M3D_PYTHON="$(uv python find 3.12)"` |
+
+Notes:
+
+- No Homebrew on macOS? It is at https://brew.sh. Ask before installing it.
+- After a winget install on Windows, open a **new** terminal (or restart the agent session) so the PATH updates. If `ffmpeg` is still not found, it sits under `%LOCALAPPDATA%\Microsoft\WinGet\Packages\Gyan.FFmpeg*\...\bin`; add that folder to the user PATH.
+- On macOS Blender is often not on the PATH: use `/Applications/Blender.app/Contents/MacOS/Blender`. On Windows it is under `C:\Program Files\Blender Foundation\Blender <version>\blender.exe`.
+- Never use `sudo npm install -g`. HyperFrames runs through `npx`, so no global npm installs are needed.
+
+## Step 3. Get the repo and install the skill
+
+```bash
+git clone https://github.com/qualixar/brief2mp4.git
+cd brief2mp4
+```
+
+macOS, Linux, WSL, Git Bash:
+
+```bash
+bash install.sh # Claude Code and Codex
+bash install.sh --with-3d # also the 3D pack (core components)
+bash install.sh --with-3d=core,cad # 3D pack with the CadQuery modeller (about 1.3 GB more)
+```
+
+Windows PowerShell:
+
+```powershell
+powershell -ExecutionPolicy Bypass -File .\install.ps1
+powershell -ExecutionPolicy Bypass -File .\install.ps1 -With3D core,cad
+```
+
+Install the 3D pack only when the user wants 3D products, physics, exploded views or turntables. Everything else works without it. The pack is described in `plugin/skills/brief2mp4/3d/README-3D.md`.
+
+The user may prefer the plugin route instead of the script. Then they run, inside Claude Code: `/plugin marketplace add qualixar/brief2mp4` and `/plugin install brief2mp4@brief2mp4`; in a terminal for Codex: `codex plugin marketplace add qualixar/brief2mp4` and `codex plugin add brief2mp4@brief2mp4`. Plugins do not install system tools, so Step 2 still applies.
+
+## Step 4. Check the machine
+
+```bash
+bash plugin/skills/brief2mp4/scripts/doctor.sh
+```
+
+On Windows run the same line from Git Bash, or from PowerShell as `& "C:\Program Files\Git\bin\bash.exe" plugin/skills/brief2mp4/scripts/doctor.sh`. Every required line must say `ok`. Fix any `missing` line with the command it prints and run the doctor again.
+
+## Step 5. Prove it works: the two-minute first render
+
+Make an empty folder outside the repo, copy `examples/01-kinetic-type/BRIEF.md` into it, and in that folder follow the skill: spec, build, self-check, deliver. A working setup produces `final.mp4` (12.000 s, 1920x1080, 30 fps) and `check_delivery.sh` ends with `RESULT: PASS`. If the 3D pack was installed, also run `examples/04-3d-product/BRIEF.md`.
+
+## Step 6. Tell the user
+
+Report in five lines or fewer: the OS, what you installed, the doctor result, the path of the first `final.mp4` with its duration, and the next thing to try:
+
+> Start a new session, then send: Use the brief2mp4 skill to make the video in this brief: (paste your brief)
+
+A new session is needed because the apps load skills at session start.
diff --git a/VERSION b/VERSION
index 0ea3a94..0d91a54 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.2.0
+0.3.0
diff --git a/assets/architecture.png b/assets/architecture.png
new file mode 100644
index 0000000..0f3b1e2
Binary files /dev/null and b/assets/architecture.png differ
diff --git a/assets/example04-3d-product.webp b/assets/example04-3d-product.webp
new file mode 100644
index 0000000..c6c0708
Binary files /dev/null and b/assets/example04-3d-product.webp differ
diff --git a/assets/example04-stills.png b/assets/example04-stills.png
new file mode 100644
index 0000000..e3f0c87
Binary files /dev/null and b/assets/example04-stills.png differ
diff --git a/assets/example05-explainer.png b/assets/example05-explainer.png
new file mode 100644
index 0000000..da00f4b
Binary files /dev/null and b/assets/example05-explainer.png differ
diff --git a/assets/example06-short.png b/assets/example06-short.png
new file mode 100644
index 0000000..dd91c7d
Binary files /dev/null and b/assets/example06-short.png differ
diff --git a/docs/3d-walkthrough.md b/docs/3d-walkthrough.md
new file mode 100644
index 0000000..094d6ac
--- /dev/null
+++ b/docs/3d-walkthrough.md
@@ -0,0 +1,96 @@
+# 3D walkthrough: from a brief to a physics product shot
+
+This guide follows example 04 from brief to checked MP4, so you can see what the agent does with the 3D pack and do the same by hand. The full command reference is [3d/README-3D.md](../plugin/skills/brief2mp4/3d/README-3D.md).
+
+<p align="center">
+ <img src="../assets/example04-stills.png" alt="Four stills from example 04: parts falling at 1.2 s, the settled stack at 2.9 s, the exploded view opening at 3.9 s, the title over the exploded column at 6.2 s" width="900">
+</p>
+
+## 1. Install the pack (once)
+
+```bash
+bash install.sh --with-3d # macOS, Linux: core (about 280 MB)
+bash install.sh --with-3d=core,cad # add CadQuery for exact CAD parts (about 1.3 GB more)
+```
+
+```powershell
+powershell -ExecutionPolicy Bypass -File .\install.ps1 -With3D core
+```
+
+It installs into `~/.brief2mp4/3d` with its own Python venv and Node packages, so your global Python and npm stay untouched. `bash plugin/skills/brief2mp4/scripts/detect_3d.sh` prints `3d: ready` when it worked.
+
+## 2. Read the brief as shots
+
+[Brief 04](../examples/04-3d-product/BRIEF.md) asks for five parts of a small sensor to drop and settle, open into an exploded view, and close on a title. The agent translates each phrase:
+
+| Brief phrase | Shot JSON |
+|---|---|
+| "the parts fall one after another ... and settle" | a `physics` bake; each model gets `track: "<part>"` |
+| "real rigid-body physics, not hand-keyed" | Jolt, baked once to `track.json`, replayed by time |
+| "the stack opens into an exploded view" | `explode` with an upward offset per part, eased in and out |
+| "camera pushes in ... then pulls back to frame the whole column" | `camera.keys` (the automatic camera does not know about the explode) |
+| "neutral tone mapping, a dim environment, strong key light, bloom off" | `tonemapping: "neutral"`, `envIntensity: 0.35`, `lights: "dramatic"`, no `bloom` |
+| "title bottom left ... fades out before the end" | `titles` with `position: "bottom-left"`, `start` and `duration` |
+
+## 3. The build, step by step
+
+```mermaid
+flowchart LR
+ A[device.py<br/>5 parts as Manifold solids] -->|model| B[5 GLBs]
+ B -->|material assign| C[matte plastic, aluminium,<br/>circuit green, ceramic, smoked glass]
+ C -->|optimize| D[compressed GLBs]
+ E[scene.json<br/>bodies, drop heights, damping] -->|physics| F[track.json]
+ D --> G[shot.json]
+ F --> G
+ G -->|hf| H[HyperFrames project]
+ H -->|lint + snapshot| I[look at 4 stills]
+ I -->|render| J[render.mp4]
+ J -->|finish.sh| K[final.mp4]
+ K -->|check_delivery.sh| L[PASS]
+```
+
+The worked files ship with the pack in `plugin/skills/brief2mp4/3d/examples/04-3d-product/`: `device.py` (the parts), `scene.json` (the physics), `shot.json` (camera, lights, explode, title) and `build.py`, which runs every step. With the pack's Python:
+
+```bash
+export B2M3D_HOME=~/.brief2mp4/3d
+$B2M3D_HOME/venv/bin/python plugin/skills/brief2mp4/3d/examples/04-3d-product/build.py ~/videos/ex04
+cd ~/videos/ex04/project
+npx --yes [email protected] lint
+npx --yes [email protected] snapshot --at 1.2,2.9,3.9,7.8
+npx --yes [email protected] render . -o ../render.mp4 --quality delivery --fps 30 --workers 4
+```
+
+Each `b2m3d` subcommand prints one JSON result (`build.py` hides them for brevity; run the steps by hand to see them), so an agent can read exactly what happened. Then finish and check:
+
+```bash
+S=plugin/skills/brief2mp4/scripts
+bash $S/sound_bed.sh bed.wav --seconds 8 --hits 0.6,1.2,1.8,2.4,3.0,3.2
+bash $S/finish.sh --in render.mp4 --out final.mp4 --seconds 8 --audio bed.wav
+bash $S/check_delivery.sh final.mp4 --seconds 8 --size 1920x1080 --fps 30
+bash $S/contact_sheet.sh final.mp4 --at 1.2,2.9,3.9,6.2
+```
+
+On an Apple M-series laptop the 8 s render takes about 5 seconds and the delivery check passes.
+
+## 4. Look before you render the full shot
+
+Snapshots cost seconds; a wrong full render costs minutes. Check each still for:
+
+- **Framing.** Is the subject in frame at every sampled time? A camera that frames the fall instead of the landing zone makes the parts tiny.
+- **Contact.** Do shadows sit under the parts? A floating shadow means `ground.y` is off.
+- **Colour.** Is the green board green and the white cover white? Colours in glTF are linear: convert sRGB with `(c / 255) ** 2.2` (`b2m3d material linear "#rrggbb"` does it).
+- **Text.** Is the title spelled exactly, clear of the product, and inside the safe margins? In our first render of this example the end of "inside." touched the tray; dropping the title from 76 px to 64 px fixed it.
+
+## 5. Make it your own
+
+| You want | Change |
+|---|---|
+| A different product | Edit `device.py`: each part is a Manifold solid with a name, colour, metalness and roughness. With the `cad` component, return CadQuery parts for fillets and exact dimensions |
+| A turntable instead of a drop | Remove `physics` and `track`; give the model `spin` (degrees per second) and a fixed camera |
+| A photoreal hero frame | `b2m3d blender product.glb frames/ --mp4 hero.mp4 --look dramatic`, then place `hero.mp4` as a video layer under your title |
+| A glowing logo | `material assign ... --assign '*=neon_emissive'` and `"bloom": true` (the only case where bloom helps) |
+| Your palette | `background` (any CSS) and `accent` in the shot; pick material presets that sit well on it |
+
+## Without the pack
+
+If `detect_3d.sh` says `not installed`, the skill still makes 3D shots with the Three.js template (`templates/threejs/index.html`): stylised scenes, orbits, particles, hand-keyed motion. It says in `REPORT.md` that physics and exploded views were animated by hand, and how to add the pack (`3d/install_3d.sh --components core` from the skill folder).
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..569a2bb
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,9 @@
+# brief2mp4 docs
+
+Three guides for people. The agent reads the skill's own files (`plugin/skills/brief2mp4/SKILL.md` and `references/`); these are for you, to understand what it does and to get more out of it.
+
+| Guide | Read it when |
+|---|---|
+| [Getting started](getting-started.md) | You are installing brief2mp4 on macOS, Windows or Linux and want your first video |
+| [Architecture](architecture.md) | You want to know how the loop, the routing and the checks work, or you want to extend it |
+| [3D walkthrough](3d-walkthrough.md) | Your brief has a 3D product, physics, an exploded view or a turntable |
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..acd872b
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,118 @@
+# Architecture
+
+brief2mp4 is not a renderer. It is a loop that an agent runs, plus the scripts and references that make each step of the loop checkable. The renderers are open-source tools it routes to.
+
+<p align="center"><img src="../assets/architecture.png" alt="How brief2mp4 works, from brief to checked MP4" width="100%"></p>
+
+The image is generated from code: edit `docs/diagrams/architecture.html` and run `bash docs/diagrams/render.sh`.
+
+## The loop
+
+```mermaid
+stateDiagram-v2
+ [*] --> Spec: brief arrives
+ Spec --> Build: SPEC.md written
+ Build --> Measure: render.mp4 finished
+ Measure --> Look: check_delivery.sh
+ Look --> Walk: contact_sheet.sh stills viewed
+ Walk --> Fix: a done-when line is not met
+ Fix --> Build: worst miss first (max 3 rounds)
+ Walk --> Deliver: every line met
+ Deliver --> [*]: final.mp4 + REPORT.md
+ Deliver --> Recheck: user sends "Check it against the brief"
+ Recheck --> Walk: re-read the ORIGINAL brief
+```
+
+Three design choices make the loop work:
+
+1. **The spec is a contract.** The agent turns every line of the brief into a checkable "done when" line before it writes any code: "at 9.5 s the words FINISH SOMETHING TODAY are fully on screen, nothing cut off". The self-check measures against that list, not against the agent's memory of what it meant to build.
+2. **Machines measure, eyes look.** `check_delivery.sh` measures what a script can: duration to the frame, size, frame rate, codecs, loudness, true peak, silence. What it can't measure (spelling on screen, overlap, whether the hero moment is there) is checked by pulling stills at named times and viewing them. The report says which evidence came from where.
+3. **Recheck against the brief, not the spec.** The follow-up "Check it against the brief" goes back to the user's words, because a spec can drift from the brief.
+
+## Routing
+
+Each beat in the beat sheet is routed on its own. One film often uses several routes.
+
+```mermaid
+flowchart TD
+ Beat[A beat from the beat sheet] --> Q1{Mostly words,<br/>UI or 2D shapes?}
+ Q1 -->|yes| HF[HyperFrames<br/>HTML + CSS + GSAP]
+ Q1 -->|no| Q2{Needs physics, CAD parts,<br/>exploded view, real materials?}
+ Q2 -->|yes| D{3D pack<br/>installed?}
+ D -->|yes| P[3D pack: model, material,<br/>physics, hf]
+ D -->|no| T
+ Q2 -->|no| Q3{Must look photoreal?<br/>glass, metal, soft shadow}
+ Q3 -->|yes| B[Blender, headless]
+ Q3 -->|no| T[Three.js template<br/>inside HyperFrames]
+ P --> HF
+ T --> HF
+ B -->|PNG frames or<br/>ProRes 4444 alpha| HF
+ HF --> FF[ffmpeg: finish.sh]
+```
+
+HyperFrames is the spine. It is the one place where layers meet on a single timeline, so type always sits in HTML above 3D and stays sharp, exact and spell-checkable.
+
+## Why every frame is a function of time
+
+```mermaid
+sequenceDiagram
+ participant R as HyperFrames renderer
+ participant W1 as Chrome worker 1
+ participant W2 as Chrome worker 2
+ participant S as Scene (time t to pixels)
+ R->>W1: seek t = 4.20 s
+ R->>W2: seek t = 0.80 s
+ W1->>S: draw(4.20)
+ W2->>S: draw(0.80)
+ S-->>W1: frame 126
+ S-->>W2: frame 24
+ W1-->>R: PNG 126
+ W2-->>R: PNG 24
+ R->>R: encode frames in order
+```
+
+The renderer seeks frames out of order across parallel workers. A scene that reads the wall clock, uses unseeded randomness or fetches from the network at render time would draw a different frame for the same `t` in different workers, and the video would flicker or jump. So every visible value is computed from `t` alone. Physics is the hard case: the 3D pack runs the simulation once with Jolt at a fixed step, saves one pose per frame, and the page looks poses up by `t`. The bake is byte-identical across runs, and the tests check that.
+
+## The 3D pack
+
+```mermaid
+flowchart LR
+ subgraph Assets
+ SP[spec.py<br/>Manifold, trimesh or CadQuery] -->|model| G[part GLBs]
+ G -->|material| GM[GLBs with PBR presets]
+ GM -->|optimize| GO[compressed GLBs]
+ end
+ subgraph Motion
+ SC[scene.json<br/>bodies, gravity, fps] -->|physics: Jolt bake| TR[track.json<br/>one pose per frame]
+ end
+ GO --> SH[shot.json<br/>models, camera, lights, titles]
+ TR --> SH
+ SH -->|hf| PR[HyperFrames project<br/>three.js, GSAP, fonts, GLBs vendored]
+ PR --> SN[snapshot at 3-5 times]
+ SN --> RD[render] --> F[finish.sh]
+ GM -->|blender| BL[photoreal frames / MP4]
+ BL --> PR
+```
+
+Every subcommand prints one JSON object, so an agent reads results instead of parsing logs. The pack is optional and lives in its own folder (`~/.brief2mp4/3d`) with its own Python venv and `node_modules`, so it never touches the user's global Python or npm. `detect_3d.sh` lets the skill branch: with the pack it builds physics and exploded views; without it, it uses the Three.js template and says so in the report.
+
+## Files and responsibilities
+
+| Path | Responsibility |
+|---|---|
+| `plugin/skills/brief2mp4/SKILL.md` | The loop: spec, route, build, self-check, fix, deliver |
+| `references/*.md` | What the agent needs per tool: HyperFrames, Three.js, Blender, ffmpeg, mixed pipelines, the wider ecosystem |
+| `scripts/finish.sh` | Any render to a delivery MP4: exact length, H.264 and AAC, -14 LUFS, true peak at or below -1.5 dBTP |
+| `scripts/check_delivery.sh` | PASS, WARN or FAIL against the delivery spec |
+| `scripts/contact_sheet.sh` | Stills at named times, plus a grid |
+| `scripts/doctor.sh`, `detect_3d.sh` | What is installed, and the fix for what is not |
+| `templates/` | Starting points that already render: SPEC.md, a Three.js scene, a Blender turntable |
+| `3d/` | The optional pack: `b2m3d` CLI, shot runtime, material presets, installers |
+| `SETUP.md` | Machine setup an agent follows, per OS |
+| `tests/` | Determinism, generation, detection and render tests; CI on macOS, Windows and Ubuntu |
+
+## Extending it
+
+- **A new tool route:** add a reference file in `references/`, a row to the routing table in SKILL.md, and a template that already renders. The tool must pass the determinism test: render the same frame twice in separate runs and get identical PNGs.
+- **A new check:** add it to `check_delivery.sh` if a script can measure it, otherwise to the "Look" step as a named question about a still.
+- **A new 3D motion:** add a model key to the shot runtime in `3d/templates/shot-runtime.js`, computed from `t` alone, with a test in `tests/`.
diff --git a/docs/diagrams/architecture.html b/docs/diagrams/architecture.html
new file mode 100644
index 0000000..31c49ee
--- /dev/null
+++ b/docs/diagrams/architecture.html
@@ -0,0 +1,111 @@
+<!doctype html>
+<!-- Source of assets/architecture.png. Render: bash docs/diagrams/render.sh -->
+<html><head><meta charset="utf-8">
+<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@500&display=block" rel="stylesheet">
+<style>
+:root{--paper:#F2EDE4;--card:#FBF8F2;--ink:#16130F;--mute:#6E675C;--line:#D9D1C3;--acc:#FF5A1F;--acc2:#FFE3D6}
+*{box-sizing:border-box;margin:0;padding:0}
+body{width:1600px;height:900px;background:var(--paper);font-family:Inter,sans-serif;color:var(--ink);position:relative;overflow:hidden}
+h1{position:absolute;left:64px;top:46px;font:700 46px 'Space Grotesk';letter-spacing:-.5px}
+h1 span{color:var(--acc)}
+.sub{position:absolute;left:66px;top:108px;font:400 20px Inter;color:var(--mute)}
+.card{position:absolute;background:var(--card);border:2px solid var(--ink);border-radius:18px;padding:18px 18px 16px}
+.n{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:50%;background:var(--ink);color:var(--paper);font:700 16px 'Space Grotesk';margin-bottom:10px}
+.t{font:700 22px 'Space Grotesk';margin-bottom:6px}
+.d{font:400 14.5px/1.42 Inter;color:var(--mute)}
+.mono{font:500 13px 'JetBrains Mono';color:var(--ink);background:var(--paper);border-radius:6px;padding:2px 6px;display:inline-block;margin-top:8px}
+.lane{position:absolute;left:18px;right:18px;height:66px;border:1.5px solid var(--line);border-radius:12px;background:#fff;padding:10px 12px}
+.lane b{font:600 15.5px Inter;display:block}
+.lane i{font:400 13px Inter;color:var(--mute);font-style:normal}
+.lane .tag{position:absolute;right:10px;top:10px;font:500 11px 'JetBrains Mono';color:var(--mute)}
+.lane.opt{border-style:dashed}
+.acc{border-color:var(--acc)!important}
+.accbg{background:var(--acc2)}
+.stack{position:absolute;left:18px;right:18px;top:216px;height:170px}.stack div{position:absolute;left:0;right:0;height:34px;border:1.5px solid var(--ink);border-radius:8px;background:var(--card);font:500 13px Inter;padding:8px 10px}.stack div:nth-child(1){margin-left:0}.stack div:nth-child(2){margin-left:6px}.stack div:nth-child(3){margin-left:12px}.stack div:nth-child(4){margin-left:18px}
+.loop{position:absolute;font:600 15px Inter;color:var(--acc);background:var(--paper);padding:0 8px}
+.foot{position:absolute;left:64px;right:64px;bottom:40px;display:flex;gap:14px}
+.pill{border:1.5px solid var(--ink);border-radius:999px;padding:9px 18px;font:500 15px Inter;background:var(--card)}
+.pill em{font-style:normal;color:var(--acc);font-weight:600}
+svg{position:absolute;left:0;top:0}
+</style></head><body>
+<h1>How <span>brief2mp4</span> works</h1>
+<div class="sub">One loop an agent runs in Claude Code or Codex: every line of your brief becomes a check, and nothing ships until the checks pass.</div>
+
+<svg width="1600" height="900" viewBox="0 0 1600 900">
+ <defs><marker id="a" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#16130F"/></marker>
+ <marker id="o" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#FF5A1F"/></marker></defs>
+ <g stroke="#16130F" stroke-width="2.5" fill="none" marker-end="url(#a)">
+ <path d="M254 420 H292"/>
+ <path d="M494 420 H532"/>
+ <path d="M884 420 H922"/>
+ <path d="M1124 300 H1160"/>
+ <path d="M1252 380 V412"/>
+ </g>
+ <g stroke="#FF5A1F" stroke-width="2.5" fill="none" stroke-dasharray="7 6" marker-end="url(#o)">
+ <path d="M1252 710 V752 H1024 V664"/>
+ </g>
+ <g stroke="#16130F" stroke-width="2.5" fill="none" marker-end="url(#a)">
+ <path d="M1344 570 H1372"/>
+ </g>
+</svg>
+
+<!-- 1 brief -->
+<div class="card" style="left:64px;top:300px;width:190px;height:240px">
+ <div class="n">1</div><div class="t">Your brief</div>
+ <div class="d">Length, size, palette, the exact words, what happens when, and a "done when" list.</div>
+ <div class="mono">BRIEF.md</div>
+</div>
+<!-- 2 spec -->
+<div class="card" style="left:294px;top:300px;width:200px;height:240px">
+ <div class="n">2</div><div class="t">Spec</div>
+ <div class="d">Delivery table, exact text, look, a timed beat sheet, one checkable line per requirement.</div>
+ <div class="mono">SPEC.md</div>
+</div>
+<!-- 3 route -->
+<div class="card" style="left:534px;top:170px;width:350px;height:490px">
+ <div class="n">3</div><div class="t">Route each beat</div>
+ <div class="d" style="margin-bottom:8px">Formats guide picks the beat sheet; each beat goes to the tool that fits it.</div>
+ <div class="lane" style="top:150px"><span class="tag">2D</span><b>HyperFrames</b><i>type, UI, charts, explainers, Shorts</i></div>
+ <div class="lane" style="top:228px"><span class="tag">3D</span><b>Three.js</b><i>stylised 3D, particles, camera moves</i></div>
+ <div class="lane opt" style="top:306px"><span class="tag">optional</span><b>3D pack</b><i>CAD parts, materials, physics, explode</i></div>
+ <div class="lane opt" style="top:384px"><span class="tag">optional</span><b>Blender</b><i>photoreal products, glass, metal</i></div>
+</div>
+<!-- 4 compose -->
+<div class="card acc accbg" style="left:924px;top:170px;width:200px;height:490px">
+ <div class="n" style="background:var(--acc)">4</div><div class="t">Compose</div>
+ <div class="d" style="color:var(--ink)">HyperFrames is the spine: every layer meets on one timeline. Every frame is a function of time.</div>
+ <div class="stack">
+ <div style="top:0">Type &amp; captions</div>
+ <div style="top:42px">Charts &amp; diagrams</div>
+ <div style="top:84px">3D canvas / clips</div>
+ <div style="top:126px">Sound bed</div>
+ </div>
+ <div class="mono" style="position:absolute;left:18px;bottom:16px">render.mp4</div>
+</div>
+<!-- 5 finish -->
+<div class="card" style="left:1162px;top:170px;width:180px;height:210px">
+ <div class="n">5</div><div class="t">Finish</div>
+ <div class="d">ffmpeg: exact length, H.264 + AAC, -14 LUFS.</div>
+ <div class="mono">finish.sh</div>
+</div>
+<!-- 6 check -->
+<div class="card acc" style="left:1162px;top:414px;width:180px;height:296px">
+ <div class="n" style="background:var(--acc)">6</div><div class="t">Self-check</div>
+ <div class="d"><b style="color:var(--ink)">Measure</b> the file: PASS, WARN or FAIL.<br><b style="color:var(--ink)">Look</b> at stills at every beat. Mark each brief line met or not, with evidence.</div>
+</div>
+<div class="loop" style="left:1046px;top:762px">fix the worst miss, render again (max 3 rounds)</div>
+<!-- 7 deliver -->
+<div class="card" style="left:1374px;top:470px;width:162px;height:200px;background:var(--ink);color:var(--paper)">
+ <div class="n" style="background:var(--acc)">7</div><div class="t">Deliver</div>
+ <div class="d" style="color:#CFC7B8">Every line met.</div>
+ <div class="mono" style="background:#2A2620;color:var(--paper)">final.mp4</div>
+ <div class="mono" style="background:#2A2620;color:var(--paper)">REPORT.md</div>
+</div>
+
+<div class="foot">
+ <div class="pill"><em>Local</em>: renders on your machine</div>
+ <div class="pill"><em>macOS · Windows · Linux</em></div>
+ <div class="pill">Follow-up: <em>"Check it against the brief."</em></div>
+ <div class="pill"><em>MIT</em> licence</div>
+</div>
+</body></html>
diff --git a/docs/diagrams/render.sh b/docs/diagrams/render.sh
new file mode 100644
index 0000000..0aa2460
--- /dev/null
+++ b/docs/diagrams/render.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Render docs/diagrams/*.html to assets/*.png at 2x with headless Chrome.
+# bash docs/diagrams/render.sh # all diagrams
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+OUT="$HERE/../../assets"
+CHROME="${CHROME:-}"
+for c in "$CHROME" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" "$(command -v google-chrome || true)" "$(command -v chromium || true)"; do
+ [[ -n "$c" && -x "$c" ]] && { CHROME="$c"; break; }
+done
+[[ -x "$CHROME" ]] || { echo "render.sh: set CHROME to a Chrome or Chromium binary" >&2; exit 1; }
+for f in "$HERE"/*.html; do
+ name="$(basename "$f" .html)"
+ w="$(sed -n 's/.*body{width:\([0-9]*\)px;height:\([0-9]*\)px.*/\1/p' "$f")"
+ h="$(sed -n 's/.*body{width:\([0-9]*\)px;height:\([0-9]*\)px.*/\2/p' "$f")"
+ "$CHROME" --headless=new --disable-gpu --hide-scrollbars --force-device-scale-factor=2 \
+ --window-size="${w},${h}" --virtual-time-budget=8000 --screenshot="$OUT/$name.png" "file://$f" >/dev/null 2>&1
+ echo "wrote assets/$name.png"
+done
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..466f030
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,114 @@
+# Getting started
+
+From nothing to your first checked video. About ten minutes on a fresh machine, two if Node and ffmpeg are already installed.
+
+```mermaid
+flowchart TD
+ A[Open Claude Code or Codex] --> B{Want the agent<br/>to do the setup?}
+ B -->|yes| C["Send: Set up brief2mp4 from<br/>github.com/qualixar/brief2mp4<br/>by following its SETUP.md"]
+ B -->|no| D[Install the tools for your OS]
+ D --> E[Install the skill:<br/>plugin, install.sh or install.ps1]
+ C --> F[Agent detects OS, asks,<br/>installs, runs the doctor]
+ E --> G[Run the doctor]
+ F --> H[Test render of example 01]
+ G --> H
+ H --> I{RESULT: PASS?}
+ I -->|yes| J[Start a new session<br/>and send your brief]
+ I -->|no| K[Run the command the<br/>doctor printed, try again]
+ K --> G
+```
+
+## 1. Install the tools
+
+You need Node.js 22 or newer and ffmpeg for every video. Windows also needs Git for Windows, because the skill's scripts are bash and Git Bash runs them. Blender and Python are optional.
+
+### macOS
+
+```bash
+brew install node ffmpeg
+brew install --cask blender # optional: photoreal shots
+brew install [email protected] # optional: the 3D pack
+```
+
+No Homebrew yet? Install it from [brew.sh](https://brew.sh).
+
+### Windows (PowerShell)
+
+```powershell
+winget install -e --id OpenJS.NodeJS.LTS
+winget install -e --id Gyan.FFmpeg
+winget install -e --id Git.Git
+winget install -e --id BlenderFoundation.Blender # optional
+winget install -e --id Python.Python.3.12 # optional: the 3D pack
+```
+
+Close the terminal and open a new one so the PATH updates. `install.ps1 -InstallTools` runs the first three for you.
+
+### Ubuntu and Debian
+
+```bash
+sudo apt install -y ffmpeg git python3 python3-venv
+curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt install -y nodejs
+```
+
+Blender from [blender.org](https://www.blender.org/download): the apt package is often several versions old.
+
+## 2. Install the skill
+
+Pick one way per app. Installing both ways gives you two copies of the same skill.
+
+| Way | Command |
+|---|---|
+| Claude Code plugin | `/plugin marketplace add qualixar/brief2mp4`, then `/plugin install brief2mp4@brief2mp4` |
+| Codex plugin | `codex plugin marketplace add qualixar/brief2mp4`, then `codex plugin add brief2mp4@brief2mp4` |
+| Script, macOS or Linux | `git clone https://github.com/qualixar/brief2mp4.git && bash brief2mp4/install.sh` |
+| Script, Windows | clone the repo, then `powershell -ExecutionPolicy Bypass -File .\brief2mp4\install.ps1` |
+
+Add `--with-3d` (or `-With3D core`) for the 3D pack. See the [3D walkthrough](3d-walkthrough.md) for what it adds.
+
+## 3. Check the machine
+
+```bash
+bash brief2mp4/plugin/skills/brief2mp4/scripts/doctor.sh
+```
+
+```
+brief2mp4 doctor (macos)
+ ok node v22.22.3
+ ok ffmpeg ffmpeg version 9.0.2
+ ok ffprobe ffprobe version 9.0.2
+ ok git git version 2.54.0
+ ok blender Blender 5.2.1 LTS [optional]
+ ok python python3.13 3.13 [optional]
+ missing 3d-pack optional. Install: bash install.sh --with-3d [optional]
+RESULT: ready
+```
+
+Every required line must say `ok`. A `missing` line prints the command that fixes it. Add `--json` for a machine-readable version.
+
+## 4. Make your first video
+
+Start a new session in an empty folder (apps load skills when a session starts) and send:
+
+> Use the brief2mp4 skill to make the video in this brief: *(paste examples/01-kinetic-type/BRIEF.md)*
+
+You get `final.mp4` and `REPORT.md`. Then send:
+
+> Check it against the brief.
+
+The agent re-reads your brief line by line, shows the evidence for each line, fixes any miss and renders again.
+
+## 5. Write your own brief
+
+The checklist that makes briefs work: length and size, palette as hex codes and a font, every on-screen word exactly, what happens when (with times), sound, and a "done when" list of checkable lines. The README has a template, and the [free guide](https://qualixar.com/learn/guides/brief2mp4-guide) covers it in depth.
+
+## When something goes wrong
+
+| Symptom | Fix |
+|---|---|
+| `ffmpeg: command not found` right after a winget install | Open a new terminal. If it persists, add the `bin` folder under `%LOCALAPPDATA%\Microsoft\WinGet\Packages\Gyan.FFmpeg*` to your user PATH |
+| The agent says it cannot run `.sh` scripts on Windows | Install Git for Windows; Claude Code then uses Git Bash. From PowerShell run scripts as `& "C:\Program Files\Git\bin\bash.exe" script.sh` |
+| The skill is not found after installing | Start a new session. Apps load skills at session start |
+| `node` is older than 22 | Upgrade Node (`brew upgrade node`, or the winget/nodesource line above) |
+| Blender is installed but the doctor says missing (Windows, custom folder) | Put `blender.exe`'s folder on the PATH, or set `B2M3D_BLENDER` to its full path |
+| The render is slow | Close other heavy apps and render one video at a time; drafts use `--quality draft` |
diff --git a/examples/04-3d-product/BRIEF.md b/examples/04-3d-product/BRIEF.md
new file mode 100644
index 0000000..5a2f960
--- /dev/null
+++ b/examples/04-3d-product/BRIEF.md
@@ -0,0 +1,16 @@
+# Brief 04: 3D pack, "Everything inside."
+
+Make an 8-second 3D product shot with the optional 3D pack: the parts of a small gadget drop in and settle into a stack, the stack opens into an exploded view, and a title closes the shot. It needs the pack's `core` component (see `plugin/skills/brief2mp4/3d/README-3D.md`); no Blender and no CAD component.
+
+- Delivery: final.mp4, 1920x1080, 30 fps, exactly 8.0 s, H.264 + AAC.
+- The product: an original, generic pocket-sized sensor, no brand and no logo. Five parts, stacked from the bottom: a dark matte tray (60 x 40 x 10 mm, rounded corners, a shallow pocket in the top), a brushed-aluminium battery slab, a dark green circuit board with three small chips, a white ceramic-look cover, and a small smoked-glass lens disc on top.
+- Set: a dark neutral grey gradient background with a soft contact shadow under the parts. No visible floor edge, no horizon line.
+- Motion, 0.0 to 3.0 s: the parts fall one after another from above the frame, bottom part first, each landing on the one below with a small wobble, and settle into a neat stack. Real rigid-body physics, not hand-keyed.
+- Camera: starts wide and above, pushes in on the settled stack by 3.0 s, then pulls back to frame the whole exploded column by 5.0 s and drifts slightly closer until the end.
+- Exploded view, 3.2 to 4.6 s: the parts rise apart along the vertical axis with an ease in and out, the bottom tray staying put, each part higher than the one below. Hold the exploded view to the end.
+- At 5.3 s the title "Everything inside." appears bottom left with the line "Five parts, one pocket-sized sensor." under it, and fades out before the end. No kicker line above it.
+- Look: neutral tone mapping, a dim environment and a strong key light, bloom off, nothing glowing.
+- Sound: a quiet soundtrack with a soft low thud for each landing and a light rising sweep for the exploded view.
+- Check before the full render: snapshot at 1.2 s, 2.9 s, 3.9 s and 7.8 s and look at the frames.
+
+The worked build for this brief ships with the pack: `plugin/skills/brief2mp4/3d/examples/04-3d-product/` holds the spec (`device.py`), the physics scene, the shot JSON and `build.py`, which runs every step.
diff --git a/examples/05-2d-explainer/BRIEF.md b/examples/05-2d-explainer/BRIEF.md
new file mode 100644
index 0000000..606405f
--- /dev/null
+++ b/examples/05-2d-explainer/BRIEF.md
@@ -0,0 +1,13 @@
+# Brief 05: 2D explainer, "How a cache works"
+
+Make a 20-second 2D explainer in the style of a YouTube or course video. Flat shapes, no 3D, no photos.
+
+- Delivery: final.mp4, 1920x1080, 30 fps, exactly 20.0 s, H.264 + AAC.
+- Look: background #F4F1EA, ink #1B1A17, one accent #2F6BFF for the thing that matters, a soft grey #B9B4A8 for secondary elements. Font: Inter, bold for headlines, regular for labels.
+- 0.0 to 3.0 s (hook): the question "Why is the second visit faster?" types on, word by word, 110 px, centred.
+- 3.0 to 8.0 s (setup): a diagram builds left to right: a "Browser" box, a long arrow drawn on to a "Server" box far right. A small clock label "800 ms" appears above the arrow.
+- 8.0 to 14.0 s (idea): a "Cache" box appears between them in the accent colour. The arrow is redrawn so it stops at the cache. The clock label counts down from 800 to 12 and ends on "12 ms".
+- 14.0 to 18.0 s (example): three labels appear one by one under the diagram, each 44 px: "First visit: fetch and store", "Second visit: read the copy", "Stale? Fetch again".
+- 18.0 to 20.0 s (takeaway): everything except the cache box fades to the soft grey and the line "Keep a copy close." lands below it, 96 px, held still to the end.
+- Sound: a quiet bed with soft clicks at 3.0, 8.0 and 14.0 s.
+- Done when: every word above is spelled exactly; the final number reads "12 ms"; at 13.9 s and at 19.5 s no text overlaps any box or arrow other than a box's own label inside it; headlines are set at a font-size of at least 90 px and labels at least 40 px (font-size, as set in the CSS, not the measured glyph height); every line of text stays inside 96 px side and 54 px top and bottom margins.
diff --git a/examples/06-vertical-short/BRIEF.md b/examples/06-vertical-short/BRIEF.md
new file mode 100644
index 0000000..5c4304a
--- /dev/null
+++ b/examples/06-vertical-short/BRIEF.md
@@ -0,0 +1,23 @@
+# Brief 06: vertical Short, "3 easing rules"
+
+Make a 15-second vertical Short for YouTube Shorts, Instagram Reels and TikTok.
+
+- Delivery: final.mp4, 1080x1920, 30 fps, exactly 15.0 s, H.264 + AAC.
+- Look: background #101114, text #F7F5F0, accent #FFB224. Font: Space Grotesk Bold.
+- Safe zones: no text or dot in the top 288 px, the bottom 672 px, the left 64 px or the right 192 px. That leaves a box from x 64 to 888 and y 288 to 1248; keep every line of text at most 824 px wide, centred in that box.
+- 0.0 to 2.0 s (hook): "Your animations feel cheap?" at a font-size of 96 px, already on screen and moving in the first frame.
+- 2.0 to 4.0 s: "3 rules. 15 seconds." at 80 px.
+- 4.0 to 7.0 s: "1. Ease out to arrive". An accent dot (40 px) slides in from the left edge of the safe box and decelerates into place at the centre: power3.out over 1.2 s, starting at 4.2 s.
+- 7.0 to 10.0 s: "2. Ease in to leave". The dot starts at the centre and accelerates off to the right edge of the safe box: power3.in over 1.2 s, starting at 7.4 s.
+- 10.0 to 13.0 s: "3. Linear only for spins". The dot orbits a 160 px circle at a constant speed, one full turn every 2.0 s.
+- 13.0 to 15.0 s: "Save this." at 120 px in the accent colour; it lands by 13.3 s and holds still to the end.
+- Captions: none (the words on screen are the content).
+- Sound: a quiet bed with a tick on each beat change at 2.0, 4.0, 7.0, 10.0 and 13.0 s.
+- Done when:
+ - every line is spelled exactly;
+ - the first frame (0.0 s) already shows the hook text;
+ - in stills at 1.0, 3.0, 5.5, 8.5, 11.5 and 14.5 s, all text and the dot sit inside the safe box (check with `scripts/bounds.py --safe top=288,bottom=672,left=64,right=192`);
+ - rule 1 eases out: at 4.6 s (a third of the way through the move) the dot has covered more than half of its distance;
+ - rule 2 eases in: at 7.8 s (a third of the way through) the dot has covered less than a fifth of its distance;
+ - rule 3 is linear: stills at 10.5, 11.0 and 11.5 s show the dot advanced by the same angle (90 degrees, within 5) each time;
+ - "Save this." is fully on screen and unmoving from 13.3 s to 15.0 s.
diff --git a/install.ps1 b/install.ps1
new file mode 100644
index 0000000..b6f5820
--- /dev/null
+++ b/install.ps1
@@ -0,0 +1,139 @@
+# Install the brief2mp4 skill for Claude Code and Codex on Windows (PowerShell 5.1 or 7).
+#
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 # both apps
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -Claude # Claude Code only
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -Codex # Codex only
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -InstallTools # also winget-install Node, ffmpeg, Git
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -With3D core,cad # also the optional 3D pack
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -Uninstall
+# powershell -ExecutionPolicy Bypass -File .\install.ps1 -Uninstall -Uninstall3D # also remove the 3D pack folder
+#
+# Claude Code reads skills from %USERPROFILE%\.claude\skills (or $env:CLAUDE_CONFIG_DIR\skills).
+# Codex reads skills from %USERPROFILE%\.codex\skills (or $env:CODEX_HOME\skills).
+param(
+ [switch]$Claude,
+ [switch]$Codex,
+ [switch]$Uninstall,
+ [switch]$InstallTools,
+ [switch]$Uninstall3D,
+ [string[]]$With3D = @()
+)
+$ErrorActionPreference = 'Stop'
+
+$Name = 'brief2mp4'
+$Here = Split-Path -Parent $MyInvocation.MyCommand.Path
+$Src = Join-Path $Here "plugin\skills\$Name"
+$VersionFile = Join-Path $Here 'VERSION'
+$Version = if (Test-Path $VersionFile) { (Get-Content $VersionFile -Raw).Trim() } else { 'dev' }
+$ClaudeBase = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $env:USERPROFILE '.claude' }
+$CodexBase = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' }
+$DoClaude = -not $Codex -or $Claude
+$DoCodex = -not $Claude -or $Codex
+$Marker = ".installed-by-$Name"
+
+if (-not (Test-Path (Join-Path $Src 'SKILL.md'))) {
+ Write-Error "install.ps1: cannot find $Src\SKILL.md (run it from the repo folder)"; exit 1
+}
+
+function Remove-Ours([string]$Dest) {
+ # Only ever removes a folder this installer (or install.sh) created: it carries our marker file.
+ if ((Split-Path -Leaf $Dest) -ne $Name) { return $false }
+ if (-not (Test-Path (Join-Path $Dest $Marker))) { return $false }
+ $item = Get-Item -LiteralPath $Dest -Force
+ if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
+ # A junction or symlink: remove only the link, never the folder it points to.
+ [System.IO.Directory]::Delete($Dest)
+ } else {
+ Remove-Item -LiteralPath $Dest -Recurse -Force
+ }
+ return $true
+ return $false
+}
+
+function Install-To([string]$Base, [string]$Label) {
+ $Skills = Join-Path $Base 'skills'
+ $Dest = Join-Path $Skills $Name
+ New-Item -ItemType Directory -Force -Path $Skills | Out-Null
+ if (Test-Path $Dest) {
+ if (-not (Remove-Ours $Dest)) {
+ $Backup = "$Dest.backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
+ Move-Item $Dest $Backup
+ Write-Host " kept your existing $Name folder at $Backup"
+ }
+ }
+ Copy-Item -Recurse $Src $Dest
+ Set-Content -Path (Join-Path $Dest $Marker) -Value $Version -NoNewline
+ Write-Host " ${Label}: installed to $Dest"
+}
+
+function Uninstall-From([string]$Base, [string]$Label) {
+ $Dest = Join-Path (Join-Path $Base 'skills') $Name
+ if (-not (Test-Path $Dest)) { Write-Host " ${Label}: nothing to remove"; return }
+ if (Remove-Ours $Dest) { Write-Host " ${Label}: removed $Dest" }
+ else { Write-Host " ${Label}: $Dest was not installed by this script; left it alone" }
+}
+
+function Install-Tools {
+ if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
+ Write-Host " winget not found. Install 'App Installer' from the Microsoft Store, or install Node 22+, ffmpeg and Git for Windows by hand."
+ return
+ }
+ $Tools = @(
+ @{ Cmd = 'node'; Id = 'OpenJS.NodeJS.LTS' },
+ @{ Cmd = 'ffmpeg'; Id = 'Gyan.FFmpeg' },
+ @{ Cmd = 'git'; Id = 'Git.Git' }
+ )
+ foreach ($t in $Tools) {
+ if (Get-Command $t.Cmd -ErrorAction SilentlyContinue) { Write-Host " ok $($t.Cmd)"; continue }
+ Write-Host " installing $($t.Cmd) ($($t.Id))"
+ winget install -e --id $t.Id --accept-source-agreements --accept-package-agreements
+ }
+ Write-Host " Open a NEW terminal afterwards so the PATH picks up the new tools."
+}
+
+function Find-Bash {
+ $git = Get-Command git -ErrorAction SilentlyContinue
+ if ($git) {
+ $gitBash = Join-Path (Split-Path -Parent (Split-Path -Parent $git.Source)) 'bin\bash.exe'
+ if (Test-Path $gitBash) { return $gitBash }
+ }
+ foreach ($p in @("$env:ProgramFiles\Git\bin\bash.exe", "${env:ProgramFiles(x86)}\Git\bin\bash.exe", "$env:LOCALAPPDATA\Programs\Git\bin\bash.exe")) {
+ if ($p -and (Test-Path $p)) { return $p }
+ }
+ return $null
+}
+
+if ($Uninstall) {
+ Write-Host "Removing $Name"
+ if ($DoClaude) { Uninstall-From $ClaudeBase 'Claude Code' }
+ if ($DoCodex) { Uninstall-From $CodexBase 'Codex' }
+ if ($Uninstall3D) { & (Join-Path $Src '3d\install_3d.ps1') -Uninstall }
+ else { Write-Host " The optional 3D pack (if installed) stays in %USERPROFILE%\.brief2mp4\3d; add -Uninstall3D to remove it." }
+ exit 0
+}
+
+if ($InstallTools) { Write-Host 'Installing tools with winget'; Install-Tools; Write-Host '' }
+
+Write-Host "Installing $Name $Version"
+if ($DoClaude) { Install-To $ClaudeBase 'Claude Code' }
+if ($DoCodex) { Install-To $CodexBase 'Codex' }
+
+if ($With3D.Count -gt 0) {
+ $Components = ($With3D -join ',')
+ Write-Host ''
+ Write-Host "Installing the 3D pack (components: $Components)"
+ & (Join-Path $Src '3d\install_3d.ps1') -Components $Components
+}
+
+Write-Host ''
+$Bash = Find-Bash
+if ($Bash) {
+ & $Bash (Join-Path $Src 'scripts/doctor.sh')
+} else {
+ Write-Host 'Git Bash not found. The skill scripts are bash, so install Git for Windows:'
+ Write-Host ' winget install -e --id Git.Git (or run this script again with -InstallTools)'
+}
+
+Write-Host ''
+Write-Host 'Done. Start a new Claude Code or Codex session, then try:'
+Write-Host " Use the $Name skill to make the video in this brief: <paste a brief from examples\>"
diff --git a/install.sh b/install.sh
index c0f6b25..e2525fd 100755
--- a/install.sh
+++ b/install.sh
@@ -5,6 +5,10 @@
# bash install.sh --claude # Claude Code only
# bash install.sh --codex # Codex only
# bash install.sh --uninstall # remove from both
+# bash install.sh --uninstall --uninstall-3d # also remove the 3D pack folder
+# bash install.sh --with-3d # also install the optional 3D pack (core components)
+# bash install.sh --with-3d=core,cad # pick 3D components: core, cad, blender
+# Windows PowerShell: use install.ps1 instead.
#
# Claude Code reads skills from ~/.claude/skills (or $CLAUDE_CONFIG_DIR/skills).
# Codex reads skills from ~/.codex/skills (or $CODEX_HOME/skills).
@@ -17,13 +21,16 @@ VERSION="$(cat "$HERE/VERSION" 2>/dev/null || echo dev)"
CLAUDE_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"
CODEX_DIR="${CODEX_HOME:-$HOME/.codex}/skills"
-DO_CLAUDE=1 DO_CODEX=1 UNINSTALL=0
+DO_CLAUDE=1 DO_CODEX=1 UNINSTALL=0 UNINSTALL_3D=0 WITH_3D=""
for arg in "$@"; do
case "$arg" in
--claude) DO_CODEX=0 ;;
--codex) DO_CLAUDE=0 ;;
--uninstall) UNINSTALL=1 ;;
- -h|--help) sed -n '2,10p' "$0"; exit 0 ;;
+ --uninstall-3d) UNINSTALL_3D=1 ;;
+ --with-3d) WITH_3D="core" ;;
+ --with-3d=*) WITH_3D="${arg#--with-3d=}" ;;
+ -h|--help) sed -n '2,14p' "$0"; exit 0 ;;
*) echo "install.sh: unknown option $arg" >&2; exit 2 ;;
esac
done
@@ -72,6 +79,8 @@ if [[ "$UNINSTALL" == 1 ]]; then
echo "Removing $NAME"
[[ "$DO_CLAUDE" == 1 ]] && uninstall_from "$CLAUDE_DIR" "Claude Code"
[[ "$DO_CODEX" == 1 ]] && uninstall_from "$CODEX_DIR" "Codex"
+ if [[ "$UNINSTALL_3D" == 1 ]]; then bash "$SRC/3d/install_3d.sh" --uninstall
+ else echo " The optional 3D pack (if installed) stays in ${B2M3D_HOME:-$HOME/.brief2mp4/3d}; add --uninstall-3d to remove it."; fi
exit 0
fi
@@ -79,25 +88,15 @@ echo "Installing $NAME $VERSION"
[[ "$DO_CLAUDE" == 1 ]] && install_to "$CLAUDE_DIR" "Claude Code"
[[ "$DO_CODEX" == 1 ]] && install_to "$CODEX_DIR" "Codex"
-echo
-echo "Tools the skill uses:"
-check() {
- local cmd="$1" why="$2" fix="$3"
- if command -v "$cmd" >/dev/null 2>&1; then echo " ok $cmd ($why)"
- else echo " missing $cmd ($why). Install: $fix"; fi
-}
-check node "HyperFrames and Three.js, version 22 or newer" "https://nodejs.org or: brew install node"
-check ffmpeg "finishing and checks, needed for every video" "brew install ffmpeg (Linux: apt install ffmpeg)"
-if command -v blender >/dev/null 2>&1 || [[ -x /Applications/Blender.app/Contents/MacOS/Blender ]]; then
- echo " ok blender (only for Blender briefs)"
-else
- echo " missing blender (only for Blender briefs). Install: https://www.blender.org/download or: brew install --cask blender"
-fi
-if command -v node >/dev/null 2>&1; then
- major="$(node -v | sed 's/^v//; s/\..*//')"
- [[ "$major" -ge 22 ]] 2>/dev/null || echo " note node $(node -v) is older than 22; HyperFrames needs 22 or newer"
+if [[ -n "$WITH_3D" ]]; then
+ echo
+ echo "Installing the 3D pack (components: $WITH_3D)"
+ bash "$SRC/3d/install_3d.sh" --components "$WITH_3D"
fi
+echo
+bash "$SRC/scripts/doctor.sh" || true
+
echo
echo "Done. Start a new Claude Code or Codex session, then try:"
echo " Use the $NAME skill to make the video in this brief: <paste a brief from examples/>"
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index e7ed1d4..67e5074 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,10 +1,24 @@
{
"name": "brief2mp4",
- "version": "0.2.0",
- "description": "Turn a written brief into a finished, checked MP4 motion graphic with HyperFrames, Three.js, Blender and ffmpeg.",
- "author": { "name": "Varun Pratap Bhardwaj", "url": "https://github.com/qualixar" },
+ "version": "0.3.0",
+ "description": "Turn a written brief into a finished, checked MP4 motion graphic: HyperFrames, Three.js, an optional 3D pack (CAD, materials, physics), Blender and ffmpeg. macOS, Windows, Linux.",
+ "author": {
+ "name": "Varun Pratap Bhardwaj",
+ "url": "https://github.com/qualixar"
+ },
"homepage": "https://github.com/qualixar/brief2mp4",
"repository": "https://github.com/qualixar/brief2mp4",
"license": "MIT",
- "keywords": ["video", "motion-graphics", "hyperframes", "threejs", "blender", "ffmpeg"]
+ "keywords": [
+ "video",
+ "motion-graphics",
+ "hyperframes",
+ "threejs",
+ "blender",
+ "ffmpeg",
+ "3d",
+ "physics",
+ "agent-skills",
+ "text-to-video"
+ ]
}
diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json
index 8707c1c..b97471c 100644
--- a/plugin/.codex-plugin/plugin.json
+++ b/plugin/.codex-plugin/plugin.json
@@ -1,20 +1,37 @@
{
"name": "brief2mp4",
- "version": "0.2.0",
- "description": "Turn a written brief into a finished, checked MP4 motion graphic with HyperFrames, Three.js, Blender and ffmpeg.",
- "author": { "name": "Varun Pratap Bhardwaj", "url": "https://github.com/qualixar" },
+ "version": "0.3.0",
+ "description": "Turn a written brief into a finished, checked MP4 motion graphic: HyperFrames, Three.js, an optional 3D pack (CAD, materials, physics), Blender and ffmpeg. macOS, Windows, Linux.",
+ "author": {
+ "name": "Varun Pratap Bhardwaj",
+ "url": "https://github.com/qualixar"
+ },
"homepage": "https://github.com/qualixar/brief2mp4",
"repository": "https://github.com/qualixar/brief2mp4",
"license": "MIT",
- "keywords": ["video", "motion-graphics", "hyperframes", "threejs", "blender", "ffmpeg"],
+ "keywords": [
+ "video",
+ "motion-graphics",
+ "hyperframes",
+ "threejs",
+ "blender",
+ "ffmpeg",
+ "3d",
+ "physics",
+ "agent-skills",
+ "text-to-video"
+ ],
"skills": "./skills/",
"interface": {
"displayName": "brief2mp4",
"shortDescription": "Write a brief, get a checked MP4",
- "longDescription": "Paste a written video brief and the agent writes a spec, picks HyperFrames, Three.js or Blender, renders, finishes the file with ffmpeg, checks it against the brief and writes a report.",
+ "longDescription": "Paste a written video brief and the agent writes a spec, routes each beat to HyperFrames, Three.js, the optional 3D pack or Blender, renders, finishes the file with ffmpeg, checks every line of the brief against real frames, fixes what fails and writes a report.",
"developerName": "Varun Pratap Bhardwaj",
"category": "Productivity",
- "capabilities": ["Interactive", "Write"],
+ "capabilities": [
+ "Interactive",
+ "Write"
+ ],
"websiteURL": "https://github.com/qualixar/brief2mp4",
"composerIcon": "./assets/icon.png",
"logo": "./assets/icon.png",
diff --git a/plugin/skills/brief2mp4/3d/README-3D.md b/plugin/skills/brief2mp4/3d/README-3D.md
new file mode 100644
index 0000000..f6ed0f4
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/README-3D.md
@@ -0,0 +1,158 @@
+# The 3D pack (optional)
+
+brief2mp4 works without this folder. The pack adds one thing: when a brief asks for real 3D (a product that falls and settles, an exploded view, a turntable, a logo with depth, a path-traced hero shot), it gives you a tested command line that goes from an idea to a HyperFrames project, without hand-writing a Three.js scene each time.
+
+It is a Python module, `b2m3d`, plus a few Node helpers. Every subcommand prints one JSON result, so an agent can read what happened. Nothing here runs unless the brief needs it.
+
+## Check and install
+
+Check first. The command always exits 0 and prints one line you can branch on:
+
+```bash
+bash scripts/detect_3d.sh # macOS, Linux
+powershell -File scripts\detect_3d.ps1 # Windows
+# 3d: ready (components: core,cad,blender) or 3d: not installed
+```
+
+If it says `not installed` and the brief needs 3D, install only the components the brief needs. Nothing uses sudo or admin rights.
+
+| Component | Installs | Size (macOS, measured) | Pick it when |
+|---|---|---|---|
+| `core` | Node: three, GSAP, glTF Transform, meshoptimizer, Jolt, two fonts. Python venv: numpy, scipy, trimesh, manifold3d | about 280 MB (venv 165, node_modules 111) | any `model`, `material`, `physics`, `optimize` or `hf` work |
+| `cad` | CadQuery with the OpenCascade kernel | about 1.3 GB (large) | exact parametric CAD (fillets, assemblies); Manifold covers most shapes without it |
+| `blender` | nothing: it finds a system Blender and prints how to install one | 0 | photoreal hero shots, glass, true soft shadows, alpha renders |
+
+```bash
+# macOS and Linux
+bash 3d/install_3d.sh --components core
+bash 3d/install_3d.sh --components core,cad
+bash 3d/install_3d.sh --components blender # only checks, prints the install command
+
+# Windows (PowerShell)
+powershell -ExecutionPolicy Bypass -File 3d\install_3d.ps1 -Components core
+powershell -ExecutionPolicy Bypass -File 3d\install_3d.ps1 -Components core,cad
+```
+
+Run these from this skill's folder (or give the full path). The installer needs Node.js 20 or newer and Python 3.12 or 3.13 on the PATH (the pinned numpy and scipy need 3.12+). If one is missing it stops and prints the command that installs it. To use a specific interpreter (for example one from uv on Debian 12, which ships 3.11), set `B2M3D_PYTHON`: `B2M3D_PYTHON="$(uv python find 3.12)" bash 3d/install_3d.sh`. Remove the pack with `bash 3d/install_3d.sh --uninstall` (or `install_3d.ps1 -Uninstall`); it only deletes a folder it created. It installs into `~/.brief2mp4/3d` (Windows: `%USERPROFILE%\.brief2mp4\3d`), keeps a Python venv, a `node_modules` folder and its own copy of the pack there (so moving or deleting the clone or plugin cache does not break it), prints what it installs and the disk size, and is safe to run again: finished work is skipped. Set `B2M3D_HOME` to use another folder. Versions are pinned in `requirements-core.txt`, `requirements-cad.txt` and `package.json` (with `package-lock.json`).
+
+After install the command is `~/.brief2mp4/3d/venv/bin/brief2mp4-3d` (Windows: `venv\Scripts\brief2mp4-3d.cmd`), or `~/.brief2mp4/3d/venv/bin/python -m b2m3d` from any folder. The examples below write `b2m3d` for either form.
+
+`b2m3d doctor` reports every component as ok or missing with the exact install command for your OS. If the pack is not installed, the skill's plain Three.js template (`templates/threejs/index.html`) still works for simple 3D.
+
+## Commands
+
+```bash
+b2m3d model spec.py out.glb [--param teeth=24] [--units mm|cm|m] [--up z|y] [--smooth 30]
+b2m3d material presets
+b2m3d material assign in.glb out.glb --assign lid=brushed_aluminum --assign '*=matte_plastic'
+b2m3d material linear "#2a6f4e" # sRGB hex -> linear triple
+b2m3d optimize in.glb out.glb [--simplify 0.5] [--join] [--no-compress]
+b2m3d physics scene.json track.json # Jolt WASM bake, deterministic
+b2m3d hf shot.json project/ # self-contained HyperFrames project
+b2m3d blender in.glb frames/ --mp4 out.mp4 --look studio|dramatic|soft [--transparent] [--frames 120] [--samples 128]
+b2m3d doctor
+```
+
+**model.** A spec is a Python file with `build(params)`, and `model` runs it as Python: only use specs you wrote or trust. It may set `PARAMS` (defaults), `UNITS` and `UP`. Return a `manifold3d.Manifold`, a trimesh, or a list of `{"name", "geom", "color", "metallic", "roughness"}` parts; with the `cad` component also a CadQuery Workplane or Assembly. CAD convention is millimetres and Z up; glTF is metres and Y up, and `--units` and `--up` convert. Vertex normals are cached before export: trimesh writes them only when cached, and without them Three.js renders the model flat-shaded. Colours in a part are linear (see look rule 4).
+
+**material.** Presets are JSON files in `presets/materials/` (aluminium, steel, gold, copper, anodised blue, car paint, glossy and matte plastic, rubber, ceramic, clear and smoked glass, silicon die, circuit-board green, velvet, an emissive neon). `--assign` maps a node name (or `*` for all) to a preset or to a path of your own preset JSON. A colour you pick in sRGB must be converted to linear first: `linear = (srgb / 255) ** 2.2`. `material linear "#rrggbb"` does it. Skipping this renders dark colours about two stops too light.
+
+**physics.** `scene.json` lists bodies (`box`, `sphere`, `cylinder` or `hull` from a GLB node), gravity, fps, duration and substeps. Jolt runs once, in WASM, at a fixed step, and the result is one pose per frame. The bake is byte-for-byte repeatable, which is what lets a parallel renderer seek to any frame. Static bodies use `"motion": "static"`. A hull body takes `"glb"` (path relative to the scene file) and optionally `"node"`.
+
+**optimize.** Dedup, weld, resample, prune, optional simplify, then meshopt compression. Node names are kept, because `explode` addresses parts by node name; `--join` merges meshes and breaks that. Python readers cannot decode meshopt, so the pack decodes a temporary copy when `physics` needs the geometry.
+
+**hf.** Turns a shot JSON into a HyperFrames project folder with three.js, GSAP, fonts and every GLB copied in. A render never touches the network. The page holds the first frame until models are loaded and shaders compiled (`window.__hf.buildReady`). Unknown keys in the shot are reported in `warnings`.
+
+**blender.** Uses the system Blender (never bundled; it is GPL software run as an external program). It is found on the PATH, in `/Applications/Blender.app/Contents/MacOS/Blender`, in `C:\Program Files\Blender Foundation\Blender *\blender.exe`, or at `B2M3D_BLENDER`. GPU: Metal on macOS, OptiX then CUDA then HIP then oneAPI on Windows and Linux, else CPU (the result JSON says which). Encode: `hevc_videotoolbox` on macOS when ffmpeg has it, else `libx264`; with `--transparent` the output is ProRes 4444 (`prores_ks`, `.mov`) and the floor defaults to a shadow catcher. Run one Blender render at a time: it takes the whole GPU.
+
+## Shot JSON for `hf`
+
+```json
+{ "duration": 8, "fps": 30, "width": 1920, "height": 1080,
+ "physics": "build/track.json",
+ "models": [
+ { "src": "build/shell.glb", "track": "shell" },
+ { "src": "build/logo.glb", "spin": 14, "reveal": { "start": 0.1, "duration": 1.1 } } ],
+ "camera": { "fov": 28, "auto": { "azimuth": 30, "elevation": 26, "startPadding": 1.9, "padding": 1.05 } },
+ "ground": { "shadow": 0.5 }, "lights": "dramatic", "tonemapping": "neutral", "envIntensity": 0.35,
+ "titles": [ { "text": "Headline", "sub": "One line", "start": 5, "duration": 2.5 } ] }
+```
+
+Paths are relative to the shot file. Top level: `duration` (required), `fps`, `width`, `height`, `physics`, `models`, `camera`, `ground`, `lights`, `tonemapping`, `exposure`, `envIntensity`, `envRotation`, `hdri`, `bloom`, `bounds`, `background` (CSS), `accent`, `font` (`Inter` or `Space Grotesk`), `titles`.
+
+Model keys: `src`, `position`, `rotation` (degrees), `scale`, `track` (a body name from the physics bake) with `trackStart`, `spin` (degrees per second) with `spinOffset`, `float` (`amp`, `speed`), `reveal` (scale in: `start`, `duration`, `ease`), `explode` (`start`, `duration`, `dirs` as `{partName: [x, y, z]}` offsets in the model's own space, or `step` for an even lift of each child), and glTF animation clips, which play automatically and are seeked by time.
+
+Camera: `auto` (starts wide on the landing zone, pushes to the settled pose; it does not know about `explode`, so for an exploded finish use `keys`), `orbit` (`from`, `to`, `radius`, `height`, `ease`), or `keys` (a list of `{t, pos, target, fov, ease}`). Eases: `linear`, `inOutCubic`, `outExpo`, `inOutSine`. Lights: `"studio"`, `"dramatic"`, `"soft"`, or your own list of `{type: key|rim|fill, color, intensity, pos}`. Titles: `text`, `sub`, `kicker` (empty by default), `start`, `duration`, `size`, `position` (`bottom-left`, `top-left`, `center`, `bottom-center`). Default colours are a neutral grey gradient and a near-white accent; set `background` and `accent` to the palette you chose for the video.
+
+## What the brief says, and what to build
+
+| The brief says | Build |
+|---|---|
+| "parts fall and settle", "things drop and pile up" | One GLB per part, `physics` bake, each model with `track`, `camera.auto` (frame the landing zone, parts fall into frame). Keep drops about 0.25 m apart for parts the size of a hand; for small parts lower gravity (`"gravity": [0, -3, 0]`) reads better. |
+| "show what's inside", "exploded view", "take it apart" | `explode` with `dirs` per part, `ease` in and out, a camera `keys` pull-back so the whole column stays in frame. |
+| "turntable", "rotate it", "show every side" | `spin` on the model (degrees per second) and a fixed `orbit` or `keys` camera; or, for a photoreal one, `blender --look studio`. |
+| "hero product shot", "premium", "glass", "cinematic close-up" | `blender --look dramatic` (add `--transparent` for an overlay), then use the frames or MP4 as video inside the HyperFrames composition. |
+| "logo in 3D", "our mark with depth" | `model` a Manifold extrusion of the mark, `material assign` a preset, `reveal` plus a slow `spin` or `float`, `bloom` only if the logo glows. |
+| "floating", "hovering" | `float` on the model, `ground.shadow` low (0.3). |
+| "glowing", "neon" | an emissive preset (`neon_emissive`) and `bloom` on, the only case where bloom is right. |
+| "title over the 3D" | `titles` in the shot; they share the same paused timeline, so they seek like everything else. |
+| anything the shot keys cannot say | plain Three.js with `templates/threejs/index.html`, or write the scene by hand following `references/threejs.md`. |
+
+Snapshot every 3D shot and look at the frames before the full render:
+
+```bash
+cd project && npx --yes [email protected] lint
+npx --yes [email protected] snapshot --at 0.5,1.5,3,6,7.5 --no-end
+```
+
+Open the contact sheet. Check that the subject is in frame at every sampled time, that shadows sit under the parts, and that colours are right. Then render: `npx hyperframes render --workers 4 --quality delivery -o out.mp4`.
+
+## Look rules (each one learned from a frame that failed)
+
+1. **Tone mapping Neutral by default** (`"tonemapping": "neutral"`). Filmic curves shift product colours; Neutral keeps a green board green. In Blender use the AgX or "Khronos PBR Neutral" view.
+2. **Environment dim, key light strong.** `envIntensity` 0.3 to 0.45 with the `dramatic` rig. A bright environment flattens everything.
+3. **The floor is a shadow catcher** (`"ground": {"shadow": 0.5}`) over the CSS background. A glossy coloured floor catches the rim light as a glowing column. Set `ground.y` if parts do not rest on the lowest point of the models.
+4. **Colours in glTF are linear.** Convert sRGB with `(c / 255) ** 2.2` before you write them.
+5. **Bloom off unless something is emissive.** Specular hotspots bloom into blobs.
+6. **Physics for parts on a desk:** restitution 0.05, friction 1.0, linear damping 0.6, angular damping 0.9, drops staggered. Otherwise parts scatter far wider than they are and the framing makes them tiny.
+7. **Frame the landing zone, not the fall** (`camera.auto`), so parts fall into frame.
+8. **Depth of field off for small objects** in Blender. f/4 on a 5 cm part is a macro lens and everything goes soft.
+9. **No fixed palette.** Pick one for the video from the brief, and set `background` and `accent` to it.
+
+## Determinism contract
+
+HyperFrames seeks frames out of order across parallel Chrome workers. So every visible value is a pure function of the time `t`. Physics is baked once and replayed by lookup with interpolation between frames. The runtime uses no `Date.now`, `performance.now`, unseeded `Math.random`, `setAnimationLoop` or network fetch. If you hand-write extra JavaScript for a shot, keep to the same rules.
+
+## Gotchas already handled (do not reintroduce)
+
+- trimesh exports normals only if they are cached; otherwise Three.js is flat-shaded. `model` caches them.
+- trimesh cannot read meshopt-compressed GLBs; `physics` decodes a temporary copy.
+- `physics` hulls are convex and limited to 200 points. A part with a hollow cannot hold another part inside; stack parts instead.
+- Blender's `view_transform` and the EEVEE engine name differ between versions; the script tries each name.
+- Blender receives its config through a temporary file, because JSON on a command line is mangled by some Windows shells.
+- CadQuery's first import can take close to a minute (compiled bytecode is cached after that).
+- With no GPU, HyperFrames falls back to software WebGL: slower but correct. `--workers 4` is a safe default.
+
+## Tests
+
+`tests/run_tests.sh` at the repository root runs the fast tests (model, material, physics and project determinism, the offline check, detect and doctor). `tests/run_tests.sh --slow` adds the renders: example 04 through lint and a short 1080p render, a one-frame Blender render, and the fallback path with the pack hidden. Install `core,dev` first (the `dev` component is pytest).
+
+## Credits and licences
+
+The pack itself is MIT, like the rest of this repository. It builds on, and credits, these projects. Check each licence before you ship a video or an asset inside a product.
+
+| Project | Licence | Used for |
+|---|---|---|
+| three.js | MIT | the 3D renderer in the HyperFrames page |
+| glTF Transform (`@gltf-transform`) | MIT | materials, optimise, decompress |
+| meshoptimizer | MIT | mesh compression and simplification |
+| Jolt Physics (`jolt-physics`, JoltPhysics.js) | MIT | rigid-body bake |
+| manifold3d | Apache-2.0 | robust boolean geometry |
+| sharp and libvips | Apache-2.0 and LGPL-3.0 | image handling inside glTF Transform; installed from npm as a dependency, not bundled in this repository |
+| CadQuery (and OpenCascade through `cadquery-ocp`) | Apache-2.0 (OpenCascade is LGPL-2.1 with an exception) | optional parametric CAD |
+| trimesh | MIT | meshes, hulls, GLB export |
+| NumPy, SciPy | BSD-3-Clause | numerics |
+| GSAP | the GSAP "no charge" standard licence (gsap.com/standard-license), not MIT | the paused timeline; vendored into each render project |
+| Inter, Space Grotesk (`@fontsource-variable`) | SIL Open Font Licence 1.1 | title fonts |
+| Blender | GPL | external program for path-traced shots; not bundled, not linked |
+| HyperFrames | see its own licence | the renderer |
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/__init__.py b/plugin/skills/brief2mp4/3d/b2m3d/__init__.py
new file mode 100644
index 0000000..85fd8e2
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/__init__.py
@@ -0,0 +1,2 @@
+"""b2m3d: the optional 3D pack for the brief2mp4 skill. Every subcommand prints one JSON result."""
+__version__ = "1.0.0"
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/__main__.py b/plugin/skills/brief2mp4/3d/b2m3d/__main__.py
new file mode 100644
index 0000000..dd8a8c9
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/__main__.py
@@ -0,0 +1,5 @@
+import sys
+
+from .cli import main
+
+sys.exit(main())
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/blender.py b/plugin/skills/brief2mp4/3d/b2m3d/blender.py
new file mode 100644
index 0000000..7e52586
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/blender.py
@@ -0,0 +1,26 @@
+"""b2m3d blender: path-traced hero shots with the system Blender (Cycles on the best GPU, else CPU)."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from . import encode, paths
+from .run import B2M3DError, blender_script, last_json
+
+SCRIPT = paths.TEMPLATES / "blender_shot.py"
+
+
+def render(src: Path, out_dir: Path, *, mp4: Path | None = None, **cfg) -> dict:
+ if not src.is_file():
+ raise FileNotFoundError(f"input not found: {src}")
+ out_dir.mkdir(parents=True, exist_ok=True)
+ for old in out_dir.glob("frame_*.png"):
+ old.unlink()
+ config = {"glb": str(src.resolve()), "out_dir": str(out_dir.resolve()), **cfg}
+ result = last_json(blender_script(SCRIPT, config), "B2M3D_BLENDER")
+ frames = sorted(out_dir.glob("frame_*.png"))
+ if len(frames) != result["frames"] and not cfg.get("setup_only"):
+ raise B2M3DError(f"expected {result['frames']} frames, found {len(frames)} in {out_dir}")
+ if mp4 and frames:
+ result["video"] = encode.frames_to_video(out_dir, mp4, fps=int(cfg.get("fps", 30)),
+ alpha=bool(cfg.get("transparent")))
+ return result
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/cli.py b/plugin/skills/brief2mp4/3d/b2m3d/cli.py
new file mode 100644
index 0000000..ba274d3
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/cli.py
@@ -0,0 +1,134 @@
+"""b2m3d: the optional 3D pack for brief2mp4. Every subcommand prints one JSON result."""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+from .run import B2M3DError, last_json, node_script
+
+P = Path
+
+
+def _model(a):
+ from . import model
+ return model.build(P(a.spec), P(a.out), model.parse_params(a.param), a.units, a.up, a.tol, a.smooth)
+
+
+def _optimize(a):
+ args = [a.src, a.out, "--simplify", str(a.simplify), "--error", str(a.error)]
+ args += ["--join"] if a.join else []
+ args += ["--no-compress"] if a.no_compress else []
+ return last_json(node_script("optimize.mjs", args), "B2M3D_OPTIMIZE")
+
+
+def _material(a):
+ from . import material
+ if a.action == "presets":
+ presets = material.load_presets()
+ return {"presets": {n: p.get("description", "") for n, p in presets.items()}}
+ if a.action == "linear":
+ return {"srgb": a.src, "linear": material.srgb_to_linear(a.src)}
+ if not (a.src and a.out):
+ raise ValueError("material assign needs: in.glb out.glb --assign name=preset")
+ return material.assign(P(a.src), P(a.out), material.parse_assignments(a.assign))
+
+
+def _physics(a):
+ from . import physics
+ return physics.bake(P(a.scene), P(a.out))
+
+
+def _hf(a):
+ from . import hf
+ return hf.scaffold(P(a.shot), P(a.out))
+
+
+def _blender(a):
+ from . import blender
+ cfg = json.loads(a.config) if a.config else {}
+ given = {"frames": a.frames, "fps": a.fps, "width": a.width, "height": a.height, "engine": a.engine,
+ "samples": a.samples, "look": a.look, "transparent": a.transparent or None,
+ "save_blend": a.save_blend}
+ cfg.update({k: v for k, v in given.items() if v is not None})
+ return blender.render(P(a.src), P(a.out_dir), mp4=P(a.mp4) if a.mp4 else None, **cfg)
+
+
+def _doctor(_a):
+ from . import doctor
+ return doctor.run_all()
+
+
+def _add_model(sub) -> None:
+ s = sub.add_parser("model", help="parametric spec (CadQuery, Manifold or trimesh) -> GLB")
+ s.add_argument("spec"); s.add_argument("out")
+ s.add_argument("--param", action="append", default=[], help="key=value (JSON values ok)")
+ s.add_argument("--units", default="mm", choices=["mm", "cm", "m"])
+ s.add_argument("--up", default="z", choices=["z", "y"])
+ s.add_argument("--tol", type=float, default=0.05, help="CAD tessellation tolerance (spec units)")
+ s.add_argument("--smooth", type=float, default=None, help="smooth-shade angle in degrees")
+ s.set_defaults(fn=_model)
+
+
+def _add_assets(sub) -> None:
+ s = sub.add_parser("optimize", help="glTF Transform + meshoptimizer (dedup, weld, simplify, compress)")
+ s.add_argument("src"); s.add_argument("out")
+ s.add_argument("--simplify", type=float, default=1.0, help="keep ratio, e.g. 0.5")
+ s.add_argument("--error", type=float, default=0.001)
+ s.add_argument("--join", action="store_true", help="merge meshes (breaks per-part explode)")
+ s.add_argument("--no-compress", action="store_true", help="skip EXT_meshopt_compression")
+ s.set_defaults(fn=_optimize)
+
+ s = sub.add_parser("material", help="material presets -> glTF PBR materials")
+ s.add_argument("action", choices=["presets", "assign", "linear"])
+ s.add_argument("src", nargs="?", help="assign: in.glb; linear: '#rrggbb'")
+ s.add_argument("out", nargs="?")
+ s.add_argument("--assign", action="append", default=[], help="node=preset|file.json ('*' = all)")
+ s.set_defaults(fn=_material)
+
+ s = sub.add_parser("physics", help="bake a Jolt rigid-body scene to per-frame tracks")
+ s.add_argument("scene"); s.add_argument("out")
+ s.set_defaults(fn=_physics)
+
+
+def _add_render(sub) -> None:
+ s = sub.add_parser("hf", help="shot JSON -> self-contained HyperFrames project")
+ s.add_argument("shot"); s.add_argument("out")
+ s.set_defaults(fn=_hf)
+
+ s = sub.add_parser("blender", help="Blender Cycles/EEVEE render -> PNG frames (+ video)")
+ s.add_argument("src"); s.add_argument("out_dir")
+ s.add_argument("--mp4"); s.add_argument("--frames", type=int); s.add_argument("--fps", type=int)
+ s.add_argument("--width", type=int); s.add_argument("--height", type=int)
+ s.add_argument("--engine", choices=["cycles", "eevee"]); s.add_argument("--samples", type=int)
+ s.add_argument("--look", choices=["studio", "dramatic", "soft"])
+ s.add_argument("--transparent", action="store_true", help="alpha output (ProRes 4444 .mov)")
+ s.add_argument("--save-blend"); s.add_argument("--config", help="extra JSON config")
+ s.set_defaults(fn=_blender)
+
+ s = sub.add_parser("doctor", help="report each component as ok or missing, with install commands")
+ s.set_defaults(fn=_doctor)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(prog="b2m3d", description="Optional 3D pack for brief2mp4: model, "
+ "material, optimize, physics, HyperFrames shot, Blender render, doctor.")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ _add_model(sub)
+ _add_assets(sub)
+ _add_render(sub)
+ return ap
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ try:
+ result = args.fn(args)
+ except (B2M3DError, ValueError, KeyError, FileNotFoundError, TypeError, RuntimeError, ImportError) as exc:
+ print(json.dumps({"ok": False, "error": f"{type(exc).__name__}: {exc}"}), file=sys.stderr)
+ return 1
+ print(json.dumps(result, indent=2, default=str))
+ if args.cmd == "doctor":
+ return 0 # a report, not a check: the JSON carries ok/missing
+ return 0 if result.get("ok", True) else 2
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/doctor.py b/plugin/skills/brief2mp4/3d/b2m3d/doctor.py
new file mode 100644
index 0000000..9bcce5a
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/doctor.py
@@ -0,0 +1,93 @@
+"""b2m3d doctor: report each component as ok or missing, with the exact install command for this OS."""
+from __future__ import annotations
+
+import json
+import platform
+import shutil
+import subprocess
+from pathlib import Path
+
+from . import paths
+
+NODE_PACKAGES = ["three", "gsap", "@gltf-transform/core", "@gltf-transform/extensions",
+ "@gltf-transform/functions", "meshoptimizer", "jolt-physics",
+ "@fontsource-variable/inter", "@fontsource-variable/space-grotesk"]
+CORE_PY_MODULES = ["numpy", "scipy", "trimesh", "manifold3d"]
+BLENDER_HINTS = {
+ "darwin": "brew install --cask blender (or download from https://www.blender.org/download/)",
+ "win32": "winget install BlenderFoundation.Blender (or download from https://www.blender.org/download/)",
+ "linux": "install Blender 4.2 or newer from your package manager or https://www.blender.org/download/",
+}
+
+
+def install_command(components: str) -> str:
+ if paths.IS_WINDOWS:
+ return f'powershell -ExecutionPolicy Bypass -File "{paths.PACK / "install_3d.ps1"}" -Components {components}'
+ return f'bash "{paths.PACK / "install_3d.sh"}" --components {components}'
+
+
+def _probe(cmd: list[str], timeout: int = 60) -> tuple[bool, str]:
+ try:
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return False, str(exc)[:160]
+ text = (proc.stdout or proc.stderr).strip()
+ return proc.returncode == 0, (text.splitlines() or [""])[0][:160]
+
+
+def _node_versions() -> dict[str, str | None]:
+ out: dict[str, str | None] = {}
+ for pkg in NODE_PACKAGES:
+ pj = paths.node_modules() / pkg / "package.json"
+ out[pkg] = json.loads(pj.read_text(encoding="utf-8"))["version"] if pj.exists() else None
+ return out
+
+
+def _py_modules(modules: list[str]) -> dict[str, bool]:
+ py = paths.venv_python()
+ if not py.exists():
+ return {m: False for m in modules}
+ code = "import importlib.util as u,json;print(json.dumps({m:u.find_spec(m) is not None for m in %r}))" % modules
+ ok, text = _probe([str(py), "-c", code])
+ return json.loads(text) if ok else {m: False for m in modules}
+
+
+def check_core() -> dict:
+ node = paths.node()
+ node_pkgs = _node_versions()
+ py_mods = _py_modules(CORE_PY_MODULES)
+ missing = (([] if node else ["node on PATH (Node.js 20 or newer)"])
+ + [f"npm:{k}" for k, v in node_pkgs.items() if v is None]
+ + [f"python:{k}" for k, v in py_mods.items() if not v])
+ return {"ok": not missing, "missing": missing, "node": node, "node_packages": node_pkgs,
+ "python_modules": py_mods, "venv_python": str(paths.venv_python()),
+ "install": install_command("core")}
+
+
+def check_cad() -> dict:
+ ok = _py_modules(["cadquery"])["cadquery"]
+ return {"ok": ok, "missing": [] if ok else ["python:cadquery"], "optional": True,
+ "install": install_command("cad"), "note": "large download (OpenCascade kernel)"}
+
+
+def check_blender() -> dict:
+ exe = paths.blender()
+ version = _probe([exe, "--version"])[1] if exe else None
+ hint = BLENDER_HINTS["darwin" if paths.IS_MAC else "win32" if paths.IS_WINDOWS else "linux"]
+ return {"ok": bool(exe), "optional": True, "path": exe, "version": version,
+ "missing": [] if exe else ["blender executable"], "install": hint,
+ "note": "Blender is GPL software used as an external program; set B2M3D_BLENDER to point at a custom install"}
+
+
+def check_tools() -> dict:
+ ffmpeg = shutil.which("ffmpeg")
+ listing = subprocess.run([ffmpeg, "-hide_banner", "-encoders"], capture_output=True, text=True).stdout if ffmpeg else ""
+ return {"node": paths.node(), "npx": shutil.which("npx"), "ffmpeg": ffmpeg,
+ "hevc_videotoolbox": "hevc_videotoolbox" in listing, "libx264": "libx264" in listing,
+ "prores_ks": "prores_ks" in listing}
+
+
+def run_all() -> dict:
+ components = {"core": check_core(), "cad": check_cad(), "blender": check_blender()}
+ return {"ok": components["core"]["ok"], "home": str(paths.home()), "platform": platform.platform(),
+ "components": components, "tools": check_tools()}
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/encode.py b/plugin/skills/brief2mp4/3d/b2m3d/encode.py
new file mode 100644
index 0000000..3b58484
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/encode.py
@@ -0,0 +1,55 @@
+"""b2m3d encode: PNG frames -> video with ffmpeg, using hardware encoding only where it exists.
+
+Opaque frames -> HEVC via hevc_videotoolbox on macOS when ffmpeg has it, else H.264 (libx264).
+Frames with alpha -> ProRes 4444 (prores_ks, .mov), which editors and HyperFrames keep
+transparency in.
+"""
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+from .run import B2M3DError
+
+
+def ffmpeg_path() -> str:
+ found = shutil.which("ffmpeg")
+ if not found:
+ raise B2M3DError("ffmpeg was not found on PATH (macOS: brew install ffmpeg; "
+ "Windows: winget install ffmpeg; Linux: your package manager)")
+ return found
+
+
+def has_encoder(name: str) -> bool:
+ proc = subprocess.run([ffmpeg_path(), "-hide_banner", "-encoders"], capture_output=True, text=True)
+ return name in proc.stdout
+
+
+def pick_encoder(alpha: bool, platform: str | None = None, available=has_encoder) -> tuple[str, list[str]]:
+ """(encoder, extra ffmpeg args). Pure given `available`, so it is unit-testable."""
+ platform = platform or sys.platform
+ if alpha:
+ return "prores_ks", ["-profile:v", "4444", "-pix_fmt", "yuva444p10le"]
+ if platform == "darwin" and available("hevc_videotoolbox"):
+ return "hevc_videotoolbox", ["-q:v", "70", "-tag:v", "hvc1", "-pix_fmt", "yuv420p"]
+ return "libx264", ["-crf", "16", "-pix_fmt", "yuv420p"]
+
+
+def _ffmpeg(args: list[str]) -> None:
+ proc = subprocess.run([ffmpeg_path(), "-hide_banner", "-loglevel", "error", "-y", *args],
+ capture_output=True, text=True)
+ if proc.returncode != 0:
+ raise B2M3DError(f"ffmpeg failed: {proc.stderr[-1500:]}")
+
+
+def frames_to_video(frames_dir: Path, out: Path, fps: int = 30, alpha: bool = False) -> dict:
+ out.parent.mkdir(parents=True, exist_ok=True)
+ encoder, extra = pick_encoder(alpha)
+ if alpha:
+ out = out.with_suffix(".mov")
+ movflags = [] if alpha else ["-movflags", "+faststart"]
+ _ffmpeg(["-framerate", str(fps), "-i", str(frames_dir / "frame_%04d.png"),
+ "-c:v", encoder, *extra, *movflags, str(out)])
+ return {"path": str(out), "encoder": encoder}
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/glbio.py b/plugin/skills/brief2mp4/3d/b2m3d/glbio.py
new file mode 100644
index 0000000..9eebe9c
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/glbio.py
@@ -0,0 +1,43 @@
+"""GLB helpers: make compressed GLBs readable by Python tools.
+
+``b2m3d optimize`` writes EXT_meshopt_compression by default (small and fast in the browser),
+but trimesh cannot decode it. ``readable`` returns a plain copy when needed.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import struct
+import tempfile
+from pathlib import Path
+
+from .run import last_json, node_script
+
+COMPRESSED = {"EXT_meshopt_compression", "KHR_mesh_quantization", "KHR_draco_mesh_compression"}
+
+
+def gltf_json(path: Path) -> dict:
+ data = path.read_bytes()
+ if data[:4] != b"glTF":
+ return json.loads(data) if path.suffix == ".gltf" else {}
+ length = struct.unpack_from("<I", data, 12)[0]
+ return json.loads(data[20:20 + length])
+
+
+def is_compressed(path: Path) -> bool:
+ if path.suffix.lower() not in {".glb", ".gltf"}:
+ return False
+ return bool(COMPRESSED & set(gltf_json(path).get("extensionsUsed", [])))
+
+
+def readable(path: Path) -> Path:
+ """The path itself if plain, else a cached decompressed copy."""
+ path = Path(path).resolve()
+ if not is_compressed(path):
+ return path
+ key = hashlib.sha1(f"{path}:{path.stat().st_mtime_ns}".encode()).hexdigest()[:16]
+ out = Path(tempfile.gettempdir()) / "b2m3d-plain" / f"{path.stem}-{key}.glb"
+ if not out.exists():
+ out.parent.mkdir(parents=True, exist_ok=True)
+ last_json(node_script("decompress.mjs", [str(path), str(out)]), "B2M3D_DECOMPRESS")
+ return out
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/hf.py b/plugin/skills/brief2mp4/3d/b2m3d/hf.py
new file mode 100644
index 0000000..a30c561
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/hf.py
@@ -0,0 +1,130 @@
+"""b2m3d hf: turn a shot JSON into a self-contained, frame-seekable HyperFrames project.
+
+The project vendors three.js, GSAP, fonts and every GLB, so a render never touches the
+network, and every frame is a pure function of time (see templates/shot-runtime.js).
+Titles are GSAP tweens on the same paused timeline.
+"""
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+from . import paths
+from .hf_html import FONTS, render_html
+from .run import B2M3DError
+
+THREE_FILES = ["build/three.module.js", "build/three.core.js"]
+THREE_ADDONS = ["loaders/GLTFLoader.js", "loaders/HDRLoader.js", "libs/meshopt_decoder.module.js",
+ "environments/RoomEnvironment.js", "postprocessing", "shaders", "utils"]
+
+SHOT_KEYS = {"name", "duration", "fps", "width", "height", "physics", "models", "camera", "ground",
+ "lights", "tonemapping", "exposure", "envIntensity", "envRotation", "hdri", "bloom",
+ "bounds", "background", "accent", "font", "titles"}
+MODEL_KEYS = {"src", "position", "rotation", "scale", "track", "trackStart", "spin", "spinOffset",
+ "float", "reveal", "explode"}
+TITLE_KEYS = {"text", "kicker", "sub", "start", "duration", "size", "position"}
+
+
+def _num(value) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def validate(shot: dict, physics: dict | None) -> list[str]:
+ """Raise ValueError on a shot that cannot render; return warnings (unknown keys)."""
+ errors: list[str] = []
+ if not _num(shot.get("duration")) or shot["duration"] <= 0:
+ errors.append("'duration' must be a number of seconds above 0")
+ for key in ("width", "height", "fps"):
+ if not isinstance(shot.get(key), int) or shot[key] <= 0:
+ errors.append(f"'{key}' must be a positive integer")
+ models = shot.get("models")
+ if not isinstance(models, list) or not models:
+ errors.append("'models' must be a non-empty list of {src, ...}")
+ for i, m in enumerate(models if isinstance(models, list) else []):
+ if not isinstance(m, dict) or not isinstance(m.get("src"), str):
+ errors.append(f"models[{i}] needs a 'src' path to a .glb")
+ elif m.get("track") and (physics is None or m["track"] not in physics.get("tracks", {})):
+ errors.append(f"models[{i}].track '{m['track']}' is not in the physics bake "
+ f"(set shot 'physics' to the track.json from `b2m3d physics`)")
+ for i, t in enumerate(shot.get("titles", [])):
+ if not isinstance(t, dict) or not t.get("text") or not _num(t.get("start")) or not _num(t.get("duration")):
+ errors.append(f"titles[{i}] needs 'text', 'start' and 'duration'")
+ if errors:
+ raise ValueError("invalid shot JSON: " + "; ".join(errors))
+ return _unknown_keys(shot)
+
+
+def _unknown_keys(shot: dict) -> list[str]:
+ warnings = [f"unknown shot key '{k}' (ignored)" for k in shot if k not in SHOT_KEYS]
+ for i, m in enumerate(shot["models"]):
+ warnings += [f"unknown key '{k}' in models[{i}] (ignored)" for k in m if k not in MODEL_KEYS]
+ for i, t in enumerate(shot.get("titles", [])):
+ warnings += [f"unknown key '{k}' in titles[{i}] (ignored)" for k in t if k not in TITLE_KEYS]
+ return warnings
+
+
+def _copy(src: Path, dst: Path) -> None:
+ if not src.exists():
+ raise B2M3DError(f"missing file {src}. Is the `core` component installed? "
+ f"Run: {paths.PACK / 'install_3d.sh'} --components core")
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ if src.is_dir():
+ shutil.copytree(src, dst, dirs_exist_ok=True)
+ else:
+ shutil.copy2(src, dst)
+
+
+def vendor(out: Path) -> None:
+ nm = paths.node_modules()
+ three = nm / "three"
+ for f in THREE_FILES:
+ _copy(three / f, out / "vendor/three" / f)
+ for f in THREE_ADDONS:
+ _copy(three / "examples/jsm" / f, out / "vendor/three/addons" / f)
+ for rel in FONTS.values():
+ _copy(nm / rel, out / "fonts" / Path(rel).name)
+ _copy(nm / "gsap/dist/gsap.min.js", out / "vendor/gsap.min.js")
+ _copy(paths.TEMPLATES / "shot-runtime.js", out / "b2m3d-runtime.js")
+
+
+def _asset_name(src: Path, taken: dict[str, Path]) -> str:
+ """Keep the file name; add a counter when two different files share it."""
+ name, n = src.name, 1
+ while name in taken and taken[name] != src:
+ n += 1
+ name = f"{src.stem}-{n}{src.suffix}"
+ taken[name] = src
+ return name
+
+
+def _assets(shot: dict, base: Path, out: Path) -> dict:
+ taken: dict[str, Path] = {}
+ models = []
+ for m in shot["models"]:
+ src = (base / m["src"]).resolve()
+ if not src.is_file():
+ raise FileNotFoundError(f"model not found: {src}")
+ name = _asset_name(src, taken)
+ _copy(src, out / "assets" / name)
+ models.append({**m, "src": f"assets/{name}"})
+ shot = {**shot, "models": models}
+ if shot.get("hdri"):
+ src = (base / shot["hdri"]).resolve()
+ name = _asset_name(src, taken)
+ _copy(src, out / "assets" / name)
+ shot = {**shot, "hdri": f"assets/{name}"}
+ return shot
+
+
+def scaffold(shot_path: Path, out: Path) -> dict:
+ shot = {"width": 1920, "height": 1080, "fps": 30, **json.loads(shot_path.read_text(encoding="utf-8"))}
+ base = shot_path.parent
+ physics = json.loads((base / shot["physics"]).read_text(encoding="utf-8")) if shot.get("physics") else None
+ warnings = validate(shot, physics)
+ out.mkdir(parents=True, exist_ok=True)
+ vendor(out)
+ shot = _assets(shot, base, out)
+ (out / "index.html").write_text(render_html(shot, physics), encoding="utf-8")
+ return {"out": str(out), "models": len(shot["models"]), "duration": shot["duration"],
+ "physics_bodies": len(physics["tracks"]) if physics else 0, "warnings": warnings}
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/hf_html.py b/plugin/skills/brief2mp4/3d/b2m3d/hf_html.py
new file mode 100644
index 0000000..a785c23
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/hf_html.py
@@ -0,0 +1,111 @@
+"""HTML for a b2m3d HyperFrames project: stage, titles and one paused GSAP timeline."""
+from __future__ import annotations
+
+import html
+import json
+from pathlib import Path
+
+FONTS = {"Inter": "@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
+ "Space Grotesk": "@fontsource-variable/space-grotesk/files/space-grotesk-latin-wght-normal.woff2"}
+
+DEFAULT_BACKGROUND = "radial-gradient(120% 90% at 50% 35%, #2a2d35 0%, #0d0e11 72%)"
+DEFAULT_ACCENT = "#e6e8ee"
+DEFAULT_FONT = "Inter"
+
+TITLE_POS = {
+ "bottom-left": "left:7%;bottom:11%;text-align:left;",
+ "top-left": "left:7%;top:10%;text-align:left;",
+ "center": "left:0;right:0;top:42%;text-align:center;",
+ "bottom-center": "left:0;right:0;bottom:10%;text-align:center;",
+}
+
+
+def js_json(value) -> str:
+ """JSON that is safe inside a <script> element."""
+ return json.dumps(value).replace("</", "<\\/").replace("<!--", "<\\!--")
+
+
+def font_faces() -> str:
+ return "\n".join(
+ f'@font-face{{font-family:"{name}";src:url("fonts/{Path(rel).name}") format("woff2");'
+ f'font-weight:100 900;font-display:block;}}' for name, rel in FONTS.items())
+
+
+def _title_block(i: int, t: dict) -> tuple[str, list[str]]:
+ pos = TITLE_POS.get(t.get("position", "bottom-left"), TITLE_POS["bottom-left"])
+ kicker, sub = t.get("kicker", ""), t.get("sub", "")
+ ids = []
+ parts = []
+ if kicker:
+ parts.append(f'<div class="b2m3d-kicker" id="b2m3d-kick-{i}">{html.escape(kicker)}</div>')
+ ids.append(f"#b2m3d-kick-{i}")
+ parts.append(f'<div class="b2m3d-head" id="b2m3d-head-{i}" style="font-size:{int(t.get("size", 84))}px">'
+ f'{html.escape(t["text"])}</div>')
+ ids.append(f"#b2m3d-head-{i}")
+ if sub:
+ parts.append(f'<div class="b2m3d-sub" id="b2m3d-sub-{i}">{html.escape(sub)}</div>')
+ ids.append(f"#b2m3d-sub-{i}")
+ block = f'<div class="b2m3d-title" id="b2m3d-title-{i}" style="{pos}">{"".join(parts)}</div>'
+ return block, ids
+
+
+def titles_html(titles: list[dict]) -> tuple[str, str]:
+ """(markup, gsap tweens). Titles share the scene's paused timeline, so they seek like everything else."""
+ blocks, tweens = [], []
+ for i, t in enumerate(titles):
+ block, ids = _title_block(i, t)
+ blocks.append(block)
+ start, dur = float(t["start"]), float(t["duration"])
+ for j, sel in enumerate(ids):
+ tweens.append(f'tl.fromTo("{sel}",{{y:38,opacity:0}},{{y:0,opacity:1,duration:0.7,'
+ f'ease:"power3.out"}},{start + 0.08 * j:.3f});')
+ tweens.append(f'tl.to("#b2m3d-title-{i}",{{opacity:0,y:-18,duration:0.45,ease:"power2.in"}},'
+ f'{max(start, start + dur - 0.45):.3f});')
+ return "\n".join(blocks), "\n".join(tweens)
+
+
+def render_html(shot: dict, physics: dict | None) -> str:
+ w, h, dur = shot["width"], shot["height"], shot["duration"]
+ bg = shot.get("background", DEFAULT_BACKGROUND)
+ accent = shot.get("accent", DEFAULT_ACCENT)
+ head_font = shot.get("font", DEFAULT_FONT)
+ blocks, tweens = titles_html(shot.get("titles", []))
+ return f"""<!doctype html>
+<html lang="en"><head><meta charset="UTF-8" />
+<meta name="viewport" content="width={w}, height={h}" />
+<title>{html.escape(shot.get("name", "b2m3d shot"))}</title>
+<script src="vendor/gsap.min.js"></script>
+<script type="importmap">{{"imports":{{"three":"./vendor/three/build/three.module.js","three/addons/":"./vendor/three/addons/"}}}}</script>
+<style>
+{font_faces()}
+body{{margin:0;background:#000;}}
+#root{{position:relative;width:100%;height:100%;overflow:hidden;}}
+.b2m3d-stage{{position:absolute;inset:0;}}
+.b2m3d-bg{{position:absolute;inset:0;background:{bg};}}
+#b2m3d-canvas{{position:absolute;inset:0;width:100%;height:100%;display:block;}}
+.b2m3d-title{{position:absolute;color:#f4f5f7;font-family:"Inter";max-width:80%;}}
+.b2m3d-kicker{{font-family:"Inter";font-weight:600;font-size:26px;letter-spacing:.22em;text-transform:uppercase;color:{accent};margin-bottom:14px;}}
+.b2m3d-head{{font-family:"{head_font}";font-weight:700;line-height:1.02;letter-spacing:-.02em;}}
+.b2m3d-sub{{font-family:"Inter";font-weight:400;font-size:34px;color:#c9ccd3;margin-top:18px;}}
+</style></head>
+<body>
+<div id="root" data-composition-id="b2m3d" data-start="0" data-width="{w}" data-height="{h}" data-duration="{dur}">
+ <div id="b2m3d-stage" class="b2m3d-stage">
+ <div class="b2m3d-bg" id="b2m3d-bg"></div>
+ <canvas id="b2m3d-canvas" width="{w}" height="{h}"></canvas>
+ {blocks}
+ </div>
+</div>
+<script>
+window.B2M3D_SHOT = {js_json(shot)};
+window.B2M3D_PHYSICS = {js_json(physics) if physics else "null"};
+window.__timelines = window.__timelines || {{}};
+const tl = gsap.timeline({{ paused: true }});
+tl.to({{}}, {{ duration: {dur} }}, 0);
+{tweens}
+tl.eventCallback("onUpdate", () => window.__b2m3dRenderAt && window.__b2m3dRenderAt(tl.time()));
+window.__timelines["b2m3d"] = tl;
+</script>
+<script type="module" src="b2m3d-runtime.js"></script>
+</body></html>
+"""
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/material.py b/plugin/skills/brief2mp4/3d/b2m3d/material.py
new file mode 100644
index 0000000..d932f09
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/material.py
@@ -0,0 +1,98 @@
+"""b2m3d material: named presets -> glTF PBR materials (+ KHR extensions), applied by node name.
+
+Presets are plain JSON in presets/materials/ with LINEAR colours, which is what glTF expects.
+A colour picked in sRGB must be converted first: ``linear = (srgb / 255) ** 2.2``
+(``b2m3d material linear "#rrggbb"`` does it). Skipping this renders dark colours about two
+stops too light. Extensions written: clearcoat, transmission (+ volume), ior,
+emissive_strength and sheen, which three.js and Blender's glTF importer both read.
+"""
+from __future__ import annotations
+
+import json
+import re
+import tempfile
+from pathlib import Path
+
+from . import paths
+from .run import B2M3DError, last_json, node_script
+
+SRGB_GAMMA = 2.2
+
+
+def srgb_to_linear(hex_color: str) -> list[float]:
+ """'#1a2b3c' -> linear [r, g, b] using the pure 2.2 power curve."""
+ m = re.fullmatch(r"#?([0-9a-fA-F]{6})", hex_color.strip())
+ if not m:
+ raise ValueError(f"expected a #rrggbb colour, got {hex_color!r}")
+ raw = m.group(1)
+ return [round((int(raw[i:i + 2], 16) / 255) ** SRGB_GAMMA, 5) for i in (0, 2, 4)]
+
+
+def load_presets(folder: Path | None = None) -> dict[str, dict]:
+ folder = folder or paths.PRESETS
+ return {p.stem: json.loads(p.read_text(encoding="utf-8")) for p in sorted(folder.glob("*.json"))}
+
+
+def to_gltf(preset: dict, name: str | None = None) -> dict:
+ """Preset JSON -> glTF material JSON (core metallic-roughness + KHR extensions)."""
+ mat: dict = {
+ "name": name or preset["name"],
+ "baseColorFactor": [*preset["baseColor"], 1.0],
+ "metallicFactor": preset.get("metallic", 0.0),
+ "roughnessFactor": preset.get("roughness", 0.5),
+ "extensions": {},
+ }
+ ext = mat["extensions"]
+ if preset.get("clearcoat", 0) > 0:
+ ext["KHR_materials_clearcoat"] = {"clearcoatFactor": preset["clearcoat"],
+ "clearcoatRoughnessFactor": preset.get("clearcoatRoughness", 0.1)}
+ if preset.get("transmission", 0) > 0:
+ ext["KHR_materials_transmission"] = {"transmissionFactor": preset["transmission"]}
+ ext["KHR_materials_volume"] = {"thicknessFactor": 0.01}
+ if "ior" in preset:
+ ext["KHR_materials_ior"] = {"ior": preset["ior"]}
+ if preset.get("emissiveStrength", 0) > 0:
+ mat["emissiveFactor"] = list(preset.get("emissive", (1, 1, 1)))
+ ext["KHR_materials_emissive_strength"] = {"emissiveStrength": preset["emissiveStrength"]}
+ if preset.get("sheen", 0) > 0:
+ color = preset.get("sheenColor", (1, 1, 1))
+ ext["KHR_materials_sheen"] = {"sheenColorFactor": [c * preset["sheen"] for c in color],
+ "sheenRoughnessFactor": preset.get("sheenRoughness", 0.3)}
+ return mat
+
+
+def resolve(spec: str) -> dict:
+ """'gold' (a preset) or 'path/to/preset.json' -> glTF material JSON."""
+ path = Path(spec)
+ if path.suffix == ".json" and path.exists():
+ return to_gltf(json.loads(path.read_text(encoding="utf-8")), path.stem)
+ presets = load_presets()
+ if spec in presets:
+ return to_gltf(presets[spec], spec)
+ raise KeyError(f"unknown material {spec!r}; presets: {', '.join(presets)}")
+
+
+def parse_assignments(pairs: list[str]) -> dict[str, str]:
+ out = {}
+ for pair in pairs:
+ key, sep, val = pair.partition("=")
+ if not sep or not key or not val:
+ raise ValueError(f"--assign expects name=preset (or '*=preset'), got {pair!r}")
+ out[key] = val
+ return out
+
+
+def assign(src: Path, out: Path, mapping: dict[str, str]) -> dict:
+ """mapping: node/mesh name (or '*') -> preset name or preset .json. Applied with glTF Transform."""
+ if not mapping:
+ raise B2M3DError("nothing to assign: pass --assign name=preset")
+ resolved = {k: resolve(v) for k, v in mapping.items()}
+ out.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as fh:
+ json.dump(resolved, fh)
+ tmp = Path(fh.name)
+ try:
+ stdout = node_script("material_apply.mjs", [str(src), str(out), str(tmp)])
+ finally:
+ tmp.unlink(missing_ok=True)
+ return last_json(stdout, "B2M3D_MATERIAL")
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/model.py b/plugin/skills/brief2mp4/3d/b2m3d/model.py
new file mode 100644
index 0000000..a406d6d
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/model.py
@@ -0,0 +1,158 @@
+"""b2m3d model: run a parametric spec (CadQuery / Manifold / trimesh) and write a GLB.
+
+Spec contract: a Python file with ``build(params: dict)`` returning any of
+ manifold3d.Manifold, trimesh.Trimesh, trimesh.Scene, cadquery Workplane / Shape / Assembly
+ (CadQuery is the optional ``cad`` component), or a list of Part dicts
+ {"name", "geom", "color", "metallic", "roughness"}.
+The file may also set PARAMS (defaults), UNITS ("mm" | "cm" | "m") and UP ("z" | "y").
+CAD convention is millimetres, Z-up; glTF is metres, Y-up. ``units``/``up`` convert.
+Colours in a Part are LINEAR RGBA (see README-3D.md for the sRGB conversion).
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import trimesh
+
+from .run import B2M3DError
+
+Z_UP_TO_Y_UP = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
+UNIT_SCALE = {"mm": 0.001, "cm": 0.01, "m": 1.0}
+DEFAULT_COLOR = (0.8, 0.8, 0.82, 1.0)
+
+
+@dataclass(frozen=True)
+class Part:
+ name: str
+ mesh: trimesh.Trimesh
+ color: tuple[float, float, float, float] = DEFAULT_COLOR
+ metallic: float = 0.0
+ roughness: float = 0.5
+
+
+def load_spec(path: Path):
+ spec = importlib.util.spec_from_file_location(f"b2m3d_spec_{path.stem}", path)
+ if spec is None or spec.loader is None:
+ raise ValueError(f"cannot import spec {path}")
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ if not hasattr(mod, "build"):
+ raise ValueError(f"{path} must define build(params)")
+ return mod
+
+
+def _cq_shape_to_mesh(shape: Any, tol: float) -> trimesh.Trimesh:
+ verts, tris = shape.tessellate(tol, 0.2)
+ v = np.array([(p.x, p.y, p.z) for p in verts], dtype=np.float64)
+ f = np.array(tris, dtype=np.int64)
+ return trimesh.Trimesh(v, f, process=False)
+
+
+def _cq_to_parts(obj: Any, name: str, tol: float) -> list[Part]:
+ try:
+ import cadquery as cq
+ except ImportError as exc:
+ raise B2M3DError("this spec returns a CadQuery object but the `cad` component is not "
+ "installed (run `python -m b2m3d doctor` for the command)") from exc
+ if isinstance(obj, cq.Assembly):
+ parts = []
+ for shape, pname, loc, color in obj: # flattened traversal
+ moved = shape.moved(loc) if loc is not None else shape
+ rgba = tuple(color.toTuple()) if color is not None else DEFAULT_COLOR
+ parts.append(Part(pname or name, _cq_shape_to_mesh(moved, tol), rgba))
+ return parts
+ if isinstance(obj, cq.Workplane):
+ shapes = [s for s in obj.vals() if isinstance(s, cq.Shape)]
+ obj = cq.Compound.makeCompound(shapes)
+ return [Part(name, _cq_shape_to_mesh(obj, tol))]
+
+
+def _manifold_to_mesh(m: Any) -> trimesh.Trimesh:
+ mesh = m.to_mesh()
+ v = np.asarray(mesh.vert_properties)[:, :3]
+ f = np.asarray(mesh.tri_verts)
+ return trimesh.Trimesh(v, f, process=False)
+
+
+def _dict_part(item: dict, tol: float, name: str, index: int) -> list[Part]:
+ pname = item.get("name", f"{name}_{index}")
+ base = to_parts(item["geom"], tol, pname)
+ return [Part(pname if len(base) == 1 else p.name, p.mesh,
+ tuple(item.get("color", p.color)),
+ float(item.get("metallic", p.metallic)),
+ float(item.get("roughness", p.roughness))) for p in base]
+
+
+def to_parts(obj: Any, tol: float = 0.05, name: str = "part") -> list[Part]:
+ if isinstance(obj, list):
+ out: list[Part] = []
+ for i, item in enumerate(obj):
+ out += _dict_part(item, tol, name, i) if isinstance(item, dict) else to_parts(item, tol, f"{name}_{i}")
+ return out
+ if isinstance(obj, trimesh.Trimesh):
+ return [Part(name, obj)]
+ if isinstance(obj, trimesh.Scene):
+ return [Part(m.metadata.get("name", f"{name}_{i}"), m) for i, m in enumerate(obj.dump())]
+ module = type(obj).__module__
+ if module.startswith("manifold3d"):
+ return [Part(name, _manifold_to_mesh(obj))]
+ if module.startswith(("cadquery", "OCP")):
+ return _cq_to_parts(obj, name, tol)
+ raise TypeError(f"build() returned unsupported type {type(obj)!r}")
+
+
+def _material(p: Part) -> trimesh.visual.material.PBRMaterial:
+ rgba = [int(round(c * 255)) for c in (list(p.color) + [1.0])[:4]]
+ return trimesh.visual.material.PBRMaterial(
+ name=f"{p.name}_mat", baseColorFactor=rgba,
+ metallicFactor=p.metallic, roughnessFactor=p.roughness)
+
+
+def write_glb(parts: list[Part], out: Path, units: str = "mm", up: str = "z",
+ smooth_angle: float | None = None) -> dict:
+ scene = trimesh.Scene()
+ xf = np.eye(4)
+ xf[:3, :3] *= UNIT_SCALE[units]
+ if up == "z":
+ xf = Z_UP_TO_Y_UP @ xf
+ for p in parts:
+ mesh = p.mesh.copy()
+ mesh.apply_transform(xf)
+ if smooth_angle is not None:
+ mesh = trimesh.graph.smooth_shade(mesh, angle=np.radians(smooth_angle))
+ _ = mesh.vertex_normals # cache them: they are only exported when cached, and three.js goes flat-shaded without
+ mesh.visual = trimesh.visual.TextureVisuals(material=_material(p))
+ scene.add_geometry(mesh, node_name=p.name, geom_name=p.name)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ scene.export(out)
+ lo, hi = scene.bounds
+ return {"out": str(out), "parts": len(parts),
+ "triangles": int(sum(len(p.mesh.faces) for p in parts)),
+ "bounds_m": [lo.round(4).tolist(), hi.round(4).tolist()]}
+
+
+def build(spec_path: Path, out: Path, params: dict | None = None, units: str = "mm",
+ up: str = "z", tol: float = 0.05, smooth_angle: float | None = None) -> dict:
+ mod = load_spec(spec_path)
+ defaults = getattr(mod, "PARAMS", {})
+ result = mod.build({**defaults, **(params or {})})
+ parts = to_parts(result, tol, spec_path.stem)
+ return write_glb(parts, out, getattr(mod, "UNITS", units), getattr(mod, "UP", up), smooth_angle)
+
+
+def parse_params(raw: list[str]) -> dict:
+ out: dict = {}
+ for item in raw:
+ key, sep, val = item.partition("=")
+ if not sep:
+ raise ValueError(f"--param expects key=value, got {item!r}")
+ try:
+ out[key] = json.loads(val)
+ except json.JSONDecodeError:
+ out[key] = val
+ return out
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/paths.py b/plugin/skills/brief2mp4/3d/b2m3d/paths.py
new file mode 100644
index 0000000..d564486
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/paths.py
@@ -0,0 +1,73 @@
+"""Where the 3D pack lives, and where its installed components live.
+
+PACK the folder this package ships in (js helpers, templates, presets).
+home() the install folder with the venv and node_modules: ``B2M3D_HOME`` if set,
+ else ``~/.brief2mp4/3d`` (Windows: ``%USERPROFILE%\\.brief2mp4\\3d``).
+Everything is resolved at call time so a test or a user can point B2M3D_HOME elsewhere.
+"""
+from __future__ import annotations
+
+import glob
+import os
+import re
+import shutil
+import sys
+from pathlib import Path
+
+PACK = Path(__file__).resolve().parent.parent
+PRESETS = PACK / "presets" / "materials"
+TEMPLATES = PACK / "templates"
+IS_WINDOWS = os.name == "nt"
+IS_MAC = sys.platform == "darwin"
+
+
+def home() -> Path:
+ env = os.environ.get("B2M3D_HOME")
+ return Path(env).expanduser() if env else Path.home() / ".brief2mp4" / "3d"
+
+
+def venv_python() -> Path:
+ sub = ("Scripts", "python.exe") if IS_WINDOWS else ("bin", "python")
+ return home().joinpath("venv", *sub)
+
+
+def node_modules() -> Path:
+ return home() / "node_modules"
+
+
+def js_dir() -> Path:
+ """node resolves ESM imports from the script's own folder upward, so the helpers
+ are copied next to node_modules (see run.sync_js)."""
+ return home() / "js"
+
+
+def node() -> str | None:
+ return shutil.which("node")
+
+
+def _version_key(path: str) -> tuple[int, ...]:
+ """'.../Blender 4.2/blender.exe' -> (4, 2), so the newest install sorts first."""
+ return tuple(int(n) for n in re.findall(r"\d+", Path(path).parent.name))
+
+
+def _blender_candidates() -> list[str]:
+ if IS_MAC:
+ return ["/Applications/Blender.app/Contents/MacOS/Blender"]
+ if IS_WINDOWS:
+ roots = {os.environ.get("ProgramFiles", r"C:\Program Files"), r"C:\Program Files"}
+ found: list[str] = []
+ for root in sorted(roots):
+ found += glob.glob(str(Path(root) / "Blender Foundation" / "Blender *" / "blender.exe"))
+ return sorted(found, key=_version_key, reverse=True)
+ return ["/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/opt/blender/blender"]
+
+
+def blender() -> str | None:
+ """B2M3D_BLENDER, then PATH, then the usual install folders of this OS."""
+ env = os.environ.get("B2M3D_BLENDER")
+ if env and Path(env).exists():
+ return env
+ on_path = shutil.which("blender")
+ if on_path:
+ return on_path
+ return next((c for c in _blender_candidates() if Path(c).exists()), None)
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/physics.py b/plugin/skills/brief2mp4/3d/b2m3d/physics.py
new file mode 100644
index 0000000..2e8d746
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/physics.py
@@ -0,0 +1,52 @@
+"""b2m3d physics: prepare a scene (hulls from GLB nodes) and bake it with Jolt (WASM)."""
+from __future__ import annotations
+
+import json
+import tempfile
+from pathlib import Path
+
+import numpy as np
+import trimesh
+
+from .glbio import readable
+from .run import last_json, node_script
+
+MAX_HULL_POINTS = 200
+
+
+def hull_points(glb: Path, node: str | None, max_points: int = MAX_HULL_POINTS) -> list[list[float]]:
+ """Convex-hull vertices of one node (or the whole file) in metres, in the model's own space."""
+ scene = trimesh.load(readable(glb), force="scene")
+ meshes = []
+ for name in scene.graph.nodes_geometry:
+ if node is None or name == node or name.split("/")[-1] == node:
+ xf, geom = scene.graph[name]
+ meshes.append(scene.geometry[geom].copy().apply_transform(xf))
+ if not meshes:
+ raise KeyError(f"node {node!r} not found in {glb}")
+ pts = np.asarray(trimesh.util.concatenate(meshes).convex_hull.vertices)
+ if len(pts) > max_points:
+ pts = pts[np.linspace(0, len(pts) - 1, max_points).astype(int)]
+ return pts.round(6).tolist()
+
+
+def prepare(scene: dict, base: Path) -> dict:
+ bodies = []
+ for b in scene["bodies"]:
+ if b.get("shape") == "hull" and "points" not in b:
+ b = {**b, "points": hull_points((base / b["glb"]).resolve(), b.get("node"))}
+ bodies.append(b)
+ return {**scene, "bodies": bodies}
+
+
+def bake(scene_path: Path, out: Path) -> dict:
+ scene = json.loads(scene_path.read_text(encoding="utf-8"))
+ ready = prepare(scene, scene_path.parent)
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as fh:
+ json.dump(ready, fh)
+ tmp = Path(fh.name)
+ try:
+ out.parent.mkdir(parents=True, exist_ok=True)
+ return last_json(node_script("jolt_bake.mjs", [str(tmp), str(out)]), "B2M3D_PHYSICS")
+ finally:
+ tmp.unlink(missing_ok=True)
diff --git a/plugin/skills/brief2mp4/3d/b2m3d/run.py b/plugin/skills/brief2mp4/3d/b2m3d/run.py
new file mode 100644
index 0000000..269314a
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/b2m3d/run.py
@@ -0,0 +1,74 @@
+"""Subprocess helpers: run node scripts and Blender with clear errors."""
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+from . import paths
+
+
+class B2M3DError(RuntimeError):
+ """A step failed; the message says which tool and why."""
+
+
+def run(cmd: list[str], *, cwd: Path | None = None, timeout: int = 3600,
+ env: dict[str, str] | None = None) -> str:
+ merged = {**os.environ, **(env or {})}
+ try:
+ proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=merged)
+ except FileNotFoundError as exc:
+ raise B2M3DError(f"cannot run {cmd[0]}: {exc}") from exc
+ except subprocess.TimeoutExpired as exc:
+ raise B2M3DError(f"{Path(cmd[0]).name} timed out after {timeout}s") from exc
+ if proc.returncode != 0:
+ tail = (proc.stderr or proc.stdout)[-2000:]
+ raise B2M3DError(f"{Path(cmd[0]).name} exited {proc.returncode}:\n{tail}")
+ return proc.stdout
+
+
+def sync_js() -> Path:
+ """Copy the pack's .mjs helpers next to node_modules (only when they differ)."""
+ if not paths.node_modules().is_dir():
+ raise B2M3DError(f"node components are not installed in {paths.home()}. Run: "
+ f"{paths.PACK / 'install_3d.sh'} --components core")
+ dest = paths.js_dir()
+ dest.mkdir(parents=True, exist_ok=True)
+ for src in (paths.PACK / "js").glob("*.mjs"):
+ target = dest / src.name
+ if not target.exists() or target.read_bytes() != src.read_bytes():
+ shutil.copyfile(src, target)
+ return dest
+
+
+def node_script(script: str, args: list[str], timeout: int = 3600) -> str:
+ node = paths.node()
+ if not node:
+ raise B2M3DError("node was not found on PATH (Node.js 20 or newer is required)")
+ return run([node, str(sync_js() / script), *args], timeout=timeout)
+
+
+def blender_script(script: Path, config: dict, timeout: int = 7200) -> str:
+ exe = paths.blender()
+ if not exe:
+ raise B2M3DError("Blender was not found. Install it, or set B2M3D_BLENDER to its executable "
+ "(run `python -m b2m3d doctor` for the install command).")
+ # The config goes through a file: JSON on a command line is mangled by some Windows shells.
+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as fh:
+ json.dump(config, fh)
+ cfg = Path(fh.name)
+ try:
+ return run([exe, "-b", "--factory-startup", "-P", str(script), "--", str(cfg)], timeout=timeout)
+ finally:
+ cfg.unlink(missing_ok=True)
+
+
+def last_json(stdout: str, marker: str) -> dict:
+ """Scripts print '<marker> {json}' as their result line."""
+ for line in reversed(stdout.splitlines()):
+ if line.startswith(marker + " "):
+ return json.loads(line[len(marker) + 1:])
+ raise B2M3DError(f"no {marker} result line in output:\n{stdout[-1500:]}")
diff --git a/plugin/skills/brief2mp4/3d/examples/04-3d-product/build.py b/plugin/skills/brief2mp4/3d/examples/04-3d-product/build.py
new file mode 100644
index 0000000..7ea28e8
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/examples/04-3d-product/build.py
@@ -0,0 +1,40 @@
+"""Build example 04 end to end: parts -> materials -> optimise -> physics -> HyperFrames project.
+
+ python build.py WORKDIR
+
+Copies the spec, scene and shot into WORKDIR, runs every b2m3d step (the same commands you would
+type), and leaves a ready project in WORKDIR/project. Render it with
+`npx hyperframes render WORKDIR/project`.
+"""
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+MATERIALS = {"shell": "matte_plastic", "cell": "brushed_aluminum", "board": "pcb_green",
+ "cover": "ceramic_white", "lens": "smoked_glass"}
+
+
+def b2m3d(*args: str) -> None:
+ subprocess.run([sys.executable, "-m", "b2m3d", *args], check=True, stdout=subprocess.DEVNULL)
+
+
+def main(work: Path) -> None:
+ (work / "build").mkdir(parents=True, exist_ok=True)
+ for name in ("device.py", "scene.json", "shot.json"):
+ shutil.copy2(HERE / name, work / name)
+ for part, preset in MATERIALS.items():
+ raw, coloured, final = (work / "build" / f"{part}{s}.glb" for s in ("_raw", "_mat", ""))
+ b2m3d("model", str(work / "device.py"), str(raw), "--param", f"part={part}")
+ b2m3d("material", "assign", str(raw), str(coloured), "--assign", f"*={preset}")
+ b2m3d("optimize", str(coloured), str(final))
+ b2m3d("physics", str(work / "scene.json"), str(work / "build" / "track.json"))
+ b2m3d("hf", str(work / "shot.json"), str(work / "project"))
+ print(f"ready: {work / 'project'}")
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ sys.exit(__doc__)
+ main(Path(sys.argv[1]).resolve())
diff --git a/plugin/skills/brief2mp4/3d/examples/04-3d-product/device.py b/plugin/skills/brief2mp4/3d/examples/04-3d-product/device.py
new file mode 100644
index 0000000..d86715d
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/examples/04-3d-product/device.py
@@ -0,0 +1,75 @@
+"""Spec for example 04: a small desk gadget made of five stacked parts (Manifold booleans).
+
+Millimetres, Z-up. Every part is centred on its own origin, because a physics body is placed by
+its origin and the part then falls and settles into the stack. Run one part at a time:
+
+ python -m b2m3d model device.py build/shell.glb --param part=shell
+
+Colours here are placeholders; `b2m3d material assign` gives each part its real material.
+"""
+from manifold3d import CrossSection, JoinType, Manifold
+
+PARAMS = {"part": "all"}
+
+
+def slab(width, depth, height, radius):
+ """Rounded-rectangle prism, centred on the origin."""
+ outline = CrossSection.square((width - 2 * radius, depth - 2 * radius), True).offset(
+ radius, JoinType.Round, 2.0, 32)
+ solid = Manifold.extrude(outline, height)
+ return solid.translate([0, 0, -height / 2])
+
+
+def centred(solid):
+ x0, y0, z0, x1, y1, z1 = solid.bounding_box()
+ return solid.translate([-(x0 + x1) / 2, -(y0 + y1) / 2, -(z0 + z1) / 2])
+
+
+def shell():
+ tray = slab(60, 40, 10, 7)
+ pocket = slab(52, 32, 2, 4).translate([0, 0, 4.5])
+ return tray - pocket
+
+
+def cell():
+ return slab(50, 30, 6, 4)
+
+
+def board():
+ base = slab(56, 36, 2, 3)
+ chips = [Manifold.cube([10, 10, 1.2], True).translate([-12, 0, 1.6]),
+ Manifold.cube([14, 6, 1.0], True).translate([10, 7, 1.5]),
+ Manifold.cube([6, 6, 1.4], True).translate([13, -8, 1.7])]
+ for chip in chips:
+ base = base + chip
+ return centred(base)
+
+
+def cover():
+ return slab(60, 40, 5, 7)
+
+
+def lens():
+ return Manifold.cylinder(3, 9, 8, 64, True)
+
+
+PARTS = {
+ "shell": (shell, [0.05, 0.05, 0.055, 1.0], 0.0, 0.7),
+ "cell": (cell, [0.8, 0.8, 0.82, 1.0], 1.0, 0.35),
+ "board": (board, [0.006, 0.045, 0.02, 1.0], 0.0, 0.4),
+ "cover": (cover, [0.9, 0.9, 0.88, 1.0], 0.0, 0.25),
+ "lens": (lens, [0.2, 0.2, 0.24, 1.0], 0.0, 0.1),
+}
+
+
+def build(params):
+ wanted = list(PARTS) if params["part"] == "all" else [params["part"]]
+ unknown = [w for w in wanted if w not in PARTS]
+ if unknown:
+ raise ValueError(f"unknown part {unknown}; choose one of {', '.join(PARTS)} or 'all'")
+ out = []
+ for name in wanted:
+ make, color, metallic, roughness = PARTS[name]
+ out.append({"name": name, "geom": make(), "color": color, "metallic": metallic,
+ "roughness": roughness})
+ return out
diff --git a/plugin/skills/brief2mp4/3d/examples/04-3d-product/scene.json b/plugin/skills/brief2mp4/3d/examples/04-3d-product/scene.json
new file mode 100644
index 0000000..f63747a
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/examples/04-3d-product/scene.json
@@ -0,0 +1,14 @@
+{
+ "fps": 30,
+ "duration": 8,
+ "substeps": 6,
+ "gravity": [0, -3, 0],
+ "bodies": [
+ {"name": "floor", "shape": "box", "size": [3, 0.2, 3], "position": [0, -0.1, 0], "motion": "static", "friction": 1.0},
+ {"name": "shell", "shape": "hull", "glb": "build/shell.glb", "position": [0, 0.3, 0], "rotation": [0.0436, 0, 0.0436, 0.9981], "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9},
+ {"name": "cell", "shape": "hull", "glb": "build/cell.glb", "position": [0, 1.35, 0], "rotation": [0, 0.0436, 0.0436, 0.9981], "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9},
+ {"name": "board", "shape": "hull", "glb": "build/board.glb", "position": [0, 3.15, 0], "rotation": [0.0436, 0.0436, 0, 0.9981], "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9},
+ {"name": "cover", "shape": "hull", "glb": "build/cover.glb", "position": [0, 5.7, 0], "rotation": [0, 0.0436, -0.0218, 0.9988], "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9},
+ {"name": "lens", "shape": "hull", "glb": "build/lens.glb", "position": [0, 9.0, 0], "rotation": [0, 0.0436, 0, 0.999], "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9}
+ ]
+}
diff --git a/plugin/skills/brief2mp4/3d/examples/04-3d-product/shot.json b/plugin/skills/brief2mp4/3d/examples/04-3d-product/shot.json
new file mode 100644
index 0000000..e454554
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/examples/04-3d-product/shot.json
@@ -0,0 +1,31 @@
+{
+ "name": "example 04: parts drop, settle, explode",
+ "duration": 8,
+ "fps": 30,
+ "width": 1920,
+ "height": 1080,
+ "physics": "build/track.json",
+ "models": [
+ { "src": "build/shell.glb", "track": "shell", "explode": { "start": 3.2, "duration": 1.4, "dirs": { "shell": [0, 0, 0] } } },
+ { "src": "build/cell.glb", "track": "cell", "explode": { "start": 3.2, "duration": 1.4, "dirs": { "cell": [0, 0.022, 0] } } },
+ { "src": "build/board.glb", "track": "board", "explode": { "start": 3.2, "duration": 1.4, "dirs": { "board": [0, 0.044, 0] } } },
+ { "src": "build/cover.glb", "track": "cover", "explode": { "start": 3.2, "duration": 1.4, "dirs": { "cover": [0, 0.068, 0] } } },
+ { "src": "build/lens.glb", "track": "lens", "explode": { "start": 3.2, "duration": 1.4, "dirs": { "lens": [0, 0.096, 0] } } }
+ ],
+ "ground": { "shadow": 0.5 },
+ "camera": {
+ "fov": 28,
+ "keys": [
+ { "t": 0, "pos": [0.3062, 0.3, 0.3062], "target": [0, 0.05, 0] },
+ { "t": 2.9, "pos": [0.1088, 0.1134, 0.1884], "target": [0, 0.012, 0] },
+ { "t": 5.0, "pos": [0.1529, 0.1968, 0.3434], "target": [0, 0.06, 0] },
+ { "t": 8, "pos": [0.0672, 0.1651, 0.3163], "target": [0, 0.06, 0] }
+ ]
+ },
+ "lights": "dramatic",
+ "tonemapping": "neutral",
+ "envIntensity": 0.35,
+ "titles": [
+ { "text": "Everything inside.", "sub": "Five parts, one pocket-sized sensor.", "start": 5.3, "duration": 2.5, "size": 64, "position": "bottom-left" }
+ ]
+}
diff --git a/plugin/skills/brief2mp4/3d/install_3d.ps1 b/plugin/skills/brief2mp4/3d/install_3d.ps1
new file mode 100644
index 0000000..041c669
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/install_3d.ps1
@@ -0,0 +1,179 @@
+# install_3d.ps1: install components of the optional brief2mp4 3D pack on Windows. No admin rights needed.
+#
+# powershell -ExecutionPolicy Bypass -File install_3d.ps1 # core only
+# powershell -ExecutionPolicy Bypass -File install_3d.ps1 -Components core,cad # pick what the brief needs
+# powershell -ExecutionPolicy Bypass -File install_3d.ps1 -Uninstall # remove the install folder (only if this script made it)
+#
+# Components
+# core node: three, GSAP, glTF Transform, meshoptimizer, Jolt, fonts
+# python: numpy, scipy, trimesh, manifold3d (in a venv, Python 3.12 or 3.13)
+# cad CadQuery (large: ships the OpenCascade kernel). Needs core.
+# blender checks for a system Blender and prints how to install it. Installs nothing.
+# dev pytest, for tests\run_tests.sh. Needs core.
+#
+# Installs into $env:B2M3D_HOME (default $env:USERPROFILE\.brief2mp4\3d), including its own copy of the pack,
+# so moving or deleting the folder you ran this from does not break it. Safe to run again.
+param([string[]]$Components = @("core"), [switch]$Uninstall)
+$ErrorActionPreference = "Stop"
+
+$Pack = Split-Path -Parent $MyInvocation.MyCommand.Path
+$HomeDir = if ($env:B2M3D_HOME) { $env:B2M3D_HOME } else { Join-Path $env:USERPROFILE ".brief2mp4\3d" }
+$Venv = Join-Path $HomeDir "venv"
+$VPy = Join-Path $Venv "Scripts\python.exe"
+
+$Marker = Join-Path $HomeDir ".installed-by-brief2mp4-3d"
+if ($Uninstall) {
+ if (Test-Path $Marker) { Remove-Item -LiteralPath $HomeDir -Recurse -Force; Write-Output "removed $HomeDir" }
+ elseif (Test-Path $HomeDir) { throw "$HomeDir was not created by this script; left it alone" }
+ else { Write-Output "nothing to remove at $HomeDir" }
+ exit 0
+}
+# Accept "-Components core,cad" (an array), "core cad" or "core,cad" (one string) alike.
+$wanted = @($Components | ForEach-Object { $_ -split "[,\s]+" } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
+if ($wanted.Count -eq 0) { throw "-Components needs a value, e.g. core,cad" }
+foreach ($c in $wanted) {
+ if (@("core", "cad", "blender", "dev") -notcontains $c) { throw "unknown component '$c' (core, cad, blender, dev)" }
+}
+if ((($wanted -contains "cad") -or ($wanted -contains "dev")) -and ($wanted -notcontains "core")) { $wanted = @("core") + $wanted }
+
+function Get-SizeMB([string]$path) {
+ if (-not (Test-Path $path)) { return 0 }
+ $sum = (Get-ChildItem -Path $path -Recurse -File -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
+ return [int](($sum + 0) / 1MB)
+}
+
+function Find-Python {
+ if ($env:B2M3D_PYTHON) { return ,@($env:B2M3D_PYTHON) }
+ $candidates = @(@("py", "-3.13"), @("py", "-3.12"), @("python"), @("python3"))
+ foreach ($cand in $candidates) {
+ if (-not (Get-Command $cand[0] -ErrorAction SilentlyContinue)) { continue }
+ $extra = @($cand | Select-Object -Skip 1)
+ try { $v = (& $cand[0] @extra -c "import sys; print('%d.%d' % sys.version_info[:2])" 2>$null) } catch { continue }
+ if (@("3.12", "3.13") -contains $v) { return ,$cand }
+ }
+ return $null
+}
+
+function Invoke-Checked([scriptblock]$block, [string]$what) {
+ & $block
+ if ($LASTEXITCODE -ne 0) { throw "$what failed (exit $LASTEXITCODE)" }
+}
+
+function Install-NodePackages {
+ Write-Output "core: installing three, gsap, glTF Transform, meshoptimizer, jolt-physics, fonts"
+ Copy-Item (Join-Path $Pack "package.json") (Join-Path $HomeDir "package.json") -Force
+ $lockSrc = Join-Path $Pack "package-lock.json"
+ $lock = Join-Path $HomeDir "package-lock.json"
+ if (Test-Path $lockSrc) { Copy-Item $lockSrc $lock -Force }
+ $stampFile = Join-Path $HomeDir ".node-stamp"
+ $stamp = (Get-FileHash (Join-Path $HomeDir "package.json")).Hash
+ if (Test-Path $lock) { $stamp += (Get-FileHash $lock).Hash }
+ if ((Test-Path (Join-Path $HomeDir "node_modules\three")) -and (Test-Path $stampFile) -and ((Get-Content $stampFile -Raw).Trim() -eq $stamp)) {
+ Write-Output "core: node packages already up to date"
+ return
+ }
+ Push-Location $HomeDir
+ try {
+ $verb = if (Test-Path $lock) { "ci" } else { "install" }
+ Invoke-Checked { npm.cmd $verb --omit=dev --no-audit --no-fund --loglevel=error } "npm $verb"
+ } finally { Pop-Location }
+ $stamp = (Get-FileHash (Join-Path $HomeDir "package.json")).Hash
+ if (Test-Path $lock) { $stamp += (Get-FileHash $lock).Hash }
+ Set-Content -Path $stampFile -Value $stamp
+}
+
+function Write-Utf8([string]$path, [string]$text) {
+ [System.IO.File]::WriteAllText($path, $text, (New-Object System.Text.UTF8Encoding $false))
+}
+
+function Link-Pack {
+ # Copy the pack into the install home and point a .pth file at the copy, so `python -m b2m3d`
+ # works from any folder and keeps working if the clone or plugin cache moves.
+ $dest = Join-Path $HomeDir "pack"
+ $tmp = "$dest.new"
+ if (Test-Path $tmp) { Remove-Item -LiteralPath $tmp -Recurse -Force }
+ New-Item -ItemType Directory -Force -Path $tmp | Out-Null
+ foreach ($part in @("b2m3d", "js", "templates", "presets", "examples")) {
+ $src = Join-Path $Pack $part
+ if (Test-Path $src) { Copy-Item -Recurse -Path $src -Destination $tmp }
+ }
+ Get-ChildItem -Path $tmp -Recurse -Directory -Filter "__pycache__" | Remove-Item -Recurse -Force
+ if (Test-Path $dest) { Remove-Item -LiteralPath $dest -Recurse -Force }
+ Move-Item -LiteralPath $tmp -Destination $dest
+ $site = (& $VPy -c "import sysconfig; print(sysconfig.get_paths()['purelib'])").Trim()
+ Write-Utf8 (Join-Path $site "b2m3d-pack.pth") "$dest`n"
+ Write-Utf8 (Join-Path $Venv "Scripts\brief2mp4-3d.cmd") "@echo off`r`n`"$VPy`" -m b2m3d %*`r`n"
+ Invoke-Checked { & $VPy -c "import b2m3d.cli" } "importing the pack copy in $dest"
+ Write-Output "core: command ready: $Venv\Scripts\brief2mp4-3d.cmd (or: $VPy -m b2m3d)"
+}
+
+function Install-Core {
+ if (-not (Get-Command node -ErrorAction SilentlyContinue)) { throw "node not found. Install Node.js 20 or newer: winget install OpenJS.NodeJS.LTS" }
+ if (-not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) { throw "npm not found. It ships with Node.js: https://nodejs.org" }
+ $major = [int](node -p "process.versions.node.split('.')[0]")
+ if ($major -lt 20) { throw "Node.js $major is too old: 20 or newer is needed." }
+ $py = Find-Python
+ if (-not $py) { throw "Python 3.12 or 3.13 not found. Install it: winget install Python.Python.3.13 (then open a new terminal)." }
+
+ New-Item -ItemType Directory -Force -Path $HomeDir | Out-Null
+ Write-Utf8 $Marker "brief2mp4 3D pack`n"
+ $before = (Get-SizeMB $Venv) + (Get-SizeMB (Join-Path $HomeDir "node_modules"))
+ Write-Output "core: python venv ($($py -join ' ')) at $Venv"
+ if (-not (Test-Path $VPy)) {
+ $extra = @($py | Select-Object -Skip 1)
+ Invoke-Checked { & $py[0] @extra -m venv $Venv } "venv creation"
+ }
+ Write-Output "core: installing numpy, scipy, trimesh, manifold3d"
+ Invoke-Checked { & $VPy -m pip install --disable-pip-version-check -q -r (Join-Path $Pack "requirements-core.txt") } "pip install (core)"
+ Install-NodePackages
+ Link-Pack
+ $after = (Get-SizeMB $Venv) + (Get-SizeMB (Join-Path $HomeDir "node_modules"))
+ Write-Output "core: done, $($after - $before) MB added (venv $(Get-SizeMB $Venv) MB, node_modules $(Get-SizeMB (Join-Path $HomeDir 'node_modules')) MB)"
+}
+
+function Install-Cad {
+ $before = Get-SizeMB $Venv
+ Write-Output "cad: installing CadQuery (large download)"
+ Invoke-Checked { & $VPy -m pip install --disable-pip-version-check -q -r (Join-Path $Pack "requirements-cad.txt") } "pip install (cad)"
+ Write-Output "cad: done, $((Get-SizeMB $Venv) - $before) MB added"
+}
+
+function Install-Dev {
+ Write-Output "dev: installing pytest"
+ Invoke-Checked { & $VPy -m pip install --disable-pip-version-check -q -r (Join-Path $Pack "requirements-dev.txt") } "pip install (dev)"
+}
+
+function Check-Blender {
+ $found = $null
+ if ($env:B2M3D_BLENDER -and (Test-Path $env:B2M3D_BLENDER)) { $found = $env:B2M3D_BLENDER }
+ elseif (Get-Command blender -ErrorAction SilentlyContinue) { $found = (Get-Command blender).Source }
+ else {
+ $roots = @($env:ProgramFiles, "C:\Program Files") | Where-Object { $_ } | Select-Object -Unique
+ foreach ($root in $roots) {
+ $hit = Get-ChildItem -Path (Join-Path $root "Blender Foundation\Blender *\blender.exe") -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
+ if ($hit) { $found = $hit.FullName; break }
+ }
+ }
+ if ($found) {
+ $ver = ""
+ try { $ver = (& $found --version 2>&1 | Select-Object -First 1) } catch { $ver = "version unknown" }
+ Write-Output "blender: found $found ($ver)"
+ }
+ else {
+ Write-Output "blender: not found. Install it yourself:"
+ Write-Output " winget install BlenderFoundation.Blender (or https://www.blender.org/download/)"
+ }
+}
+
+if ($wanted -contains "core") { Install-Core }
+if ($wanted -contains "cad") { Install-Cad }
+if ($wanted -contains "dev") { Install-Dev }
+if ($wanted -contains "blender") { Check-Blender }
+
+New-Item -ItemType Directory -Force -Path $HomeDir | Out-Null
+$marker = Join-Path $HomeDir ".components"
+$all = @()
+if (Test-Path $marker) { $all += Get-Content $marker }
+$all = @($all + $wanted | Where-Object { $_ } | Sort-Object -Unique)
+Set-Content -Path $marker -Value $all
+Write-Output ("installed components: " + ($all -join ",") + " total on disk: $(Get-SizeMB $HomeDir) MB in $HomeDir")
diff --git a/plugin/skills/brief2mp4/3d/install_3d.sh b/plugin/skills/brief2mp4/3d/install_3d.sh
new file mode 100755
index 0000000..2ac2d50
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/install_3d.sh
@@ -0,0 +1,170 @@
+#!/usr/bin/env bash
+# install_3d.sh: install components of the optional brief2mp4 3D pack. No sudo, ever.
+#
+# bash install_3d.sh # core only
+# bash install_3d.sh --components core,cad # pick what the brief needs
+# bash install_3d.sh --components core,dev # core + pytest, to run the test suite
+# bash install_3d.sh --uninstall # remove $B2M3D_HOME (only if this script created it)
+#
+# Components
+# core node: three, GSAP, glTF Transform, meshoptimizer, Jolt, fonts
+# python: numpy, scipy, trimesh, manifold3d (in a venv, Python 3.12 or 3.13)
+# cad CadQuery (large: ships the OpenCascade kernel). Needs core.
+# blender checks for a system Blender and prints how to install it. Installs nothing.
+# dev pytest, for tests/run_tests.sh. Needs core.
+#
+# Installs into $B2M3D_HOME (default ~/.brief2mp4/3d), including its own copy of the pack, so moving
+# or deleting the folder you ran this from does not break it. Safe to run again.
+set -euo pipefail
+
+PACK="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+HOME_DIR="${B2M3D_HOME:-$HOME/.brief2mp4/3d}"
+COMPONENTS="core"
+UNINSTALL=0
+MARKER=".installed-by-brief2mp4-3d"
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --components) [[ -n "${2:-}" ]] || { echo "install_3d.sh: --components needs a value, e.g. core,cad" >&2; exit 2; }; COMPONENTS="$2"; shift 2 ;;
+ --uninstall) UNINSTALL=1; shift ;;
+ --components=*) COMPONENTS="${1#*=}"; shift ;;
+ -h|--help) sed -n '2,19p' "$0"; exit 0 ;;
+ *) echo "install_3d.sh: unknown option $1" >&2; exit 2 ;;
+ esac
+done
+
+if [[ "$UNINSTALL" == 1 ]]; then
+ if [[ -f "$HOME_DIR/$MARKER" ]]; then rm -r "$HOME_DIR"; echo "removed $HOME_DIR"
+ elif [[ -e "$HOME_DIR" ]]; then echo "install_3d.sh: $HOME_DIR was not created by this script; left it alone" >&2; exit 1
+ else echo "nothing to remove at $HOME_DIR"; fi
+ exit 0
+fi
+
+want() { [[ ",$COMPONENTS," == *",$1,"* ]]; }
+for c in ${COMPONENTS//,/ }; do
+ case "$c" in core|cad|blender|dev) ;; *) echo "install_3d.sh: unknown component '$c' (core, cad, blender, dev)" >&2; exit 2 ;; esac
+done
+if { want cad || want dev; } && ! want core; then COMPONENTS="core,$COMPONENTS"; fi
+
+VENV="$HOME_DIR/venv"
+VBIN="$VENV/bin"; VPY="$VBIN/python"
+case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) VBIN="$VENV/Scripts"; VPY="$VBIN/python.exe" ;; esac
+size_mb() { [[ -d "$1" ]] && du -sk "$1" | awk '{printf "%d", $1/1024}' || echo 0; }
+say() { printf '%s\n' "$*"; }
+
+find_python() {
+ local cand v
+ if [[ -n "${B2M3D_PYTHON:-}" ]]; then # explicit interpreter, e.g. B2M3D_PYTHON="$(uv python find 3.12)"
+ v="$("$B2M3D_PYTHON" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)"
+ case "$v" in 3.12|3.13) echo "$B2M3D_PYTHON"; return 0 ;; esac
+ say "B2M3D_PYTHON=$B2M3D_PYTHON is Python ${v:-unknown}; 3.12 or 3.13 is needed." >&2; return 1
+ fi
+ for cand in python3.13 python3.12 python3 python py; do
+ command -v "$cand" >/dev/null 2>&1 || continue
+ v="$("$cand" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)"
+ case "$v" in 3.12|3.13) command -v "$cand"; return 0 ;; esac
+ done
+ return 1
+}
+
+install_core() {
+ command -v node >/dev/null 2>&1 || { say "node not found. Install Node.js 20 or newer (macOS: brew install node; Linux: your package manager or https://nodejs.org)." >&2; exit 1; }
+ command -v npm >/dev/null 2>&1 || { say "npm not found. It ships with Node.js: https://nodejs.org" >&2; exit 1; }
+ local major; major="$(node -p 'process.versions.node.split(".")[0]')"
+ [[ "$major" -ge 20 ]] || { say "Node.js $major is too old: 20 or newer is needed." >&2; exit 1; }
+
+ local py
+ py="$(find_python)" || { say "Python 3.12 or 3.13 not found. macOS: brew install [email protected]. Debian/Ubuntu: python3.13 and python3.13-venv from your package manager. Then run this again." >&2; exit 1; }
+
+ mkdir -p "$HOME_DIR"
+ touch "$HOME_DIR/$MARKER"
+ local before; before=$(( $(size_mb "$VENV") + $(size_mb "$HOME_DIR/node_modules") ))
+
+ say "core: python venv ($py) at $VENV"
+ [[ -x "$VPY" ]] || "$py" -m venv "$VENV"
+ say "core: installing numpy, scipy, trimesh, manifold3d"
+ "$VPY" -m pip install --disable-pip-version-check -q -r "$PACK/requirements-core.txt"
+
+ install_node_packages
+ link_pack
+ say "core: done, $(( $(size_mb "$VENV") + $(size_mb "$HOME_DIR/node_modules") - before )) MB added (venv $(size_mb "$VENV") MB, node_modules $(size_mb "$HOME_DIR/node_modules") MB)"
+}
+
+node_stamp() {
+ { cat "$HOME_DIR/package.json"; cat "$HOME_DIR/package-lock.json" 2>/dev/null || true; } | cksum
+}
+
+install_node_packages() {
+ say "core: installing three, gsap, glTF Transform, meshoptimizer, jolt-physics, fonts"
+ cp "$PACK/package.json" "$HOME_DIR/package.json"
+ if [[ -f "$PACK/package-lock.json" ]]; then cp "$PACK/package-lock.json" "$HOME_DIR/package-lock.json"; fi
+ local stamp; stamp="$(node_stamp)"
+ if [[ -d "$HOME_DIR/node_modules/three" && "$(cat "$HOME_DIR/.node-stamp" 2>/dev/null || true)" == "$stamp" ]]; then
+ say "core: node packages already up to date"
+ return
+ fi
+ if [[ -f "$HOME_DIR/package-lock.json" ]]; then
+ (cd "$HOME_DIR" && npm ci --omit=dev --no-audit --no-fund --loglevel=error)
+ else
+ (cd "$HOME_DIR" && npm install --omit=dev --no-audit --no-fund --loglevel=error)
+ fi
+ stamp="$(node_stamp)"
+ printf '%s\n' "$stamp" > "$HOME_DIR/.node-stamp"
+}
+
+link_pack() {
+ # Copy the pack into the install home, then point a .pth file at the copy, so `python -m b2m3d`
+ # works from any folder and keeps working if the clone or plugin cache moves.
+ local dest="$HOME_DIR/pack" site
+ rm -rf "$dest.new"; mkdir -p "$dest.new"
+ cp -R "$PACK/b2m3d" "$PACK/js" "$PACK/templates" "$PACK/presets" "$dest.new/"
+ [[ -d "$PACK/examples" ]] && cp -R "$PACK/examples" "$dest.new/"
+ find "$dest.new" -name __pycache__ -type d -prune -exec rm -rf {} +
+ rm -rf "$dest"; mv "$dest.new" "$dest"
+ site="$("$VPY" -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')"
+ printf '%s\n' "$dest" > "$site/b2m3d-pack.pth"
+ printf '#!/usr/bin/env bash\nexec "%s" -m b2m3d "$@"\n' "$VPY" > "$VBIN/brief2mp4-3d"
+ chmod +x "$VBIN/brief2mp4-3d"
+ "$VPY" -c "import b2m3d.cli" || { say "core: the pack copy in $dest does not import" >&2; exit 1; }
+ say "core: command ready: $VBIN/brief2mp4-3d (or: $VPY -m b2m3d)"
+}
+
+install_cad() {
+ local before; before=$(size_mb "$VENV")
+ say "cad: installing CadQuery (large download)"
+ "$VPY" -m pip install --disable-pip-version-check -q -r "$PACK/requirements-cad.txt"
+ say "cad: done, $(( $(size_mb "$VENV") - before )) MB added"
+}
+
+install_dev() {
+ say "dev: installing pytest"
+ "$VPY" -m pip install --disable-pip-version-check -q -r "$PACK/requirements-dev.txt"
+}
+
+check_blender() {
+ local found=""
+ if [[ -n "${B2M3D_BLENDER:-}" && -x "${B2M3D_BLENDER}" ]]; then found="$B2M3D_BLENDER"
+ elif command -v blender >/dev/null 2>&1; then found="$(command -v blender)"
+ else
+ for c in /Applications/Blender.app/Contents/MacOS/Blender /usr/bin/blender /usr/local/bin/blender /snap/bin/blender; do
+ [[ -x "$c" ]] && { found="$c"; break; }
+ done
+ fi
+ if [[ -n "$found" ]]; then
+ say "blender: found $found ($("$found" --version 2>/dev/null | head -1))"
+ else
+ say "blender: not found. Install it yourself (this script never uses sudo):"
+ say " macOS: brew install --cask blender"
+ say " Linux: your package manager (Blender 4.2 or newer), or https://www.blender.org/download/"
+ fi
+}
+
+want core && install_core
+want cad && install_cad
+want dev && install_dev
+want blender && check_blender
+mkdir -p "$HOME_DIR"
+touch "$HOME_DIR/.components"
+{ cat "$HOME_DIR/.components"; printf '%s\n' ${COMPONENTS//,/ }; } | sort -u > "$HOME_DIR/.components.tmp"
+mv "$HOME_DIR/.components.tmp" "$HOME_DIR/.components"
+say "installed components: $(paste -sd, "$HOME_DIR/.components") total on disk: $(size_mb "$HOME_DIR") MB in $HOME_DIR"
diff --git a/plugin/skills/brief2mp4/3d/js/decompress.mjs b/plugin/skills/brief2mp4/3d/js/decompress.mjs
new file mode 100644
index 0000000..0e57dd8
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/js/decompress.mjs
@@ -0,0 +1,18 @@
+// Decode EXT_meshopt_compression / KHR_mesh_quantization so Python readers (trimesh) can load the file.
+// usage: node decompress.mjs <in.glb> <out.glb>
+import { NodeIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+import { dequantize } from "@gltf-transform/functions";
+import { MeshoptDecoder } from "meshoptimizer";
+
+const [src, out] = process.argv.slice(2);
+await MeshoptDecoder.ready;
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder });
+const doc = await io.read(src);
+const COMPRESSION = ["EXT_meshopt_compression", "KHR_mesh_quantization", "KHR_draco_mesh_compression"];
+for (const ext of doc.getRoot().listExtensionsUsed()) {
+ if (COMPRESSION.includes(ext.extensionName)) ext.dispose();
+}
+await doc.transform(dequantize());
+await io.write(out, doc);
+console.log("B2M3D_DECOMPRESS " + JSON.stringify({ out }));
diff --git a/plugin/skills/brief2mp4/3d/js/jolt_bake.mjs b/plugin/skills/brief2mp4/3d/js/jolt_bake.mjs
new file mode 100644
index 0000000..d69fefd
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/js/jolt_bake.mjs
@@ -0,0 +1,115 @@
+// b2m3d physics: deterministic Jolt rigid-body bake -> per-frame transforms.
+// HyperFrames seeks frames out of order across parallel workers, so physics can't
+// run live in the page. We simulate once here at a fixed step and store a pose per
+// frame; the page just reads track[frame].
+// usage: node jolt_bake.mjs <scene.json> <out.json>
+// Prints: B2M3D_PHYSICS {json summary}
+import initJolt from "jolt-physics/wasm-compat";
+import { readFileSync, writeFileSync } from "node:fs";
+
+const [scenePath, outPath] = process.argv.slice(2);
+const scene = JSON.parse(readFileSync(scenePath, "utf8"));
+const Jolt = await initJolt();
+
+const NON_MOVING = 0, MOVING = 1;
+function makeInterface() {
+ const settings = new Jolt.JoltSettings();
+ const pairs = new Jolt.ObjectLayerPairFilterTable(2);
+ pairs.EnableCollision(NON_MOVING, MOVING);
+ pairs.EnableCollision(MOVING, MOVING);
+ const bp = new Jolt.BroadPhaseLayerInterfaceTable(2, 2);
+ bp.MapObjectToBroadPhaseLayer(NON_MOVING, new Jolt.BroadPhaseLayer(0));
+ bp.MapObjectToBroadPhaseLayer(MOVING, new Jolt.BroadPhaseLayer(1));
+ settings.mObjectLayerPairFilter = pairs;
+ settings.mBroadPhaseLayerInterface = bp;
+ settings.mObjectVsBroadPhaseLayerFilter =
+ new Jolt.ObjectVsBroadPhaseLayerFilterTable(bp, 2, pairs, 2);
+ const jolt = new Jolt.JoltInterface(settings);
+ Jolt.destroy(settings);
+ return jolt;
+}
+
+function makeShape(b) {
+ const s = b.shape;
+ if (s === "box") {
+ const [x, y, z] = b.size;
+ return new Jolt.BoxShape(new Jolt.Vec3(x / 2, y / 2, z / 2), Math.min(0.05, x / 10, y / 10, z / 10));
+ }
+ if (s === "sphere") return new Jolt.SphereShape(b.radius);
+ if (s === "cylinder") return new Jolt.CylinderShape(b.height / 2, b.radius, Math.min(0.05, b.radius / 10));
+ if (s === "hull") {
+ const hs = new Jolt.ConvexHullShapeSettings();
+ for (const [x, y, z] of b.points) hs.mPoints.push_back(new Jolt.Vec3(x, y, z));
+ const res = hs.Create();
+ if (res.HasError()) throw new Error(`hull for ${b.name}: ${res.GetError().c_str()}`);
+ return res.Get();
+ }
+ throw new Error(`unknown shape ${s} for body ${b.name}`);
+}
+
+const MOTION = {
+ static: Jolt.EMotionType_Static,
+ dynamic: Jolt.EMotionType_Dynamic,
+ kinematic: Jolt.EMotionType_Kinematic,
+};
+
+const jolt = makeInterface();
+const system = jolt.GetPhysicsSystem();
+const bodies = system.GetBodyInterface();
+const g = scene.gravity ?? [0, -9.81, 0];
+system.SetGravity(new Jolt.Vec3(g[0], g[1], g[2]));
+
+const handles = [];
+for (const b of scene.bodies) {
+ const motion = b.motion ?? "dynamic";
+ const [px, py, pz] = b.position ?? [0, 0, 0];
+ const [qx, qy, qz, qw] = b.rotation ?? [0, 0, 0, 1];
+ const cs = new Jolt.BodyCreationSettings(makeShape(b), new Jolt.RVec3(px, py, pz),
+ new Jolt.Quat(qx, qy, qz, qw), MOTION[motion], motion === "static" ? NON_MOVING : MOVING);
+ cs.mFriction = b.friction ?? 0.5;
+ cs.mRestitution = b.restitution ?? 0.2;
+ cs.mLinearDamping = b.linearDamping ?? 0.05;
+ cs.mAngularDamping = b.angularDamping ?? 0.05;
+ if (motion !== "static") cs.mMotionQuality = Jolt.EMotionQuality_LinearCast;
+ const body = bodies.CreateBody(cs);
+ Jolt.destroy(cs);
+ const id = body.GetID();
+ bodies.AddBody(id, motion === "static" ? Jolt.EActivation_DontActivate : Jolt.EActivation_Activate);
+ if (b.velocity) bodies.SetLinearVelocity(id, new Jolt.Vec3(...b.velocity));
+ if (b.angular) bodies.SetAngularVelocity(id, new Jolt.Vec3(...b.angular));
+ handles.push({ name: b.name, id, body, motion });
+}
+
+const fps = scene.fps ?? 30;
+const frames = Math.round((scene.duration ?? 4) * fps);
+const substeps = scene.substeps ?? 4;
+const dt = 1 / fps / substeps;
+const tracks = Object.fromEntries(handles.map((h) => [h.name, []]));
+const r = (v) => Math.round(v * 1e5) / 1e5;
+
+function record() {
+ for (const h of handles) {
+ const p = h.body.GetPosition();
+ const q = h.body.GetRotation();
+ tracks[h.name].push([r(p.GetX()), r(p.GetY()), r(p.GetZ()), r(q.GetX()), r(q.GetY()), r(q.GetZ()), r(q.GetW())]);
+ }
+}
+
+record();
+let maxSpeed = 0;
+for (let f = 1; f < frames; f++) {
+ for (let s = 0; s < substeps; s++) jolt.Step(dt, 1);
+ record();
+}
+for (const h of handles) {
+ const v = h.body.GetLinearVelocity();
+ maxSpeed = Math.max(maxSpeed, Math.hypot(v.GetX(), v.GetY(), v.GetZ()));
+}
+
+const out = { fps, frames, substeps, tracks };
+writeFileSync(outPath, JSON.stringify(out));
+const settled = maxSpeed < 0.05;
+console.log("B2M3D_PHYSICS " + JSON.stringify({
+ out: outPath, fps, frames, bodies: handles.length,
+ final_max_speed: r(maxSpeed), settled,
+}));
diff --git a/plugin/skills/brief2mp4/3d/js/material_apply.mjs b/plugin/skills/brief2mp4/3d/js/material_apply.mjs
new file mode 100644
index 0000000..97fb4af
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/js/material_apply.mjs
@@ -0,0 +1,75 @@
+// Apply glTF materials to meshes by node/mesh name.
+// usage: node material_apply.mjs <in.glb> <out.glb> <mapping.json> (mapping: {name|*: gltfMaterial})
+import { NodeIO } from "@gltf-transform/core";
+import {
+ ALL_EXTENSIONS, KHRMaterialsClearcoat, KHRMaterialsEmissiveStrength, KHRMaterialsIOR,
+ KHRMaterialsSheen, KHRMaterialsTransmission, KHRMaterialsVolume,
+} from "@gltf-transform/extensions";
+import { MeshoptDecoder, MeshoptEncoder } from "meshoptimizer";
+import { readFileSync } from "node:fs";
+
+const [src, out, mappingPath] = process.argv.slice(2);
+const mapping = JSON.parse(readFileSync(mappingPath, "utf8"));
+
+function build(doc, spec) {
+ const m = doc.createMaterial(spec.name)
+ .setBaseColorFactor(spec.baseColorFactor)
+ .setMetallicFactor(spec.metallicFactor)
+ .setRoughnessFactor(spec.roughnessFactor);
+ if (spec.emissiveFactor) m.setEmissiveFactor(spec.emissiveFactor);
+ const e = spec.extensions || {};
+ if (e.KHR_materials_clearcoat) {
+ const x = doc.createExtension(KHRMaterialsClearcoat).createClearcoat()
+ .setClearcoatFactor(e.KHR_materials_clearcoat.clearcoatFactor)
+ .setClearcoatRoughnessFactor(e.KHR_materials_clearcoat.clearcoatRoughnessFactor);
+ m.setExtension("KHR_materials_clearcoat", x);
+ }
+ if (e.KHR_materials_transmission) {
+ m.setExtension("KHR_materials_transmission", doc.createExtension(KHRMaterialsTransmission)
+ .createTransmission().setTransmissionFactor(e.KHR_materials_transmission.transmissionFactor));
+ m.setExtension("KHR_materials_volume", doc.createExtension(KHRMaterialsVolume)
+ .createVolume().setThicknessFactor(e.KHR_materials_volume?.thicknessFactor ?? 0.01));
+ }
+ if (e.KHR_materials_ior) {
+ m.setExtension("KHR_materials_ior", doc.createExtension(KHRMaterialsIOR)
+ .createIOR().setIOR(e.KHR_materials_ior.ior));
+ }
+ if (e.KHR_materials_emissive_strength) {
+ m.setExtension("KHR_materials_emissive_strength", doc.createExtension(KHRMaterialsEmissiveStrength)
+ .createEmissiveStrength().setEmissiveStrength(e.KHR_materials_emissive_strength.emissiveStrength));
+ }
+ if (e.KHR_materials_sheen) {
+ m.setExtension("KHR_materials_sheen", doc.createExtension(KHRMaterialsSheen).createSheen()
+ .setSheenColorFactor(e.KHR_materials_sheen.sheenColorFactor)
+ .setSheenRoughnessFactor(e.KHR_materials_sheen.sheenRoughnessFactor));
+ }
+ return m;
+}
+
+await MeshoptDecoder.ready;
+await MeshoptEncoder.ready;
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ "meshopt.decoder": MeshoptDecoder, "meshopt.encoder": MeshoptEncoder });
+const doc = await io.read(src);
+const cache = new Map();
+const mat = (key) => {
+ if (!cache.has(key)) cache.set(key, build(doc, mapping[key]));
+ return cache.get(key);
+};
+const hits = {};
+for (const node of doc.getRoot().listNodes()) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const names = [node.getName(), mesh.getName()].filter(Boolean);
+ const leaves = names.map((n) => n.split("/").pop());
+ const key = [...names, ...leaves].find((n) => n in mapping) ?? ("*" in mapping ? "*" : null);
+ if (!key) continue;
+ for (const prim of mesh.listPrimitives()) prim.setMaterial(mat(key));
+ hits[node.getName() || mesh.getName()] = mapping[key].name;
+}
+// Drop the materials this script replaced, so they do not ship as dead weight.
+for (const m of doc.getRoot().listMaterials()) {
+ if (m.listParents().every((parent) => parent.propertyType === "Root")) m.dispose();
+}
+await io.write(out, doc);
+console.log("B2M3D_MATERIAL " + JSON.stringify({ out, assigned: hits }));
diff --git a/plugin/skills/brief2mp4/3d/js/optimize.mjs b/plugin/skills/brief2mp4/3d/js/optimize.mjs
new file mode 100644
index 0000000..6be1b03
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/js/optimize.mjs
@@ -0,0 +1,65 @@
+// b2m3d optimize: glTF Transform + meshoptimizer pipeline for web and HyperFrames delivery.
+// usage: node optimize.mjs <in.glb> <out.glb> [--simplify 0.5] [--error 0.001] [--join] [--no-compress]
+// Node names are kept (the shot runtime's `explode` addresses parts by node name), so meshes are
+// only merged when --join is passed.
+// Prints: B2M3D_OPTIMIZE {json}
+import { NodeIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+import { dedup, join, meshopt, prune, resample, simplify, weld } from "@gltf-transform/functions";
+import { MeshoptDecoder, MeshoptEncoder, MeshoptSimplifier } from "meshoptimizer";
+import { statSync } from "node:fs";
+
+function parse(argv) {
+ const opts = { simplify: 1, error: 0.001, compress: true, join: false };
+ const pos = [];
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === "--simplify") opts.simplify = Number(argv[++i]);
+ else if (a === "--error") opts.error = Number(argv[++i]);
+ else if (a === "--no-compress") opts.compress = false;
+ else if (a === "--join") opts.join = true;
+ else pos.push(a);
+ }
+ if (pos.length !== 2) throw new Error("usage: optimize.mjs <in.glb> <out.glb> [opts]");
+ if (!(opts.simplify > 0 && opts.simplify <= 1)) throw new Error("--simplify must be in (0, 1]");
+ return { src: pos[0], out: pos[1], ...opts };
+}
+
+function countTriangles(doc) {
+ let tris = 0;
+ for (const mesh of doc.getRoot().listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ const idx = prim.getIndices();
+ const pos = prim.getAttribute("POSITION");
+ tris += idx ? idx.getCount() / 3 : (pos ? pos.getCount() / 3 : 0);
+ }
+ }
+ return Math.round(tris);
+}
+
+async function main() {
+ const o = parse(process.argv.slice(2));
+ await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready, MeshoptSimplifier.ready]);
+ const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ "meshopt.encoder": MeshoptEncoder, "meshopt.decoder": MeshoptDecoder });
+ const doc = await io.read(o.src);
+ const before = countTriangles(doc);
+
+ const steps = [dedup(), weld(), resample(), prune()];
+ if (o.join) steps.push(join());
+ if (o.simplify < 1) {
+ steps.push(simplify({ simplifier: MeshoptSimplifier, ratio: o.simplify, error: o.error }));
+ }
+ if (o.compress) steps.push(meshopt({ encoder: MeshoptEncoder, level: "medium" }));
+ await doc.transform(...steps);
+ await io.write(o.out, doc);
+
+ console.log("B2M3D_OPTIMIZE " + JSON.stringify({
+ out: o.out, triangles_before: before, triangles_after: countTriangles(doc),
+ bytes_before: statSync(o.src).size, bytes_after: statSync(o.out).size,
+ meshopt_compressed: o.compress,
+ }));
+}
+
+main().catch((e) => { console.error(e.stack || String(e)); process.exit(1); });
diff --git a/plugin/skills/brief2mp4/3d/package-lock.json b/plugin/skills/brief2mp4/3d/package-lock.json
new file mode 100644
index 0000000..0917a2b
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/package-lock.json
@@ -0,0 +1,781 @@
+{
+ "name": "brief2mp4-3d-runtime",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "brief2mp4-3d-runtime",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@fontsource-variable/inter": "5.3.0",
+ "@fontsource-variable/space-grotesk": "5.3.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "gsap": "3.15.0",
+ "jolt-physics": "1.1.1",
+ "meshoptimizer": "1.3.0",
+ "three": "0.187.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@fontsource-variable/inter": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
+ "integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource-variable/space-grotesk": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/space-grotesk/-/space-grotesk-5.3.0.tgz",
+ "integrity": "sha512-2IxmvfB08i9vnGB3Ym/AXvhRE+8XOjWMXIyDum03c+tPwH0FUoMNQfGpU8NXPxjbws0Vvss3AH0Zqt4oJBBAdw==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@gltf-transform/core": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-4.5.1.tgz",
+ "integrity": "sha512-OWgBYssKHKoXMIrMb2N20jXqWRnMP9HdtcTFQBEAJtz4P+OOxx5fozl5eAeK7nktIs5uDE/lu4NbkE5VCZaR9g==",
+ "license": "MIT",
+ "dependencies": {
+ "property-graph": "^4.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/extensions": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.5.1.tgz",
+ "integrity": "sha512-3jTe+GWRy4fj1TU790LPsO+rpO/4byUWPTpNkjy6M6h8RvrUivRf12Mptc0770K4ZczibpJDNHXZFkFsFMRDLA==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.5.1",
+ "ktx-parse": "^1.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/functions": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/functions/-/functions-4.5.1.tgz",
+ "integrity": "sha512-rfm4nQY2DJ+ip1e15xp7YfQwhRno3kPLcGw4EZiRk1dVwMV3cdFMcF08glYcO/+oLyYkUEs3xXMJYXa0cPgcTg==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.5.1",
+ "@gltf-transform/extensions": "^4.5.1",
+ "ktx-parse": "^1.1.0",
+ "ndarray": "^1.0.19",
+ "ndarray-lanczos": "^0.3.0",
+ "ndarray-pixels": "^5.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.3"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@types/ndarray": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.1.0.tgz",
+ "integrity": "sha512-go+C6vHBUuO9jH6Tj6qEZ63JEGoMSxFdmd+6QAtthGD6xumBfIz3RbNDDs2aoRVLf9naH8lk5jnWy2UHHKgYQQ==",
+ "license": "MIT"
+ },
+ "node_modules/cwise-compiler": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/cwise-compiler/-/cwise-compiler-1.1.3.tgz",
+ "integrity": "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "uniq": "^1.0.0"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/gsap": {
+ "version": "3.15.0",
+ "resolved": "https://registry.npmjs.org/gsap/-/gsap-3.15.0.tgz",
+ "integrity": "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A==",
+ "license": "Standard 'no charge' license: https://gsap.com/standard-license."
+ },
+ "node_modules/iota-array": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
+ "integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==",
+ "license": "MIT"
+ },
+ "node_modules/is-buffer": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
+ "license": "MIT"
+ },
+ "node_modules/jolt-physics": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/jolt-physics/-/jolt-physics-1.1.1.tgz",
+ "integrity": "sha512-kMCQu/b4wbHwy7EgZWaSbUyDthIKZUvAGGqta4pBF4Pdq+ljWaNvQoa5hPr/PkVCUVsqcoLwXITUm6975mQhiQ==",
+ "license": "MIT"
+ },
+ "node_modules/ktx-parse": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
+ "integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
+ "license": "MIT"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.3.0.tgz",
+ "integrity": "sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==",
+ "license": "MIT"
+ },
+ "node_modules/ndarray": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.1.1.tgz",
+ "integrity": "sha512-AsE8w/M2MS+0pD3nP5qbRRtJFeJJJaJ+qXZaZr0XjVGXhy6LIj2TERTlkpdK2AI3WufoOP+pwPk3q2ilAJcZ9g==",
+ "license": "MIT",
+ "dependencies": {
+ "iota-array": "^1.0.0",
+ "is-buffer": "^1.0.2"
+ }
+ },
+ "node_modules/ndarray-lanczos": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/ndarray-lanczos/-/ndarray-lanczos-0.3.0.tgz",
+ "integrity": "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.11",
+ "ndarray": "^1.0.19"
+ }
+ },
+ "node_modules/ndarray-ops": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/ndarray-ops/-/ndarray-ops-1.2.2.tgz",
+ "integrity": "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==",
+ "license": "MIT",
+ "dependencies": {
+ "cwise-compiler": "^1.0.0"
+ }
+ },
+ "node_modules/ndarray-pixels": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ndarray-pixels/-/ndarray-pixels-5.2.0.tgz",
+ "integrity": "sha512-lTh4tFKziAatVTa9crIsidUyn+lqujVOQpzfdBWvdFu2wo9Uo6z261lVX7SgMyP89xGmj3TMTPbbxl9YDnV4SA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.14",
+ "ndarray": "^1.0.19",
+ "ndarray-ops": "^1.2.2",
+ "sharp": "^0.35.0"
+ }
+ },
+ "node_modules/property-graph": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",
+ "integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.8.6",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.5",
+ "@img/sharp-darwin-x64": "0.35.5",
+ "@img/sharp-freebsd-wasm32": "0.35.5",
+ "@img/sharp-libvips-darwin-arm64": "1.3.4",
+ "@img/sharp-libvips-darwin-x64": "1.3.4",
+ "@img/sharp-libvips-linux-arm": "1.3.4",
+ "@img/sharp-libvips-linux-arm64": "1.3.4",
+ "@img/sharp-libvips-linux-ppc64": "1.3.4",
+ "@img/sharp-libvips-linux-riscv64": "1.3.4",
+ "@img/sharp-libvips-linux-s390x": "1.3.4",
+ "@img/sharp-libvips-linux-x64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
+ "@img/sharp-linux-arm": "0.35.5",
+ "@img/sharp-linux-arm64": "0.35.5",
+ "@img/sharp-linux-ppc64": "0.35.5",
+ "@img/sharp-linux-riscv64": "0.35.5",
+ "@img/sharp-linux-s390x": "0.35.5",
+ "@img/sharp-linux-x64": "0.35.5",
+ "@img/sharp-linuxmusl-arm64": "0.35.5",
+ "@img/sharp-linuxmusl-x64": "0.35.5",
+ "@img/sharp-webcontainers-wasm32": "0.35.5",
+ "@img/sharp-win32-arm64": "0.35.5",
+ "@img/sharp-win32-ia32": "0.35.5",
+ "@img/sharp-win32-x64": "0.35.5"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/three": {
+ "version": "0.187.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz",
+ "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==",
+ "license": "MIT"
+ },
+ "node_modules/tslib": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/uniq": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz",
+ "integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/plugin/skills/brief2mp4/3d/package.json b/plugin/skills/brief2mp4/3d/package.json
new file mode 100644
index 0000000..81ef31e
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "brief2mp4-3d-runtime",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "description": "Node components of the optional brief2mp4 3D pack: three.js, glTF Transform, meshoptimizer, Jolt, GSAP and fonts (vendored into render projects, so renders never touch the network).",
+ "license": "MIT",
+ "dependencies": {
+ "@fontsource-variable/inter": "5.3.0",
+ "@fontsource-variable/space-grotesk": "5.3.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "gsap": "3.15.0",
+ "jolt-physics": "1.1.1",
+ "meshoptimizer": "1.3.0",
+ "three": "0.187.0"
+ }
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/anodized_blue.json b/plugin/skills/brief2mp4/3d/presets/materials/anodized_blue.json
new file mode 100644
index 0000000..eaa4c5b
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/anodized_blue.json
@@ -0,0 +1,14 @@
+{
+ "name": "anodized_blue",
+ "description": "Blue anodised metal with a thin clear coat.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.18,
+ 0.36,
+ 0.86
+ ],
+ "metallic": 1.0,
+ "roughness": 0.3,
+ "clearcoat": 0.4,
+ "clearcoatRoughness": 0.15
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/brushed_aluminum.json b/plugin/skills/brief2mp4/3d/presets/materials/brushed_aluminum.json
new file mode 100644
index 0000000..a43f0bb
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/brushed_aluminum.json
@@ -0,0 +1,12 @@
+{
+ "name": "brushed_aluminum",
+ "description": "Satin aluminium, soft broad highlights.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.91,
+ 0.92,
+ 0.92
+ ],
+ "metallic": 1.0,
+ "roughness": 0.34
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/car_paint_red.json b/plugin/skills/brief2mp4/3d/presets/materials/car_paint_red.json
new file mode 100644
index 0000000..d8129cb
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/car_paint_red.json
@@ -0,0 +1,14 @@
+{
+ "name": "car_paint_red",
+ "description": "Deep red lacquer under a glossy coat.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.62,
+ 0.03,
+ 0.04
+ ],
+ "metallic": 0.4,
+ "roughness": 0.35,
+ "clearcoat": 1.0,
+ "clearcoatRoughness": 0.04
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/ceramic_white.json b/plugin/skills/brief2mp4/3d/presets/materials/ceramic_white.json
new file mode 100644
index 0000000..3621b38
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/ceramic_white.json
@@ -0,0 +1,14 @@
+{
+ "name": "ceramic_white",
+ "description": "Glazed white ceramic.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.94,
+ 0.93,
+ 0.9
+ ],
+ "metallic": 0.0,
+ "roughness": 0.25,
+ "clearcoat": 0.6,
+ "clearcoatRoughness": 0.08
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/clear_glass.json b/plugin/skills/brief2mp4/3d/presets/materials/clear_glass.json
new file mode 100644
index 0000000..017d636
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/clear_glass.json
@@ -0,0 +1,14 @@
+{
+ "name": "clear_glass",
+ "description": "Clear glass (transmission).",
+ "colorSpace": "linear",
+ "baseColor": [
+ 1.0,
+ 1.0,
+ 1.0
+ ],
+ "metallic": 0.0,
+ "roughness": 0.02,
+ "transmission": 1.0,
+ "ior": 1.5
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/copper.json b/plugin/skills/brief2mp4/3d/presets/materials/copper.json
new file mode 100644
index 0000000..4880ffb
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/copper.json
@@ -0,0 +1,12 @@
+{
+ "name": "copper",
+ "description": "Warm copper.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.95,
+ 0.64,
+ 0.54
+ ],
+ "metallic": 1.0,
+ "roughness": 0.25
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/glossy_plastic.json b/plugin/skills/brief2mp4/3d/presets/materials/glossy_plastic.json
new file mode 100644
index 0000000..62d29b3
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/glossy_plastic.json
@@ -0,0 +1,12 @@
+{
+ "name": "glossy_plastic",
+ "description": "Light glossy plastic.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.9,
+ 0.9,
+ 0.9
+ ],
+ "metallic": 0.0,
+ "roughness": 0.2
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/gold.json b/plugin/skills/brief2mp4/3d/presets/materials/gold.json
new file mode 100644
index 0000000..bb6e868
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/gold.json
@@ -0,0 +1,12 @@
+{
+ "name": "gold",
+ "description": "Polished gold (measured F0).",
+ "colorSpace": "linear",
+ "baseColor": [
+ 1.0,
+ 0.77,
+ 0.34
+ ],
+ "metallic": 1.0,
+ "roughness": 0.18
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/matte_plastic.json b/plugin/skills/brief2mp4/3d/presets/materials/matte_plastic.json
new file mode 100644
index 0000000..a7bdc79
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/matte_plastic.json
@@ -0,0 +1,12 @@
+{
+ "name": "matte_plastic",
+ "description": "Near-black matte plastic.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.03,
+ 0.03,
+ 0.035
+ ],
+ "metallic": 0.0,
+ "roughness": 0.72
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/neon_emissive.json b/plugin/skills/brief2mp4/3d/presets/materials/neon_emissive.json
new file mode 100644
index 0000000..58b69e2
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/neon_emissive.json
@@ -0,0 +1,18 @@
+{
+ "name": "neon_emissive",
+ "description": "Glowing orange emitter (the only preset that wants bloom).",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.05,
+ 0.05,
+ 0.05
+ ],
+ "metallic": 0.0,
+ "roughness": 0.4,
+ "emissiveStrength": 8.0,
+ "emissive": [
+ 1.0,
+ 0.35,
+ 0.1
+ ]
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/pcb_green.json b/plugin/skills/brief2mp4/3d/presets/materials/pcb_green.json
new file mode 100644
index 0000000..dfd6845
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/pcb_green.json
@@ -0,0 +1,14 @@
+{
+ "name": "pcb_green",
+ "description": "Solder-mask green circuit board (dark, linear).",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.006,
+ 0.045,
+ 0.02
+ ],
+ "metallic": 0.0,
+ "roughness": 0.38,
+ "clearcoat": 0.5,
+ "clearcoatRoughness": 0.2
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/polished_steel.json b/plugin/skills/brief2mp4/3d/presets/materials/polished_steel.json
new file mode 100644
index 0000000..41ecf5e
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/polished_steel.json
@@ -0,0 +1,12 @@
+{
+ "name": "polished_steel",
+ "description": "Mirror-ish steel.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.78,
+ 0.78,
+ 0.8
+ ],
+ "metallic": 1.0,
+ "roughness": 0.12
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/rubber.json b/plugin/skills/brief2mp4/3d/presets/materials/rubber.json
new file mode 100644
index 0000000..a6ce8c7
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/rubber.json
@@ -0,0 +1,12 @@
+{
+ "name": "rubber",
+ "description": "Black rubber.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.04,
+ 0.04,
+ 0.045
+ ],
+ "metallic": 0.0,
+ "roughness": 0.9
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/silicon_die.json b/plugin/skills/brief2mp4/3d/presets/materials/silicon_die.json
new file mode 100644
index 0000000..ad197f7
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/silicon_die.json
@@ -0,0 +1,12 @@
+{
+ "name": "silicon_die",
+ "description": "Dark silicon die.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.08,
+ 0.08,
+ 0.12
+ ],
+ "metallic": 0.7,
+ "roughness": 0.15
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/smoked_glass.json b/plugin/skills/brief2mp4/3d/presets/materials/smoked_glass.json
new file mode 100644
index 0000000..92a9664
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/smoked_glass.json
@@ -0,0 +1,14 @@
+{
+ "name": "smoked_glass",
+ "description": "Tinted smoked glass.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.35,
+ 0.36,
+ 0.4
+ ],
+ "metallic": 0.0,
+ "roughness": 0.05,
+ "transmission": 0.85,
+ "ior": 1.5
+}
diff --git a/plugin/skills/brief2mp4/3d/presets/materials/velvet.json b/plugin/skills/brief2mp4/3d/presets/materials/velvet.json
new file mode 100644
index 0000000..ac31d41
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/presets/materials/velvet.json
@@ -0,0 +1,18 @@
+{
+ "name": "velvet",
+ "description": "Deep red velvet with sheen.",
+ "colorSpace": "linear",
+ "baseColor": [
+ 0.08,
+ 0.005,
+ 0.02
+ ],
+ "metallic": 0.0,
+ "roughness": 0.8,
+ "sheen": 1.0,
+ "sheenColor": [
+ 1.0,
+ 0.6,
+ 0.7
+ ]
+}
diff --git a/plugin/skills/brief2mp4/3d/requirements-cad.txt b/plugin/skills/brief2mp4/3d/requirements-cad.txt
new file mode 100644
index 0000000..fc62882
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/requirements-cad.txt
@@ -0,0 +1,2 @@
+# CAD component (large, optional): CadQuery brings the OpenCascade kernel (cadquery-ocp).
+cadquery==2.8.0
diff --git a/plugin/skills/brief2mp4/3d/requirements-core.txt b/plugin/skills/brief2mp4/3d/requirements-core.txt
new file mode 100644
index 0000000..cba9ec7
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/requirements-core.txt
@@ -0,0 +1,6 @@
+# Core component: geometry from specs, GLB export, convex hulls for physics.
+# Python 3.12 or 3.13 (numpy 2.5 and scipy 1.18 need 3.12+). Pinned to the versions the test suite ran against.
+numpy==2.5.4
+trimesh==5.2.1
+scipy==1.18.1
+manifold3d==3.5.5
diff --git a/plugin/skills/brief2mp4/3d/requirements-dev.txt b/plugin/skills/brief2mp4/3d/requirements-dev.txt
new file mode 100644
index 0000000..7ecc9b8
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/requirements-dev.txt
@@ -0,0 +1,2 @@
+# Only needed to run the test suite in tests/.
+pytest==9.2.0
diff --git a/plugin/skills/brief2mp4/3d/templates/blender_shot.py b/plugin/skills/brief2mp4/3d/templates/blender_shot.py
new file mode 100644
index 0000000..59f3bde
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/templates/blender_shot.py
@@ -0,0 +1,210 @@
+"""b2m3d Blender shot: GLB -> studio-lit, camera-orbited render on the best GPU available.
+
+GPU order: Metal on macOS; OptiX, CUDA, HIP, oneAPI on Windows and Linux; CPU otherwise.
+Run: blender -b --factory-startup -P blender_shot.py -- <config.json>
+Config keys: glb, out_dir, frames, fps, width, height, engine (cycles|eevee),
+samples, orbit_from, orbit_to, height_ratio, distance, lens, transparent,
+look (studio|dramatic|soft), floor (dark|shadow|none), view (agx|neutral|filmic),
+save_blend. Prints: B2M3D_BLENDER {json}
+"""
+import json
+import math
+import sys
+import time
+from pathlib import Path
+
+import bpy
+from mathutils import Vector
+
+CFG = json.loads(Path(sys.argv[sys.argv.index("--") + 1]).read_text())
+
+
+GPU_BACKENDS = ["METAL"] if sys.platform == "darwin" else ["OPTIX", "CUDA", "HIP", "ONEAPI"]
+
+
+def setup_gpu(scene):
+ """Enable the first GPU backend this Blender build and machine offer; else CPU."""
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ for kind in GPU_BACKENDS:
+ try:
+ prefs.compute_device_type = kind
+ prefs.refresh_devices()
+ except (TypeError, AttributeError, RuntimeError):
+ continue # this build does not offer that backend
+ gpus = [d for d in prefs.devices if d.type == kind]
+ if gpus:
+ for d in prefs.devices:
+ d.use = d.type == kind
+ scene.cycles.device = "GPU"
+ return [f"{kind}: {d.name}" for d in gpus]
+ scene.cycles.device = "CPU"
+ return []
+
+
+def setup_render(scene):
+ engine = CFG.get("engine", "cycles")
+ # The EEVEE identifier changed between Blender versions, so try each name it has had.
+ for name in (["CYCLES"] if engine == "cycles" else ["BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"]):
+ try:
+ scene.render.engine = name
+ break
+ except TypeError as exc:
+ print("B2M3D_WARN engine:", exc)
+ devices = setup_gpu(scene) if engine == "cycles" else []
+ if engine == "cycles":
+ c = scene.cycles
+ c.samples = int(CFG.get("samples", 96))
+ c.use_adaptive_sampling = True
+ c.adaptive_threshold = 0.02
+ c.use_denoising = True
+ for attr, val in (("denoiser", "OPENIMAGEDENOISE"), ("denoising_use_gpu", True)):
+ if hasattr(c, attr):
+ try:
+ setattr(c, attr, val)
+ except (TypeError, AttributeError):
+ pass
+ c.max_bounces = 8
+ c.glossy_bounces = 4
+ c.transmission_bounces = 8
+ r = scene.render
+ r.resolution_x, r.resolution_y = int(CFG.get("width", 1920)), int(CFG.get("height", 1080))
+ r.resolution_percentage = 100
+ r.fps = int(CFG.get("fps", 30))
+ r.film_transparent = bool(CFG.get("transparent", False))
+ r.image_settings.file_format = "PNG"
+ r.image_settings.color_mode = "RGBA" if r.film_transparent else "RGB"
+ r.filepath = CFG["out_dir"].rstrip("/") + "/frame_"
+ scene.frame_start, scene.frame_end = 1, int(CFG.get("frames", 120))
+ want = {"agx": "AgX", "neutral": "Khronos PBR Neutral", "filmic": "Filmic"}[CFG.get("view", "agx")]
+ try: # dynamic enum: static enum_items is a placeholder, so just try it
+ scene.view_settings.view_transform = want
+ except TypeError as exc:
+ print("B2M3D_WARN view transform:", exc)
+ if CFG.get("look_preset"):
+ try:
+ scene.view_settings.look = CFG["look_preset"] # e.g. "AgX - Punchy"
+ except TypeError as exc:
+ print("B2M3D_WARN look:", exc)
+ return devices
+
+
+def import_glb():
+ before = set(bpy.data.objects)
+ src = CFG["glb"]
+ if src.lower().endswith((".usd", ".usda", ".usdc", ".usdz")):
+ bpy.ops.wm.usd_import(filepath=src, set_frame_range=False)
+ elif src.lower().endswith(".obj"):
+ bpy.ops.wm.obj_import(filepath=src)
+ else:
+ bpy.ops.import_scene.gltf(filepath=src)
+ objs = [o for o in bpy.data.objects if o not in before]
+ meshes = [o for o in objs if o.type == "MESH"]
+ lo = Vector((1e9, 1e9, 1e9))
+ hi = Vector((-1e9, -1e9, -1e9))
+ for o in meshes:
+ for corner in o.bound_box:
+ w = o.matrix_world @ Vector(corner)
+ lo = Vector(map(min, lo, w))
+ hi = Vector(map(max, hi, w))
+ return meshes, lo, hi
+
+
+def area_light(name, loc, target, energy, size, color):
+ data = bpy.data.lights.new(name, "AREA")
+ data.energy, data.size, data.color = energy, size, color
+ obj = bpy.data.objects.new(name, data)
+ obj.location = loc
+ bpy.context.scene.collection.objects.link(obj)
+ direction = Vector(target) - Vector(loc)
+ obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
+ return obj
+
+
+LOOKS = { # (rel position, energy per m^2 of scene, size ratio, colour)
+ "studio": [((2.2, -2.0, 2.6), 900, 1.4, (1, 1, 1)), ((-2.4, 2.2, 1.6), 700, 0.8, (0.75, 0.85, 1)),
+ ((-2.6, -1.8, 0.8), 160, 1.8, (1, 0.93, 0.86))],
+ "dramatic": [((1.6, -1.4, 3.0), 1300, 0.9, (1, 0.96, 0.9)), ((-2.2, 2.6, 1.2), 1100, 0.5, (0.55, 0.65, 1))],
+ "soft": [((0, -1.5, 3.2), 700, 2.6, (1, 1, 1)), ((-2.5, 1.5, 1.5), 250, 2.0, (1, 1, 1))],
+}
+
+
+def lights(centre, size):
+ for i, (rel, energy, sz, col) in enumerate(LOOKS[CFG.get("look", "dramatic")]):
+ loc = centre + Vector(rel) * size
+ area_light(f"b2m3d_light_{i}", loc, centre, energy * size * size, sz * size, col)
+
+
+def world(scene):
+ w = bpy.data.worlds.new("b2m3d_world")
+ scene.world = w
+ w.use_nodes = True
+ bg = next(n for n in w.node_tree.nodes if n.type == "BACKGROUND")
+ bg.inputs[0].default_value = CFG.get("world_color", (0.012, 0.014, 0.02, 1))
+ bg.inputs[1].default_value = float(CFG.get("world_strength", 1.0))
+
+
+def floor(lo, centre, size):
+ mode = CFG.get("floor", "shadow" if CFG.get("transparent") else "dark")
+ if mode == "none":
+ return
+ bpy.ops.mesh.primitive_plane_add(size=size * 60, location=(centre.x, centre.y, lo.z))
+ plane = bpy.context.active_object
+ if mode == "shadow":
+ plane.is_shadow_catcher = True
+ return
+ mat = bpy.data.materials.new("b2m3d_floor")
+ mat.use_nodes = True
+ bsdf = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
+ bsdf.inputs["Base Color"].default_value = tuple(CFG.get("floor_color", (0.0025, 0.0028, 0.0035))) + (1,)
+ bsdf.inputs["Roughness"].default_value = float(CFG.get("floor_roughness", 0.42))
+ plane.data.materials.append(mat)
+
+
+def camera(centre, size, frames):
+ rig = bpy.data.objects.new("b2m3d_rig", None)
+ rig.location = centre
+ bpy.context.scene.collection.objects.link(rig)
+ cam_data = bpy.data.cameras.new("b2m3d_cam")
+ cam_data.lens = float(CFG.get("lens", 70))
+ cam_data.dof.use_dof = bool(CFG.get("dof", False)) # small objects = macro DOF; opt in
+ cam_data.dof.aperture_fstop = float(CFG.get("fstop", 4.0))
+ cam = bpy.data.objects.new("b2m3d_cam", cam_data)
+ bpy.context.scene.collection.objects.link(cam)
+ dist = size * float(CFG.get("distance", 2.6))
+ cam.location = (0, -dist, dist * float(CFG.get("height_ratio", 0.62)))
+ cam.parent = rig
+ track = cam.constraints.new("TRACK_TO")
+ track.target = rig
+ track.track_axis, track.up_axis = "TRACK_NEGATIVE_Z", "UP_Y"
+ cam_data.dof.focus_object = rig
+ bpy.context.scene.camera = cam
+ a0, a1 = math.radians(CFG.get("orbit_from", -30)), math.radians(CFG.get("orbit_to", 30))
+ rig.rotation_euler = (0, 0, a0)
+ rig.keyframe_insert("rotation_euler", index=2, frame=1)
+ rig.rotation_euler = (0, 0, a1)
+ rig.keyframe_insert("rotation_euler", index=2, frame=frames)
+
+
+def main():
+ t0 = time.time()
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ devices = setup_render(scene)
+ meshes, lo, hi = import_glb()
+ scene.frame_start, scene.frame_end = 1, int(CFG.get("frames", 120)) # importers may reset it
+ centre, size = (lo + hi) / 2, max((hi - lo).length, 1e-4)
+ world(scene)
+ lights(centre, size)
+ floor(lo, centre, size)
+ camera(centre, size, scene.frame_end)
+ if CFG.get("save_blend"):
+ bpy.ops.wm.save_as_mainfile(filepath=CFG["save_blend"])
+ if not CFG.get("setup_only"):
+ bpy.ops.render.render(animation=True)
+ print("B2M3D_BLENDER " + json.dumps({
+ "out_dir": CFG["out_dir"], "frames": scene.frame_end, "engine": scene.render.engine,
+ "gpu": devices, "device": scene.cycles.device if scene.render.engine == "CYCLES" else "GPU/EEVEE", "meshes": len(meshes), "size_m": round(size, 4),
+ "view": scene.view_settings.view_transform, "seconds": round(time.time() - t0, 1)}))
+
+
+main()
diff --git a/plugin/skills/brief2mp4/3d/templates/shot-runtime.js b/plugin/skills/brief2mp4/3d/templates/shot-runtime.js
new file mode 100644
index 0000000..5a6b041
--- /dev/null
+++ b/plugin/skills/brief2mp4/3d/templates/shot-runtime.js
@@ -0,0 +1,278 @@
+// b2m3d shot runtime: a deterministic, frame-seekable Three.js scene for HyperFrames.
+// Everything visible is a pure function of time t. Config arrives as window.B2M3D_SHOT.
+import * as THREE from "three";
+import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
+import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
+import { MeshoptDecoder } from "three/addons/libs/meshopt_decoder.module.js";
+import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
+import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
+import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
+import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
+
+const SHOT = window.B2M3D_SHOT;
+const W = SHOT.width, H = SHOT.height;
+const TONE = { aces: THREE.ACESFilmicToneMapping, agx: THREE.AgXToneMapping,
+ neutral: THREE.NeutralToneMapping, none: THREE.NoToneMapping };
+
+const ease = {
+ linear: (x) => x,
+ inOutCubic: (x) => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2),
+ outExpo: (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * x)),
+ inOutSine: (x) => -(Math.cos(Math.PI * x) - 1) / 2,
+};
+const clamp01 = (x) => Math.min(1, Math.max(0, x));
+const v3 = (a) => new THREE.Vector3(a[0], a[1], a[2]);
+
+function makeRenderer() {
+ const canvas = document.getElementById("b2m3d-canvas");
+ const r = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true,
+ preserveDrawingBuffer: true, powerPreference: "high-performance" });
+ r.setPixelRatio(1);
+ r.setSize(W, H, false);
+ r.outputColorSpace = THREE.SRGBColorSpace;
+ r.toneMapping = TONE[SHOT.tonemapping ?? "neutral"];
+ r.toneMappingExposure = SHOT.exposure ?? 1.0;
+ r.shadowMap.enabled = true;
+ r.shadowMap.type = THREE.PCFSoftShadowMap;
+ r.setClearColor(0x000000, 0);
+ return r;
+}
+
+async function makeEnvironment(renderer, scene) {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ let tex;
+ if (SHOT.hdri) {
+ const hdr = await new HDRLoader().loadAsync(SHOT.hdri);
+ tex = pmrem.fromEquirectangular(hdr).texture;
+ hdr.dispose();
+ } else {
+ tex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ }
+ scene.environment = tex;
+ scene.environmentIntensity = SHOT.envIntensity ?? 0.35;
+ scene.environmentRotation.y = THREE.MathUtils.degToRad(SHOT.envRotation ?? 0);
+ pmrem.dispose();
+}
+
+const LIGHT_RIGS = {
+ studio: [{ type: "key", color: "#ffffff", intensity: 2.6, pos: [3, 5, 4] },
+ { type: "rim", color: "#9fc4ff", intensity: 2.0, pos: [-4, 3, -4] },
+ { type: "fill", color: "#ffe9d6", intensity: 0.4, pos: [-3, 1.5, 3] }],
+ dramatic: [{ type: "key", color: "#fff4e6", intensity: 4.0, pos: [2.5, 6, 2] },
+ { type: "rim", color: "#6f8cff", intensity: 3.5, pos: [-3, 2, -5] }],
+ soft: [{ type: "key", color: "#ffffff", intensity: 1.4, pos: [2, 6, 3] },
+ { type: "fill", color: "#ffffff", intensity: 0.8, pos: [-3, 3, 2] }],
+};
+
+function addLights(scene, bounds) {
+ const rig = Array.isArray(SHOT.lights) ? SHOT.lights : LIGHT_RIGS[SHOT.lights ?? "dramatic"];
+ const size = bounds.getSize(new THREE.Vector3()).length() || 1;
+ const centre = bounds.getCenter(new THREE.Vector3());
+ for (const l of rig) {
+ const light = new THREE.DirectionalLight(l.color, l.intensity);
+ light.position.copy(v3(l.pos).multiplyScalar(size * 0.6).add(centre));
+ light.target.position.copy(centre);
+ if (l.type === "key") {
+ light.castShadow = true;
+ const s = light.shadow;
+ s.mapSize.set(4096, 4096);
+ s.bias = -0.0002;
+ s.normalBias = 0.02 * size;
+ s.radius = 6;
+ const half = size * 1.2;
+ Object.assign(s.camera, { left: -half, right: half, top: half, bottom: -half,
+ near: 0.01, far: size * 6 });
+ }
+ scene.add(light, light.target);
+ }
+}
+
+function addGround(scene, bounds) {
+ const g = SHOT.ground ?? { shadow: 0.35 };
+ if (g === false) return;
+ const size = bounds.getSize(new THREE.Vector3()).length() || 1;
+ const plane = new THREE.Mesh(new THREE.PlaneGeometry(size * 40, size * 40),
+ g.color ? new THREE.MeshStandardMaterial({ color: g.color, roughness: g.roughness ?? 0.6, metalness: 0 })
+ : new THREE.ShadowMaterial({ opacity: g.shadow ?? 0.35 }));
+ plane.rotation.x = -Math.PI / 2;
+ plane.position.y = g.y ?? bounds.min.y;
+ plane.receiveShadow = true;
+ scene.add(plane);
+}
+
+async function loadModels(scene) {
+ const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);
+ const out = [];
+ for (const m of SHOT.models ?? []) {
+ const gltf = await loader.loadAsync(m.src);
+ const root = gltf.scene;
+ root.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ if (m.position) root.position.copy(v3(m.position));
+ if (m.rotation) root.rotation.set(...m.rotation.map(THREE.MathUtils.degToRad));
+ if (m.scale) root.scale.setScalar(m.scale);
+ const pivot = new THREE.Group();
+ pivot.add(root);
+ scene.add(pivot);
+ const mixer = gltf.animations.length ? new THREE.AnimationMixer(root) : null;
+ if (mixer) gltf.animations.forEach((clip) => mixer.clipAction(clip).play());
+ out.push({ cfg: m, pivot, root, mixer, rest: root.position.clone() });
+ }
+ return out;
+}
+
+function trackPose(track, fps, t) {
+ const f = Math.min(track.length - 1, Math.max(0, t * fps));
+ const i = Math.floor(f), j = Math.min(track.length - 1, i + 1), a = f - i;
+ const p = v3(track[i]).lerp(v3(track[j]), a);
+ const qa = new THREE.Quaternion(...track[i].slice(3)), qb = new THREE.Quaternion(...track[j].slice(3));
+ return { p, q: qa.slerp(qb, a) };
+}
+
+// The parts of an exploded view are the children of the first node that has several; exporters
+// often wrap everything in one root node, so skip down through single-child wrappers.
+function explodeParts(root) {
+ let node = root;
+ while (node.children.length === 1) node = node.children[0];
+ return node.children.length ? node.children : [node];
+}
+
+function animateModel(m, t, physics) {
+ const c = m.cfg;
+ if (c.track && physics) {
+ const { p, q } = trackPose(physics.tracks[c.track], physics.fps, t - (c.trackStart ?? 0));
+ m.pivot.position.copy(p);
+ m.pivot.quaternion.copy(q);
+ }
+ if (c.spin) m.pivot.rotation.y = THREE.MathUtils.degToRad(c.spin) * t + (c.spinOffset ?? 0);
+ if (c.float) m.pivot.position.y = Math.sin(t * (c.float.speed ?? 1.2)) * (c.float.amp ?? 0.01);
+ if (c.reveal) {
+ const k = ease[c.reveal.ease ?? "outExpo"](clamp01((t - (c.reveal.start ?? 0)) / (c.reveal.duration ?? 0.8)));
+ m.pivot.scale.setScalar(Math.max(1e-4, k));
+ }
+ if (c.explode) {
+ const e = c.explode;
+ const k = ease.inOutCubic(clamp01((t - (e.start ?? 0)) / (e.duration ?? 1)));
+ explodeParts(m.root).forEach((child, idx) => {
+ const dir = e.dirs?.[child.name] ?? [0, idx * (e.step ?? 0.03), 0];
+ child.userData.rest ??= child.position.clone();
+ child.position.copy(child.userData.rest).addScaledVector(v3(dir), k);
+ });
+ }
+ if (m.mixer) m.mixer.setTime(t);
+}
+
+function fitBox(box, auto, fov) {
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
+ const az = THREE.MathUtils.degToRad(auto.azimuth ?? 35), el = THREE.MathUtils.degToRad(auto.elevation ?? 22);
+ const dir = new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el));
+ const dist = (sphere.radius / Math.sin(THREE.MathUtils.degToRad(fov) / 2)) * (auto.padding ?? 1.15);
+ return { pos: sphere.center.clone().addScaledVector(dir, dist), target: sphere.center.clone() };
+}
+
+// camera.auto: frame everything at t=0 and the settled pose at the end (from the physics bake).
+function autoCamera(t, bounds, physics, auto) {
+ const fov = SHOT.camera.fov ?? 28;
+ const endBox = new THREE.Box3();
+ if (physics) {
+ for (const [name, tr] of Object.entries(physics.tracks)) {
+ if ((auto.ignore ?? ["floor"]).includes(name)) continue;
+ endBox.expandByPoint(v3(tr[tr.length - 1]));
+ }
+ endBox.expandByScalar(auto.margin ?? 0.03);
+ }
+ // Start wide on the landing zone (parts fall INTO frame), end tight on the settled pile.
+ const land = endBox.isEmpty() ? bounds : endBox;
+ const a = fitBox(land, { ...auto, padding: auto.startPadding ?? 1.8,
+ azimuth: auto.startAzimuth ?? auto.azimuth, elevation: auto.startElevation ?? auto.elevation }, fov);
+ const b = fitBox(land, auto, fov);
+ const x = ease[auto.ease ?? "inOutSine"](clamp01((t - (auto.start ?? 0)) / (auto.duration ?? SHOT.duration)));
+ return { pos: a.pos.lerp(b.pos, x), target: a.target.lerp(b.target, x), fov };
+}
+
+function cameraAt(t, bounds, physics) {
+ const cam = SHOT.camera ?? {};
+ if (cam.auto) return autoCamera(t, bounds, physics, cam.auto);
+ const centre = bounds.getCenter(new THREE.Vector3());
+ const size = bounds.getSize(new THREE.Vector3()).length() || 1;
+ if (cam.keys?.length) {
+ const keys = cam.keys;
+ let k = keys.length - 1;
+ for (let i = 0; i < keys.length - 1; i++) if (t < keys[i + 1].t) { k = i; break; }
+ const a = keys[k], b = keys[Math.min(k + 1, keys.length - 1)];
+ const span = Math.max(1e-6, b.t - a.t);
+ const x = ease[b.ease ?? cam.ease ?? "inOutCubic"](clamp01((t - a.t) / span));
+ return { pos: v3(a.pos).lerp(v3(b.pos), x), target: v3(a.target ?? centre.toArray()).lerp(v3(b.target ?? centre.toArray()), x),
+ fov: (a.fov ?? cam.fov ?? 30) + ((b.fov ?? cam.fov ?? 30) - (a.fov ?? cam.fov ?? 30)) * x };
+ }
+ const o = cam.orbit ?? {};
+ const x = ease[o.ease ?? "inOutSine"](clamp01(t / SHOT.duration));
+ const deg = (o.from ?? -35) + ((o.to ?? 35) - (o.from ?? -35)) * x;
+ const r = (o.radius ?? 1.6) * size, h = (o.height ?? 0.45) * size;
+ const ang = THREE.MathUtils.degToRad(deg);
+ return { pos: new THREE.Vector3(Math.sin(ang) * r, h, Math.cos(ang) * r).add(centre),
+ target: o.target ? v3(o.target) : centre, fov: cam.fov ?? 30 };
+}
+
+// Bounds that drive lights, shadow map and ground height: each model at rest, plus where every
+// tracked body ends up (its last pose, with its own height). The fall itself is left out on purpose,
+// or a part dropped from far above would stretch the box and blur the shadows. The physics floor
+// is not a model, so it never counts.
+function sceneBounds(models, physics) {
+ const box = new THREE.Box3();
+ models.forEach((m) => box.expandByObject(m.pivot));
+ if (physics) {
+ for (const m of models) {
+ const track = m.cfg.track && physics.tracks[m.cfg.track];
+ if (!track) continue;
+ const local = new THREE.Box3().setFromObject(m.pivot);
+ const end = v3(track[track.length - 1]);
+ box.expandByPoint(end.clone().add(new THREE.Vector3(local.min.x, local.min.y, local.min.z)));
+ box.expandByPoint(end.clone().add(new THREE.Vector3(local.max.x, local.max.y, local.max.z)));
+ }
+ }
+ if (SHOT.bounds) return new THREE.Box3(v3(SHOT.bounds[0]), v3(SHOT.bounds[1]));
+ return box.isEmpty() ? new THREE.Box3(v3([-1, -1, -1]), v3([1, 1, 1])) : box;
+}
+
+async function build() {
+ const renderer = makeRenderer();
+ const scene = new THREE.Scene();
+ const camera = new THREE.PerspectiveCamera(30, W / H, 0.001, 1000);
+ await makeEnvironment(renderer, scene);
+ const physics = window.B2M3D_PHYSICS ?? null;
+ const models = await loadModels(scene);
+ const bounds = sceneBounds(models, physics); // rest pose, before reveal/explode
+ models.forEach((m) => animateModel(m, 0, physics));
+ addLights(scene, bounds);
+ addGround(scene, bounds);
+
+ const composer = new EffectComposer(renderer);
+ composer.setPixelRatio(1);
+ composer.setSize(W, H);
+ composer.addPass(new RenderPass(scene, camera));
+ if (SHOT.bloom) {
+ const b = SHOT.bloom;
+ composer.addPass(new UnrealBloomPass(new THREE.Vector2(W, H), b.strength ?? 0.35, b.radius ?? 0.4, b.threshold ?? 0.85));
+ }
+ composer.addPass(new OutputPass());
+
+ function renderAt(t) {
+ models.forEach((m) => animateModel(m, t, physics));
+ const c = cameraAt(t, bounds, physics);
+ camera.position.copy(c.pos);
+ camera.fov = c.fov;
+ camera.updateProjectionMatrix();
+ camera.lookAt(c.target);
+ composer.render();
+ }
+ renderer.compile(scene, camera);
+ renderAt(window.__hfThreeTime || 0);
+ window.addEventListener("hf-seek", (e) => renderAt(e.detail.time));
+ window.__b2m3dRenderAt = renderAt;
+ return true;
+}
+
+window.__hf = window.__hf || {};
+window.__hf.buildReady = window.__hf.buildReady || {};
+window.__hf.buildReady["b2m3d-scene"] = build();
diff --git a/plugin/skills/brief2mp4/SKILL.md b/plugin/skills/brief2mp4/SKILL.md
index 8725c96..d17f609 100644
--- a/plugin/skills/brief2mp4/SKILL.md
+++ b/plugin/skills/brief2mp4/SKILL.md
@@ -1,6 +1,6 @@
---
name: brief2mp4
-description: Turn a written brief into a finished, checked MP4 motion graphic. Use when asked to make an animation, motion graphic, kinetic typography, title sequence, logo sting, 3D scene, product turntable or short explainer clip as a video file. Builds with HyperFrames (HTML + GSAP), Three.js or Blender, finishes with ffmpeg, then checks the video against the brief and fixes what fails before handing it over.
+description: Turn a written brief into a finished, checked MP4 motion graphic. Use when asked to make an animation, motion graphic, 2D explainer, maths or algorithm animation, tutorial intro, animated story or skit, YouTube Short or Reel, data story, kinetic typography, lyric video, title sequence, logo sting, 3D scene, 3D product shot, physics drop, exploded view, product turntable or short explainer clip as a video file. Builds with HyperFrames (HTML + GSAP), Three.js, an optional 3D pack (CAD, materials, physics) or Blender, finishes with ffmpeg, then checks the video against the brief and fixes what fails before handing it over.
---
# brief2mp4
@@ -11,19 +11,19 @@ Work in this order every time: **spec, build, self-check, fix, deliver.** Do not
## 0. Before you start
-Check the tools the job needs and say what is missing:
+Run the doctor once per machine. It checks every tool and prints the install command for this OS:
```bash
-node -v # 22 or newer (HyperFrames and Three.js paths)
-ffmpeg -version # every path
-blender --version # only for the Blender path
+bash <this skill's folder>/scripts/doctor.sh
```
-On macOS Blender is often not on the PATH: use `/Applications/Blender.app/Contents/MacOS/Blender`. If a tool is missing, tell the user the install command (`brew install node ffmpeg`, `brew install --cask blender`, or the Linux equivalent) and stop, unless the brief allows another tool.
+Required: Node.js 22 or newer and ffmpeg. Optional: Blender (realistic product shots) and the 3D pack (physics, exploded views, CAD models). If a required tool is missing, tell the user the command the doctor printed and stop. If the whole machine needs setting up, follow `SETUP.md` in the brief2mp4 repository.
+
+**Windows.** The scripts are bash. Run them with Git Bash (`bash script.sh ...`; from PowerShell: `& "C:\Program Files\Git\bin\bash.exe" script.sh ...`). If Git for Windows is missing, ask the user to install it: `winget install -e --id Git.Git`. Write paths with forward slashes inside bash. **macOS.** Blender is often not on the PATH: use `/Applications/Blender.app/Contents/MacOS/Blender`.
Work inside one project folder. Never write outside it.
-The scripts and templates named below sit next to this SKILL.md. Call them by their full path, for example `<this skill's folder>/scripts/finish.sh`; use the folder this SKILL.md was loaded from. A script install puts it in `~/.claude/skills/brief2mp4/` or `~/.codex/skills/brief2mp4/`; a plugin install puts it in the app's plugin cache.
+The scripts, templates and the 3D pack named below sit next to this SKILL.md. Call them by their full path, for example `<this skill's folder>/scripts/finish.sh`; use the folder this SKILL.md was loaded from. A script install puts it in `~/.claude/skills/brief2mp4/` or `~/.codex/skills/brief2mp4/`; a plugin install puts it in the app's plugin cache.
## 1. Spec: write SPEC.md before any code
@@ -50,6 +50,8 @@ If the brief leaves a choice open, make it, write it under **Decisions** in SPEC
A blank spec to copy is in `templates/SPEC.md`.
+If the brief names a kind of video (explainer, maths, tutorial intro, skit, Short or Reel, data story, launch, logo sting, lyric video) or is vague about structure, read `references/formats.md` first and use its beat sheet, route and checks for that format. Vertical videos have safe zones; that file lists them.
+
## 2. Pick the tool
| The brief asks for | Use | Reference |
@@ -57,17 +59,28 @@ A blank spec to copy is in `templates/SPEC.md`.
| Type, layouts, UI, charts, icons, 2D shapes, captions | HyperFrames (HTML + CSS + GSAP) | `references/hyperframes.md` |
| Stylised 3D, particles, many objects, flying cameras | Three.js inside HyperFrames | `references/threejs.md` |
| Realistic products, materials, soft light and shadows | Blender, scripted with Python, run headless | `references/blender.md` |
+| A product or object that falls and settles, explodes into parts, turns on a turntable; a logo made 3D; a CAD part | The 3D pack, if installed (see below) | `3d/README-3D.md` |
| Joining clips, adding sound, exact duration, loudness, encoding | ffmpeg (`scripts/finish.sh`) | `references/ffmpeg.md` |
Mixing is normal: render a Blender shot to frames, then use it as a video layer under HyperFrames type, or join HyperFrames and Blender clips with ffmpeg. Every path ends with `scripts/finish.sh` and `scripts/check_delivery.sh`.
-Starters that already render: `templates/threejs/index.html` and `templates/blender/scene.py`. Copy one into the project and change it, rather than starting from an empty file.
+### The 3D pack (optional)
+
+Run `bash <this skill's folder>/scripts/detect_3d.sh`. If it prints `3d: ready`, build 3D product beats with it: `model` (CAD or mesh spec to GLB), `material` (presets), `physics` (a baked, deterministic Jolt track), `hf` (shot JSON to a HyperFrames project) and `blender` (photoreal hero). Read `3d/README-3D.md` first: it maps brief language to shot JSON ("parts fall and settle" is physics plus `camera.auto`, "show what's inside" is `explode`, "hero product" is `blender --look dramatic`) and lists the look rules (Neutral tone mapping, a dim environment around 0.35, a shadow-catcher floor, linear colours, bloom only for emissive parts).
+
+Snapshot every 3D shot before the full render (`npx hyperframes snapshot --at 1,3,5`) and look at the frames: a camera framing the fall instead of the landing zone, or parts too small, shows up in seconds.
+
+If it prints `3d: not installed`, use the Three.js template for 3D beats, animate physics and exploded views by hand, and say so in REPORT.md. Mention once how to add the pack: `bash <this skill's folder>/3d/install_3d.sh --components core` (Windows: `powershell -ExecutionPolicy Bypass -File <this skill's folder>\3d\install_3d.ps1 -Components core`). This works for plugin and script installs alike.
+
+For briefs that mix tools, read `references/pipelines.md` (architecture, recipes for each mix, how layers meet in HyperFrames). For tools outside this stack (Remotion, Motion Canvas, Manim, Lottie, Rive, PixiJS, R3F, Babylon.js and more), read `references/ecosystem.md`: when each one beats the default, and how to bring its output in frame-exact.
+
+Starters that already render: `templates/threejs/index.html` (run `scripts/vendor_libs.sh <project> --three` after copying it) and `templates/blender/scene.py`. Copy one into the project and change it, rather than starting from an empty file.
## 3. Build
Rules for every tool:
-- **The picture is a pure function of time.** No wall clock, no `Math.random()` (use a seeded generator), no network calls while rendering. Render the same frame twice and you must get the same pixels.
+- **The picture is a pure function of time.** No wall clock, no `Math.random()` (use a seeded generator), no network calls while rendering: vendor GSAP and fonts into the project (`references/hyperframes.md` shows how). Render the same frame twice and you must get the same pixels.
- **Every element has a job in the beat sheet.** If you cannot say which beat it serves, cut it.
- **Text is readable.** Body text at least 40 px tall at 1080p, headlines 90 px or more. Keep 5% safe margins (96 px left and right, 54 px top and bottom at 1920x1080). No text touches or crosses the frame edge. Hold any line on screen for at least (words / 3) + 0.5 seconds.
- **Motion is eased.** Use ease-out for things arriving and ease-in for things leaving; linear only for constant spins and turntables. Most UI moves take 0.3-0.8 s. One clear hero moment beats ten small effects.
@@ -79,7 +92,7 @@ Rules for every tool:
After every full render, do all three:
1. **Measure.** `scripts/check_delivery.sh final.mp4 --seconds <N> [--size WxH] [--fps N] [--silent-ok]` must end with `RESULT: PASS`. A FAIL is a fix, not a footnote.
-2. **Look.** `scripts/contact_sheet.sh final.mp4 --at <beat starts, hero moment, last second>` writes one PNG per moment. Open and view each image. For every frame ask: is the text spelled exactly as the spec says? Is anything cut off or overlapping? Are the colours from the palette? Is the beat that should be on screen at this time actually there?
+2. **Look.** `scripts/contact_sheet.sh final.mp4 --at <beat starts, hero moment, last second>` writes one PNG per moment. Open and view each image. For every frame ask: is the text spelled exactly as the spec says? Is anything cut off or overlapping? Are the colours from the palette? Is the beat that should be on screen at this time actually there? To measure instead of eyeballing (text height, distance from the edge, safe zones on a vertical video), run `python3 scripts/bounds.py <still.png> --bg "#rrggbb" [--region x0,y0,x1,y1] [--margin 96,54 | --safe top=288,bottom=672,left=64,right=192]`: it prints the pixel box of everything that is not background and whether it sits inside the zone.
3. **Walk the list.** Go through **Done when** line by line and mark each **met** or **not met**, with the evidence: the command output line, or the frame file name.
If you cannot view images in this environment, say so plainly in the report. Never claim a visual check you did not do.
@@ -115,5 +128,9 @@ That message means: re-read the **original brief** (not your spec), go through i
- `references/threejs.md`: time-driven 3D, seeded randomness, text over 3D, performance
- `references/blender.md`: headless Blender, engines, light, camera, text, frames
- `references/ffmpeg.md`: finishing, joining, overlays, sound, loudness, inspection
-- `scripts/finish.sh`, `scripts/check_delivery.sh`, `scripts/contact_sheet.sh`, `scripts/sound_bed.sh`
+- `references/formats.md`: beat sheets, routes and checks per format (explainer, maths, tutorial, story, Short, data, launch, logo, lyric, captions)
+- `references/pipelines.md`: architecture diagram, route per beat, recipes for mixed pipelines, methods
+- `references/ecosystem.md`: 45+ open-source motion, 3D and agent-skill repos, when to use each, how to connect them
+- `3d/README-3D.md`: the optional 3D pack (components, commands, shot JSON, brief-to-shot mapping, look rules)
+- `scripts/finish.sh`, `scripts/check_delivery.sh`, `scripts/contact_sheet.sh`, `scripts/sound_bed.sh`, `scripts/doctor.sh`, `scripts/detect_3d.sh`, `scripts/bounds.py`, `scripts/vendor_libs.sh`
- `templates/SPEC.md`, `templates/threejs/index.html`, `templates/blender/scene.py`
diff --git a/plugin/skills/brief2mp4/references/ecosystem.md b/plugin/skills/brief2mp4/references/ecosystem.md
new file mode 100644
index 0000000..405f705
--- /dev/null
+++ b/plugin/skills/brief2mp4/references/ecosystem.md
@@ -0,0 +1,107 @@
+# The open-source motion ecosystem: what else exists and how to connect it
+
+brief2mp4's default stack is HyperFrames + Three.js + Blender + ffmpeg, plus the optional 3D pack. Read this file when a brief asks for something that stack does badly, or when the user already works in another tool. Star counts and licences were read from GitHub on 15 Nov 2026; check the repo before relying on a licence for commercial work.
+
+The rule for bringing anything in: **it must render frame-exact from time, or it must be rendered first to a file** (video, PNG sequence, Lottie JSON, GLB) that HyperFrames then plays as a layer. Anything driven by a wall clock or `requestAnimationFrame` alone will drift across parallel render workers.
+
+## Video frameworks (whole-video authoring)
+
+| Repo | Stars | Licence | Best at | Use with brief2mp4 |
+|---|---|---|---|---|
+| [heygen-com/hyperframes](https://github.com/heygen-com/hyperframes) | 84.5k | Apache-2.0 | HTML + CSS + GSAP to deterministic MP4, built for agents | The default spine. Its own agent skills: `npx hyperframes skills update` |
+| [remotion-dev/remotion](https://github.com/remotion-dev/remotion) | 73.3k | Remotion licence: free for individuals and small companies, company licence above a size | React components as video, big ecosystem, server-side rendering | If the user already has a Remotion project, build there. Its skills: `npx skills add remotion-dev/skills`. HyperFrames ships a `remotion-to-hyperframes` skill for porting |
+| [motion-canvas/motion-canvas](https://github.com/motion-canvas/motion-canvas) | 19.9k | MIT | TypeScript generators for explainer animation, editor with timeline | Render to MP4 or a PNG sequence, then layer in HyperFrames |
+| [midrender/revideo](https://github.com/midrender/revideo) | 4.2k | MIT | Motion Canvas fork aimed at programmatic, templated rendering | Same as Motion Canvas |
+| [ManimCommunity/manim](https://github.com/ManimCommunity/manim) | 42.6k | MIT | Maths, equations, algorithms, graphs (the 3Blue1Brown style) | Render a transparent MOV/WebM insert, layer it in HyperFrames |
+| [3b1b/manim](https://github.com/3b1b/manim) | 96.5k | MIT | The original Manim; faster moving, less stable API | Prefer the Community edition for agents |
+| [mifi/editly](https://github.com/mifi/editly) | 5.6k | MIT | Declarative JSON slideshows and clip edits | Quick joins when no motion design is needed; ffmpeg alone usually suffices |
+
+## Animation libraries (inside a HyperFrames composition)
+
+| Repo | Stars | Licence | Best at | Notes |
+|---|---|---|---|---|
+| [greensock/GSAP](https://github.com/greensock/GSAP) | 30.7k | GSAP standard no-charge licence (free, including all plugins such as SplitText and MorphSVG) | Timelines, easing, text splitting, SVG morphing | HyperFrames seeks GSAP timelines directly. The default |
+| [juliangarnier/anime](https://github.com/juliangarnier/anime) | 74.7k | MIT | Lightweight timelines, SVG, stagger | Seekable through its timeline API; drive it from `t` |
+| [motiondivision/motion](https://github.com/motiondivision/motion) | 35.2k | MIT | React and vanilla UI animation | Fine for UI mocks if you drive progress from `t`, not from springs in real time |
+| [airbnb/lottie-web](https://github.com/airbnb/lottie-web) | 32.5k | MIT | Playing After Effects exports (Lottie JSON) | Use `goToAndStop(frame, true)` from `t`. Good for icon and character loops |
+| [LottieFiles/dotlottie-web](https://github.com/LottieFiles/dotlottie-web) | 0.9k | MIT | Faster Lottie and .lottie playback (WASM) | Set the frame from `t` |
+| [rive-app/rive-wasm](https://github.com/rive-app/rive-wasm) | 1.0k | MIT | Interactive vector animation with state machines | Advance by fixed steps from `t`; test that a seek renders the same frame twice |
+
+## 2D and creative-coding renderers
+
+| Repo | Stars | Licence | Best at | Notes |
+|---|---|---|---|---|
+| [pixijs/pixijs](https://github.com/pixijs/pixijs) | 48.7k | MIT | Fast 2D WebGL: thousands of sprites, particles, filters | Render on demand from `t` with the ticker stopped |
+| [processing/p5.js](https://github.com/processing/p5.js) | 24.4k | LGPL-2.1 | Generative art, sketches | Call `noLoop()` and `redraw()` per frame; seed `randomSeed()` |
+
+## 3D engines and helpers
+
+| Repo | Stars | Licence | Best at | Notes |
+|---|---|---|---|---|
+| [mrdoob/three.js](https://github.com/mrdoob/three.js) | 118.5k | MIT | The web 3D standard | The 3D default. See `references/threejs.md` |
+| [pmndrs/react-three-fiber](https://github.com/pmndrs/react-three-fiber) | 33.7k | MIT | Three.js as React components | Use `frameloop="never"` and call `advance(t)` once per frame |
+| [pmndrs/drei](https://github.com/pmndrs/drei) | 10.2k | MIT | Ready-made R3F helpers (text, environments, controls) | Some helpers fetch from CDNs or use unseeded randomness at render: vendor the assets |
+| [pmndrs/postprocessing](https://github.com/pmndrs/postprocessing) | 3.0k | Zlib | Bloom, depth of field, film grain for Three.js | Grain and noise effects need a seed driven from `t` |
+| [BabylonJS/Babylon.js](https://github.com/BabylonJS/Babylon.js) | 26.4k | Apache-2.0 | Full engine with PBR, node materials, GUI | Turn off temporal effects or they smear across seeks |
+| [playcanvas/engine](https://github.com/playcanvas/engine) | 17.3k | MIT | Fast WebGL/WebGPU engine, Gaussian splats | Update with a fixed `dt` from `t` |
+| [google/filament](https://github.com/google/filament) | 20.7k | Apache-2.0 | Physically based rendering, accurate materials | Its post effects add per-frame noise; disable them for deterministic frames |
+| [theatre-js/theatre](https://github.com/theatre-js/theatre) | 13.0k | Apache-2.0 | A keyframe editor for Three.js and the DOM | Last push Aug 2024. Useful for hand-keyed camera paths: export the keyframes and seek them by `t` |
+| [blender/blender](https://github.com/blender/blender) | 22.0k | GPL (external tool) | Photoreal rendering, simulation, Geometry Nodes | Used headless. See `references/blender.md` |
+
+## 3D asset pipeline (what the 3D pack builds on)
+
+| Repo | Stars | Licence | Role |
+|---|---|---|---|
+| [CadQuery/cadquery](https://github.com/CadQuery/cadquery) | 6.1k | Apache-2.0 | Parametric CAD in Python: enclosures, gears, exact parts |
+| [elalish/manifold](https://github.com/elalish/manifold) | 2.4k | Apache-2.0 | Fast, robust booleans that never leave broken meshes |
+| [mikedh/trimesh](https://github.com/mikedh/trimesh) | 3.7k | MIT | Mesh loading, inspection and GLB export |
+| [donmccurdy/glTF-Transform](https://github.com/donmccurdy/glTF-Transform) | 2.1k | MIT | Edit, compress and optimise GLB files |
+| [zeux/meshoptimizer](https://github.com/zeux/meshoptimizer) | 8.9k | MIT | Simplify meshes and compress vertex data |
+| [jrouwe/JoltPhysics](https://github.com/jrouwe/JoltPhysics) | 12.3k | MIT | Rigid-body physics, baked once to deterministic tracks |
+| [AcademySoftwareFoundation/MaterialX](https://github.com/AcademySoftwareFoundation/MaterialX) | 2.3k | Apache-2.0 | Portable material definitions; a good source for physically based values when you write your own preset JSON |
+| [PixarAnimationStudios/OpenUSD](https://github.com/PixarAnimationStudios/OpenUSD) | 7.6k | TOST (Apache-2.0 based) | Scene description for big multi-asset shots; not in the pack, convert to GLB first |
+
+## Capture, reconstruction and mesh repair (outside the 3D pack)
+
+Use these to turn a real object or place into an asset, or to repair a bad mesh, before the 3D pack takes over. Check licences: several are GPL, which is fine for making videos and matters only if you ship them inside a product.
+
+| Repo | Stars | Licence | Role |
+|---|---|---|---|
+| [colmap/colmap](https://github.com/colmap/colmap) | 13.2k | BSD-style | Camera poses from photos (structure from motion); runs on CPU without CUDA |
+| [ArthurBrussee/brush](https://github.com/ArthurBrussee/brush) | 5.3k | Apache-2.0 | Gaussian-splat training on any GPU (WebGPU), including Apple silicon |
+| [nerfstudio-project/nerfstudio](https://github.com/nerfstudio-project/nerfstudio) | 12.2k | Apache-2.0 | NeRF and splat training; needs an NVIDIA GPU |
+| [alicevision/Meshroom](https://github.com/alicevision/Meshroom) | 13.1k | MPL-2.0 | Photogrammetry to textured meshes; its GPU path needs CUDA |
+| [isl-org/Open3D](https://github.com/isl-org/Open3D) | 14.2k | MIT | Point clouds, registration, surface reconstruction |
+| [cnr-isti-vclab/meshlab](https://github.com/cnr-isti-vclab/meshlab) | 5.9k | GPL-3.0 | Mesh repair and remeshing (desktop) |
+| [cnr-isti-vclab/PyMeshLab](https://github.com/cnr-isti-vclab/PyMeshLab) | 1.0k | GPL-3.0 | The same filters from Python: close holes, decimate, remesh |
+| [wjakob/instant-meshes](https://github.com/wjakob/instant-meshes) | 6.3k | BSD-style | Quad remeshing; last commit 2022, prefer PyMeshLab |
+| [sgenoud/replicad](https://github.com/sgenoud/replicad) | 0.7k | MIT (OpenCascade is LGPL) | CAD modelling in JavaScript, in the browser |
+
+## Agent skills and prompt libraries for motion
+
+These teach an agent craft: shot recipes, launch structure, polish passes, prompt patterns. Read them for ideas; follow each repo's licence before copying anything.
+
+| Repo | Stars | Licence | What to take from it |
+|---|---|---|---|
+| [remotion-dev/skills](https://github.com/remotion-dev/skills) | 7.2k | see repo | Remotion best practices for agents |
+| [heygen-com/hyperframes](https://github.com/heygen-com/hyperframes) `skills/` | (above) | Apache-2.0 | The HyperFrames contract, CLI, block registry, media and style-sampling skills |
+| [heygen-com/hyperframes-launches](https://github.com/heygen-com/hyperframes-launches) | 0.7k | Apache-2.0 (brand media excluded) | Real launch-video compositions and storyboards: how a 30-60 s launch is paced |
+| [Vincentwei1021/video-shotcraft](https://github.com/Vincentwei1021/video-shotcraft) | 19.8k | Apache-2.0 | Shot recipe cards, beat sync and sound design for product videos |
+| [charlie947/motion-graphics-skills](https://github.com/charlie947/motion-graphics-skills) | 0.7k | MIT | Brand intake, motion prompts and a polish pass for launch-grade graphics |
+| [yihui-dev/awesome-opus5-5-videos](https://github.com/yihui-dev/awesome-opus5-5-videos) | 15.3k | MIT | A large collection of videos made by Claude with the prompts behind them: study what a good prompt specifies |
+
+## Finishing
+
+| Repo | Stars | Licence | Role |
+|---|---|---|---|
+| [FFmpeg/FFmpeg](https://github.com/FFmpeg/FFmpeg) | 67.3k | LGPL/GPL | Encode, join, mix, measure. Every route ends here (`scripts/finish.sh`) |
+
+## Picking between the frameworks
+
+- **The brief is a motion graphic and an agent is building it:** HyperFrames. HTML and CSS are what language models write most reliably, the timeline is seekable by design, and lint plus snapshots catch mistakes before a render.
+- **The user's team already ships React video:** Remotion, in their project, following their conventions. Check the licence tier for their company size.
+- **A maths or algorithm explainer:** Manim inserts inside a HyperFrames film.
+- **A designer will hand-tune keyframes:** Theatre.js for the camera or Lottie from After Effects, then seek either by `t` inside HyperFrames.
+- **A product must look real:** the 3D pack's Blender route, or the Blender template, layered under HyperFrames type.
+
+If you bring in a tool that is not listed here, apply the same test before you build on it: render frame 90 twice in separate runs and compare the PNGs. Identical files mean it is safe for parallel rendering.
diff --git a/plugin/skills/brief2mp4/references/formats.md b/plugin/skills/brief2mp4/references/formats.md
new file mode 100644
index 0000000..c0b0d7e
--- /dev/null
+++ b/plugin/skills/brief2mp4/references/formats.md
@@ -0,0 +1,143 @@
+# Formats: what each kind of video needs
+
+Read this when the brief names a kind of video ("an explainer", "a Short", "a tutorial intro") or when it is vague about structure. Each format gives a beat sheet that works, the route for each beat, and the checks that matter most for it. Times are for the length shown; scale them to the brief.
+
+Rules that hold for every format:
+
+- **Something is on screen and moving by 0.3 s.** Viewers decide in the first second.
+- **One idea per beat, one hero moment per video.** Put the hero moment in the beat sheet with a time.
+- **Readable time.** Hold any line for at least (words / 3) + 0.5 s. Body text 40 px or more at 1080p, headlines 90 px or more.
+- **The last 1.5-2.5 s hold still** on the final message, so it can be read and so a loop or end screen does not cut it.
+- **Sound shapes the cut.** Put accents on beat starts; a quiet bed under everything is better than silence.
+
+## 2D explainer (YouTube, course, product page)
+
+Length 30-120 s, 16:9. Route: HyperFrames for everything; Three.js only for a single 3D object that explains the idea better than a diagram.
+
+| Beat | Time (60 s) | What is on screen |
+|---|---|---|
+| Hook | 0-4 s | The question or the surprising fact, in big type, with one moving element |
+| Setup | 4-14 s | The problem shown as a simple diagram that builds piece by piece |
+| Idea | 14-38 s | Three steps, each its own beat: icon or shape, a 3-7 word label, one motion that shows the change |
+| Example | 38-52 s | One concrete case: numbers counting up, a before and after, or a UI mock |
+| Takeaway | 52-60 s | One sentence, held still |
+
+Techniques: build diagrams with SVG paths that draw on (`stroke-dashoffset`), reveal labels word by word, move a highlight box instead of cutting, keep one consistent visual metaphor through the whole video. Use a narrow palette: background, ink, one accent for "the thing that matters".
+
+Checks: every label spelled exactly; nothing overlapping when the diagram is complete (pull a still at the end of each build); the accent colour used only for the key element.
+
+## Maths and algorithms
+
+Length 20-180 s. Route: HyperFrames for titles and layout; equations with MathJax (it outputs SVG, which you can animate term by term) or KaTeX (HTML and CSS, vendor its fonts and stylesheet); for heavy maths animation (transforming equations, graphs that morph, geometric proofs) use [Manim Community](https://github.com/ManimCommunity/manim) (`pip install manim`; `MathTex` and `Tex` also need a LaTeX install such as TeX Live or MiKTeX) to render a transparent clip at the video's size and frame rate, then place it as a video layer.
+
+| Beat | What is on screen |
+|---|---|
+| Question | The problem stated plainly, maybe one figure |
+| Intuition | A picture before any symbols: a shape, a graph, a moving point |
+| Symbols | The equation appears term by term, each term coloured to match the part of the picture it describes |
+| Step | One transformation per beat, never two at once |
+| Result | The final form, boxed or highlighted, held still |
+
+Techniques: colour-code terms consistently (the same colour for the same quantity everywhere), animate one change at a time, keep the previous line visible but dimmed so the eye can compare. For an algorithm, show the data structure and move a pointer through it in sync with the code line highlighted beside it.
+
+Checks: every symbol correct (pull stills and read them); colours consistent across beats; Manim clips rendered at the video's frame rate and size so they do not stutter or blur.
+
+## Tutorial and screen-recording intros
+
+Length 5-20 s for an intro, plus lower thirds and callouts over a recording. Route: HyperFrames with the recording as a `<video>` layer; trim and normalise the recording with ffmpeg first (`references/ffmpeg.md`).
+
+| Element | How |
+|---|---|
+| Title card | 3-6 s: topic in big type, the tool's name or version smaller |
+| Chapter cards | 1.5-2.5 s between sections, same layout every time |
+| Callouts | A box or arrow that grows onto the UI element being discussed, with a 2-5 word label, held while it is talked about |
+| Zoom-ins | Scale and position the recording layer to the area of interest, eased, then back out |
+| Keyboard keys | Small key caps that pop on when a shortcut is used |
+
+Checks: callouts land on the right UI element at the right time (pull stills at each callout); text never covers what is being explained; the recording is sharp after zoom (record at a higher resolution than the output if you zoom more than 1.5x).
+
+## Storytelling, skits and character pieces
+
+Length 15-90 s. Route: HyperFrames with SVG characters or cut-out illustrations; simple 3D props from the Three.js template or the 3D pack. Lip sync and full character animation are outside this skill: use pre-made Lottie or Rive characters ([references/ecosystem.md](ecosystem.md)) seeked by time, or keep characters still and let the camera, captions and props carry the motion.
+
+| Beat | What is on screen |
+|---|---|
+| Situation | Where we are and who is there, in one wide shot |
+| Want | What the character wants, shown not told (a thought bubble, a goal on screen) |
+| Obstacle | Something gets in the way; the biggest motion of the piece |
+| Turn | The twist or punchline; give it a beat of stillness first |
+| Out | The result, and a caption or title |
+
+Techniques: one camera move per shot (push, pan or parallax across layered SVG), hold a reaction for half a second before the next line, put dialogue in captions or speech bubbles timed to the voice. For a skit, timing is the joke: leave a pause of 0.3-0.6 s before the punchline.
+
+Checks: captions match the voiceover word for word and in time (time them from `npx hyperframes transcribe voice.wav` word timestamps); characters never cut off at the frame edge; every shot change motivated by the story.
+
+## Vertical Shorts and Reels (9:16)
+
+Length 15-60 s, 1080x1920. Route: as for the content, but laid out for a phone.
+
+Safe zones at 1080x1920: keep essential text and faces out of the top 288 px (status bar, search, account name), the bottom 672 px (title, caption, channel name, sound and buttons drawn by the app), the right 192 px (like, comment and share buttons) and the left 64 px. These are conservative working values that cover the overlays YouTube Shorts, Instagram Reels and TikTok draw; the platforms publish their safe areas as reference graphics (for example [Google Ads: square and vertical video](https://support.google.com/google-ads/answer/9128498)) and move their buttons over time, so check a current screenshot when an element sits near an edge. That leaves a box of about 824 x 960 px, from 288 to 1248 px down: put the main text there. Measure it with `scripts/bounds.py still.png --bg "#rrggbb" --safe top=288,bottom=672,left=64,right=192`.
+
+| Beat | Time (30 s) | What is on screen |
+|---|---|---|
+| Hook | 0-2 s | The payoff or the question, huge type, motion in the first frame |
+| Promise | 2-5 s | What the viewer gets if they stay |
+| Body | 5-25 s | 3-5 quick beats, a change every 2-4 s (cut, zoom, new word) |
+| Payoff | 25-28 s | The answer or the result |
+| End | 28-30 s | Either hold the payoff still for the last 1.5-2.5 s (the default rule above), or, when the brief asks for a loop, end on a frame that leads back into the first one so replays feel seamless. Pick one and write it in SPEC.md |
+
+Checks: nothing important inside the unsafe zones (pull stills and check positions); captions large (60 px or more) and on screen the whole time someone speaks; the first frame works as a cover.
+
+## Data stories and charts
+
+Length 15-60 s. Route: HyperFrames with SVG or canvas charts (D3 for layout is fine; animate with GSAP from `t`).
+
+Beats: the claim in words, the axes and context, the data drawing on, the one number that matters highlighted, the takeaway. Animate bars and lines from the baseline, count numbers up with the final value exact, label directly on the chart instead of in a legend.
+
+Checks: every number on screen matches the brief exactly at its final frame; axes start where honesty demands (bar charts from zero); units shown.
+
+## Product launch and feature announcements
+
+Length 15-60 s. Route: HyperFrames for type and UI; the 3D pack or Blender for the product itself.
+
+Beats: the problem in one line, the product reveal (the hero moment), 2-3 features each with one visual and a 3-6 word label, the call to action (name, URL or "available now"), held still. Show the real UI where possible: a recreated UI mock in HTML stays sharp at any zoom.
+
+Checks: product name and URL spelled exactly; feature labels consistent in style; the reveal lands on a sound accent.
+
+## Logo stings and titles
+
+Length 2-8 s. Route: HyperFrames (SVG logo drawn on, masked, or assembled from parts); the 3D pack's `model` + `reveal` for a logo with depth.
+
+Beats: build-up (0.5-2 s), the logo resolves (the hero moment), hold (1-3 s). Use the logo's own colours and proportions; never distort it.
+
+Checks: the final frame shows the logo exactly as supplied (compare against the source file); it resolves on the sound accent.
+
+## Kinetic typography and lyric videos
+
+Length 10-240 s. Route: HyperFrames.
+
+Techniques: time each word or phrase to the audio (measure word times with `npx hyperframes transcribe audio.wav`, which writes word-level timestamps; never guess), vary scale and weight to show stress, move the camera through a typographic space instead of replacing words in place, keep one or two typefaces. Every word must be readable for its duration.
+
+Checks: text matches the lyrics or script exactly; sync within one frame on stressed words (pull stills at those times); nothing too fast to read.
+
+## Captions over any video
+
+Route: HyperFrames caption layer timed to word timestamps from `npx hyperframes transcribe`. Two to seven words per caption, broken at phrase boundaries, never more than two lines, a solid or blurred backing so they read on any background. Highlight the word being spoken if the brief asks for "TikTok-style" captions.
+
+Checks: every caption matches the audio word for word; none on screen when nobody speaks; inside the safe zone for the format.
+
+## Choosing when the brief is vague
+
+| The brief says | Treat it as |
+|---|---|
+| "explain X", "how X works" | 2D explainer |
+| an equation, proof, algorithm, graph | Maths and algorithms |
+| "intro for my tutorial", "lower third", "callout" | Tutorial |
+| characters, a joke, "a short story" | Storytelling |
+| "Short", "Reel", "TikTok", "vertical" | Vertical, plus the content format |
+| numbers, "growth", "chart" | Data story |
+| "launch", "announce", "new feature" | Product launch |
+| "logo animation", "intro sting" | Logo sting |
+| song, lyrics, "words on beat" | Kinetic typography |
+
+Write the chosen format and its beat sheet into SPEC.md, then build.
diff --git a/plugin/skills/brief2mp4/references/hyperframes.md b/plugin/skills/brief2mp4/references/hyperframes.md
index a47d184..3bac45e 100644
--- a/plugin/skills/brief2mp4/references/hyperframes.md
+++ b/plugin/skills/brief2mp4/references/hyperframes.md
@@ -8,6 +8,8 @@ Docs: https://hyperframes.heygen.com (machine-readable index at `/llms.txt`). Of
```bash
npx hyperframes init my-video --example blank --non-interactive --skip-skills
+# or, inside a folder you already made for the video:
+npx hyperframes init . --example blank --non-interactive --skip-skills
cd my-video
```
@@ -32,7 +34,7 @@ This writes `index.html` (the root composition), `hyperframes.json`, `meta.json`
- Every timed element has `data-start` and `data-duration` (seconds) and the class `clip`.
- Register exactly one **paused** root timeline per composition in `window.__timelines["<composition-id>"]`. Child timelines you nest into it must not be paused, or they will not move when the root is seeked.
- Timeline positions are seconds from the start of the composition. Keep a comment block at the top of the script that lists the beat sheet times; it makes fixes fast.
-- Load GSAP from a pinned CDN version (`https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js`).
+- **Vendor GSAP into the project; no CDN at render time.** Run `bash <skill>/scripts/vendor_libs.sh . [--three] [--fonts inter,space-grotesk]` in the project: it writes pinned copies to `vendor/` (GSAP 3.15.0, three 0.170.0, font files with their licences and a `fonts.css`). Load GSAP with `<script src="vendor/gsap.min.js">`. The `init` template points at a CDN; replace that line. A render that fetches from the network can differ between runs and fails offline.
## Sound
@@ -50,6 +52,7 @@ Put each scene in its own file under `compositions/` and pull it into the root w
npx hyperframes lint . # structure errors, fast
npx hyperframes check . # lint + runtime + layout + contrast in one gate
npx hyperframes snapshot . --at 0.5,3,7.5 # PNG stills at exact seconds: look at them
+ # they are written under .hyperframes/artifacts/snapshots/<id>/ (the command prints the path)
npx hyperframes render . -o draft.mp4 --quality draft --workers 4
npx hyperframes render . -o render.mp4 --quality delivery --fps 30
npx hyperframes render . -o fix.mp4 --start 4 --end 7 # re-render a span only
@@ -63,7 +66,7 @@ Quality presets: `draft` for iterating, `looks` (default) for review, `delivery`
- **Count-ups:** tween a plain object and write the rounded value into the element in `onUpdate`. Format with `toLocaleString("en-US")` so the commas are right.
- **A shape that carries across scenes:** one element (a bar, a circle) that grows to fill the frame becomes the next background. It reads as one continuous film instead of a slide show.
- **Camera feel on 2D:** scale the whole stage from 1.0 to 1.04 over the shot. Tiny, but it keeps a held frame alive.
-- **Fonts:** use a web font loaded with `<link>` from Google Fonts, or a system stack. Check the snapshot to confirm the font actually loaded; a fallback font is the most common silent failure.
+- **Fonts: vendor them too.** `vendor_libs.sh . --fonts inter,space-grotesk` (any [Fontsource](https://fontsource.org) id) writes the `.woff2` files and `vendor/fonts/fonts.css`; link that stylesheet and use the family name as written there. Check a snapshot to confirm the face actually loaded; a fallback font is the most common silent failure.
## Common failures and the fix
@@ -73,5 +76,11 @@ Quality presets: `draft` for iterating, `looks` (default) for review, `delivery`
| An element never appears | Missing `data-start` / `data-duration`, or its time range does not cover the tween | Give it the full range it is on screen |
| Nested animation frozen | Child timeline created paused | Create children unpaused; only the root is paused |
| Different result every render | `Math.random()`, `Date.now()`, or a fetch | Seeded random, fixed values, local files |
-| Text in the wrong font | Font not loaded before capture | Load from a pinned URL or local file; confirm in a snapshot |
+| Text in the wrong font | Font not loaded before capture | Vendor the font files locally with `@font-face`; confirm in a snapshot |
| Render is the wrong length | Root `data-duration` differs from the brief | Set it to the exact seconds; `finish.sh --seconds` trims and pads too |
+
+## Reading the output, and warnings to expect
+
+- `render` prints a long trace. The line that matters says `rendered in`; search for it rather than reading the whole log.
+- `hyperframes check` and `check_delivery.sh` warn about **holds**: a closing line held still, or a freeze over 1.5 s. When the brief asks for that hold, the warning is expected: say so in REPORT.md next to the brief line that asked for it. When it did not, it is dead air: fix it.
+- `hyperframes check` may also suggest a longer closing hold than the brief allows. The brief wins; note the difference in REPORT.md.
diff --git a/plugin/skills/brief2mp4/references/pipelines.md b/plugin/skills/brief2mp4/references/pipelines.md
new file mode 100644
index 0000000..c81e504
--- /dev/null
+++ b/plugin/skills/brief2mp4/references/pipelines.md
@@ -0,0 +1,102 @@
+# Pipelines: how the tools connect
+
+Read this when a brief needs more than one tool, or when you are choosing between routes. Every route ends the same way: one master file, `scripts/finish.sh`, `scripts/check_delivery.sh`, stills you have looked at, and `REPORT.md`.
+
+## The architecture
+
+```mermaid
+flowchart LR
+ B[BRIEF.md] --> S[SPEC.md<br/>delivery, exact text, look,<br/>beat sheet, done-when]
+ S --> R{Route per beat}
+ R -->|type, UI, charts, 2D| HF[HyperFrames<br/>HTML + CSS + GSAP]
+ R -->|stylised 3D| TJ[Three.js scene<br/>inside HyperFrames]
+ R -->|3D product, physics,<br/>exploded view| P3[3D pack<br/>model, material, physics, hf]
+ R -->|photoreal hero| BL[Blender<br/>headless render]
+ P3 --> TJ
+ P3 --> BL
+ BL -->|frames or ProRes alpha| HF
+ TJ --> HF
+ HF --> RN[render.mp4]
+ RN --> FN[finish.sh<br/>exact length, H.264/AAC, -14 LUFS]
+ FN --> CK[check_delivery.sh<br/>+ contact_sheet.sh]
+ CK -->|any miss| FX[fix worst miss,<br/>re-render, max 3 rounds]
+ FX --> CK
+ CK -->|all met| OUT[final.mp4 + REPORT.md]
+```
+
+HyperFrames is the spine: it is the one place where layers meet on a single timeline. Other tools produce layers (a Blender clip, a Three.js canvas, an image sequence, a sound bed) and HyperFrames composes them. ffmpeg only finishes, joins and measures.
+
+## Choosing a route, beat by beat
+
+Route each beat of the beat sheet on its own, not the whole video. A 15 s product film is often three routes: a HyperFrames title, a 3D-pack physics shot and a Blender hero frame.
+
+| The beat needs | Route | Cost on a laptop |
+|---|---|---|
+| Words, layouts, lower thirds, UI mock, counters, charts | HyperFrames only | seconds per draft |
+| Abstract 3D: particles, planets, shapes, flying camera | Three.js template in HyperFrames | seconds to a minute |
+| A product or object that falls, stacks, explodes into parts, turns | 3D pack (`hf` route) | about a minute |
+| Glass, metal, soft shadows, a beauty shot | 3D pack `blender` route, or the Blender template | a minute or more per second of video |
+| A logo or icon that becomes 3D | 3D pack `model` (extrude) + `material` + `reveal` | about a minute |
+| Real footage, screen recordings | `<video>` layer in HyperFrames; trim and normalise with ffmpeg first | seconds |
+| Captions from a voiceover | HyperFrames caption layer timed to the audio | seconds |
+
+When the 3D pack is not installed (`scripts/detect_3d.sh` says `not installed`), use the Three.js template for 3D beats and say in REPORT.md that physics and exploded views were animated by hand.
+
+## Pipeline recipes
+
+### 1. Kinetic type (one tool)
+
+`SPEC.md` -> HyperFrames composition -> draft render (2-3 s) -> look -> full render -> `finish.sh` -> checks.
+Use for titles, quotes, launch cards, explainers made of words. Example: `examples/01-kinetic-type`.
+
+### 2. Type over 3D (two layers, one timeline)
+
+```mermaid
+flowchart LR
+ A[Three.js canvas<br/>time-driven] --> C[HyperFrames<br/>one composition]
+ B[Type layers<br/>GSAP] --> C
+ C --> D[render.mp4] --> E[finish.sh]
+```
+
+The 3D scene is a pure function of time `t` that HyperFrames seeks. Type sits in HTML above the canvas, so it stays sharp and spell-checkable. Example: `examples/02-threejs-orbit`.
+
+### 3. Physics product shot (3D pack)
+
+```mermaid
+flowchart LR
+ M[model<br/>spec.py -> GLB] --> MT[material<br/>presets, linear colours]
+ MT --> PH[physics<br/>Jolt bake -> track.json]
+ PH --> SJ[shot.json<br/>camera, lights, titles]
+ SJ --> HFP[hf -> HyperFrames project]
+ HFP --> SN[snapshot at 3-5 times<br/>LOOK before rendering]
+ SN --> RD[render] --> FS[finish.sh]
+```
+
+Bake physics once, replay it by lookup: every worker sees the same frame for the same `t`. Snapshot first. A camera that frames the fall instead of the landing zone is the most common miss, and a snapshot shows it in seconds. Example: `examples/04-3d-product`.
+
+### 4. Photoreal hero inside a motion graphic
+
+Render the hero in Blender to PNG frames or ProRes 4444 with alpha, then use it as a `<video>` or image-sequence layer in HyperFrames with type and graphics on top. Keep Blender for the shots that need it: a 3 s hero inside a 12 s HyperFrames film is a normal mix. Example: `examples/03-blender-product`.
+
+### 5. Long or multi-scene films
+
+Split the beat sheet into scenes of 5-20 s, one HyperFrames sub-composition each, rendered separately. Join with ffmpeg (`references/ffmpeg.md`, concat with matching codecs), then put one continuous sound bed over the joined file in `finish.sh --audio`. One bed across the film sounds finished; a fade at every scene join sounds like a slideshow.
+
+## Methods that make the result better
+
+- **Spec first, then pixels.** The done-when list is what the self-check measures. Vague brief lines become measurable lines in SPEC.md before any code.
+- **Draft small, look, then scale.** Render 2-3 s at draft quality, view the stills, then build the rest. A wrong font or a cut-off word costs seconds to find in a draft and minutes in a final.
+- **Time is the only input.** No wall clock, no unseeded random, no network while rendering. Same `t`, same pixels, so parallel renders and re-renders match.
+- **One hero moment per film.** Put it in the beat sheet with a time. Everything else supports it.
+- **Look at frames, not logs.** A render that finished is not a video that is right. Pull stills at every beat start, the hero moment and the last second, and view them.
+- **Fix the worst miss first,** then re-check everything, because fixes move other things.
+- **Layer, don't bake text into 3D.** Type in HTML over a 3D layer stays sharp, exact and easy to change.
+
+## Where to go deeper
+
+- `references/hyperframes.md`: composition rules, commands, sub-compositions
+- `references/threejs.md`: time-driven 3D inside HyperFrames
+- `references/blender.md`: headless Blender
+- `references/ffmpeg.md`: finishing, joining, loudness
+- `references/ecosystem.md`: other open-source motion tools, when they beat these, and how to bring their output in
+- `3d/README-3D.md`: the 3D pack, its components, shot JSON and the brief-to-shot mapping
diff --git a/plugin/skills/brief2mp4/references/threejs.md b/plugin/skills/brief2mp4/references/threejs.md
index a4fa19b..649ba0a 100644
--- a/plugin/skills/brief2mp4/references/threejs.md
+++ b/plugin/skills/brief2mp4/references/threejs.md
@@ -1,5 +1,7 @@
# Three.js inside HyperFrames
+**Offline by design.** The template loads `vendor/gsap.min.js` and `vendor/three.module.js`. After copying it into a project, run `bash <skill>/scripts/vendor_libs.sh <project> --three` once, so every render uses the same pinned copies and never fetches from a CDN.
+
Three.js draws 3D with WebGL. On its own it animates with a render loop that runs in real time, which a frame-by-frame renderer cannot capture reliably. The fix is to make the 3D scene a pure function of time: GSAP owns the clock, and every time HyperFrames seeks the timeline, one `draw(t)` call positions everything for second `t` and renders once.
Start from `templates/threejs/index.html`. It renders as is (10 s, a low-poly shape, a slow camera dolly, seeded stars, an HTML title on top).
diff --git a/plugin/skills/brief2mp4/scripts/bounds.py b/plugin/skills/brief2mp4/scripts/bounds.py
new file mode 100644
index 0000000..8a75e7b
--- /dev/null
+++ b/plugin/skills/brief2mp4/scripts/bounds.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+"""bounds.py: measure where content sits in a still, and check it against margins or safe zones.
+
+Uses only the Python standard library, so it runs wherever Python 3.8+ does. Reads the 8-bit
+PNGs that contact_sheet.sh and ffmpeg write.
+
+ python3 bounds.py still.png --bg "#101114"
+ prints the bounding box of every pixel that differs from the background
+ python3 bounds.py still.png --bg "#F4F1EA" --region 0,700,1920,1080
+ only look inside x0,y0,x1,y1 (for example the band where a label sits)
+ python3 bounds.py still.png --bg "#101114" --safe top=288,bottom=672,left=64,right=192
+ also checks the box against safe zones (vertical Shorts and Reels)
+ python3 bounds.py still.png --bg "#F2EDE4" --margin 96,54
+ checks a left/right and top/bottom safe margin (5% at 1920x1080)
+
+Prints one JSON object. Exit 0 when the box is inside the zones (or none were given), 1 otherwise.
+A box height is a good proxy for text height when you measure a single line.
+"""
+import argparse
+import json
+import struct
+import sys
+import zlib
+
+
+def read_png(path):
+ with open(path, "rb") as f:
+ data = f.read()
+ if data[:8] != b"\x89PNG\r\n\x1a\n":
+ raise ValueError("not a PNG file")
+ pos, idat, w = 8, [], None
+ while pos < len(data):
+ length, kind = struct.unpack(">I4s", data[pos:pos + 8])
+ body = data[pos + 8:pos + 8 + length]
+ if kind == b"IHDR":
+ w, h, depth, ctype, _, _, interlace = struct.unpack(">IIBBBBB", body)
+ if depth != 8 or ctype not in (0, 2, 4, 6) or interlace:
+ raise ValueError("only 8-bit, non-interlaced grey, RGB or RGBA PNGs are supported")
+ elif kind == b"IDAT":
+ idat.append(body)
+ elif kind == b"IEND":
+ break
+ pos += 12 + length
+ channels = {0: 1, 2: 3, 4: 2, 6: 4}[ctype]
+ return w, h, channels, unfilter(zlib.decompress(b"".join(idat)), w, h, channels)
+
+
+def paeth(a, b, c):
+ p = a + b - c
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
+ return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
+
+
+def unfilter(raw, w, h, bpp):
+ stride, out, prev, i = w * bpp, [], bytearray(w * bpp), 0
+ for _ in range(h):
+ ftype, line = raw[i], bytearray(raw[i + 1:i + 1 + stride])
+ i += 1 + stride
+ for x in range(stride):
+ a = line[x - bpp] if x >= bpp else 0
+ b, c = prev[x], (prev[x - bpp] if x >= bpp else 0)
+ if ftype == 1:
+ line[x] = (line[x] + a) & 255
+ elif ftype == 2:
+ line[x] = (line[x] + b) & 255
+ elif ftype == 3:
+ line[x] = (line[x] + ((a + b) >> 1)) & 255
+ elif ftype == 4:
+ line[x] = (line[x] + paeth(a, b, c)) & 255
+ out.append(bytes(line))
+ prev = line
+ return out
+
+
+def hex_rgb(value):
+ value = value.lstrip("#")
+ return tuple(int(value[k:k + 2], 16) for k in (0, 2, 4))
+
+
+def bbox(rows, w, h, ch, bg, tol, region):
+ x0r, y0r, x1r, y1r = region or (0, 0, w, h)
+ found = [w, h, -1, -1]
+ for y in range(max(0, y0r), min(h, y1r)):
+ row = rows[y]
+ for x in range(max(0, x0r), min(w, x1r)):
+ px = row[x * ch:x * ch + ch]
+ rgb = (px[0],) * 3 if ch <= 2 else px[:3]
+ if max(abs(rgb[k] - bg[k]) for k in range(3)) > tol:
+ found = [min(found[0], x), min(found[1], y), max(found[2], x), max(found[3], y)]
+ return None if found[2] < 0 else found
+
+
+def parse_zones(args, w, h):
+ zones = {}
+ if args.safe:
+ for part in args.safe.split(","):
+ key, val = part.split("=")
+ zones[key.strip()] = int(val)
+ if args.margin:
+ mx, my = (int(v) for v in args.margin.split(","))
+ zones = {"left": mx, "right": mx, "top": my, "bottom": my, **zones}
+ return {"left": zones.get("left", 0), "right": w - zones.get("right", 0),
+ "top": zones.get("top", 0), "bottom": h - zones.get("bottom", 0)} if zones else None
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("png")
+ ap.add_argument("--bg", required=True, help="background colour as #rrggbb")
+ ap.add_argument("--tol", type=int, default=24, help="per-channel difference that counts as content (default 24)")
+ ap.add_argument("--region", help="x0,y0,x1,y1 to search inside")
+ ap.add_argument("--safe", help="safe zones in px, e.g. top=288,bottom=672,left=64,right=192")
+ ap.add_argument("--margin", help="symmetric margins in px as X,Y, e.g. 96,54")
+ args = ap.parse_args()
+ w, h, ch, rows = read_png(args.png)
+ region = tuple(int(v) for v in args.region.split(",")) if args.region else None
+ box = bbox(rows, w, h, ch, hex_rgb(args.bg), args.tol, region)
+ result = {"file": args.png, "size": [w, h], "box": None, "inside": None}
+ if box:
+ result["box"] = {"x0": box[0], "y0": box[1], "x1": box[2], "y1": box[3],
+ "width": box[2] - box[0] + 1, "height": box[3] - box[1] + 1}
+ zone = parse_zones(args, w, h)
+ if zone and box:
+ result["zone"] = zone
+ result["inside"] = (box[0] >= zone["left"] and box[2] < zone["right"]
+ and box[1] >= zone["top"] and box[3] < zone["bottom"])
+ print(json.dumps(result))
+ return 1 if result["inside"] is False else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugin/skills/brief2mp4/scripts/check_delivery.sh b/plugin/skills/brief2mp4/scripts/check_delivery.sh
index 8c62176..59a8781 100755
--- a/plugin/skills/brief2mp4/scripts/check_delivery.sh
+++ b/plugin/skills/brief2mp4/scripts/check_delivery.sh
@@ -70,10 +70,12 @@ else
fi
# Picture health: long black stretches and long frozen stretches.
-black="$(ffmpeg -nostats -hide_banner -i "$FILE" -vf "blackdetect=d=0.5:pic_th=0.98" -an -f null - 2>&1 | grep -c black_start || true)"
+# pix_th=0.03 counts only true black (luma within 3% of black), so a dark designed background
+# such as #101114 is not mistaken for a black frame.
+black="$(ffmpeg -nostats -hide_banner -i "$FILE" -vf "blackdetect=d=0.5:pic_th=0.98:pix_th=0.03" -an -f null - 2>&1 | grep -c black_start || true)"
[[ "$black" == 0 ]] && pass "no black stretch over 0.5 s" || warn "$black black stretch(es) over 0.5 s: intended?"
frozen="$(ffmpeg -nostats -hide_banner -i "$FILE" -vf "freezedetect=n=0.001:d=1.5" -an -f null - 2>&1 | grep -c freeze_start || true)"
-[[ "$frozen" == 0 ]] && pass "nothing frozen over 1.5 s" || warn "$frozen frozen stretch(es) over 1.5 s: a hold the brief asked for, or dead air?"
+[[ "$frozen" == 0 ]] && pass "nothing frozen over 1.5 s" || warn "$frozen frozen stretch(es) over 1.5 s: expected where the brief asks for a hold (say so in REPORT.md), otherwise dead air"
echo "----"
if [[ "$FAILS" == 0 ]]; then echo "RESULT: PASS ($FILE)"; exit 0; else echo "RESULT: FAIL, $FAILS check(s) ($FILE)"; exit 1; fi
diff --git a/plugin/skills/brief2mp4/scripts/detect_3d.ps1 b/plugin/skills/brief2mp4/scripts/detect_3d.ps1
new file mode 100644
index 0000000..f4687cf
--- /dev/null
+++ b/plugin/skills/brief2mp4/scripts/detect_3d.ps1
@@ -0,0 +1,37 @@
+# detect_3d.ps1: say whether the optional 3D pack is installed. Always exits 0, so a caller can branch on the text.
+#
+# 3d: ready (components: core,cad,blender)
+# 3d: not installed
+#
+# "ready" needs the core component. cad and blender are listed when present.
+# B2M3D_HOME overrides the install folder (default %USERPROFILE%\.brief2mp4\3d).
+$HomeDir = if ($env:B2M3D_HOME) { $env:B2M3D_HOME } else { Join-Path $env:USERPROFILE ".brief2mp4\3d" }
+$found = @()
+
+$py = Join-Path $HomeDir "venv\Scripts\python.exe"
+$hasCore = (Test-Path $py) -and
+ (Test-Path (Join-Path $HomeDir "node_modules\three")) -and
+ (Test-Path (Join-Path $HomeDir "node_modules\jolt-physics"))
+# "ready" means the pack actually imports, not just that files exist.
+if ($hasCore) {
+ try { & $py -c "import b2m3d.cli" *> $null; $hasCore = ($LASTEXITCODE -eq 0) } catch { $hasCore = $false }
+}
+if ($hasCore) {
+ $found += "core"
+ try { & $py -c "import cadquery" *> $null; if ($LASTEXITCODE -eq 0) { $found += "cad" } } catch { }
+
+ $blender = $false
+ if ($env:B2M3D_BLENDER -and (Test-Path $env:B2M3D_BLENDER)) { $blender = $true }
+ elseif (Get-Command blender -ErrorAction SilentlyContinue) { $blender = $true }
+ else {
+ $roots = @($env:ProgramFiles, "C:\Program Files") | Where-Object { $_ } | Select-Object -Unique
+ foreach ($root in $roots) {
+ if (Get-ChildItem -Path (Join-Path $root "Blender Foundation\Blender *\blender.exe") -ErrorAction SilentlyContinue) { $blender = $true }
+ }
+ }
+ if ($blender) { $found += "blender" }
+ Write-Output ("3d: ready (components: " + ($found -join ",") + ")")
+} else {
+ Write-Output "3d: not installed"
+}
+exit 0
diff --git a/plugin/skills/brief2mp4/scripts/detect_3d.sh b/plugin/skills/brief2mp4/scripts/detect_3d.sh
new file mode 100755
index 0000000..a64a4a4
--- /dev/null
+++ b/plugin/skills/brief2mp4/scripts/detect_3d.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# detect_3d.sh: say whether the optional 3D pack is installed. Always exits 0, so a caller can branch on the text.
+#
+# 3d: ready (components: core,cad,blender)
+# 3d: not installed
+#
+# "ready" needs the core component. cad and blender are listed when present.
+# B2M3D_HOME overrides the install folder (default ~/.brief2mp4/3d).
+set -u
+
+HOME_DIR="${B2M3D_HOME:-$HOME/.brief2mp4/3d}"
+found=()
+
+PY="$HOME_DIR/venv/bin/python"
+[[ -x "$PY" ]] || PY="$HOME_DIR/venv/Scripts/python.exe" # Windows venv layout (Git Bash)
+# "ready" means the pack actually imports and its node packages are present, not just that files exist.
+if [[ -x "$PY" && -d "$HOME_DIR/node_modules/three" && -d "$HOME_DIR/node_modules/jolt-physics" ]] \
+ && "$PY" -c "import b2m3d.cli" >/dev/null 2>&1; then
+ found+=(core)
+ "$PY" -c "import cadquery" >/dev/null 2>&1 && found+=(cad)
+fi
+
+blender_found=0
+if [[ -n "${B2M3D_BLENDER:-}" && -x "${B2M3D_BLENDER}" ]]; then blender_found=1
+elif command -v blender >/dev/null 2>&1; then blender_found=1
+else
+ for c in /Applications/Blender.app/Contents/MacOS/Blender /usr/bin/blender /usr/local/bin/blender /snap/bin/blender "/c/Program Files/Blender Foundation"/Blender*/blender.exe; do
+ [[ -x "$c" ]] && { blender_found=1; break; }
+ done
+fi
+
+if [[ " ${found[*]-} " == *" core "* ]]; then
+ [[ $blender_found -eq 1 ]] && found+=(blender)
+ (IFS=,; echo "3d: ready (components: ${found[*]})")
+else
+ echo "3d: not installed"
+fi
+exit 0
diff --git a/plugin/skills/brief2mp4/scripts/doctor.sh b/plugin/skills/brief2mp4/scripts/doctor.sh
new file mode 100755
index 0000000..cb1888e
--- /dev/null
+++ b/plugin/skills/brief2mp4/scripts/doctor.sh
@@ -0,0 +1,109 @@
+#!/usr/bin/env bash
+# doctor.sh: check every tool brief2mp4 can use and print the install command for anything missing.
+# bash doctor.sh # human-readable
+# bash doctor.sh --json # one JSON object
+# Exit 0 when every REQUIRED tool is present, 1 otherwise. Optional tools never fail the check.
+set -uo pipefail
+
+JSON=0; [[ "${1:-}" == "--json" ]] && JSON=1
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+case "$(uname -s)" in
+ Darwin) OS=macos ;;
+ Linux) OS=linux; grep -qi microsoft /proc/version 2>/dev/null && OS=wsl ;;
+ MINGW*|MSYS*|CYGWIN*) OS=windows ;;
+ *) OS=unknown ;;
+esac
+
+PKG="sudo apt install -y"
+command -v dnf >/dev/null 2>&1 && PKG="sudo dnf install -y"
+command -v pacman >/dev/null 2>&1 && PKG="sudo pacman -S --needed"
+command -v zypper >/dev/null 2>&1 && PKG="sudo zypper install -y"
+
+fix() { # fix <tool> -> install command for this OS
+ case "$OS:$1" in
+ macos:node) echo "brew install node" ;;
+ macos:ffmpeg) echo "brew install ffmpeg" ;;
+ macos:git) echo "xcode-select --install" ;;
+ macos:blender) echo "brew install --cask blender" ;;
+ macos:python) echo "brew install [email protected]" ;;
+ windows:node) echo "winget install -e --id OpenJS.NodeJS.LTS" ;;
+ windows:ffmpeg) echo "winget install -e --id Gyan.FFmpeg" ;;
+ windows:git) echo "winget install -e --id Git.Git" ;;
+ windows:blender) echo "winget install -e --id BlenderFoundation.Blender" ;;
+ windows:python) echo "winget install -e --id Python.Python.3.12" ;;
+ *:node) echo "install Node.js 22+ from https://nodejs.org (or nodesource setup_22.x)" ;;
+ *:ffmpeg) echo "$PKG ffmpeg" ;;
+ *:git) echo "$PKG git" ;;
+ *:blender) echo "download from https://www.blender.org/download" ;;
+ *:python) echo "$PKG python3 (3.12 or 3.13; Debian 12 ships 3.11: uv python install 3.12)" ;;
+ esac
+}
+
+find_blender() {
+ command -v blender 2>/dev/null && return
+ local c
+ for c in /Applications/Blender.app/Contents/MacOS/Blender "/c/Program Files/Blender Foundation"/Blender*/blender.exe; do
+ [[ -x "$c" ]] && { echo "$c"; return; }
+ done
+}
+
+find_python() {
+ local p v
+ for p in python3.13 python3.12 python3 python py; do
+ command -v "$p" >/dev/null 2>&1 || continue
+ v="$("$p" -c 'import sys;print("%d.%d"%sys.version_info[:2])' 2>/dev/null)" || continue
+ case "$v" in 3.12|3.13) echo "$p $v"; return ;; esac
+ done
+}
+
+ROWS=(); FAIL=0
+row() { # row <name> <required:1|0> <status> <detail>
+ ROWS+=("$1|$2|$3|$4")
+ [[ "$2" == 1 && "$3" != ok ]] && FAIL=1
+}
+
+if command -v node >/dev/null 2>&1; then
+ major="$(node -v | sed 's/^v//; s/\..*//')"
+ if [[ "$major" -ge 22 ]] 2>/dev/null; then row node 1 ok "$(node -v)"
+ else row node 1 old "$(node -v) is older than 22. $(fix node)"; fi
+else row node 1 missing "$(fix node)"; fi
+
+for t in ffmpeg ffprobe; do
+ if command -v "$t" >/dev/null 2>&1; then row "$t" 1 ok "$("$t" -version 2>/dev/null | head -1 | cut -c1-60)"
+ else row "$t" 1 missing "$(fix ffmpeg)"; fi
+done
+
+if command -v git >/dev/null 2>&1; then row git 1 ok "$(git --version)"; else row git 1 missing "$(fix git)"; fi
+
+b="$(find_blender)"
+if [[ -n "$b" ]]; then row blender 0 ok "$("$b" --version 2>/dev/null | head -1) ($b)"
+else row blender 0 missing "only for Blender briefs. $(fix blender)"; fi
+
+py="$(find_python)"
+if [[ -n "$py" ]]; then row python 0 ok "$py"
+else row python 0 missing "only for the 3D pack (3.12 or 3.13). $(fix python)"; fi
+
+d3="$(bash "$HERE/detect_3d.sh" 2>/dev/null || echo '3d: not installed')"
+if [[ "$d3" == *ready* ]]; then row 3d-pack 0 ok "${d3#3d: }"
+else row 3d-pack 0 missing "optional. Install: bash \"$(cd "$HERE/.." && pwd)/3d/install_3d.sh\" --components core (Windows: install_3d.ps1 -Components core in the same folder)"; fi
+
+if [[ "$JSON" == 1 ]]; then
+ printf '{"os":"%s","ok":%s,"tools":[' "$OS" "$([[ $FAIL == 0 ]] && echo true || echo false)"
+ sep=""
+ for r in "${ROWS[@]}"; do
+ IFS='|' read -r n req st det <<<"$r"
+ det="${det//\\/\\\\}"; det="${det//\"/\\\"}"
+ printf '%s{"name":"%s","required":%s,"status":"%s","detail":"%s"}' "$sep" "$n" "$([[ $req == 1 ]] && echo true || echo false)" "$st" "$det"
+ sep=","
+ done
+ printf ']}\n'
+else
+ echo "brief2mp4 doctor ($OS)"
+ for r in "${ROWS[@]}"; do
+ IFS='|' read -r n req st det <<<"$r"
+ printf ' %-8s %-9s %s%s\n' "$st" "$n" "$det" "$([[ $req == 0 ]] && echo ' [optional]')"
+ done
+ [[ $FAIL == 0 ]] && echo "RESULT: ready" || echo "RESULT: missing required tools (see above)"
+fi
+exit "$FAIL"
diff --git a/plugin/skills/brief2mp4/scripts/finish.sh b/plugin/skills/brief2mp4/scripts/finish.sh
index 7711fcc..89efce5 100755
--- a/plugin/skills/brief2mp4/scripts/finish.sh
+++ b/plugin/skills/brief2mp4/scripts/finish.sh
@@ -56,13 +56,36 @@ fi
# Fit inside the frame, pad the rest, hold the last frame if the render is short.
VF="scale=${W}:${H}:force_original_aspect_ratio=decrease:flags=lanczos,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2,fps=${FPS},tpad=stop_mode=clone:stop_duration=${SECONDS_},format=yuv420p"
-AF="loudnorm=I=${LUFS}:TP=-1.5:LRA=11,aresample=48000,apad,atrim=0:${SECONDS_},afade=t=out:st=$(awk "BEGIN{print ${SECONDS_}-0.4}"):d=0.4"
+# Loudness: a soft limiter tames sharp hits (so short, peaky beds can still reach the target),
+# then two-pass loudnorm: measure first, then apply linearly with the measured values. Single-pass
+# loudnorm undershoots on short clips because it needs several seconds of look-ahead.
+PRE="alimiter=limit=0.5:level=disabled"
+TAIL="aresample=48000,apad,atrim=0:${SECONDS_},afade=t=out:st=$(awk "BEGIN{print ${SECONDS_}-0.4}"):d=0.4"
+loudness_filter() { # loudness_filter <input file> -> prints the -af chain
+ local m val k f="${PRE},loudnorm=I=${LUFS}:TP=-1.5:LRA=11"
+ m="$(ffmpeg -hide_banner -nostats -t "$SECONDS_" -i "$1" -vn -af "${PRE},loudnorm=I=${LUFS}:TP=-1.5:LRA=11:print_format=json" -f null - 2>&1 | awk '/^\{/,/^\}/')"
+ for k in input_i input_tp input_lra input_thresh target_offset; do
+ val="$(printf '%s\n' "$m" | sed -n "s/.*\"$k\" : \"\([^\"]*\)\".*/\1/p")"
+ case "$val" in
+ *inf*|*nan*) echo "${TAIL}"; return ;; # silent input: nothing to normalise
+ "") echo "${PRE},loudnorm=I=${LUFS}:TP=-1.5:LRA=11,${TAIL}"; return ;;
+ esac
+ case "$k" in
+ input_i) f="$f:measured_I=$val" ;; input_tp) f="$f:measured_TP=$val" ;;
+ input_lra) f="$f:measured_LRA=$val" ;; input_thresh) f="$f:measured_thresh=$val" ;;
+ target_offset) f="$f:offset=$val" ;;
+ esac
+ done
+ echo "$f:linear=true,${TAIL}"
+}
if [[ -n "$AUDIO" ]]; then
+ AF="$(loudness_filter "$AUDIO")"
ffmpeg -v error -y "${VIN[@]}" -i "$AUDIO" -map 0:v:0 -map 1:a:0 -vf "$VF" -af "$AF" \
-t "$SECONDS_" -c:v libx264 -preset slow -crf "$CRF" -profile:v high -r "$FPS" \
-c:a aac -b:a 192k -ar 48000 -ac 2 -movflags +faststart "$OUT"
elif [[ "$KEEP" == 1 ]]; then
+ AF="$(loudness_filter "$IN")"
ffmpeg -v error -y "${VIN[@]}" -map 0:v:0 -map 0:a:0 -vf "$VF" -af "$AF" \
-t "$SECONDS_" -c:v libx264 -preset slow -crf "$CRF" -profile:v high -r "$FPS" \
-c:a aac -b:a 192k -ar 48000 -ac 2 -movflags +faststart "$OUT"
diff --git a/plugin/skills/brief2mp4/scripts/sound_bed.sh b/plugin/skills/brief2mp4/scripts/sound_bed.sh
index 9a97fbf..6864d89 100755
--- a/plugin/skills/brief2mp4/scripts/sound_bed.sh
+++ b/plugin/skills/brief2mp4/scripts/sound_bed.sh
@@ -9,20 +9,22 @@
# Options
# --seconds N length (required)
# --bpm N pulse tempo (default 100)
-# --hits LIST extra low "boom" accents at these seconds (e.g. on a reveal)
+# --hits LIST extra low "boom" accents at these seconds (e.g. on a reveal or a landing)
+# --ticks LIST short bright clicks at these seconds (e.g. a cut, a new label, a UI tap)
set -euo pipefail
OUT="${1:-}"; shift || true
-SECONDS_="" BPM=100 HITS=""
+SECONDS_="" BPM=100 HITS="" TICKS=""
while [[ $# -gt 0 ]]; do
case "$1" in
--seconds) SECONDS_="$2"; shift 2 ;;
--bpm) BPM="$2"; shift 2 ;;
--hits) HITS="$2"; shift 2 ;;
+ --ticks) TICKS="$2"; shift 2 ;;
*) echo "sound_bed.sh: unknown option $1" >&2; exit 2 ;;
esac
done
-[[ -n "$OUT" && -n "$SECONDS_" ]] || { echo "usage: sound_bed.sh OUT.wav --seconds N [--bpm N] [--hits t1,t2]" >&2; exit 2; }
+[[ -n "$OUT" && -n "$SECONDS_" ]] || { echo "usage: sound_bed.sh OUT.wav --seconds N [--bpm N] [--hits t1,t2] [--ticks t1,t2]" >&2; exit 2; }
BEAT="$(awk -v b="$BPM" 'BEGIN{print 60/b}')"
# Pad: an A-minor-ish chord with a slow swell. Pulse: a soft low thump on every beat.
@@ -36,6 +38,13 @@ if [[ -n "$HITS" ]]; then
done
fi
+if [[ -n "$TICKS" ]]; then
+ IFS=',' read -r -a K <<< "$TICKS"
+ for k in "${K[@]}"; do
+ EXPR="${EXPR}+0.35*sin(2*PI*2400*(t-${k}))*exp(-90*(t-${k}))*gte(t\,${k})"
+ done
+fi
+
ffmpeg -v error -y -f lavfi -i "aevalsrc=${EXPR}|${EXPR}:s=48000:d=${SECONDS_}" \
-af "afade=t=in:d=0.6,afade=t=out:st=$(awk -v s="$SECONDS_" 'BEGIN{print s-1}'):d=1,lowpass=f=6000" \
-c:a pcm_s16le "$OUT"
diff --git a/plugin/skills/brief2mp4/scripts/vendor_libs.sh b/plugin/skills/brief2mp4/scripts/vendor_libs.sh
new file mode 100755
index 0000000..8efe925
--- /dev/null
+++ b/plugin/skills/brief2mp4/scripts/vendor_libs.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# vendor_libs.sh: copy pinned GSAP, three.js and web fonts into a project's vendor/ folder, so a
+# render never touches the network (same pixels every run, works offline).
+#
+# vendor_libs.sh PROJECT_DIR # GSAP only
+# vendor_libs.sh PROJECT_DIR --three # GSAP + three.js
+# vendor_libs.sh PROJECT_DIR --fonts inter,space-grotesk
+#
+# Writes PROJECT_DIR/vendor/gsap.min.js, vendor/three.module.js (with --three) and
+# vendor/fonts/<family>-<weight>.woff2 plus vendor/fonts/fonts.css (with --fonts; weights 400 and 700,
+# latin subset). Load them with <script src="vendor/gsap.min.js">, an import map pointing "three" at
+# ./vendor/three.module.js, and <link rel="stylesheet" href="vendor/fonts/fonts.css">.
+# Needs npm (it ships with Node.js). Safe to run again.
+set -euo pipefail
+
+GSAP_VERSION="3.15.0"
+THREE_VERSION="0.170.0"
+FONT_VERSION="5.3.0"
+
+DIR="${1:-}"; [[ -n "$DIR" ]] || { echo "usage: vendor_libs.sh PROJECT_DIR [--three] [--fonts a,b]" >&2; exit 2; }
+shift
+THREE=0 FONTS=""
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --three) THREE=1; shift ;;
+ --fonts) [[ -n "${2:-}" ]] || { echo "vendor_libs.sh: --fonts needs a list, e.g. inter,space-grotesk" >&2; exit 2; }; FONTS="$2"; shift 2 ;;
+ *) echo "vendor_libs.sh: unknown option $1" >&2; exit 2 ;;
+ esac
+done
+command -v npm >/dev/null 2>&1 || { echo "vendor_libs.sh: npm not found; install Node.js 22+" >&2; exit 1; }
+
+mkdir -p "$DIR/vendor"
+VENDOR="$(cd "$DIR/vendor" && pwd)"
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+fetch() { # fetch <package@version> -> prints the unpacked package folder
+ local tgz
+ tgz="$(cd "$WORK" && npm pack "$1" --silent 2>/dev/null | tail -1)"
+ mkdir -p "$WORK/${tgz%.tgz}"
+ tar xzf "$WORK/$tgz" -C "$WORK/${tgz%.tgz}"
+ echo "$WORK/${tgz%.tgz}/package"
+}
+
+pkg="$(fetch "gsap@$GSAP_VERSION")"
+cp "$pkg/dist/gsap.min.js" "$VENDOR/gsap.min.js"
+echo "vendor: gsap $GSAP_VERSION -> vendor/gsap.min.js"
+
+if [[ "$THREE" == 1 ]]; then
+ pkg="$(fetch "three@$THREE_VERSION")"
+ cp "$pkg/build/three.module.js" "$VENDOR/three.module.js"
+ echo "vendor: three $THREE_VERSION -> vendor/three.module.js"
+fi
+
+if [[ -n "$FONTS" ]]; then
+ mkdir -p "$VENDOR/fonts"
+ : > "$VENDOR/fonts/fonts.css"
+ for fam in ${FONTS//,/ }; do
+ pkg="$(fetch "@fontsource/$fam@$FONT_VERSION")"
+ name="$(sed -n 's/.*"family": *"\([^"]*\)".*/\1/p' "$pkg/metadata.json" 2>/dev/null | head -1)"
+ [[ -f "$pkg/LICENSE" ]] && cp "$pkg/LICENSE" "$VENDOR/fonts/LICENSE-$fam.txt" # fonts are OFL: ship the licence
+ [[ -n "$name" ]] || name="$fam"
+ for w in 400 700; do
+ src="$pkg/files/$fam-latin-$w-normal.woff2"
+ if [[ -f "$src" ]]; then
+ cp "$src" "$VENDOR/fonts/$fam-$w.woff2"
+ printf '@font-face{font-family:"%s";font-weight:%s;font-style:normal;font-display:block;src:url("%s-%s.woff2") format("woff2")}\n' \
+ "$name" "$w" "$fam" "$w" >> "$VENDOR/fonts/fonts.css"
+ fi
+ done
+ echo "vendor: font $name ($fam) -> vendor/fonts/"
+ done
+fi
diff --git a/plugin/skills/brief2mp4/templates/threejs/index.html b/plugin/skills/brief2mp4/templates/threejs/index.html
index 8e27c7d..bbeedd2 100644
--- a/plugin/skills/brief2mp4/templates/threejs/index.html
+++ b/plugin/skills/brief2mp4/templates/threejs/index.html
@@ -8,7 +8,8 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
+ <!-- Local copies, so the render never touches the network: run scripts/vendor_libs.sh <project> --three first. -->
+ <script src="vendor/gsap.min.js"></script>
<style>
:root {
--ground: #14112b;
@@ -44,7 +45,7 @@
</div>
<script type="importmap">
- { "imports": { "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js" } }
+ { "imports": { "three": "./vendor/three.module.js" } }
</script>
<script type="module">
import * as THREE from "three";
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..761cdf6
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,97 @@
+"""Shared fixtures for the 3D pack tests.
+
+The pack is tested against an installed copy: B2M3D_HOME (default ~/.brief2mp4/3d) must hold the
+`core` component. Run through tests/run_tests.sh, which picks that venv's Python. Tests that need
+an optional piece (CadQuery, Blender, network) skip with a reason instead of failing.
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import shutil
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[1]
+SKILL = REPO / "plugin" / "skills" / "brief2mp4"
+PACK = SKILL / "3d"
+EXAMPLE = PACK / "examples" / "04-3d-product"
+HYPERFRAMES = "[email protected]"
+
+sys.path.insert(0, str(PACK))
+from b2m3d import paths # noqa: E402 (stdlib only, safe before the venv check)
+
+HOME = Path(os.environ.get("B2M3D_HOME") or Path.home() / ".brief2mp4" / "3d")
+os.environ["B2M3D_HOME"] = str(HOME)
+
+
+def core_installed() -> bool:
+ return paths.venv_python().exists() and (paths.node_modules() / "three").is_dir()
+
+
+def has_module(name: str) -> bool:
+ return importlib.util.find_spec(name) is not None
+
+
+needs_core = pytest.mark.skipif(
+ not (core_installed() and has_module("trimesh") and has_module("numpy")),
+ reason="core component not installed or tests not run with its Python (use tests/run_tests.sh)")
+needs_cadquery = pytest.mark.skipif(not has_module("cadquery"), reason="cad component not installed")
+needs_blender = pytest.mark.skipif(paths.blender() is None, reason="Blender not found")
+needs_npx = pytest.mark.skipif(shutil.which("npx") is None, reason="npx not found")
+
+
+def pytest_configure(config):
+ config.addinivalue_line("markers", "slow: renders or launches external tools (HyperFrames, Blender)")
+
+
+def cli(*args: str, home: Path | None = None, cwd: Path | None = None) -> subprocess.CompletedProcess:
+ """Run `python -m b2m3d ...` the way an agent would."""
+ env = {**os.environ, "B2M3D_HOME": str(home or HOME), "PYTHONPATH": str(PACK)}
+ py = paths.venv_python() if (home is None and paths.venv_python().exists()) else Path(sys.executable)
+ return subprocess.run([str(py), "-m", "b2m3d", *args], capture_output=True, text=True, env=env, cwd=cwd)
+
+
+def cli_json(*args: str, **kw) -> dict:
+ proc = cli(*args, **kw)
+ assert proc.returncode == 0, f"b2m3d {' '.join(args)} failed:\n{proc.stdout}\n{proc.stderr}"
+ return json.loads(proc.stdout)
+
+
+def online(host: str = "cdn.jsdelivr.net") -> bool:
+ try:
+ socket.create_connection((host, 443), timeout=5).close()
+ return True
+ except OSError:
+ return False
+
+
+def ffprobe(path: Path) -> dict:
+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
+ "stream=codec_name,width,height:format=duration", "-of", "json", str(path)],
+ capture_output=True, text=True, check=True).stdout
+ data = json.loads(out)
+ return {**data["streams"][0], "duration": float(data["format"]["duration"])}
+
+
+def hyperframes(*args: str, cwd: Path, timeout: int = 900) -> subprocess.CompletedProcess:
+ npx = shutil.which("npx")
+ return subprocess.run([npx, "--yes", HYPERFRAMES, *args], capture_output=True, text=True,
+ cwd=cwd, timeout=timeout)
+
+
[email protected](scope="session")
+def parts(tmp_path_factory) -> dict[str, Path]:
+ """Raw GLBs for the example's five parts, built in-process (fast)."""
+ from b2m3d import model
+ out = tmp_path_factory.mktemp("parts")
+ built = {}
+ for name in ("shell", "cell", "board", "cover", "lens"):
+ built[name] = out / f"{name}.glb"
+ model.build(EXAMPLE / "device.py", built[name], {"part": name})
+ return built
diff --git a/tests/data/cad_spec.py b/tests/data/cad_spec.py
new file mode 100644
index 0000000..8b3eb0a
--- /dev/null
+++ b/tests/data/cad_spec.py
@@ -0,0 +1,9 @@
+"""A CadQuery assembly spec (needs the cad component)."""
+import cadquery as cq
+
+
+def build(params):
+ assy = cq.Assembly(name="demo")
+ assy.add(cq.Workplane("XY").box(20, 20, 4), name="plate", color=cq.Color(0.5, 0.5, 0.6))
+ assy.add(cq.Workplane("XY").workplane(offset=4).circle(5).extrude(6), name="post", color=cq.Color(0.8, 0.4, 0.2))
+ return assy
diff --git a/tests/data/trimesh_spec.py b/tests/data/trimesh_spec.py
new file mode 100644
index 0000000..5040859
--- /dev/null
+++ b/tests/data/trimesh_spec.py
@@ -0,0 +1,9 @@
+"""A spec that returns a trimesh directly, with its own PARAMS and UNITS."""
+import trimesh
+
+PARAMS = {"size": 2.0}
+UNITS = "cm"
+
+
+def build(params):
+ return trimesh.creation.box(extents=[params["size"]] * 3)
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
new file mode 100755
index 0000000..deb5227
--- /dev/null
+++ b/tests/run_tests.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# run_tests.sh: run the brief2mp4 tests.
+#
+# bash tests/run_tests.sh # fast tests only (seconds)
+# bash tests/run_tests.sh --slow # also the renders: example 04 through HyperFrames, Blender, fallback
+# bash tests/run_tests.sh -k hf # any other argument goes to pytest
+#
+# The 3D tests run against an installed pack: B2M3D_HOME (default ~/.brief2mp4/3d) with the `core`
+# component, plus `dev` for pytest: bash plugin/skills/brief2mp4/3d/install_3d.sh --components core,dev
+# Tests that need an optional piece (CadQuery, Blender, network) skip with a reason.
+set -euo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+export B2M3D_HOME="${B2M3D_HOME:-$HOME/.brief2mp4/3d}"
+PY="$B2M3D_HOME/venv/bin/python"
+[[ -x "$PY" ]] || PY="$B2M3D_HOME/venv/Scripts/python.exe" # Git Bash on Windows
+if [[ ! -x "$PY" ]]; then
+ PY="$(command -v python3 || command -v python)"
+ echo "run_tests.sh: no pack venv in $B2M3D_HOME; the 3D tests will skip. Install: bash plugin/skills/brief2mp4/3d/install_3d.sh --components core,dev" >&2
+fi
+"$PY" -c "import pytest" 2>/dev/null || { echo "run_tests.sh: pytest is missing for $PY. Install it: bash plugin/skills/brief2mp4/3d/install_3d.sh --components dev" >&2; exit 1; }
+
+ARGS=(-m "not slow")
+PASSTHROUGH=()
+for a in "$@"; do
+ if [[ "$a" == "--slow" ]]; then ARGS=(); else PASSTHROUGH+=("$a"); fi
+done
+exec "$PY" -m pytest "$HERE" -p no:cacheprovider -q ${ARGS[@]+"${ARGS[@]}"} ${PASSTHROUGH[@]+"${PASSTHROUGH[@]}"}
diff --git a/tests/test_cli_detect.py b/tests/test_cli_detect.py
new file mode 100644
index 0000000..f371f76
--- /dev/null
+++ b/tests/test_cli_detect.py
@@ -0,0 +1,141 @@
+"""CLI, doctor, detect_3d, installer arguments, Blender lookup, encoder choice, public-repo hygiene."""
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from conftest import EXAMPLE, PACK, REPO, SKILL, cli, needs_core
+
+BASH = None if os.name == "nt" else "bash"
+posix_only = pytest.mark.skipif(BASH is None, reason="bash scripts")
+
+
+def test_doctor_reports_components_as_json():
+ proc = cli("doctor")
+ assert proc.returncode == 0
+ report = json.loads(proc.stdout)
+ assert set(report["components"]) == {"core", "cad", "blender"}
+ for comp in report["components"].values():
+ assert "ok" in comp and "install" in comp
+ assert "install_3d" in report["components"]["core"]["install"]
+
+
+def test_doctor_on_empty_home_lists_what_is_missing(tmp_path):
+ home = tmp_path / "empty"
+ home.mkdir()
+ proc = cli("doctor", home=home)
+ report = json.loads(proc.stdout)
+ assert proc.returncode == 0 and report["ok"] is False
+ core = report["components"]["core"]
+ assert core["ok"] is False and any(m.startswith("npm:three") for m in core["missing"])
+ assert "--components core" in core["install"] or "-Components core" in core["install"]
+
+
+@needs_core
+def test_doctor_ok_when_core_installed():
+ report = json.loads(cli("doctor").stdout)
+ assert report["ok"] is True and report["components"]["core"]["missing"] == []
+
+
+@needs_core
+def test_material_presets_command_lists_sixteen():
+ out = json.loads(cli("material", "presets").stdout)
+ assert len(out["presets"]) == 16 and "gold" in out["presets"]
+
+
+def test_errors_are_one_json_line_on_stderr(tmp_path):
+ proc = cli("hf", str(tmp_path / "missing.json"), str(tmp_path / "out"), home=tmp_path)
+ assert proc.returncode == 1
+ assert json.loads(proc.stderr)["ok"] is False
+
+
+@posix_only
+def test_detect_3d_branches_on_installed_state(tmp_path):
+ script = SKILL / "scripts" / "detect_3d.sh"
+ empty = subprocess.run([BASH, str(script)], capture_output=True, text=True,
+ env={**os.environ, "B2M3D_HOME": str(tmp_path / "none")})
+ assert empty.returncode == 0 and empty.stdout.strip() == "3d: not installed"
+ home = tmp_path / "fake"
+ (home / "venv" / "bin").mkdir(parents=True)
+ (home / "venv" / "bin" / "python").write_text("#!/bin/sh\n")
+ (home / "venv" / "bin" / "python").chmod(0o755)
+ (home / "node_modules" / "three").mkdir(parents=True)
+ (home / "node_modules" / "jolt-physics").mkdir()
+ ready = subprocess.run([BASH, str(script)], capture_output=True, text=True,
+ env={**os.environ, "B2M3D_HOME": str(home), "B2M3D_BLENDER": ""})
+ assert ready.returncode == 0 and ready.stdout.startswith("3d: ready (components: core")
+
+
+@posix_only
+def test_installer_rejects_unknown_component_and_never_uses_sudo(tmp_path):
+ script = PACK / "install_3d.sh"
+ proc = subprocess.run([BASH, str(script), "--components", "bogus"], capture_output=True, text=True,
+ env={**os.environ, "B2M3D_HOME": str(tmp_path / "h")})
+ assert proc.returncode == 2 and "unknown component" in proc.stderr
+ for installer in (script, PACK / "install_3d.ps1"):
+ code = "\n".join(l for l in installer.read_text(encoding="utf-8").splitlines() if not l.lstrip().startswith(("#", "say ", "Write-Output")))
+ assert "sudo" not in code
+
+
+def test_pins_exist_for_every_component():
+ for name in ("requirements-core.txt", "requirements-cad.txt", "requirements-dev.txt"):
+ lines = [l for l in (PACK / name).read_text(encoding="utf-8").splitlines() if l and not l.startswith("#")]
+ assert lines and all("==" in l for l in lines), name
+ deps = json.loads((PACK / "package.json").read_text(encoding="utf-8"))["dependencies"]
+ assert deps and all(v[0].isdigit() for v in deps.values()), "node versions must be exact"
+ assert (PACK / "package-lock.json").exists()
+
+
+def test_blender_lookup_prefers_override_then_picks_newest_windows_install(tmp_path, monkeypatch):
+ from b2m3d import paths
+ fake = tmp_path / "my-blender"
+ fake.write_text("")
+ monkeypatch.setenv("B2M3D_BLENDER", str(fake))
+ assert paths.blender() == str(fake)
+ monkeypatch.delenv("B2M3D_BLENDER")
+ monkeypatch.setenv("PATH", str(tmp_path))
+ ordered = sorted(["C:/P/Blender Foundation/Blender 4.2/blender.exe", "C:/P/Blender Foundation/Blender 5.1/blender.exe",
+ "C:/P/Blender Foundation/Blender 4.10/blender.exe"], key=paths._version_key, reverse=True)
+ assert ordered[0].endswith("Blender 5.1/blender.exe") and ordered[1].endswith("4.10/blender.exe")
+
+
+def test_encoder_choice_per_platform():
+ from b2m3d.encode import pick_encoder
+ yes, no = (lambda n: True), (lambda n: False)
+ assert pick_encoder(True, "darwin", yes)[0] == "prores_ks"
+ assert "4444" in pick_encoder(True, "linux", yes)[1]
+ assert pick_encoder(False, "darwin", yes)[0] == "hevc_videotoolbox"
+ assert pick_encoder(False, "darwin", no)[0] == "libx264"
+ assert pick_encoder(False, "win32", yes)[0] == "libx264"
+ assert pick_encoder(False, "linux", yes)[0] == "libx264"
+
+
+def test_blender_script_gpu_order_covers_every_platform():
+ text = (PACK / "templates" / "blender_shot.py").read_text(encoding="utf-8")
+ assert '["METAL"] if sys.platform == "darwin"' in text
+ for backend in ("OPTIX", "CUDA", "HIP", "ONEAPI"):
+ assert backend in text
+ assert 'scene.cycles.device = "CPU"' in text
+
+
+def test_public_repo_hygiene():
+ """No personal paths, private names or secrets in anything the pack ships."""
+ banned = ["/Us" + "ers/", "C:\\Us" + "ers\\", "api_key", "secret"]
+ # Maintainers can add private terms locally without committing them: B2M_BANNED="a,b,c"
+ banned += [t for t in os.environ.get("B2M_BANNED", "").split(",") if t]
+ files = [p for root in (PACK, REPO / "examples" / "04-3d-product", SKILL / "scripts") for p in root.rglob("*")
+ if p.is_file() and "__pycache__" not in p.parts and p.suffix not in {".pyc"} and p.name != "package-lock.json" # integrity hashes can contain any letters
+
+ and (root != SKILL / "scripts" or p.name.startswith("detect_3d"))]
+ files += [p for p in (REPO / "tests").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "test_cli_detect.py"]
+ hits = []
+ for path in files:
+ try:
+ text = path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ continue
+ hits += [f"{path.relative_to(REPO)}: {b}" for b in banned if b.lower() in text.lower()]
+ assert not hits, hits
+ assert max(len(p.read_text(encoding="utf-8").splitlines()) for p in files if p.suffix in {".py", ".js", ".mjs", ".sh", ".md"}) < 800
diff --git a/tests/test_e2e.py b/tests/test_e2e.py
new file mode 100644
index 0000000..f30a6b3
--- /dev/null
+++ b/tests/test_e2e.py
@@ -0,0 +1,94 @@
+"""Slow tests: real renders. One heavy job at a time, HyperFrames with 4 workers."""
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import (EXAMPLE, PACK, SKILL, cli, cli_json, ffprobe, hyperframes, needs_blender, needs_core,
+ needs_npx, online, paths)
+
+pytestmark = pytest.mark.slow
+BASH = None if os.name == "nt" else "bash"
+
+
+@needs_core
+@needs_npx
+def test_example_04_lints_clean_and_renders_two_seconds(tmp_path):
+ work = tmp_path / "work"
+ build = subprocess.run([str(paths.venv_python()), str(EXAMPLE / "build.py"), str(work)],
+ capture_output=True, text=True, env={**os.environ, "PYTHONPATH": str(PACK)})
+ assert build.returncode == 0, build.stderr
+ lint = hyperframes("lint", str(work / "project"), cwd=work)
+ assert lint.returncode == 0 and "0 errors" in lint.stdout, lint.stdout + lint.stderr
+
+ shot = json.loads((work / "shot.json").read_text(encoding="utf-8"))
+ shot["duration"] = 2
+ (work / "short.json").write_text(json.dumps(shot), encoding="utf-8")
+ cli_json("hf", str(work / "short.json"), str(work / "short"))
+ out = work / "short.mp4"
+ render = hyperframes("render", str(work / "short"), "--workers", "4", "--quality", "draft",
+ "-o", str(out), "--quiet", cwd=work)
+ assert render.returncode == 0 and out.exists(), render.stdout + render.stderr
+ info = ffprobe(out)
+ assert (info["width"], info["height"]) == (1920, 1080)
+ assert info["duration"] == pytest.approx(2.0, abs=0.15)
+
+
+@needs_core
+@needs_blender
+def test_blender_renders_opaque_and_transparent(tmp_path, parts):
+ from b2m3d import encode
+ opaque = cli_json("blender", str(parts["cover"]), str(tmp_path / "f1"), "--frames", "2", "--width", "320",
+ "--height", "180", "--samples", "8", "--look", "dramatic", "--mp4", str(tmp_path / "o.mp4"))
+ assert opaque["frames"] == 2 and len(list((tmp_path / "f1").glob("frame_*.png"))) == 2
+ assert opaque["device"] in {"GPU", "CPU"}
+ info = ffprobe(tmp_path / "o.mp4")
+ expected = "hevc" if sys.platform == "darwin" and encode.has_encoder("hevc_videotoolbox") else "h264"
+ assert (info["codec_name"], info["width"]) == (expected, 320)
+
+ alpha = cli_json("blender", str(parts["cover"]), str(tmp_path / "f2"), "--frames", "2", "--width", "320",
+ "--height", "180", "--samples", "8", "--look", "studio", "--transparent",
+ "--mp4", str(tmp_path / "a.mp4"))
+ assert alpha["video"]["encoder"] == "prores_ks" and alpha["video"]["path"].endswith(".mov")
+ assert ffprobe(tmp_path / "a.mov")["codec_name"] == "prores"
+
+
+@needs_npx
[email protected](BASH is None, reason="uses detect_3d.sh")
+def test_fallback_when_pack_is_hidden_plain_template_still_renders(tmp_path):
+ hidden = tmp_path / "no-pack"
+ hidden.mkdir()
+ detect = subprocess.run([BASH, str(SKILL / "scripts" / "detect_3d.sh")], capture_output=True, text=True,
+ env={**os.environ, "B2M3D_HOME": str(hidden)})
+ assert detect.stdout.strip() == "3d: not installed" and detect.returncode == 0
+ doctor = json.loads(cli("doctor", home=hidden).stdout)
+ assert doctor["ok"] is False
+
+ if not online():
+ pytest.skip("vendoring three.js and GSAP needs npm and the network once; offline")
+ project = tmp_path / "plain"
+ project.mkdir()
+ html = (SKILL / "templates" / "threejs" / "index.html").read_text(encoding="utf-8")
+ html = re.sub(r'data-duration="\d+(\.\d+)?"', 'data-duration="2"', html)
+ html = re.sub(r"const DURATION = \d+(\.\d+)?;", "const DURATION = 2;", html)
+ (project / "index.html").write_text(html, encoding="utf-8")
+ vendor = subprocess.run(["bash", str(SKILL / "scripts" / "vendor_libs.sh"), str(project), "--three"],
+ capture_output=True, text=True)
+ assert vendor.returncode == 0, vendor.stderr
+ out = tmp_path / "plain.mp4"
+ render = hyperframes("render", str(project), "--workers", "4", "--quality", "draft", "-o", str(out),
+ "--quiet", cwd=tmp_path)
+ assert render.returncode == 0 and out.exists(), render.stdout + render.stderr
+ info = ffprobe(out)
+ assert (info["width"], info["height"]) == (1920, 1080)
+ assert info["duration"] == pytest.approx(2.0, abs=0.15)
+
+
+def test_threejs_template_has_no_network_urls():
+ """The plain template must render offline: libraries come from vendor/, never a CDN."""
+ html = (SKILL / "templates" / "threejs" / "index.html").read_text(encoding="utf-8")
+ assert "https://" not in html and "http://" not in html
diff --git a/tests/test_model_material.py b/tests/test_model_material.py
new file mode 100644
index 0000000..9685542
--- /dev/null
+++ b/tests/test_model_material.py
@@ -0,0 +1,155 @@
+"""model, material and optimize: determinism, units, normals, linear colour, error paths."""
+import json
+import sys
+
+import pytest
+
+from conftest import EXAMPLE, cli, needs_cadquery, needs_core
+
+pytestmark = needs_core
+
+
+def gltf(path):
+ from b2m3d.glbio import gltf_json
+ return gltf_json(path)
+
+
+def test_manifold_part_is_metres_y_up_with_normals(parts):
+ meta = gltf(parts["shell"])
+ prim = meta["meshes"][0]["primitives"][0]
+ assert "NORMAL" in prim["attributes"], "normals must be exported or three.js renders flat-shaded"
+ import trimesh
+ lo, hi = trimesh.load(parts["shell"], force="scene").bounds
+ size = (hi - lo).round(4)
+ assert size.tolist() == [0.06, 0.01, 0.04] # 60 x 40 x 10 mm, Z-up in the spec, Y-up in the file
+
+
+def test_model_bake_is_byte_identical(tmp_path):
+ from b2m3d import model
+ a, b = tmp_path / "a.glb", tmp_path / "b.glb"
+ model.build(EXAMPLE / "device.py", a, {"part": "board"})
+ model.build(EXAMPLE / "device.py", b, {"part": "board"})
+ assert a.read_bytes() == b.read_bytes()
+
+
+def test_trimesh_spec_uses_its_own_units_and_params(tmp_path):
+ from b2m3d import model
+ from conftest import REPO
+ out = tmp_path / "box.glb"
+ res = model.build(REPO / "tests" / "data" / "trimesh_spec.py", out, {"size": 4.0})
+ assert res["bounds_m"][1][0] - res["bounds_m"][0][0] == pytest.approx(0.04, abs=1e-4) # 4 cm
+
+
+def test_all_parts_in_one_glb_have_named_nodes(tmp_path):
+ from b2m3d import model
+ out = tmp_path / "all.glb"
+ res = model.build(EXAMPLE / "device.py", out, {"part": "all"})
+ names = {n.get("name") for n in gltf(out)["nodes"]}
+ assert res["parts"] == 5 and {"shell", "cell", "board", "cover", "lens"} <= names
+
+
+def test_parse_params_json_and_strings():
+ from b2m3d.model import parse_params
+ assert parse_params(["n=3", "s=abc", "f=[1,2]"]) == {"n": 3, "s": "abc", "f": [1, 2]}
+ with pytest.raises(ValueError):
+ parse_params(["novalue"])
+
+
+def test_unknown_part_is_a_json_error(tmp_path):
+ proc = cli("model", str(EXAMPLE / "device.py"), str(tmp_path / "x.glb"), "--param", "part=nope")
+ assert proc.returncode == 1
+ assert json.loads(proc.stderr)["ok"] is False and "unknown part" in proc.stderr
+
+
+def test_missing_cadquery_gives_install_hint(monkeypatch):
+ from b2m3d import model
+ from b2m3d.run import B2M3DError
+ monkeypatch.setitem(sys.modules, "cadquery", None)
+ with pytest.raises(B2M3DError, match="cad"):
+ model._cq_to_parts(object(), "x", 0.05)
+
+
+@needs_cadquery
+def test_cadquery_assembly_keeps_parts_and_colours(tmp_path):
+ from b2m3d import model
+ from conftest import REPO
+ out = tmp_path / "cad.glb"
+ res = model.build(REPO / "tests" / "data" / "cad_spec.py", out)
+ assert res["parts"] == 2
+ mats = gltf(out)["materials"]
+ assert len(mats) == 2 and mats[0]["pbrMetallicRoughness"]["baseColorFactor"][3] == 1.0
+
+
+def test_presets_are_valid_and_linear():
+ from b2m3d import material
+ presets = material.load_presets()
+ assert len(presets) == 16
+ for name, p in presets.items():
+ assert p["name"] == name and p["colorSpace"] == "linear"
+ assert len(p["baseColor"]) == 3 and all(0 <= c <= 1 for c in p["baseColor"])
+ assert 0 <= p["metallic"] <= 1 and 0 <= p["roughness"] <= 1
+
+
+def test_srgb_to_linear_uses_power_2_2():
+ from b2m3d.material import srgb_to_linear
+ assert srgb_to_linear("#808080")[0] == pytest.approx((128 / 255) ** 2.2, abs=1e-4)
+ assert srgb_to_linear("#ffffff") == [1.0, 1.0, 1.0]
+ with pytest.raises(ValueError):
+ srgb_to_linear("teal")
+
+
+def test_to_gltf_maps_extensions():
+ from b2m3d import material
+ presets = material.load_presets()
+ glass = material.to_gltf(presets["smoked_glass"])["extensions"]
+ assert {"KHR_materials_transmission", "KHR_materials_volume", "KHR_materials_ior"} <= set(glass)
+ neon = material.to_gltf(presets["neon_emissive"])
+ assert neon["emissiveFactor"] == [1.0, 0.35, 0.1]
+ assert neon["extensions"]["KHR_materials_emissive_strength"]["emissiveStrength"] == 8.0
+ assert "KHR_materials_clearcoat" in material.to_gltf(presets["car_paint_red"])["extensions"]
+
+
+def test_material_assign_is_linear_exact_and_byte_identical(parts, tmp_path):
+ from b2m3d import material
+ a, b = tmp_path / "a.glb", tmp_path / "b.glb"
+ res = material.assign(parts["board"], a, {"*": "pcb_green"})
+ material.assign(parts["board"], b, {"*": "pcb_green"})
+ assert a.read_bytes() == b.read_bytes()
+ assert res["assigned"] == {"board": "pcb_green"}
+ mats = gltf(a)["materials"]
+ assert len(mats) == 1, "the replaced material must not ship as dead weight"
+ assert mats[0]["pbrMetallicRoughness"]["baseColorFactor"] == [0.006, 0.045, 0.02, 1.0]
+
+
+def test_material_assign_by_node_name(parts, tmp_path):
+ from b2m3d import material
+ out = tmp_path / "named.glb"
+ res = material.assign(parts["shell"], out, {"shell": "gold"})
+ assert res["assigned"] == {"shell": "gold"}
+
+
+def test_material_assign_errors(parts, tmp_path):
+ from b2m3d import material
+ from b2m3d.run import B2M3DError
+ with pytest.raises(KeyError, match="unknown material"):
+ material.assign(parts["shell"], tmp_path / "o.glb", {"*": "unobtainium"})
+ with pytest.raises(B2M3DError, match="nothing to assign"):
+ material.assign(parts["shell"], tmp_path / "o.glb", {})
+ with pytest.raises(ValueError):
+ material.parse_assignments(["noequals"])
+
+
+def test_optimize_keeps_names_compresses_and_stays_readable(parts, tmp_path):
+ from b2m3d import glbio
+ out = tmp_path / "opt.glb"
+ proc = cli("optimize", str(parts["board"]), str(out))
+ assert proc.returncode == 0, proc.stderr
+ assert glbio.is_compressed(out)
+ assert any(n.get("name") == "board" for n in gltf(out)["nodes"])
+ import trimesh
+ assert len(trimesh.load(glbio.readable(out), force="scene").geometry) == 1
+
+
+def test_optimize_rejects_bad_ratio(parts, tmp_path):
+ proc = cli("optimize", str(parts["board"]), str(tmp_path / "o.glb"), "--simplify", "2")
+ assert proc.returncode == 1
diff --git a/tests/test_physics_hf.py b/tests/test_physics_hf.py
new file mode 100644
index 0000000..515d0ae
--- /dev/null
+++ b/tests/test_physics_hf.py
@@ -0,0 +1,177 @@
+"""physics bake and hf project generation: determinism, offline project, validation."""
+import json
+import re
+import shutil
+
+import pytest
+
+from conftest import EXAMPLE, needs_core
+
+pytestmark = needs_core
+
+FORBIDDEN_RUNTIME = ["Date.now", "performance.now", "Math.random", "setAnimationLoop", "requestAnimationFrame"]
+
+
+def drop_scene(tmp_path, parts, names=("shell", "lens")):
+ """A small drop: the shell falls onto the floor, the lens falls onto the shell."""
+ bodies = [{"name": "floor", "shape": "box", "size": [3, 0.2, 3], "position": [0, -0.1, 0],
+ "motion": "static", "friction": 1.0}]
+ for i, name in enumerate(names):
+ shutil.copy(parts[name], tmp_path / f"{name}.glb")
+ bodies.append({"name": name, "shape": "hull", "glb": f"{name}.glb", "position": [0, 0.15 + 0.2 * i, 0],
+ "restitution": 0.05, "friction": 1.0, "linearDamping": 0.6, "angularDamping": 0.9})
+ scene = tmp_path / "scene.json"
+ scene.write_text(json.dumps({"fps": 30, "duration": 3, "substeps": 4, "gravity": [0, -3, 0], "bodies": bodies}))
+ return scene
+
+
+def test_physics_is_deterministic_and_settles(tmp_path, parts):
+ from b2m3d import physics
+ scene = drop_scene(tmp_path, parts)
+ a, b = tmp_path / "a.json", tmp_path / "b.json"
+ res = physics.bake(scene, a)
+ physics.bake(scene, b)
+ assert a.read_bytes() == b.read_bytes(), "two bakes of one scene must be byte-identical"
+ tracks = json.loads(a.read_text())["tracks"]
+ assert res["frames"] == 90 and len(tracks["shell"]) == 90 and res["settled"] is True
+ assert tracks["shell"][0][1] == pytest.approx(0.15)
+ assert tracks["shell"][-1][1] == pytest.approx(0.005, abs=0.002) # 10 mm tall, resting on the floor
+ assert tracks["floor"][0] == tracks["floor"][-1]
+
+
+def test_physics_hulls_read_compressed_glb(tmp_path, parts):
+ from b2m3d import physics
+ from conftest import cli
+ packed = tmp_path / "packed.glb"
+ assert cli("optimize", str(parts["cell"]), str(packed)).returncode == 0
+ pts = physics.hull_points(packed, None)
+ assert 8 <= len(pts) <= 200
+
+
+def test_physics_unknown_node_raises(parts):
+ from b2m3d import physics
+ with pytest.raises(KeyError):
+ physics.hull_points(parts["shell"], "no-such-node")
+
+
+def make_shot(tmp_path, parts, **extra):
+ shutil.copy(parts["shell"], tmp_path / "shell.glb")
+ shot = {"duration": 3, "models": [{"src": "shell.glb", "spin": 20}],
+ "titles": [{"text": "Hello <world> </script>", "start": 0.5, "duration": 2}], **extra}
+ path = tmp_path / "shot.json"
+ path.write_text(json.dumps(shot))
+ return path
+
+
+def test_hf_project_is_offline_and_seekable(tmp_path, parts):
+ from b2m3d import hf
+ res = hf.scaffold(make_shot(tmp_path, parts), tmp_path / "proj")
+ assert res["warnings"] == [] and res["models"] == 1
+ html = (tmp_path / "proj" / "index.html").read_text()
+ assert 'data-duration="3"' in html and 'data-composition-id="b2m3d"' in html
+ assert "Hello &lt;world&gt; &lt;/script&gt;" in html # titles are escaped
+ assert not re.search(r'(src|href)="https?://', html) # no network at render time
+ assert "/Us" + "ers/" not in html and "C:\\Us" + "ers" not in html
+ for rel in ["vendor/three/build/three.module.js", "vendor/three/addons/loaders/GLTFLoader.js",
+ "vendor/three/addons/environments/RoomEnvironment.js", "vendor/gsap.min.js",
+ "b2m3d-runtime.js", "assets/shell.glb", "fonts/inter-latin-wght-normal.woff2"]:
+ assert (tmp_path / "proj" / rel).exists(), rel
+ runtime = (tmp_path / "proj" / "b2m3d-runtime.js").read_text()
+ for token in FORBIDDEN_RUNTIME:
+ assert token not in runtime, f"{token} breaks frame seeking"
+ assert 'tonemapping ?? "neutral"' in runtime and "envIntensity ?? 0.35" in runtime
+ assert "buildReady" in runtime
+
+
+def test_hf_defaults_are_neutral_and_kicker_is_empty(tmp_path, parts):
+ from b2m3d import hf
+ hf.scaffold(make_shot(tmp_path, parts), tmp_path / "proj")
+ html = (tmp_path / "proj" / "index.html").read_text()
+ assert "b2m3d-kick-" not in html.split("<body>")[1] # no kicker element unless asked for
+ assert "teal" not in html.lower() and "mint" not in html.lower()
+ hf.scaffold(make_shot(tmp_path, parts, titles=[{"kicker": "Part one", "text": "T", "start": 0, "duration": 2}]),
+ tmp_path / "proj2")
+ assert "b2m3d-kick-0" in (tmp_path / "proj2" / "index.html").read_text().split("<body>")[1]
+
+
+def test_hf_generation_is_deterministic(tmp_path, parts):
+ from b2m3d import hf
+ shot = make_shot(tmp_path, parts)
+ hf.scaffold(shot, tmp_path / "p1")
+ hf.scaffold(shot, tmp_path / "p2")
+ assert (tmp_path / "p1" / "index.html").read_bytes() == (tmp_path / "p2" / "index.html").read_bytes()
+
+
+def test_hf_warns_on_unknown_keys(tmp_path, parts):
+ from b2m3d import hf
+ res = hf.scaffold(make_shot(tmp_path, parts, camra={"fov": 30}), tmp_path / "proj")
+ assert any("camra" in w for w in res["warnings"])
+
+
[email protected]("patch,message", [
+ ({"duration": 0}, "duration"),
+ ({"models": []}, "models"),
+ ({"models": [{"src": "shell.glb", "track": "ghost"}]}, "physics bake"),
+ ({"titles": [{"text": "x"}]}, "titles[0]"),
+])
+def test_hf_rejects_invalid_shots(tmp_path, parts, patch, message):
+ from b2m3d import hf
+ with pytest.raises(ValueError, match=re.escape(message)):
+ hf.scaffold(make_shot(tmp_path, parts, **patch), tmp_path / "proj")
+
+
+def test_hf_missing_model_file(tmp_path, parts):
+ from b2m3d import hf
+ shot = make_shot(tmp_path, parts, models=[{"src": "missing.glb"}])
+ with pytest.raises(FileNotFoundError):
+ hf.scaffold(shot, tmp_path / "proj")
+
+
+def test_hf_same_file_name_in_two_folders_gets_two_assets(tmp_path, parts):
+ from b2m3d import hf
+ for sub, part in (("a", "shell"), ("b", "cell")):
+ (tmp_path / sub).mkdir()
+ shutil.copy(parts[part], tmp_path / sub / "part.glb")
+ shot = tmp_path / "shot.json"
+ shot.write_text(json.dumps({"duration": 2, "models": [{"src": "a/part.glb"}, {"src": "b/part.glb"}]}))
+ hf.scaffold(shot, tmp_path / "proj")
+ assert sorted(p.name for p in (tmp_path / "proj" / "assets").iterdir()) == ["part-2.glb", "part.glb"]
+
+
+def test_hf_without_core_explains_how_to_install(tmp_path, parts, monkeypatch):
+ from b2m3d import hf
+ from b2m3d.run import B2M3DError
+ shot = make_shot(tmp_path, parts)
+ monkeypatch.setenv("B2M3D_HOME", str(tmp_path / "empty"))
+ with pytest.raises(B2M3DError, match="install_3d"):
+ hf.scaffold(shot, tmp_path / "proj")
+
+
+def test_example_shot_matches_example_scene():
+ """The shipped example is self-consistent: every tracked model has a body in the scene."""
+ shot = json.loads((EXAMPLE / "shot.json").read_text())
+ scene = json.loads((EXAMPLE / "scene.json").read_text())
+ bodies = {b["name"] for b in scene["bodies"]}
+ assert {m["track"] for m in shot["models"]} <= bodies
+
+
+def test_hf_keeps_non_ascii_titles(tmp_path, parts):
+ """A UTF-8 shot with accents and dashes must reach index.html intact (Windows defaults to cp1252)."""
+ from b2m3d import hf
+ shot_path = make_shot(tmp_path, parts, titles=[{"text": "Café — déjà vu", "start": 0, "duration": 2}])
+ shot = json.loads(shot_path.read_text(encoding="utf-8"))
+ shot_path.write_text(json.dumps(shot, ensure_ascii=False), encoding="utf-8")
+ hf.scaffold(shot_path, tmp_path / "proj")
+ html = (tmp_path / "proj" / "index.html").read_text(encoding="utf-8")
+ assert "Café — déjà vu" in html or json.dumps("Café — déjà vu")[1:-1] in html
+
+
+def test_text_io_always_names_utf8():
+ """Every read_text/write_text/text open in the pack passes an explicit encoding."""
+ from conftest import PACK
+ offenders = []
+ for src in (PACK / "b2m3d").glob("*.py"):
+ for n, line in enumerate(src.read_text(encoding="utf-8").splitlines(), 1):
+ if re.search(r"\.(read_text|write_text)\(|NamedTemporaryFile\(\"w\"", line) and "encoding=" not in line:
+ offenders.append(f"{src.name}:{n}")
+ assert not offenders, offenders