Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(cli): document independent asset tools and optional scenes

Soohong Kime9e4fc64ad2c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 234fbcf..085d93e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,13 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
-## Unreleased (v2.2.0)
+## v2.2.0 - Independent asset tools and optional scenes
+
+- Added standalone `background-tile`, `shadow` and `inspect-motion` commands. They accept existing artwork and report tile joins, anchor-preserving shadow projections, repeated poses and explicit foot-contact measurements without changing source animation.
+- Added optional `scene-render` and `scene-inspect` with asset references, planes, placement, playback rate, camera, lighting, PNG/MP4/GIF output and layer/placement export. Scene applies only verified stride for the matching asset and an explicitly chosen direction.
+- Added one read-only adapter for PNGs, external frame descriptors, existing loop strips and runtime atlases, preserving native timing and anchors. Source fingerprints bind measurements to loaded content; output publication uses shared locking and atomic writes.
+- Split the command catalog into ordered sprite pipelines, independent tool groups and optional workflows. Added background recipes and asset/scene contracts to the skill and documentation, plus a 20 fps, 256-colour village GIF below the existing README showcase.
+- Raised the Pillow minimum to 12.3.0 for its upstream security fixes; existing environments must update separately to satisfy the new requirement.
- Grok images now call xAI Imagine directly for generation and one-to-five-reference editing, without spawning Grok Build. The default image model is `grok-imagine-image-2.0`; `--model` now selects the image API model. Responses are decoded and published as verified PNGs with existing chroma cleanup preserved.
- Images and videos share one credential reader: `XAI_API_KEY` first, otherwise the user's Grok login (`GROK_HOME` supported). Image reports expose the auth source and API endpoint. The workflow guide checks the same source and explicitly confirms API-credit billing for either media type. Expired login and request failures stop without agent fallback or automatic image request retries.
diff --git a/README.es.md b/README.es.md
index 168cacc..a655493 100644
--- a/README.es.md
+++ b/README.es.md
@@ -1,121 +1,152 @@
<h1 align="center">sprite-gen</h1>
-<p align="center"><b>Entra un dibujo. Salen sprites listos para el juego — como atlas o como bucles de movimiento transparentes.</b></p>
+<p align="center"><b>Un dibujo a la entrada. Sprites listos para el juego a la salida: como atlas o como bucles de movimiento transparentes.</b></p>
<p align="center">
-[English](README.md) · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · **Español** · [Français](README.fr.md)
+**English** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
</p>
<p align="center">
- <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Animated sprite-gen v2 showcase: paladin, wolf and slime" /></a>
+ <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Muestra animada de sprite-gen v2: paladín, lobo y slime" /></a>
</p>
-<p align="center"><sub>Cada personaje empezó con <b>una sola imagen</b>. Grok Imagine le dio movimiento, sprite-gen extrajo los bucles transparentes y HyperFrames compuso esta escena.</sub></p>
+<p align="center"><sub>Cada personaje empezó como <b>una sola imagen fija</b>. Grok Imagine le dio vida; sprite-gen extrajo los bucles transparentes, y HyperFrames montó esta muestra.</sub></p>
----
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="Un samurái y sus acompañantes caminando por un pueblo pintado con escenografía en capas y sombras proyectadas" />
+</p>
+
+<p align="center"><sub>Una composición de pueblo aparte, hecha con recursos de sprite-gen. Este GIF conserva el vídeo de 10 segundos a 20 fps con una paleta de 256 colores.</sub></p>
+---
-Pídele a un modelo de imagen una "sprite sheet" y ya sabes lo que obtienes: un personaje cuya cara cambia en cada fotograma, un fondo que no se recorta, poses que se superponen y se salen de la rejilla, y un PNG que tu motor no puede consumir. Demo bonita, asset inútil.
+Pídele a un modelo de imagen una «hoja de sprites» y ya sabes lo que sale: un personaje cuya cara cambia en cada fotograma, un fondo que no se deja recortar, poses que se solapan y se desvían de la cuadrícula, y un PNG que tu motor de juego no puede consumir realmente. Demo mona, recurso inútil.
-`sprite-gen` es una skill de Codex/Claude y una CLI de Python que cierra esa brecha. Dale **una imagen base**: dirige la generación fila por fila, fija la identidad del personaje, convierte el fondo croma en alfa real, extrae cada pose como un fotograma transparente limpio y hornea un atlas de runtime **con un `manifest.json.frame_layout` legible por máquina**. Pasa el mismo fotograma a un modelo de vídeo y recibes un bucle transparente sin costura por cada estado de movimiento. Para el último 10 % que la generación nunca acierta, una **webview de curación** te deja comparar, descartar, ajustar y ver el bucle en vivo antes de hornear.
+`sprite-gen` es una skill de Codex/Claude y una CLI de Python que cierra esa brecha. Dale **una imagen base** — dirige la generación fila por fila, fija la identidad del personaje, elimina el fondo de croma hasta obtener alfa real, extrae cada pose como un fotograma transparente limpio y hornea un atlas de runtime **con un `manifest.json.frame_layout` legible por máquina**. O entrega esa misma imagen fija a un modelo de vídeo y recibe un bucle transparente y sin costuras por cada estado de movimiento. Para ese último 10 % que la generación nunca acierta, una **vista web de curación** te permite comparar, descartar, ajustar y ver el bucle en vivo antes de hornear.
-## Empezar con una petición
+## Empieza con una petición
-Pide **sprites** o **una imagen**. El agente comprueba el acceso, pregunta solo por las opciones que faltan y entrega los archivos mediante el proceso existente. La vista de selección es opcional. Puedes guardar valores predeterminados separados para cada uso; una elección puntual no los modifica. [Flujo y preferencias](docs/user-workflow.md).
+Pide **sprites** o **una imagen**. El agente comprueba el acceso, pregunta solo por las decisiones de proveedor/movimiento que falten, ejecuta el pipeline existente y entrega los archivos. La vista de curación es opcional. Guarda tus elecciones una vez para reutilizar valores por defecto separados para sprites e imágenes; una petición puntual no los sobrescribe. [Flujo de trabajo del usuario y valores por defecto](docs/user-workflow.md).
-## Cuatro pipelines, una CLI
+## Pipelines, herramientas independientes y escenas
-Cada verbo funciona solo o como etapa de un pipeline. `sprite-gen --help` imprime este mismo mapa con cada verbo agrupado por dominio.
+Los dos pipelines de sprites son flujos de generación ordenados. Los grupos de herramientas contienen comandos independientes; la creación de escenas es un flujo de trabajo opcional que consume recursos ya terminados. `sprite-gen --help` imprime este mapa y agrupa los comandos por el dominio de código que los posee.
```mermaid
flowchart LR
- subgraph A["A · atlas rows"]
+ subgraph A["A · filas de atlas"]
direction LR
a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
- a5 -.-> a4["curation (optional)"]
+ a5 -.-> a4["curación (opcional)"]
a4 --> a5
end
- subgraph B["B · video → loop"]
+ subgraph B["B · vídeo → bucle"]
direction LR
b1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]
end
- subgraph C["C · utilities"]
+ subgraph C["C · utilidades"]
direction LR
c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
end
- subgraph D["D · post-processing"]
+ subgraph D["D · posprocesado"]
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · herramientas de recursos (independientes)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · escena (opcional)"]
+ s1["recursos existentes + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| Pipeline | Qué entra → qué sale | Docs |
+| Pipeline / grupo de herramientas / flujo de trabajo | Qué entra → qué sale | Documentación |
|---|---|---|
-| **A · filas de atlas** | un fotograma + lista de estados → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, con **Breathe** horneado en las poses idle | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
-| **B · vídeo → bucle** | un fotograma → por estado, un GIF / WebP / tira transparente sin costura, animado por Grok Imagine y cortado en su periodo real | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
-| **C · utilidades** | una imagen importada o una hoja en rejilla → recortes transparentes limpios; un atlas terminado → un run listo para curar | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · posprocesado** | una hoja terminada → variantes de color deterministas, compuestos por capas de rig, exportaciones Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
-
-Índice completo: [`docs/README.md`](docs/README.md). Arquitectura con diagramas de dominios y pipelines: [`docs/architecture.md`](docs/architecture.md).
-
-## Lo que realmente obtienes
-
-- **Un atlas de sprites transparente** (`sprite-sheet-alpha.png`): alfa real, sin borde croma residual, verificado sobre fondo blanco ([por qué el extractor desmezcla en vez de pelar](docs/chroma-alpha.md)).
-- **Un manifiesto de runtime** (`manifest.json.frame_layout`): rectángulos absolutos por fotograma, fps y bandera de bucle por estado. Tu motor lee rectángulos; nunca adivina una rejilla.
-- **Breathe**: un idle fijo se convierte en un bucle vivo; squash & stretch determinista horneado sobre tus fotogramas curados desde un solo campo sidecar, consciente de la anatomía y fiel al píxel ([detalles](docs/breathing.md)).
-- **Pixel art que se mantiene en la rejilla**: Backbone Lattice mide una sola rejilla para todo el sujeto y ajusta cada corte a ella ([detalles](docs/pixel-unfake.md)).
-- **Bucles de movimiento desde vídeo**: los saltos reciben un lienzo alto, los ataques uno ancho, el punto de bucle es el periodo propio del clip y una acción única se corta rest → action → rest ([detalles](docs/video-pipeline.md)).
-- **Variantes de color deterministas**: `recolor` hornea N hojas variantes desde un mapa de paleta; misma entrada, mismos bytes ([detalles](docs/recolor.md)).
-- **QA que puedes ver**: GIFs y hojas de contacto por estado, para juzgar el movimiento como movimiento antes de publicar. La locomoción cíclica (walk/run) sigue siendo experimental hasta que el QA de movimiento pasa de verdad.
+| **A · filas de atlas** | una imagen fija + una lista de estados → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, con **Breathe** horneado en las poses de reposo | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
+| **B · vídeo → bucle** | una imagen fija → por estado, un GIF / WebP / tira transparente sin costuras, animado por Grok Imagine y cortado en su periodo real | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
+| **C · utilidades** | una imagen importada u hoja en cuadrícula → recortes transparentes limpios; un atlas terminado → una ejecución lista para curación | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
+| **D · posprocesado** | una hoja terminada → combinaciones de color deterministas, composiciones de capas de rig, exportaciones a Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · herramientas de recursos** | PNG o animaciones independientes → mosaicos repetibles, sombras proyectadas, mediciones de movimiento/contacto | [asset-tools](docs/asset-tools.md) |
+| **S · escena** | recursos existentes + colocación, cámara e iluminación → fotogramas PNG, MP4/GIF, metadatos de inspección y colocación | [scene](docs/scene.md) |
+
+Índice completo: [`docs/README.md`](docs/README.md). Arquitectura con diagramas de dominio y pipeline: [`docs/architecture.md`](docs/architecture.md).
+
+## Qué obtienes realmente
+
+- **Un atlas de sprites transparente** (`sprite-sheet-alpha.png`) — alfa real, sin flecos de croma residuales, verificado contra fondos blancos ([por qué el extractor desmezcla en vez de pelar](docs/chroma-alpha.md)).
+- **Un manifiesto de runtime** (`manifest.json.frame_layout`) — rectángulos de fotograma absolutos, fps por estado y banderas de bucle. Tu motor muestrea rectángulos; nunca adivina una cuadrícula.
+- **Breathe** — un reposo estático se convierte en un bucle vivo, con squash & stretch determinista horneado sobre tus fotogramas curados a partir de un solo campo sidecar, consciente de la anatomía y fiel al píxel ([detalles](docs/breathing.md)).
+- **Pixel-art que no se sale de la cuadrícula** — la Backbone Lattice mide una única cuadrícula para todo el sujeto y ajusta cada recorte a ella ([detalles](docs/pixel-unfake.md)).
+- **Bucles de movimiento a partir de vídeo** — los saltos reciben un lienzo alto, los ataques uno ancho, el punto de bucle es el propio periodo del clip, y una acción de un solo disparo se corta reposo → acción → reposo ([detalles](docs/video-pipeline.md)).
+- **Combinaciones de color deterministas** — `recolor` hornea N hojas variantes a partir de un mapa de paleta; misma entrada, mismos bytes de salida ([detalles](docs/recolor.md)).
+- **QA que puedes mirar** — GIF por estado y hojas de contacto, para que el movimiento se juzgue como movimiento antes de publicar nada. La locomoción cíclica (caminar/correr) sigue siendo experimental salvo que el QA de movimiento realmente pase.
+- **Herramientas de recursos independientes** — construye fondos repetibles, proyecta sombras desde un ancla de pie e inspecciona el tiempo, las poses duplicadas y la evidencia de contacto. Los pies ambiguos producen una medición no verificada ([detalles](docs/asset-tools.md)).
+- **Creación de escenas opcional** — coloca PNG existentes, secuencias de fotogramas externas, tiras de bucle o atlas de runtime en planos con nombre, con movimiento de cámara y proyección de sombra compartida. La generación de sprites puede terminar antes de este paso ([detalles](docs/scene.md)).
## Inicio rápido
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
+# instala (Pillow, NumPy) en un virtualenv nuevo — el venv es el único intérprete soportado
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
sprite-gen --help
```
-**A · filas de atlas**: de un fotograma a un atlas de runtime.
+**A · filas de atlas** — de una imagen fija a un atlas de runtime.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # petición, guías, prompts
+sprite-gen gen-set --run-dir <run> --provider codex # cada fila de estado, de 4 en 4
+sprite-gen extract --run-dir <run> # croma → fotogramas transparentes
+sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (opcional) elige, ajusta, respira
```
-**B · vídeo → bucle**: de un fotograma a bucles transparentes (requiere `ffmpeg`, `img2webp` y tu propio login de `grok` o `XAI_API_KEY`).
+**B · vídeo → bucle** — de una imagen fija a bucles transparentes (necesita `ffmpeg`, `img2webp` y tu propio login de `grok` o `XAI_API_KEY`).
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --out-dir set/
+# por elemento: video-canvas → video → video-frames → video-loop; set/table.md nombra cada resultado
```
-**C · utilidades**: cada una funciona por separado.
+**C · utilidades** — cada una funciona por su cuenta.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen cutout icon.png --white-check # blanco/marfil → mate, magenta/verde → motor de croma
+sprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # hoja multifigura → recortes por celda
+sprite-gen unpack-atlas --atlas sheet.png # atlas terminado → ejecución lista para curación (o --pngs-dir folder/)
```
-**D · posprocesado**: refina una hoja terminada sin regenerar.
+**D · posprocesado** — refina una hoja terminada sin regenerar.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
+sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
+sprite-gen compose-layers --run-dir <run> # ejecuciones de rig: pilas declaradas → <run>/layers/
+sprite-gen export-aseprite --run-dir <run> # JSON de Aseprite para Phaser / Flame
+```
+
+**E · herramientas de recursos** — cada una acepta recursos existentes, incluido arte de otras herramientas.
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# Solo con contacto conocido del mismo pie y una ROI de pie aislada:
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · escena** — un flujo de trabajo de composición opcional. El [contrato de escena](docs/scene.md) incluye una especificación completa.
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
```
-El flujo para agentes, sus gates y contratos viven en [`SKILL.md`](SKILL.md).
+El flujo de trabajo orientado al agente, las compuertas y los contratos viven en [`SKILL.md`](SKILL.md).
## Instalar como skill
@@ -124,16 +155,16 @@ python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-githu
--repo aldegad/sprite-gen --path . --name sprite-gen
```
-La generación de imágenes forma parte de este motor (`sprite_gen.gen`, proveedores `codex` y `grok`; la skill general `image-gen` es solo una lanzadera fina sobre ella). El vídeo usa **tu propia** credencial — el login de la CLI `grok` o un `XAI_API_KEY` — y el repositorio no incluye ninguna ([docs/video.md](docs/video.md)).
+La generación de imágenes forma parte de este motor (`sprite_gen.gen`, proveedores `codex` y `grok`; la skill genérica `image-gen` es una fina lanzadera sobre él). El vídeo usa **tu propia** credencial — el login de la CLI `grok` o una `XAI_API_KEY` — y nada se distribuye con el repositorio ([docs/video.md](docs/video.md)).
-`sprite-gen` soporta CPython 3.10+; la CI ejecuta 3.10 y 3.14. El inicio rápido necesita un Python con `venv`/`ensurepip` funcionales.
+`sprite-gen` soporta CPython 3.10+; CI ejecuta 3.10 y 3.14. El inicio rápido necesita un Python con `venv`/`ensurepip` funcionando.
## Atribución
-El flujo de filas por componente está inspirado en la skill `hatch-pet` (Apache-2.0), pero apunta a atlas de sprites genéricos para juegos y no incluye paquetes ni activos visuales de mascotas.
+El flujo de trabajo de filas por componente está inspirado en la skill `hatch-pet`, con licencia Apache-2.0, pero apunta a atlas genéricos de sprites de juego y no incluye ningún paquete de mascotas ni recursos visuales de mascotas.
Las contribuciones de la comunidad, los experimentos y sus pull requests de origen están documentados en [`CONTRIBUTORS.md`](CONTRIBUTORS.md).
## Licencia
-Apache-2.0
+Apache-2.0
\ No newline at end of file
diff --git a/README.fr.md b/README.fr.md
index 20027e8..949f0d5 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -1,6 +1,6 @@
<h1 align="center">sprite-gen</h1>
-<p align="center"><b>Un dessin entre. Des sprites prêts pour le jeu sortent — en atlas, ou en boucles de mouvement transparentes.</b></p>
+<p align="center"><b>Un dessin en entrée. Des sprites prêts pour le jeu en sortie — sous forme d'atlas, ou de boucles d'animation transparentes.</b></p>
<p align="center">
@@ -9,131 +9,162 @@
</p>
<p align="center">
- <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Animated sprite-gen v2 showcase: paladin, wolf and slime" /></a>
+ <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Démonstration animée de sprite-gen v2 : paladin, loup et slime" /></a>
</p>
-<p align="center"><sub>Chaque personnage est né d'une <b>seule image fixe</b>. Grok Imagine lui a donné vie, sprite-gen a extrait les boucles transparentes et HyperFrames a composé cette scène.</sub></p>
+<p align="center"><sub>Chaque personnage est parti d'<b>une seule image fixe</b>. Grok Imagine lui a donné vie ; sprite-gen en a extrait les boucles transparentes, et HyperFrames a assemblé cette démonstration.</sub></p>
----
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="Un samouraï et ses compagnons traversant un village peint, avec décors en couches et ombres projetées" />
+</p>
+
+<p align="center"><sub>Une composition de village distincte, réalisée à partir d'assets sprite-gen. Ce GIF conserve la vidéo de 10 secondes à 20 fps avec une palette de 256 couleurs.</sub></p>
+---
-Demandez une « sprite sheet » à un modèle d'image et vous savez ce que vous obtenez : un personnage dont le visage change à chaque image, un fond impossible à détourer, des poses qui se chevauchent et sortent de la grille, et un PNG que votre moteur de jeu ne peut pas consommer. Jolie démo, asset inutile.
+Demandez une « feuille de sprites » à un modèle d'image et vous savez ce que vous obtenez : un personnage dont le visage change à chaque frame, un fond impossible à détourer, des poses qui se chevauchent et dérivent hors de la grille, et un PNG que votre moteur de jeu ne peut pas réellement exploiter. Démo mignonne, asset inutilisable.
-`sprite-gen` est une skill Codex/Claude et une CLI Python qui comble cet écart. Donnez-lui **une image de base** : elle pilote la génération ligne par ligne, verrouille l'identité du personnage, retire le fond chroma en vrai alpha, extrait chaque pose en une image transparente propre et cuit un atlas d'exécution **avec un `manifest.json.frame_layout` lisible par machine**. Passez la même image fixe à un modèle vidéo et vous recevez une boucle transparente sans raccord par état de mouvement. Pour les 10 % que la génération ne réussit jamais, une **webview de curation** permet de comparer, rejeter, ajuster et regarder la boucle en direct avant de cuire.
+`sprite-gen` est une skill Codex/Claude et une CLI Python qui comble cet écart. Donnez-lui **une seule image de base** — elle pilote la génération ligne par ligne, verrouille l'identité du personnage, retire le fond chroma pour obtenir un vrai canal alpha, extrait chaque pose sous forme de frame transparente propre, et cuit un atlas d'exécution **avec un `manifest.json.frame_layout` lisible par la machine**. Ou confiez la même image fixe à un modèle vidéo et récupérez une boucle transparente sans raccord par état d'animation. Pour les derniers 10 % que la génération ne réussit jamais, une **webview de curation** vous permet de comparer, rejeter, ajuster et regarder la boucle en direct avant la cuisson.
-## Commencer par une demande
+## Commencez par une demande
-Demandez des **sprites** ou **une image**. L'agent vérifie l'accès, demande seulement les choix manquants et livre les fichiers avec le pipeline existant. La vue de sélection est facultative. Enregistrez des préférences distinctes pour chaque usage ; un choix ponctuel ne les remplace pas. [Parcours et préférences](docs/user-workflow.md).
+Demandez des **sprites** ou **une image**. L'agent vérifie les accès, ne pose de questions que sur les choix de provider/animation manquants, exécute le pipeline existant et livre les fichiers. La vue de curation est optionnelle. Enregistrez vos choix une fois pour réutiliser des valeurs par défaut distinctes pour les sprites et les images ; une demande ponctuelle ne les écrase pas. [Workflow utilisateur et valeurs par défaut](docs/user-workflow.md).
-## Quatre pipelines, une CLI
+## Pipelines, outils indépendants et scènes
-Chaque verbe fonctionne seul ou comme étape d'un pipeline. `sprite-gen --help` affiche cette même carte, chaque verbe groupé par domaine.
+Les deux pipelines de sprites sont des flux de génération ordonnés. Les groupes d'outils contiennent des commandes indépendantes ; la création de scène est un workflow optionnel qui consomme des assets terminés. `sprite-gen --help` affiche cette carte et regroupe les commandes par domaine de code propriétaire.
```mermaid
flowchart LR
- subgraph A["A · atlas rows"]
+ subgraph A["A · lignes d'atlas"]
direction LR
a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
- a5 -.-> a4["curation (optional)"]
+ a5 -.-> a4["curation (optionnel)"]
a4 --> a5
end
- subgraph B["B · video → loop"]
+ subgraph B["B · vidéo → boucle"]
direction LR
b1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]
end
- subgraph C["C · utilities"]
+ subgraph C["C · utilitaires"]
direction LR
c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
end
- subgraph D["D · post-processing"]
+ subgraph D["D · post-traitement"]
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · outils d'assets (indépendants)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · scène (optionnel)"]
+ s1["assets existants + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| Pipeline | Ce qui entre → ce qui sort | Docs |
+| Pipeline / groupe d'outils / workflow | Ce qui entre → ce qui sort | Docs |
|---|---|---|
| **A · lignes d'atlas** | une image fixe + une liste d'états → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, avec **Breathe** cuit sur les poses idle | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
-| **B · vidéo → boucle** | une image fixe → par état, un GIF / WebP / bande transparente sans raccord, animé par Grok Imagine et coupé à sa vraie période | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
-| **C · utilitaires** | une image importée ou une planche en grille → découpes transparentes propres ; un atlas fini → un run prêt à curer | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · post-traitement** | une planche finie → variantes de couleur déterministes, composites de calques de rig, exports Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
-
-Index complet : [`docs/README.md`](docs/README.md). Architecture avec les diagrammes de domaines et de pipelines : [`docs/architecture.md`](docs/architecture.md).
-
-## Ce que vous obtenez vraiment
-
-- **Un atlas de sprites transparent** (`sprite-sheet-alpha.png`) : vrai alpha, aucune frange chroma, vérifié sur fond blanc ([pourquoi l'extracteur démélange au lieu de peler](docs/chroma-alpha.md)).
-- **Un manifeste d'exécution** (`manifest.json.frame_layout`) : rectangles absolus par image, fps et drapeau de boucle par état. Votre moteur lit des rectangles ; il ne devine jamais une grille.
-- **Breathe** : un idle fixe devient une boucle vivante ; squash & stretch déterministe cuit sur vos images curées depuis un seul champ sidecar, conscient de l'anatomie et fidèle au pixel ([détails](docs/breathing.md)).
-- **Du pixel art qui reste sur la grille** : Backbone Lattice mesure une seule grille pour tout le sujet et y aligne chaque découpe ([détails](docs/pixel-unfake.md)).
-- **Des boucles de mouvement depuis la vidéo** : les sauts reçoivent un canevas haut, les attaques un canevas large, le point de boucle est la période propre du clip, et une action unique est coupée rest → action → rest ([détails](docs/video-pipeline.md)).
-- **Des variantes de couleur déterministes** : `recolor` cuit N planches variantes depuis une carte de palette ; même entrée, mêmes octets ([détails](docs/recolor.md)).
-- **Un QA que l'on peut regarder** : GIFs et planches-contact par état, pour juger le mouvement comme mouvement avant de livrer. La locomotion cyclique (walk/run) reste expérimentale tant que le QA de mouvement ne passe pas réellement.
+| **B · vidéo → boucle** | une image fixe → par état, un GIF / WebP / bande transparent sans raccord, animé par Grok Imagine et coupé à sa véritable période | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
+| **C · utilitaires** | une image importée ou une feuille en grille → des découpes transparentes propres ; un atlas terminé → un run prêt pour la curation | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
+| **D · post-traitement** | une feuille terminée → des variantes de couleurs déterministes, des composites de couches de rig, des exports Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · outils d'assets** | des PNG ou animations indépendants → tuiles répétables, ombres projetées, mesures de mouvement/contact | [asset-tools](docs/asset-tools.md) |
+| **S · scène** | assets existants + placement, caméra et éclairage → frames PNG, MP4/GIF, métadonnées d'inspection et de placement | [scene](docs/scene.md) |
+
+Index complet : [`docs/README.md`](docs/README.md). Architecture avec diagrammes de domaines et de pipelines : [`docs/architecture.md`](docs/architecture.md).
+
+## Ce que vous obtenez réellement
+
+- **Un atlas de sprites transparent** (`sprite-sheet-alpha.png`) — un vrai canal alpha, aucune frange chroma résiduelle, vérifié sur fond blanc ([pourquoi l'extracteur démélange au lieu de décoller](docs/chroma-alpha.md)).
+- **Un manifeste d'exécution** (`manifest.json.frame_layout`) — rectangles de frames absolus, fps et drapeaux de boucle par état. Votre moteur échantillonne des rectangles ; il ne devine jamais une grille.
+- **Breathe** — une pose idle statique devient une boucle vivante, un squash & stretch déterministe cuit sur vos frames curées à partir d'un seul champ sidecar, respectueux de l'anatomie et fidèle au pixel ([détails](docs/breathing.md)).
+- **Du pixel-art qui reste sur la grille** — le Backbone Lattice mesure une seule grille pour l'ensemble du sujet et y maintient chaque découpe ([détails](docs/pixel-unfake.md)).
+- **Des boucles d'animation issues de la vidéo** — les sauts reçoivent un canvas haut, les attaques un canvas large, le point de boucle est la période propre du clip, et une action one-shot est coupée repos → action → repos ([détails](docs/video-pipeline.md)).
+- **Des variantes de couleurs déterministes** — `recolor` cuit N feuilles variantes à partir d'une palette de correspondance ; même entrée, mêmes octets en sortie ([détails](docs/recolor.md)).
+- **Un QA que vous pouvez regarder** — des GIF et planches contact par état, pour que le mouvement soit jugé en tant que mouvement avant toute livraison. La locomotion cyclique (marche/course) reste expérimentale tant que le QA d'animation n'est pas réellement validé.
+- **Des outils d'assets indépendants** — construisez des fonds répétables, projetez des ombres depuis un point d'ancrage au pied, et inspectez le timing, les poses dupliquées et les preuves de contact. Des pieds ambigus produisent une mesure non vérifiée ([détails](docs/asset-tools.md)).
+- **Création de scène optionnelle** — placez des PNG existants, des séquences de frames externes, des bandes de boucle ou des atlas d'exécution sur des plans nommés, avec mouvement de caméra et projection d'ombre partagée. La génération de sprites peut se terminer avant cette étape ([détails](docs/scene.md)).
## Démarrage rapide
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
+# installer (Pillow, NumPy) dans un virtualenv neuf — le venv est le seul interpréteur supporté
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
sprite-gen --help
```
-**A · lignes d'atlas** : d'une image fixe à un atlas d'exécution.
+**A · lignes d'atlas** — d'une image fixe à un atlas d'exécution.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # requête, guides, prompts
+sprite-gen gen-set --run-dir <run> --provider codex # chaque ligne d'état, 4 à la fois
+sprite-gen extract --run-dir <run> # chroma → frames transparentes
+sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (optionnel) choisir, ajuster, breathe
```
-**B · vidéo → boucle** : d'une image fixe à des boucles transparentes (nécessite `ffmpeg`, `img2webp`, et votre propre login `grok` ou `XAI_API_KEY`).
+**B · vidéo → boucle** — d'une image fixe à des boucles transparentes (nécessite `ffmpeg`, `img2webp`, et votre propre connexion `grok` ou `XAI_API_KEY`).
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --out-dir set/
+# par élément : video-canvas → video → video-frames → video-loop ; set/table.md nomme chaque résultat
```
-**C · utilitaires** : chacun s'utilise seul.
+**C · utilitaires** — chacun est autonome.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen cutout icon.png --white-check # blanc/ivoire → matte, magenta/vert → moteur chroma
+sprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # feuille multi-figures → découpes par cellule
+sprite-gen unpack-atlas --atlas sheet.png # atlas terminé → run prêt pour la curation (ou --pngs-dir folder/)
```
-**D · post-traitement** : affiner une planche finie sans régénérer.
+**D · post-traitement** — affinez une feuille terminée sans régénérer.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
+sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
+sprite-gen compose-layers --run-dir <run> # runs de rig : piles déclarées → <run>/layers/
+sprite-gen export-aseprite --run-dir <run> # JSON Aseprite pour Phaser / Flame
+```
+
+**E · outils d'assets** — chacun accepte des assets existants, y compris des illustrations issues d'autres outils.
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# Uniquement avec un contact du même pied connu et une ROI de pied isolée :
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · scène** — un workflow de composition optionnel. Le [contrat de scène](docs/scene.md) inclut une spécification complète.
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
```
-Le flux destiné aux agents, ses gates et ses contrats vivent dans [`SKILL.md`](SKILL.md).
+Le workflow destiné à l'agent, les gates et les contrats se trouvent dans [`SKILL.md`](SKILL.md).
-## Installer comme skill
+## Installation en tant que skill
```bash
python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
--repo aldegad/sprite-gen --path . --name sprite-gen
```
-La génération d'images fait partie de ce moteur (`sprite_gen.gen`, fournisseurs `codex` et `grok` ; la skill générale `image-gen` n'est qu'une navette fine au-dessus). La vidéo utilise **votre propre** identifiant — le login de la CLI `grok` ou un `XAI_API_KEY` — et rien n'est livré avec le dépôt ([docs/video.md](docs/video.md)).
+La génération d'images fait partie de ce moteur (`sprite_gen.gen`, providers `codex` et `grok` ; la skill générique `image-gen` n'en est qu'une fine navette). La vidéo utilise **vos propres** identifiants — la connexion via la CLI `grok` ou une `XAI_API_KEY` — et rien n'est livré avec le dépôt ([docs/video.md](docs/video.md)).
-`sprite-gen` prend en charge CPython 3.10+ ; la CI exécute 3.10 et 3.14. Le démarrage rapide nécessite un Python avec `venv`/`ensurepip` fonctionnels.
+`sprite-gen` supporte CPython 3.10+ ; la CI tourne sur 3.10 et 3.14. Le démarrage rapide nécessite un Python avec `venv`/`ensurepip` fonctionnels.
## Attribution
-Le flux par lignes de composants s'inspire de la skill `hatch-pet` (Apache-2.0), mais vise des atlas de sprites de jeu génériques et n'inclut aucun paquet ni asset visuel d'animal de compagnie.
+Le workflow par lignes de composants s'inspire de la skill `hatch-pet` sous licence Apache-2.0, mais vise des atlas de sprites de jeu génériques et n'inclut aucun package de pet ni asset visuel de pet.
-Les contributions de la communauté, les expériences et leurs pull requests d'origine sont documentés dans [`CONTRIBUTORS.md`](CONTRIBUTORS.md).
+Les contributions de la communauté, les expérimentations et leurs pull requests d'origine sont documentées dans [`CONTRIBUTORS.md`](CONTRIBUTORS.md).
## Licence
-Apache-2.0
+Apache-2.0
\ No newline at end of file
diff --git a/README.ja.md b/README.ja.md
index cfce42a..216baa8 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -1,6 +1,6 @@
<h1 align="center">sprite-gen</h1>
-<p align="center"><b>絵を一枚入れると、ゲームでそのまま使えるスプライトが出てくる — アトラスとしても、透明なモーションループとしても。</b></p>
+<p align="center"><b>一枚の絵を入力。ゲームですぐ使えるスプライトを出力 — アトラスとして、あるいは透過モーションループとして。</b></p>
<p align="center">
@@ -12,110 +12,141 @@
<a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Animated sprite-gen v2 showcase: paladin, wolf and slime" /></a>
</p>
-<p align="center"><sub>各キャラクターは<b>1枚の静止画</b>から始まりました。Grok Imagineで動きを作り、sprite-genで透過ループを抽出し、HyperFramesでこのシーンを構成しました。</sub></p>
+<p align="center"><sub>それぞれのキャラクターは<b>一枚の静止画</b>から始まりました。Grok Imagine が命を吹き込み、sprite-gen が透過ループを抽出し、HyperFrames がこのショーケースを組み上げました。</sub></p>
----
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="A samurai and companions walking through a painted village with layered scenery and projected shadows" />
+</p>
+
+<p align="center"><sub>sprite-gen のアセットで作った別の村のコンポジション。この GIF は 10 秒の動画を 20 fps・256 色パレットで保持しています。</sub></p>
+---
-画像モデルに「スプライトシート」を頼むと結果は分かっている: フレームごとに顔が変わるキャラ、キーアウトできない背景、重なってグリッドから外れるポーズ、ゲームエンジンが読めない PNG。デモとしては可愛く、アセットとしては役に立たない。
+画像モデルに「スプライトシート」を頼めば、どうなるかは分かっているはずです。フレームごとに顔が変わるキャラクター、抜けない背景、重なってグリッドから外れていくポーズ、そしてゲームエンジンが実際には読み込めない PNG。デモとしては可愛いが、アセットとしては使えません。
-`sprite-gen` はその隙間を埋める Codex/Claude スキルであり Python CLI だ。**ベース画像一枚**を渡すと、行ごとに生成を進め、キャラの identity を固定し、クロマ背景を本物のアルファに剥がし、ポーズごとに綺麗な透明フレームを取り出し、**機械可読な `manifest.json.frame_layout`** 付きのランタイムアトラスを焼く。同じ静止画を動画モデルに渡せば、モーション状態ごとに継ぎ目のない透明ループが返ってくる。生成が最後まで合わせられない 10% は**キュレーション Webview** で比較・除外・微調整し、ループを実再生で確かめてから焼く。
+`sprite-gen` は、そのギャップを埋める Codex/Claude スキルであり、Python CLI です。**一枚のベース画像**を渡せば、行ごとに生成を進め、キャラクターのアイデンティティを固定し、クロマ背景を剥がして本物のアルファに変え、各ポーズをきれいな透過フレームとして抽出し、**機械可読な `manifest.json.frame_layout` 付き**でランタイムアトラスを焼き上げます。あるいは同じ静止画を動画モデルに渡せば、モーションステートごとにシームレスな透過ループが返ってきます。生成では決して満たせない最後の 10% のために、**キュレーション用 webview** で比較・却下・微調整を行い、焼き上げる前にループをライブで確認できます。
## リクエストから始める
-**スプライト作成**または**画像作成**を依頼してください。利用状態を確認し、未指定の生成ツールと動作方式だけを質問して、既存のパイプラインで結果を渡します。キュレーション画面は任意です。用途別の既定値を保存でき、今回だけの指定では保存値を変更しません。[リクエストと既定値](docs/user-workflow.md)。
+**スプライト**か**画像**を依頼してください。エージェントがアクセスを確認し、不足しているプロバイダ/モーションの選択だけを尋ね、既存のパイプラインを実行し、ファイルを届けます。キュレーションビューは任意です。選択を一度保存すれば、スプライト用と画像用の既定値を別々に再利用できます。一回限りのリクエストはそれらを上書きしません。[ユーザーワークフローと既定値](docs/user-workflow.md)。
-## 4 本のパイプライン、1 つの CLI
+## パイプライン・独立ツール・シーン
-どの verb も単独でも、パイプラインの一段としても使える。`sprite-gen --help` が同じ地図をドメイン別 verb で表示する。
+2 つのスプライトパイプラインは順序付きの生成フローです。ツールグループには独立したコマンドが含まれ、シーン作成は完成したアセットを利用する任意のワークフローです。`sprite-gen --help` はこのマップを表示し、コマンドを所有するコードドメインごとにグループ化します。
```mermaid
flowchart LR
- subgraph A["A · atlas rows"]
+ subgraph A["A · アトラス行"]
direction LR
a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
- a5 -.-> a4["curation (optional)"]
+ a5 -.-> a4["キュレーション (任意)"]
a4 --> a5
end
- subgraph B["B · video → loop"]
+ subgraph B["B · 動画 → ループ"]
direction LR
b1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]
end
- subgraph C["C · utilities"]
+ subgraph C["C · ユーティリティ"]
direction LR
c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
end
- subgraph D["D · post-processing"]
+ subgraph D["D · ポストプロセス"]
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · アセットツール (独立)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · シーン (任意)"]
+ s1["既存アセット + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| パイプライン | 入力 → 出力 | ドキュメント |
+| パイプライン / ツールグループ / ワークフロー | 入力 → 出力 | ドキュメント |
|---|---|---|
-| **A · アトラス行** | 静止画 1 枚 + 状態リスト → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`、idle には **Breathe** が焼き込まれる | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
-| **B · 動画 → ループ** | 静止画 1 枚 → 状態ごとに継ぎ目のない透明 GIF / WebP / ストリップ。Grok Imagine で動かし、真の周期で切る | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
-| **C · ユーティリティ** | 取り込んだ画像やグリッドシート → 綺麗な透明カット; 完成アトラス → キュレーション用 run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · 後処理** | 完成シート → 決定的なカラーウェイ、リグのレイヤー合成、Aseprite / Phaser / Flame 書き出し | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
-
-全体索引: [`docs/README.md`](docs/README.md)。ドメイン図とパイプライン図のあるアーキテクチャ: [`docs/architecture.md`](docs/architecture.md)。
-
-## 実際に得られるもの
-
-- **透明なスプライトアトラス** (`sprite-sheet-alpha.png`) — 本物のアルファ、クロマのフリンジなし、白背景で検証済み ([なぜ剥がさず unmix するのか](docs/chroma-alpha.md))。
-- **ランタイムマニフェスト** (`manifest.json.frame_layout`) — 絶対座標のフレーム矩形、状態ごとの fps と loop フラグ。エンジンは矩形を読むだけでグリッドを推測しない。
-- **Breathe** — 静止 idle が生きたループになる。サイドカーのフィールド一つで、キュレーション済みフレームの上に決定的な squash & stretch を焼く。解剖学を認識し、ピクセルを保つ ([詳細](docs/breathing.md))。
-- **グリッドを守るピクセルアート** — Backbone Lattice が被写体全体で一つのグリッドを測り、すべてのカットをそこに合わせる ([詳細](docs/pixel-unfake.md))。
-- **動画からのモーションループ** — ジャンプは縦キャンバス、攻撃は横キャンバス、ループ点はクリップ自身の周期、単発アクションは rest → action → rest で切る ([詳細](docs/video-pipeline.md))。
-- **決定的なカラーウェイ** — `recolor` がパレットマップから N 枚の派生シートを焼く。同じ入力、同じバイト ([詳細](docs/recolor.md))。
-- **目で見られる QA** — 状態別 GIF とコンタクトシート。出荷前にモーションをモーションとして判定する。周期的ロコモーション(walk/run)はモーション QA を実際に通るまで実験扱い。
+| **A · アトラス行** | 一枚の静止画 + ステート一覧 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`、アイドルポーズには **Breathe** を焼き込み | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
+| **B · 動画 → ループ** | 一枚の静止画 → ステートごとに、Grok Imagine がアニメートし実周期でカットされたシームレスな透過 GIF / WebP / ストリップ | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
+| **C · ユーティリティ** | 取り込んだ画像やグリッドシート → きれいな透過カット。完成したアトラス → キュレーション可能な run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
+| **D · ポストプロセス** | 完成したシート → 決定論的カラーウェイ、リグレイヤー合成、Aseprite / Phaser / Flame エクスポート | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · アセットツール** | 独立した PNG やアニメーション → 繰り返しタイル、投影された影、モーション/接地の計測 | [asset-tools](docs/asset-tools.md) |
+| **S · シーン** | 既存アセット + 配置・カメラ・ライティング → PNG フレーム、MP4/GIF、検査と配置のメタデータ | [scene](docs/scene.md) |
+
+全目次: [`docs/README.md`](docs/README.md)。ドメインとパイプラインの図を含むアーキテクチャ: [`docs/architecture.md`](docs/architecture.md)。
+
+## 実際に手に入るもの
+
+- **透過スプライトアトラス** (`sprite-sheet-alpha.png`) — 本物のアルファ、クロマの縁取りの残りなし、白背景に対して検証済み([抽出器が剥がすのではなくアンミックスする理由](docs/chroma-alpha.md))。
+- **ランタイムマニフェスト** (`manifest.json.frame_layout`) — 絶対座標のフレーム矩形、ステートごとの fps とループフラグ。エンジンは矩形をサンプリングするだけで、グリッドを推測しません。
+- **Breathe** — 静止したアイドルが生きたループになります。一つのサイドカーフィールドから、キュレーション済みのフレームに決定論的なスカッシュ&ストレッチを焼き込み、解剖学に沿ってピクセル忠実に仕上げます([詳細](docs/breathing.md))。
+- **グリッドから外れないピクセルアート** — Backbone Lattice が被写体全体に対して一つのグリッドを計測し、すべてのカットをそれに従わせます([詳細](docs/pixel-unfake.md))。
+- **動画からのモーションループ** — ジャンプには縦長のキャンバス、攻撃には横長のキャンバス、ループ点はクリップ自身の周期、ワンショットのアクションは静止 → アクション → 静止でカットされます([詳細](docs/video-pipeline.md))。
+- **決定論的カラーウェイ** — `recolor` はパレットマップから N 枚のバリアントシートを焼きます。同じ入力なら同じ出力バイト列([詳細](docs/recolor.md))。
+- **目で見られる QA** — ステートごとの GIF とコンタクトシートにより、何かを出荷する前にモーションはモーションとして判断されます。周期的な移動(walk/run)は、モーション QA に実際に通らない限り実験的なままです。
+- **独立したアセットツール** — 繰り返す背景を作り、足のアンカーから影を投影し、タイミング・重複ポーズ・接地の根拠を検査します。足が曖昧な場合は未検証の計測として出力されます([詳細](docs/asset-tools.md))。
+- **任意のシーン作成** — 既存の PNG、外部フレームシーケンス、ループストリップ、ランタイムアトラスを名前付きプレーンに配置し、カメラモーションと共有の影投影を加えます。スプライト生成はこのステップの前に完了していて構いません([詳細](docs/scene.md))。
## クイックスタート
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
+# 新しい virtualenv に (Pillow, NumPy) をインストール — サポートされるインタープリタは venv のみ
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
sprite-gen --help
```
-**A · アトラス行** — 静止画 1 枚からランタイムアトラスへ。
+**A · アトラス行** — 一枚の静止画からランタイムアトラスへ。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # リクエスト、ガイド、プロンプト
+sprite-gen gen-set --run-dir <run> --provider codex # 全ステート行を 4 つずつ
+sprite-gen extract --run-dir <run> # クロマ → 透過フレーム
+sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (任意) 選別、微調整、breathe
```
-**B · 動画 → ループ** — 静止画 1 枚から透明ループへ (`ffmpeg`, `img2webp`, そして自分の `grok` ログインか `XAI_API_KEY` が必要)。
+**B · 動画 → ループ** — 一枚の静止画から透過ループへ(`ffmpeg`、`img2webp`、および自分自身の `grok` ログインまたは `XAI_API_KEY` が必要)。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --out-dir set/
+# 項目ごとに: video-canvas → video → video-frames → video-loop; set/table.md が全結果に名前を付ける
```
-**C · ユーティリティ** — それぞれ単独で使う。
+**C · ユーティリティ** — それぞれ単独で動作します。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen cutout icon.png --white-check # 白/アイボリー → マット、マゼンタ/グリーン → クロマエンジン
+sprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # 複数キャラのシート → セルごとのカット
+sprite-gen unpack-atlas --atlas sheet.png # 完成したアトラス → キュレーション可能な run (または --pngs-dir folder/)
```
-**D · 後処理** — 再生成せずに完成シートを整える。
+**D · ポストプロセス** — 再生成せずに完成したシートを仕上げます。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
+sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
+sprite-gen compose-layers --run-dir <run> # リグ run: 宣言されたスタック → <run>/layers/
+sprite-gen export-aseprite --run-dir <run> # Phaser / Flame 向け Aseprite JSON
+```
+
+**E · アセットツール** — それぞれ既存アセットを受け取り、他ツールのアートワークも扱えます。
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# 同じ足の接地が既知で、足の ROI が分離できている場合のみ:
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · シーン** — 任意のコンポジションワークフロー。[シーン契約](docs/scene.md) に完全な仕様があります。
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
```
-エージェント向けのワークフロー・ゲート・契約は [`SKILL.md`](SKILL.md) にある。
+エージェント向けのワークフロー、ゲート、契約は [`SKILL.md`](SKILL.md) にあります。
## スキルとしてインストール
@@ -124,16 +155,16 @@ python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-githu
--repo aldegad/sprite-gen --path . --name sprite-gen
```
-画像生成はこのエンジンの一部だ(`sprite_gen.gen`、プロバイダは `codex` と `grok`; 汎用の `image-gen` スキルはその上の薄いシャトル)。動画は**自分の**資格情報 — `grok` CLI のログインか `XAI_API_KEY` — を使い、リポジトリには何も同梱しない ([docs/video.md](docs/video.md))。
+画像生成はこのエンジンの一部です(`sprite_gen.gen`、プロバイダは `codex` と `grok`。汎用の `image-gen` スキルはその上の薄いシャトルです)。動画には**あなた自身の**認証情報 — `grok` CLI ログインまたは `XAI_API_KEY` — を使い、リポジトリには何も同梱されていません([docs/video.md](docs/video.md))。
-`sprite-gen` は CPython 3.10+ をサポートする。CI は 3.10 と 3.14 を回す。クイックスタートには `venv`/`ensurepip` が動く Python が必要。
+`sprite-gen` は CPython 3.10+ をサポートし、CI は 3.10 と 3.14 で実行されます。クイックスタートには `venv`/`ensurepip` が動作する Python が必要です。
-## 出典
+## クレジット
-コンポーネント行ワークフローは Apache-2.0 の `hatch-pet` スキルに着想を得ているが、汎用のゲームスプライトアトラスを対象とし、ペットのパッケージや画像資産は含まない。
+コンポーネント行のワークフローは Apache-2.0 ライセンスの `hatch-pet` スキルに着想を得ていますが、汎用のゲームスプライトアトラスを対象としており、ペットパッケージやペットのビジュアルアセットは一切含みません。
-コミュニティの貢献・実験とその元 PR は [`CONTRIBUTORS.md`](CONTRIBUTORS.md) に記録している。
+コミュニティからの貢献、実験、およびその元となったプルリクエストは [`CONTRIBUTORS.md`](CONTRIBUTORS.md) に記録されています。
## ライセンス
-Apache-2.0
+Apache-2.0
\ No newline at end of file
diff --git a/README.ko.md b/README.ko.md
index d0a10f3..b3b4351 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -1,6 +1,6 @@
<h1 align="center">sprite-gen</h1>
-<p align="center"><b>그림 한 장을 넣으면 게임에 바로 쓰는 스프라이트가 나온다 — 아틀라스로도, 투명 모션 루프로도.</b></p>
+<p align="center"><b>그림 한 장을 넣으면, 게임에 바로 쓸 수 있는 스프라이트가 나온다 — 아틀라스로, 또는 투명 모션 루프로.</b></p>
<p align="center">
@@ -9,131 +9,162 @@
</p>
<p align="center">
- <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Animated sprite-gen v2 showcase: paladin, wolf and slime" /></a>
+ <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="움직이는 sprite-gen v2 쇼케이스: 팔라딘, 늑대, 슬라임" /></a>
</p>
-<p align="center"><sub>각 캐릭터는 <b>이미지 한 장</b>에서 시작했습니다. Grok Imagine으로 움직임을 만들고, sprite-gen으로 투명 루프를 추출한 뒤 HyperFrames로 이 장면을 구성했습니다.</sub></p>
+<p align="center"><sub>각 캐릭터는 <b>정지 이미지 한 장</b>에서 시작했다. 그록 이매진(Grok Imagine)이 생명을 불어넣었고, sprite-gen 이 투명 루프를 추출했으며, 하이퍼프레임즈(HyperFrames)가 이 쇼케이스를 조립했다.</sub></p>
----
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="여러 겹의 배경과 투영된 그림자 속 그려진 마을을 걷는 사무라이와 동료들" />
+</p>
+<p align="center"><sub>sprite-gen 에셋으로 만든 별개의 마을 구성. 이 GIF 는 10초 영상을 20fps, 256색 팔레트로 보존한다.</sub></p>
-이미지 모델에 "스프라이트 시트"를 부탁하면 결과는 뻔하다: 프레임마다 얼굴이 바뀌는 캐릭터, 키잉이 안 되는 배경, 겹치고 격자를 벗어나는 포즈, 게임 엔진이 소비할 수 없는 PNG. 데모로는 귀엽고 에셋으로는 무용지물.
+---
-`sprite-gen` 은 그 간극을 메우는 Codex/Claude 스킬이자 파이썬 CLI 다. **베이스 이미지 한 장**을 주면 행 단위로 생성을 몰고, 캐릭터 identity 를 고정하고, 크로마 배경을 진짜 알파로 벗기고, 포즈마다 깨끗한 투명 프레임을 뽑아 **기계가 읽는 `manifest.json.frame_layout`** 이 딸린 런타임 아틀라스를 굽는다. 같은 스틸을 영상 모델에 넘기면 모션 상태별로 이음새 없는 투명 루프가 돌아온다. 생성이 끝내 못 맞추는 마지막 10% 는 **큐레이션 웹뷰**에서 비교·거부·미세조정하고 루프를 실재생으로 본 뒤 굽는다.
+이미지 모델에 "스프라이트 시트"를 요청하면 어떤 결과가 나오는지는 이미 알 것이다. 프레임마다 얼굴이 바뀌는 캐릭터, 키잉이 안 되는 배경, 서로 겹치고 그리드에서 벗어나 떠도는 포즈, 그리고 게임 엔진이 실제로는 소비할 수 없는 PNG. 데모로는 귀엽지만 에셋으로는 쓸모없다.
+
+`sprite-gen` 은 그 간극을 메우는 Codex/Claude 스킬이자 Python CLI 다. **기본 이미지 한 장**을 주면 행 단위로 생성을 이끌고, 캐릭터의 아이덴티티를 고정하고, 크로마 배경을 벗겨 진짜 알파로 만들고, 각 포즈를 깨끗한 투명 프레임으로 추출한 뒤, **기계가 읽을 수 있는 `manifest.json.frame_layout`** 과 함께 런타임 아틀라스를 굽는다. 또는 같은 정지 이미지를 비디오 모델에 넘겨 모션 상태별로 이음매 없는 투명 루프를 받을 수도 있다. 생성이 끝내 해결하지 못하는 마지막 10% 를 위해, **큐레이션 웹뷰**가 굽기 전에 비교·거부·미세 조정하고 루프를 실시간으로 확인하게 해준다.
## 요청으로 시작하기
-**스프라이트 만들기** 또는 **이미지 만들기**를 요청하세요. 이용 상태를 확인하고 생성 도구와 동작 방식 중 빠진 선택만 물어본 뒤 기존 파이프라인으로 결과를 전달합니다. 큐레이션뷰는 선택 사항입니다. 두 요청의 기본 설정을 따로 저장할 수 있고, 이번 요청의 선택은 저장값을 바꾸지 않습니다. [요청 흐름과 기본 설정](docs/user-workflow.md).
+**스프라이트**나 **이미지**를 요청하면 된다. 에이전트가 접근 권한을 확인하고, 빠진 프로바이더/모션 선택만 물어보고, 기존 파이프라인을 실행해 파일을 전달한다. 큐레이션 뷰는 선택 사항이다. 선택을 한 번 저장해 두면 스프라이트와 이미지 기본값을 따로 재사용할 수 있고, 일회성 요청은 그 값을 덮어쓰지 않는다. [사용자 워크플로와 기본값](docs/user-workflow.md).
-## 파이프라인 4종, CLI 하나
+## 파이프라인, 독립 도구, 씬
-모든 verb 는 단독으로도, 파이프라인 단계로도 쓴다. `sprite-gen --help` 가 같은 지도를 도메인별 verb 로 출력한다.
+두 스프라이트 파이프라인은 순서가 정해진 생성 흐름이다. 도구 그룹은 독립적인 명령들을 담고 있고, 씬 생성은 완성된 에셋을 소비하는 선택적 워크플로다. `sprite-gen --help` 는 이 지도를 출력하고, 명령을 소유한 코드 도메인별로 묶어 보여준다.
```mermaid
flowchart LR
- subgraph A["A · atlas rows"]
+ subgraph A["A · 아틀라스 행"]
direction LR
a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
- a5 -.-> a4["curation (optional)"]
+ a5 -.-> a4["curation (선택)"]
a4 --> a5
end
- subgraph B["B · video → loop"]
+ subgraph B["B · 비디오 → 루프"]
direction LR
b1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]
end
- subgraph C["C · utilities"]
+ subgraph C["C · 유틸리티"]
direction LR
c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
end
- subgraph D["D · post-processing"]
+ subgraph D["D · 후처리"]
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · 에셋 도구 (독립)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · 씬 (선택)"]
+ s1["기존 에셋 + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| 파이프라인 | 입력 → 출력 | 문서 |
+| 파이프라인 / 도구 그룹 / 워크플로 | 무엇이 들어가고 → 무엇이 나오는가 | 문서 |
|---|---|---|
-| **A · 아틀라스 행** | 스틸 1장 + 상태 목록 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, idle 에는 **Breathe** 가 구워짐 | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
-| **B · 영상 → 루프** | 스틸 1장 → 상태별 이음새 없는 투명 GIF / WebP / 스트립, Grok Imagine 으로 움직이고 진짜 주기에서 자름 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
-| **C · 유틸** | 가져온 이미지·그리드 시트 → 깨끗한 투명 컷; 완성 아틀라스 → 큐레이션용 run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · 후처리** | 완성 시트 → 결정론 컬러웨이, 리그 레이어 합성, Aseprite / Phaser / Flame 내보내기 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **A · 아틀라스 행** | 정지 이미지 한 장 + 상태 목록 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, 아이들 포즈에 **Breathe** 가 구워짐 | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
+| **B · 비디오 → 루프** | 정지 이미지 한 장 → 상태별로 이음매 없는 투명 GIF / WebP / 스트립, 그록 이매진이 움직이고 실제 주기에서 잘라냄 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
+| **C · 유틸리티** | 가져온 이미지 또는 그리드 시트 → 깨끗한 투명 컷; 완성된 아틀라스 → 큐레이터가 바로 쓸 수 있는 런 | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
+| **D · 후처리** | 완성된 시트 → 결정론적 컬러웨이, 리그 레이어 합성, Aseprite / Phaser / Flame 익스포트 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · 에셋 도구** | 독립적인 PNG 또는 애니메이션 → 반복 타일, 투영 그림자, 모션/접지 측정 | [asset-tools](docs/asset-tools.md) |
+| **S · 씬** | 기존 에셋 + 배치, 카메라, 조명 → PNG 프레임, MP4/GIF, 검사 및 배치 메타데이터 | [scene](docs/scene.md) |
-전체 목차: [`docs/README.md`](docs/README.md). 도메인·파이프라인 다이어그램이 있는 아키텍처: [`docs/architecture.md`](docs/architecture.md).
+전체 색인: [`docs/README.md`](docs/README.md). 도메인 및 파이프라인 다이어그램이 포함된 아키텍처: [`docs/architecture.md`](docs/architecture.md).
## 실제로 얻는 것
-- **투명 스프라이트 아틀라스** (`sprite-sheet-alpha.png`) — 진짜 알파, 크로마 프린지 없음, 흰 배경 대비 검증 ([왜 벗기지 않고 unmix 하나](docs/chroma-alpha.md)).
-- **런타임 매니페스트** (`manifest.json.frame_layout`) — 절대 프레임 사각형, 상태별 fps 와 loop 플래그. 엔진은 사각형을 읽고 격자를 추측하지 않는다.
-- **Breathe** — 정지 idle 이 살아 있는 루프가 된다. 사이드카 필드 하나로 큐레이션 프레임 위에 결정론 squash & stretch 를 굽는다. 해부학 인식, 픽셀 보존 ([상세](docs/breathing.md)).
-- **격자를 지키는 픽셀아트** — Backbone Lattice 가 피사체 전체에 격자 하나를 재서 모든 컷을 거기에 맞춘다 ([상세](docs/pixel-unfake.md)).
-- **영상에서 나오는 모션 루프** — 점프는 세로 캔버스, 공격은 가로 캔버스, 루프 포인트는 클립 자신의 주기, 단발 액션은 rest → action → rest 로 자른다 ([상세](docs/video-pipeline.md)).
-- **결정론 컬러웨이** — `recolor` 가 팔레트 맵으로 N 개 변형 시트를 굽는다. 같은 입력, 같은 바이트 ([상세](docs/recolor.md)).
-- **볼 수 있는 QA** — 상태별 GIF 와 컨택트 시트. 출하 전에 모션을 모션으로 판정한다. 순환 로코모션(walk/run)은 모션 QA 를 실제로 통과할 때까지 실험 단계다.
+- **투명 스프라이트 아틀라스** (`sprite-sheet-alpha.png`) — 진짜 알파, 남은 크로마 테두리 없음, 흰 배경 대비로 검증됨 ([추출기가 벗겨내는 대신 언믹싱하는 이유](docs/chroma-alpha.md)).
+- **런타임 매니페스트** (`manifest.json.frame_layout`) — 절대 프레임 사각형, 상태별 fps 와 루프 플래그. 엔진은 사각형을 샘플링할 뿐, 그리드를 추측하지 않는다.
+- **Breathe** — 정지된 아이들이 살아 있는 루프가 된다. 사이드카 필드 하나로 큐레이션한 프레임 위에 결정론적 스쿼시 & 스트레치를 굽고, 해부학을 인지하며 픽셀 단위로 정확하다 ([자세히](docs/breathing.md)).
+- **그리드를 벗어나지 않는 픽셀 아트** — 백본 래티스(Backbone Lattice)가 피사체 전체에 대해 하나의 그리드를 측정하고 모든 컷을 거기에 고정한다 ([자세히](docs/pixel-unfake.md)).
+- **비디오에서 나온 모션 루프** — 점프에는 세로로 긴 캔버스, 공격에는 가로로 넓은 캔버스가 주어지고, 루프 지점은 클립 자체의 주기이며, 일회성 동작은 대기 → 동작 → 대기로 잘린다 ([자세히](docs/video-pipeline.md)).
+- **결정론적 컬러웨이** — `recolor` 가 팔레트 맵으로 N 개의 변형 시트를 굽는다. 같은 입력이면 같은 출력 바이트 ([자세히](docs/recolor.md)).
+- **눈으로 확인하는 QA** — 상태별 GIF 와 컨택트 시트로, 무엇이든 출고되기 전에 모션을 모션으로서 판단한다. 주기적 이동(걷기/달리기)은 모션 QA 를 실제로 통과하기 전까지 실험적 상태로 남는다.
+- **독립적인 에셋 도구** — 반복 배경을 만들고, 발 앵커에서 그림자를 투영하고, 타이밍·중복 포즈·접지 증거를 검사한다. 발이 모호하면 미검증 측정값이 나온다 ([자세히](docs/asset-tools.md)).
+- **선택적 씬 생성** — 기존 PNG, 외부 프레임 시퀀스, 루프 스트립 또는 런타임 아틀라스를 이름 붙인 평면에 배치하고, 카메라 모션과 공유 그림자 투영을 적용한다. 스프라이트 생성은 이 단계 전에 끝나도 된다 ([자세히](docs/scene.md)).
-## 빠른 시작
+## 퀵스타트
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
+# 새 virtualenv 에 설치 (Pillow, NumPy) — venv 가 유일하게 지원되는 인터프리터다
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
sprite-gen --help
```
-**A · 아틀라스 행** — 스틸 1장에서 런타임 아틀라스까지.
+**A · 아틀라스 행** — 정지 이미지 한 장에서 런타임 아틀라스로.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # 요청, 가이드, 프롬프트
+sprite-gen gen-set --run-dir <run> --provider codex # 모든 상태 행, 한 번에 4개씩
+sprite-gen extract --run-dir <run> # 크로마 → 투명 프레임
+sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (선택) 고르고, 미세 조정하고, breathe
```
-**B · 영상 → 루프** — 스틸 1장에서 투명 루프까지 (`ffmpeg`, `img2webp`, 그리고 본인의 `grok` 로그인 또는 `XAI_API_KEY` 필요).
+**B · 비디오 → 루프** — 정지 이미지 한 장에서 투명 루프로 (`ffmpeg`, `img2webp`, 그리고 본인의 `grok` 로그인 또는 `XAI_API_KEY` 필요).
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --out-dir set/
+# 항목별로: video-canvas → video → video-frames → video-loop; set/table.md 가 모든 결과의 이름을 담는다
```
-**C · 유틸** — 각각 단독으로 쓴다.
+**C · 유틸리티** — 각각 독립적으로 쓴다.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen cutout icon.png --white-check # 흰색/아이보리 → 매트, 마젠타/그린 → 크로마 엔진
+sprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # 다중 인물 시트 → 셀별 컷
+sprite-gen unpack-atlas --atlas sheet.png # 완성된 아틀라스 → 큐레이터용 런 (또는 --pngs-dir folder/)
```
-**D · 후처리** — 재생성 없이 완성 시트를 다듬는다.
+**D · 후처리** — 다시 생성하지 않고 완성된 시트를 다듬는다.
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
+sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
+sprite-gen compose-layers --run-dir <run> # 리그 런: 선언된 스택 → <run>/layers/
+sprite-gen export-aseprite --run-dir <run> # Phaser / Flame 용 Aseprite JSON
+```
+
+**E · 에셋 도구** — 각각 다른 도구에서 나온 아트워크를 포함해 기존 에셋을 받는다.
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# 같은 발 접지가 확실하고 발 ROI 가 분리되어 있을 때만:
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · 씬** — 선택적 구성 워크플로. [씬 계약](docs/scene.md)에 전체 스펙이 있다.
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
```
-에이전트용 워크플로우·게이트·계약은 [`SKILL.md`](SKILL.md) 에 있다.
+에이전트를 위한 워크플로, 게이트, 계약은 [`SKILL.md`](SKILL.md) 에 있다.
-## 스킬로 설치
+## 스킬로 설치하기
```bash
python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
--repo aldegad/sprite-gen --path . --name sprite-gen
```
-이미지 생성은 이 엔진의 일부다(`sprite_gen.gen`, 프로바이더 `codex`·`grok`; 범용 `image-gen` 스킬은 그 위의 얇은 셔틀). 영상은 **본인의** 자격증명 — `grok` CLI 로그인 또는 `XAI_API_KEY` — 을 쓰고 레포에는 아무것도 들어 있지 않다 ([docs/video.md](docs/video.md)).
+이미지 생성은 이 엔진의 일부다 (`sprite_gen.gen`, 프로바이더 `codex` 와 `grok`; 범용 `image-gen` 스킬은 그 위에 얹힌 얇은 셔틀이다). 비디오는 **본인의** 자격 증명 — `grok` CLI 로그인 또는 `XAI_API_KEY` — 을 사용하며, 레포에는 아무것도 함께 배포되지 않는다 ([docs/video.md](docs/video.md)).
-`sprite-gen` 은 CPython 3.10+ 를 지원한다. CI 는 3.10 과 3.14 를 돈다. 빠른 시작에는 `venv`/`ensurepip` 가 동작하는 파이썬이 필요하다.
+`sprite-gen` 은 CPython 3.10+ 를 지원하고, CI 는 3.10 과 3.14 에서 돈다. 퀵스타트에는 `venv`/`ensurepip` 이 동작하는 Python 이 필요하다.
-## 출처
+## 출처 표기
-컴포넌트-행 워크플로우는 Apache-2.0 `hatch-pet` 스킬에서 영감을 받았지만 범용 게임 스프라이트 아틀라스를 목표로 하며 펫 패키지나 펫 비주얼 자산은 포함하지 않는다.
+컴포넌트 행 워크플로는 Apache-2.0 라이선스의 `hatch-pet` 스킬에서 영감을 받았지만, 범용 게임 스프라이트 아틀라스를 대상으로 하며 펫 패키지나 펫 비주얼 에셋은 포함하지 않는다.
-커뮤니티 기여·실험과 그 원 PR 은 [`CONTRIBUTORS.md`](CONTRIBUTORS.md) 에 기록한다.
+커뮤니티 기여, 실험, 그리고 그 출발점이 된 풀 리퀘스트는 [`CONTRIBUTORS.md`](CONTRIBUTORS.md) 에 기록되어 있다.
## 라이선스
-Apache-2.0
+Apache-2.0
\ No newline at end of file
diff --git a/README.md b/README.md
index 9f641e9..0fd07fa 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,12 @@
<p align="center"><sub>Each character started as <b>one still image</b>. Grok Imagine brought it to life; sprite-gen extracted the transparent loops, and HyperFrames assembled this showcase.</sub></p>
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="A samurai and companions walking through a painted village with layered scenery and projected shadows" />
+</p>
+
+<p align="center"><sub>A separate village composition made from sprite-gen assets. This GIF preserves the 10-second video at 20 fps with a 256-colour palette.</sub></p>
+
---
Ask an image model for a "sprite sheet" and you know what you get: a character whose face changes every frame, a background that won't key out, poses that overlap and drift off-grid, and a PNG your game engine can't actually consume. Cute demo, useless asset.
@@ -24,9 +30,9 @@ Ask an image model for a "sprite sheet" and you know what you get: a character w
Ask for **sprites** or **an image**. The agent checks access, asks only for missing provider/motion choices, runs the existing pipeline, and delivers the files. The curation view is optional. Save your choices once to reuse separate sprite and image defaults; a one-off request does not overwrite them. [User workflow and defaults](docs/user-workflow.md).
-## Four pipelines, one CLI
+## Pipelines, independent tools and scenes
-Every verb works alone or as a pipeline stage. `sprite-gen --help` prints this same map, with every verb grouped by domain.
+The two sprite pipelines are ordered generation flows. Tool groups contain independent commands; scene creation is an optional workflow that consumes finished assets. `sprite-gen --help` prints this map and groups commands by the code domain that owns them.
```mermaid
flowchart LR
@@ -48,14 +54,23 @@ flowchart LR
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · asset tools (independent)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · scene (optional)"]
+ s1["existing assets + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| Pipeline | What goes in → what comes out | Docs |
+| Pipeline / tool group / workflow | What goes in → what comes out | Docs |
|---|---|---|
| **A · atlas rows** | one still + a list of states → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, with **Breathe** baked on idle poses | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · video → loop** | one still → per state, a seamless transparent GIF / WebP / strip, animated by Grok Imagine and cut at its true period | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · utilities** | an imported image or grid sheet → clean transparent cuts; a finished atlas → a curator-ready run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
| **D · post-processing** | a finished sheet → deterministic colourways, rig layer composites, Aseprite / Phaser / Flame exports | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · asset tools** | independent PNGs or animations → repeating tiles, projected shadows, motion/contact measurements | [asset-tools](docs/asset-tools.md) |
+| **S · scene** | existing assets + placement, camera and lighting → PNG frames, MP4/GIF, inspection and placement metadata | [scene](docs/scene.md) |
Full index: [`docs/README.md`](docs/README.md). Architecture with domain and pipeline diagrams: [`docs/architecture.md`](docs/architecture.md).
@@ -68,6 +83,8 @@ Full index: [`docs/README.md`](docs/README.md). Architecture with domain and pip
- **Motion loops from video** — jumps get a tall canvas, attacks a wide one, the loop point is the clip's own period, and a one-shot action is cut rest → action → rest ([details](docs/video-pipeline.md)).
- **Deterministic colourways** — `recolor` bakes N variant sheets from a palette map; same input, same output bytes ([details](docs/recolor.md)).
- **QA you can watch** — per-state GIFs and contact sheets, so motion is judged as motion before anything ships. Cyclic locomotion (walk/run) stays experimental unless motion QA actually passes.
+- **Independent asset tools** — build repeating backgrounds, project shadows from a foot anchor, and inspect timing, duplicate poses and contact evidence. Ambiguous feet produce an unverified measurement ([details](docs/asset-tools.md)).
+- **Optional scene creation** — place existing PNGs, external frame sequences, loop strips or runtime atlases on named planes, with camera motion and shared shadow projection. Sprite generation can finish before this step ([details](docs/scene.md)).
## Quickstart
@@ -112,6 +129,23 @@ sprite-gen compose-layers --run-dir <run> # rig runs: dec
sprite-gen export-aseprite --run-dir <run> # Aseprite JSON for Phaser / Flame
```
+**E · asset tools** — each accepts existing assets, including artwork from other tools.
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# Only with known same-foot contact and an isolated foot ROI:
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · scene** — an optional composition workflow. The [scene contract](docs/scene.md) includes a complete spec.
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
+```
+
The agent-facing workflow, gates and contracts live in [`SKILL.md`](SKILL.md).
## Install as a skill
diff --git a/README.zh-Hans.md b/README.zh-Hans.md
index 6c47d8b..ec34b69 100644
--- a/README.zh-Hans.md
+++ b/README.zh-Hans.md
@@ -1,6 +1,6 @@
<h1 align="center">sprite-gen</h1>
-<p align="center"><b>放进一张画,出来的是游戏可直接使用的精灵 — 既可以是图集,也可以是透明的动作循环。</b></p>
+<p align="center"><b>输入一张画稿,输出可直接用于游戏的精灵图 —— 以图集形式,或以透明动态循环形式。</b></p>
<p align="center">
@@ -9,113 +9,144 @@
</p>
<p align="center">
- <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="Animated sprite-gen v2 showcase: paladin, wolf and slime" /></a>
+ <a href="https://youtu.be/zVu9YlbPtog"><img src="docs/assets/hero-v2-party.gif" width="960" alt="sprite-gen v2 动画展示:圣骑士、狼与史莱姆" /></a>
</p>
-<p align="center"><sub>每个角色都始于<b>一张静态图</b>。Grok Imagine 生成动作,sprite-gen 提取透明循环动画,再由 HyperFrames 合成这一场景。</sub></p>
+<p align="center"><sub>每个角色都始于<b>一张静态图</b>。Grok Imagine 让它动起来,sprite-gen 提取出透明循环,HyperFrames 组装了这段展示。</sub></p>
----
+<p align="center">
+ <img src="docs/assets/village-scene.gif" width="600" alt="一名武士与同伴穿行于绘制的村庄中,带有分层景物与投影阴影" />
+</p>
+
+<p align="center"><sub>另一段由 sprite-gen 素材构成的村庄合成。此 GIF 以 20 fps、256 色调色板保留了这段 10 秒视频。</sub></p>
+---
-向图像模型要一张“精灵表”,结果可想而知:每帧都在变脸的角色、抠不掉的背景、重叠且偏离网格的姿势、游戏引擎根本无法消费的 PNG。做演示可爱,做资产无用。
+向图像模型要一张"精灵表",结果你心里有数:角色的脸每帧都在变,背景抠不干净,姿势互相重叠又偏离网格,输出的 PNG 你的游戏引擎根本用不了。演示很可爱,素材没法用。
-`sprite-gen` 是补上这道缺口的 Codex/Claude 技能兼 Python CLI。给它**一张基础图**——它逐行驱动生成、锁定角色 identity、把色键背景剥成真正的 alpha、把每个姿势提取为干净的透明帧,并烘焙出带**机器可读 `manifest.json.frame_layout`** 的运行时图集。把同一张静止图交给视频模型,就能得到每个动作状态一段无缝透明循环。生成永远做不对的最后 10%,交给**策展 Webview**:对比、剔除、微调,实时观看循环后再烘焙。
+`sprite-gen` 是一个 Codex/Claude 技能,同时也是一个 Python CLI,专门填补这道鸿沟。给它**一张基准图** —— 它会逐行驱动生成、锁定角色身份、把色键背景剥离为真正的 alpha、将每个姿势提取为干净的透明帧,并烘焙出**带有机器可读 `manifest.json.frame_layout`** 的运行时图集。或者把同一张静态图交给视频模型,为每个运动状态取回无缝的透明循环。至于生成永远搞不定的最后 10%,**策展网页视图**让你在烘焙前比较、剔除、微调,并实时观看循环效果。
-## 从请求开始
+## 从一个请求开始
-请求**制作精灵图**或**生成图片**。代理检查使用状态,只询问尚未指定的生成工具和动作方式,再通过现有流程交付结果。筛选视图可选。两种用途可分别保存默认设置;单次请求不会覆盖已保存的设置。[请求流程与默认设置](docs/user-workflow.md)。
+你可以要**精灵图**,也可以要**一张图像**。代理会检查访问权限,只询问缺失的提供方/运动选项,运行既有流水线,然后交付文件。策展视图是可选的。保存一次你的选择,即可复用各自独立的精灵图与图像默认值;一次性请求不会覆盖它们。[用户工作流与默认值](docs/user-workflow.md)。
-## 四条流水线,一个 CLI
+## 流水线、独立工具与场景
-每个 verb 既能单独使用,也能作为流水线的一环。`sprite-gen --help` 会按领域分组打印同一张地图。
+两条精灵图流水线是有序的生成流程。工具组包含彼此独立的命令;场景创建是一个消费成品素材的可选工作流。`sprite-gen --help` 会打印这张地图,并按拥有各命令的代码域进行分组。
```mermaid
flowchart LR
- subgraph A["A · atlas rows"]
+ subgraph A["A · 图集行"]
direction LR
a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
- a5 -.-> a4["curation (optional)"]
+ a5 -.-> a4["curation(可选)"]
a4 --> a5
end
- subgraph B["B · video → loop"]
+ subgraph B["B · 视频 → 循环"]
direction LR
b1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]
end
- subgraph C["C · utilities"]
+ subgraph C["C · 实用工具"]
direction LR
c1[cutout] ~~~ c2[slice-sheet] ~~~ c3[unpack-atlas]
end
- subgraph D["D · post-processing"]
+ subgraph D["D · 后期处理"]
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
end
+ subgraph E["E · 素材工具(独立)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · 场景(可选)"]
+ s1["现有素材 + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| 流水线 | 输入 → 输出 | 文档 |
+| 流水线 / 工具组 / 工作流 | 输入什么 → 输出什么 | 文档 |
|---|---|---|
-| **A · 图集行** | 一张静止图 + 状态列表 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`,idle 上烘焙 **Breathe** | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
-| **B · 视频 → 循环** | 一张静止图 → 每个状态一段无缝透明 GIF / WebP / 条带,由 Grok Imagine 驱动并在真实周期处剪切 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
-| **C · 工具** | 导入的图片或网格表 → 干净的透明切片;成品图集 → 可策展的 run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · 后处理** | 成品表 → 确定性配色变体、绑定图层合成、Aseprite / Phaser / Flame 导出 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
-
-完整索引:[`docs/README.md`](docs/README.md)。含领域图与流水线图的架构:[`docs/architecture.md`](docs/architecture.md)。
-
-## 你实际得到的
-
-- **透明精灵图集**(`sprite-sheet-alpha.png`)— 真 alpha,无色键残边,已对白底验证([为何解混而不是剥离](docs/chroma-alpha.md))。
-- **运行时清单**(`manifest.json.frame_layout`)— 绝对帧矩形、每状态 fps 与 loop 标志。引擎读取矩形,从不猜网格。
-- **Breathe** — 静止 idle 变成活的循环:一个 sidecar 字段,在策展帧上烘焙确定性的挤压拉伸,识别体态、保持像素([详情](docs/breathing.md))。
-- **守住网格的像素画** — Backbone Lattice 为整个主体测出一套网格,并让每次切割都对齐它([详情](docs/pixel-unfake.md))。
-- **来自视频的动作循环** — 跳跃用竖画布,攻击用横画布,循环点是片段自身的周期,单次动作按 rest → action → rest 剪切([详情](docs/video-pipeline.md))。
-- **确定性配色变体** — `recolor` 用调色板映射烘焙 N 张变体表;同样输入,同样字节([详情](docs/recolor.md))。
-- **看得见的 QA** — 每状态的 GIF 与联系表,出货前把动作当动作来评判。循环移动(walk/run)在真正通过动作 QA 之前保持实验状态。
+| **A · 图集行** | 一张静态图 + 一组状态列表 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`,并在待机姿势上烘焙 **Breathe** | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
+| **B · 视频 → 循环** | 一张静态图 → 每个状态一份无缝透明 GIF / WebP / 条带,由 Grok Imagine 驱动动画并按其真实周期裁切 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
+| **C · 实用工具** | 一张导入图像或网格表 → 干净的透明切片;一份成品图集 → 可供策展的运行目录 | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
+| **D · 后期处理** | 一份成品表 → 确定性配色方案、骨骼图层合成、Aseprite / Phaser / Flame 导出 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **E · 素材工具** | 独立的 PNG 或动画 → 可重复平铺图、投影阴影、运动/接地测量 | [asset-tools](docs/asset-tools.md) |
+| **S · 场景** | 现有素材 + 摆放、相机与灯光 → PNG 帧、MP4/GIF、检查与摆放元数据 | [scene](docs/scene.md) |
+
+完整索引:[`docs/README.md`](docs/README.md)。含域与流水线示意图的架构说明:[`docs/architecture.md`](docs/architecture.md)。
+
+## 你实际得到什么
+
+- **一张透明精灵图集**(`sprite-sheet-alpha.png`)—— 真正的 alpha,没有残留的色键边缘,并对照白色背景做过验证([为什么提取器采用解混而非剥离](docs/chroma-alpha.md))。
+- **一份运行时清单**(`manifest.json.frame_layout`)—— 绝对帧矩形、每状态 fps 与循环标志。你的引擎按矩形取样,绝不去猜网格。
+- **Breathe** —— 静止的待机变成有生命的循环,基于一个 sidecar 字段在你策展过的帧上烘焙确定性的挤压与拉伸,尊重解剖结构且像素精准([详情](docs/breathing.md))。
+- **始终贴合网格的像素画** —— Backbone Lattice 为整个主体测量出一套网格,并让每一次切割都严格遵守它([详情](docs/pixel-unfake.md))。
+- **来自视频的运动循环** —— 跳跃使用高画布,攻击使用宽画布,循环点取自片段自身的周期,而一次性动作按 静止 → 动作 → 静止 裁切([详情](docs/video-pipeline.md))。
+- **确定性配色方案** —— `recolor` 依据调色板映射烘焙出 N 份变体表;相同输入,相同输出字节。([详情](docs/recolor.md))。
+- **可以亲眼检验的 QA** —— 每状态 GIF 与contact sheet,让运动在交付前先以运动的方式被评判。除非运动 QA 真正通过,循环式位移(走/跑)始终视为实验性。
+- **独立的素材工具** —— 构建可重复的背景、从脚部锚点投射阴影,并检查时序、重复姿势与接地证据。脚部含糊不清时将产出一份未经验证的测量结果([详情](docs/asset-tools.md))。
+- **可选的场景创建** —— 把现有 PNG、外部帧序列、循环条带或运行时图集摆放到命名平面上,配合相机运动与共享阴影投射。精灵图生成可以在这一步之前就完成([详情](docs/scene.md))。
## 快速开始
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
+# 安装(Pillow、NumPy)到全新虚拟环境 —— venv 是唯一受支持的解释器
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
sprite-gen --help
```
-**A · 图集行** — 从一张静止图到运行时图集。
+**A · 图集行** —— 从一张静态图到运行时图集。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # 请求、指南、提示词
+sprite-gen gen-set --run-dir <run> --provider codex # 每个状态行,一次 4 个
+sprite-gen extract --run-dir <run> # 色键 → 透明帧
+sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (可选)挑选、微调、呼吸
```
-**B · 视频 → 循环** — 从一张静止图到透明循环(需要 `ffmpeg`、`img2webp`,以及你自己的 `grok` 登录或 `XAI_API_KEY`)。
+**B · 视频 → 循环** —— 从一张静态图到透明循环(需要 `ffmpeg`、`img2webp`,以及你自己的 `grok` 登录或 `XAI_API_KEY`)。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --out-dir set/
+# 每项依次:video-canvas → video → video-frames → video-loop;set/table.md 列出每个结果的名称
```
-**C · 工具** — 各自独立使用。
+**C · 实用工具** —— 每个都可独立使用。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen cutout icon.png --white-check # 白/象牙 → 哑光, 洋红/绿 → 色键引擎
+sprite-gen slice-sheet --sheet sheet.png --chroma-key magenta --grid 3x2 # 多角色表 → 逐格切片
+sprite-gen unpack-atlas --atlas sheet.png # 成品图集 → 可供策展的运行目录(或 --pngs-dir folder/)
```
-**D · 后处理** — 不重新生成即可打磨成品表。
+**D · 后期处理** —— 不重新生成即可精修成品表。
```bash
-# install (Pillow, NumPy) into a fresh virtualenv — the venv is the only supported interpreter
-python3 -m venv .venv && source .venv/bin/activate
-pip install -e .
-sprite-gen --help
+sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
+sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
+sprite-gen compose-layers --run-dir <run> # 骨骼运行:声明的图层栈 → <run>/layers/
+sprite-gen export-aseprite --run-dir <run> # 供 Phaser / Flame 使用的 Aseprite JSON
+```
+
+**E · 素材工具** —— 每个都接受现有素材,包括来自其他工具的美术资源。
+
+```bash
+sprite-gen background-tile --source background.png --period 512 --overlap 32 --out tile.png
+sprite-gen shadow --source walk.strip.json --out-dir shadows/
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+# 仅在已知同一只脚接地且脚部 ROI 已隔离时使用:
+sprite-gen inspect-motion --source walk.strip.json --contacts 0:4 --foot-box 20,70,32,10 --out stance.json
+```
+
+**S · 场景** —— 一个可选的合成工作流。[场景契约](docs/scene.md)包含完整规格。
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
```
-面向 agent 的工作流、门禁与契约见 [`SKILL.md`](SKILL.md)。
+面向代理的工作流、门禁与契约位于 [`SKILL.md`](SKILL.md)。
## 作为技能安装
@@ -124,16 +155,16 @@ python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-githu
--repo aldegad/sprite-gen --path . --name sprite-gen
```
-图像生成是本引擎的一部分(`sprite_gen.gen`,提供方 `codex` 与 `grok`;通用 `image-gen` 技能只是其上的薄壳)。视频使用**你自己的**凭据——`grok` CLI 登录或 `XAI_API_KEY`——仓库不附带任何凭据([docs/video.md](docs/video.md))。
+图像生成是本引擎的一部分(`sprite_gen.gen`,提供方 `codex` 与 `grok`;通用的 `image-gen` 技能只是覆在其上的一层薄封装)。视频使用**你自己的**凭据 —— `grok` CLI 登录或 `XAI_API_KEY` —— 仓库中不附带任何凭据([docs/video.md](docs/video.md))。
-`sprite-gen` 支持 CPython 3.10+;CI 运行 3.10 与 3.14。快速开始需要 `venv`/`ensurepip` 可用的 Python。
+`sprite-gen` 支持 CPython 3.10+;CI 运行 3.10 与 3.14。快速开始需要一个 `venv`/`ensurepip` 可用的 Python。
## 致谢
-组件行工作流受 Apache-2.0 许可的 `hatch-pet` 技能启发,但面向通用游戏精灵图集,不包含任何宠物包或宠物视觉资产。
+组件行工作流受 Apache-2.0 许可的 `hatch-pet` 技能启发,但面向通用的游戏精灵图集,不包含任何宠物包或宠物视觉素材。
-社区贡献、实验及其来源 PR 记录在 [`CONTRIBUTORS.md`](CONTRIBUTORS.md)。
+社区贡献、实验及其来源的 pull request 记录在 [`CONTRIBUTORS.md`](CONTRIBUTORS.md)。
## 许可证
-Apache-2.0
+Apache-2.0
\ No newline at end of file
diff --git a/SECURITY.md b/SECURITY.md
index 784c088..0b19e60 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -38,16 +38,12 @@ a package that arrives only because some other dependency pulls it in can leave
on the next clean environment, and this package's own code must not be at the
mercy of another package's dependency list.
-NumPy was cleared through the advisory gate above before it was declared, and
-every version that `numpy>=2.2.6,<3` resolves to on a supported interpreter
-carries a live approval: 2.2.6 on CPython 3.10, 2.4.6 on 3.11, and 2.5.1 on 3.12
-and later.
-
-Pillow is a separate matter and predates this section, so this document does not
-claim it is cleared. Its ledger approval for 12.2.0 is recorded as revoked, and
-12.3.0 — the version `pillow>=12.0,<13` actually resolves to today — has no
-ledger entry at all. The declared Pillow range is therefore not covered by a
-live approval. Closing that gap is tracked separately and is not resolved here.
+Pillow requires `>=12.3.0,<13`, which excludes versions affected by the
+security issues fixed in the [Pillow 12.3.0 release](https://pillow.readthedocs.io/en/stable/releasenotes/12.3.0.html).
+NumPy requires `>=2.2.6,<3` to retain CPython 3.10 compatibility. A version floor
+does not guarantee future advisory coverage: audit the exact versions resolved
+for each supported interpreter when releasing, and audit existing environments
+separately. Changing package metadata does not upgrade an already installed venv.
A pure-Python fallback for a missing NumPy is not permitted. The extraction path
carries a byte-identity contract, and a second code path for the same contract
diff --git a/SKILL.md b/SKILL.md
index 00ed7e8..28f321f 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,7 +1,7 @@
---
name: sprite-gen
version: 2.2.0
-description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers and engine exports."
+description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers, engine exports, repeating backgrounds, projected shadows, motion/contact inspection and optional scene composition from existing assets."
license: Apache-2.0
depends_on:
required_bins:
@@ -42,7 +42,7 @@ modes:
# Sprite Gen
-Three user entry points: **make sprites**, **make an image**, or **animate a still into a video**. Existing generation, extraction and export tools do the work; the user chooses the result and provider.
+Generation entry points: **make sprites**, **make an image**, or **animate a still into a video**. Existing generation, extraction and export tools do the work; the user chooses the result and provider. For **repeat a background**, **project a shadow**, **inspect motion** or **compose a scene**, use the independent routes below directly with existing assets.
## Start every generation request here
@@ -74,10 +74,16 @@ Pass choices already stated in the request. The guide checks access, combines ex
| Rig layer composition | `sprite-gen compose-layers` | [layer-tracks](docs/layer-tracks.md) |
| Idle breathing | curation choice, baked by compose | [breathing](docs/breathing.md) |
| Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) |
+| Background recipe or repeating tile | existing `gen` / `cutout`, then optional `background-tile` | [asset-tools](docs/asset-tools.md#background-recipe) |
+| Standalone projected shadow | `shadow` | [asset-tools](docs/asset-tools.md#projected-shadows) |
+| Duplicate poses, foot contact and stride measurement | `inspect-motion` | [asset-tools](docs/asset-tools.md#motion-and-contact-evidence) |
+| Optional scene placement, lighting, camera and render | `scene-render`, `scene-inspect` | [scene](docs/scene.md) |
| Defaults | `defaults show`, `defaults save`, `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |
Use existing automatic pipeline stages for background removal, extraction, alignment and export. Do not ask users to select each script. For a direct utility request, run that utility; no unrelated generation questions are needed. Preserve the row pipeline and component extraction for image sprites. One-shot grid generation and fixed cell cutting are not an alternative sprite-generation route.
+Scene creation consumes finished assets and remains optional. Asset metadata owns frames, native durations and anchors; scene specs own placement, scale, playback rate, planes, camera and light. Measure stride only with declared same-foot contact and an isolated foot ROI; unknown contact stays unverified. Apply only a verified report for the exact selected asset with an explicit scene direction. Never infer walking direction from the bottommost silhouette, reverse frames or change source assets to make a scene work.
+
## 실행 인터프리터
`SPRITE_GEN_ROOT` is the absolute installed repository path. Use `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen` or `$SPRITE_GEN_ROOT/.venv/bin/python`; do not assume an activated shell. **폴백 금지**: create a missing venv or report the failure, never use an arbitrary global Python. **NumPy 가 없는 인터프리터** fails at package import. Setup and diagnosis: [interpreter](docs/interpreter.md).
diff --git a/docs/README.md b/docs/README.md
index 8baf173..6050faa 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,8 +1,8 @@
# sprite-gen documentation index
-One tool, four pipelines, one taxonomy. Every verb works alone or as a pipeline stage;
-every doc below owns exactly one concern and the others point at it. Start with the
-pipeline you are running, then follow its contract doc.
+One CLI, two sprite pipelines, independent tool groups and optional scene creation.
+Each doc owns one concern. Start with the result you want, then follow its contract;
+the code domains describe ownership rather than an execution order.
```mermaid
flowchart LR
@@ -25,16 +25,25 @@ flowchart LR
direction LR
d1[recolor] ~~~ d2[compose-layers] ~~~ d3["breathe (compose)"] ~~~ d4[export-*]
end
+ subgraph E["E · asset tools (independent)"]
+ e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
+ end
+ subgraph S["S · scene (optional)"]
+ s1["existing assets + scene.json"] --> s2[scene-render]
+ s1 --> s3[scene-inspect]
+ end
```
-| Pipeline | Entry doc | Verbs |
+| Pipeline / tool group / workflow | Entry doc | Verbs |
|---|---|---|
| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |
| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` → `video-frames` → `video-loop`, `video-set` |
| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` |
| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` |
+| **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |
+| **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |
-`sprite-gen --help` prints the same four pipelines and every verb grouped by domain; the
+`sprite-gen --help` prints these separate catalogs and every verb grouped by domain; the
grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
## User requests
@@ -78,7 +87,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
| [breathing.md](breathing.md) | The idle-breathing post-process layer and the static-pose row recipe |
| [locomotion-curation.md](locomotion-curation.md) | Manual selected cycles, clean GIF export |
-## Post-processing (pipeline D)
+## Post-processing (tool group D)
| Doc | Owns |
|---|---|
@@ -86,7 +95,14 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
| [layer-tracks.md](layer-tracks.md) | Rig runs: `rig` / `track` / `layers` contract and `compose-layers` |
| [engine-export.md](engine-export.md) | Aseprite-compatible export for Phaser and Flame |
-## Specialized inputs (pipeline C and direction runs)
+## Asset tools and optional scenes
+
+| Doc | Owns |
+|---|---|
+| [asset-tools.md](asset-tools.md) | Background recipes, repeating RGBA tiles, projected shadows, shared asset formats and motion/contact measurements |
+| [scene.md](scene.md) | Scene spec, planes, camera, lighting, measured stride application, render/inspection and output contracts |
+
+## Specialized inputs (tool group C and direction runs)
| Doc | Owns |
|---|---|
diff --git a/docs/architecture.md b/docs/architecture.md
index 1af4658..c6b44ce 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -2,7 +2,7 @@
> Owns: How the code is laid out: domains, stage ownership, the numeric SSoT, the cell model, extraction internals, runtime manifest · Index: [docs/README.md](README.md)
-> Status: reference (describes the code as it actually is, v2.0.0, 2026-09-09).
+> Status: reference (v2.2.0).
> Canonical behavior contract lives in [`../SKILL.md`](../SKILL.md); this doc
> explains *how* the code realizes that contract. If this doc and `SKILL.md`
> ever disagree, `SKILL.md` wins and this doc is the bug. The documentation
@@ -11,7 +11,7 @@
## Contents
- [0. Domains — the taxonomy](#0-domains--the-taxonomy)
-- [1. Four pipelines](#1-four-pipelines)
+- [1. Pipelines, tools and scenes](#1-pipelines-tools-and-scenes)
- [2. Stage ownership (each script does one job)](#2-stage-ownership-each-script-does-one-job)
- [3. The numeric SSoT: `sprite-request.json`](#3-the-numeric-ssot-sprite-requestjson)
- [4. The cell model](#4-the-cell-model-read-this--it-is-the-most-misunderstood-part)
@@ -34,26 +34,30 @@ a group). Every domain package is a folder under `sprite_gen/`.
flowchart TB
subgraph pkg["sprite_gen/ (_modules.py owns the mapping)"]
direction LR
- spec["spec<br/>sprite-request schema · layout resolver · runio (lock + atomic writes) · migrations"]
+ spec["spec<br/>read-only asset adapters · sprite-request schema · layout resolver · runio · migrations"]
gen["gen<br/>prepare · gen (codex / grok) · gen-set · video (Grok Imagine)"]
video["video<br/>canvas · frames · loop · batch (video-set)"]
frames["frames<br/>extract · cutout · slice-sheet · unpack-atlas · segment"]
curate["curate<br/>curation sidecar · direction anchors"]
compose["compose<br/>atlas · cycle · gif · layers · export-pngs · export-aseprite"]
- effects["effects<br/>breathe · anatomy · recolor · interpolate"]
- qa["qa<br/>inspect · score · preview · correction-loop"]
+ background["background<br/>repeating RGBA tiles · join inspection"]
+ effects["effects<br/>breathe · anatomy · recolor · interpolate · projected shadows"]
+ qa["qa<br/>inspect-motion · inspect · score · preview · correction-loop"]
+ scene["scene<br/>placement · planes · camera · light · render · inspect"]
serve["serve<br/>curation webview · composition canvas"]
end
cli["cli.py — one entrypoint, verbs grouped by domain"] --> pkg
spec -.read by every stage.-> gen & frames & compose & qa
```
-## 1. Four pipelines
+## 1. Pipelines, tools and scenes
-One sentence: a character image plus a numeric request becomes a transparent sprite
-atlas (pipeline A) or a set of transparent motion loops (pipeline B); imported images
-are cut clean (C); finished sheets are refined without regeneration (D). Every verb is
-also a standalone tool — the pipelines are the order the docs recommend, not a wrapper.
+A character image plus a numeric request becomes a transparent sprite atlas (pipeline A)
+or transparent motion loops (pipeline B). C/D/E are independent tool groups: imported
+image processing, finished-sheet refinement, and background/shadow/motion tools.
+Scene creation (S) is an optional workflow consuming existing assets. `_modules.py`
+owns separate `PIPELINES`, `TOOL_GROUPS` and `WORKFLOWS` catalogs. Domains express code
+ownership; workflows express the result; pipelines express an execution order.
```mermaid
flowchart TD
@@ -85,8 +89,24 @@ flowchart TD
end
ATLAS --> D
UNPACK --> CURATE
+ subgraph E["E · independent asset tools"]
+ TILE[background-tile] ~~~ SHADOW[shadow] ~~~ MOTION[inspect-motion]
+ end
+ subgraph S["S · optional scene workflow"]
+ INPUT["existing assets + scene.json"] --> RENDER[scene-render]
+ INPUT --> CHECK[scene-inspect]
+ end
```
+`spec.assets` adapts external descriptors, native loop strips and runtime atlases into
+one `FrameSequence`. Asset metadata owns frame order, native timing and anchor;
+`scene.model` owns references, placement, scale, playback rate, planes, camera and light.
+Scene never rewrites source assets. `qa.motion` measures contact evidence; scene applies
+only a verified measurement for the matching asset, in an explicitly chosen direction.
+`effects.shadow.project_shadow` is shared by standalone shadow export and scene render.
+Background generation remains a recipe for existing `gen` and `cutout` commands.
+The complete contracts live in [asset-tools](asset-tools.md) and [scene](scene.md).
+
## 2. Stage ownership (each script does one job)
The canonical stage → script → input → output table is owned by
diff --git a/docs/asset-tools.md b/docs/asset-tools.md
new file mode 100644
index 0000000..17fde0a
--- /dev/null
+++ b/docs/asset-tools.md
@@ -0,0 +1,109 @@
+# Independent asset tools
+
+> Owns: Background recipes, repeating RGBA tiles, projected shadows, shared asset formats and motion/contact measurements · Index: [docs/README.md](README.md)
+
+These commands accept finished artwork without a sprite-generation run or scene spec. `background` owns repeating tiles, `effects` owns shadow projection, and `qa` owns motion measurements. [Scene creation](scene.md) optionally consumes their outputs. Atlas and character-part assembly remain in `compose`.
+
+## Background recipe
+
+Use the existing [image generator](gen.md) and [cutout](sheet-slicing.md) for background art. Choose the layers before generating:
+
+- Paint buildings and their immediate ground together when their overlap and perspective should remain fixed.
+- Keep distant mountains, sky or foliage separate when they need different camera parallax.
+- Request the full silhouette of roofs, trees and signs, with transparent or key-colour margin on every side. A cropped silhouette cannot be recovered by adding empty canvas later.
+- Keep shadows separate when the scene will project them from its light. Generate enough horizontal overlap for a repeating strip and inspect the join at display scale.
+
+Example prompt template for the existing generator:
+
+> Side-view painted village frontage for a 2D game. Buildings and their immediate ground share one perspective. Show every roof and tree canopy completely, with clear margin above and at both sides. Keep the foreground path unobstructed. No characters, no cast shadows. Use a uniform key colour absent from the artwork. Leave matching texture and lighting in the left and right overlap regions.
+
+Generate and remove the key with the existing tools, then run the tile command only if repetition is needed. This recipe adds no generation provider or required sprite stage.
+
+## Repeating tiles
+
+```bash
+sprite-gen background-tile --source frontage.png --axis x --period 512 --overlap 32 --out tile.png
+```
+
+`--axis x|y` chooses the repeat direction. `--period` is the output length in source pixels; `--overlap` is the input overlap used to find a low-error quilting seam. Input must contain enough pixels for the requested period and overlap. The tool preserves RGBA, writes a new PNG and `<out-stem>.report.json`, and never overwrites its source. `--report` changes the JSON destination.
+
+The report measures the join against ordinary interior differences, including alpha and colour over light/dark backgrounds. It records the selected seam and source crop. A numerical join score does not prove that architecture or silhouettes repeat convincingly: inspect at least two adjacent copies. The tool does not invent missing roofs, perspective or scenery.
+
+Python APIs: `make_tile(image, period, *, axis="x", overlap=32)` and `inspect_tile(image, axis="x")` in `sprite_gen.background.tile`. The former returns the image and report; the latter only measures.
+
+## Shared asset input
+
+`shadow`, `inspect-motion` and scene use `sprite_gen.spec.assets.load_asset(source, *, state=None, fps=None, anchor=None)`. It returns a `FrameSequence` with ordered RGBA frames, durations in seconds, a source-pixel anchor, source files and metadata. `size`, `duration`, `frame_at(t, loop=True)` and `fingerprints()` expose the shared view. Inputs remain unchanged.
+
+Supported inputs:
+
+| Input | Timing and selection |
+|---|---|
+| A static PNG | One frame; default duration one second |
+| An external `sprite-gen-asset` descriptor | Explicit ordered frame durations in seconds |
+| `video-loop` output `name.strip.json` | Reads matching `name.strip.png`; `frames`, `w`, `h`, `delay_ms` define the strip |
+| Runtime atlas `manifest.json` | Reads `sprite_sheet_alpha`, `frame_layout.rows` rectangles and `animation.rows` timing; multi-state atlases require `--state` |
+
+An arbitrary folder or animated GIF is not an implicit frame sequence. Export its frames and describe the order and durations explicitly:
+
+```json
+{
+ "kind": "sprite-gen-asset",
+ "version": 1,
+ "anchor": [32, 80],
+ "frames": [
+ {"file": "frames/step-0.png", "duration": 0.1},
+ {"file": "frames/step-1.png", "duration": 0.2},
+ {"file": "frames/step-2.png", "duration": 0.1}
+ ]
+}
+```
+
+Frame paths resolve relative to the descriptor. All frames share one canvas. The default anchor is bottom centre `(width / 2, height)` in canvas coordinates; it does not guess the foot location from visible pixels. For standalone shadow/motion commands, `--fps` explicitly replaces frame durations, and `--anchor-x` / `--anchor-y` override the anchor together. Prefer an external descriptor for metadata that must be reused consistently by scene.
+
+## Projected shadows
+
+```bash
+sprite-gen shadow --source walk.strip.json --out-dir shadows/ \
+ --squash 0.25 --shear 0.8 --opacity 0.4 --blur 3 --color 20,15,30
+```
+
+The output contains `frame-NNN.png`, a horizontal `shadow.png`, and `shadow.asset.json` with the resulting anchor and original durations. `--state`, `--fps` and paired anchor overrides use the shared input contract.
+
+`squash` controls projection length vertically, `shear` controls its sideways direction, and `opacity`, `blur`, `color` control appearance. Positive shear projects pixels above the anchor to the left. The projection canvas includes the entire shadow and blur margin.
+
+Python API: `project_shadow(image, anchor, *, squash=0.25, shear=0.8, opacity=0.4, blur=3, color=(20,15,30)) -> (image, anchor)`. Place the returned shadow anchor at the sprite's world anchor. Scene calls this same function using its light settings; there is no separate scene shadow algorithm.
+
+## Motion and contact evidence
+
+```bash
+# Read-only analysis: absent reliable contact, stride remains unverified.
+sprite-gen inspect-motion --source walk.strip.json --out motion.json
+
+# Manual same-foot stance evidence, zero-based inclusive ranges:
+sprite-gen inspect-motion --source walk.strip.json \
+ --contacts 0:4,8:12 --foot-box 20,70,32,10 --facing right --out stance.json
+```
+
+`--contacts` declares consecutive source frames during which the **same tracked foot** is planted. `--foot-box x,y,width,height` is a fixed source-canvas ROI that isolates that foot throughout the declared spans. Choose values from the actual clip; these example coordinates are not defaults. Two visible feet in the ROI, an absent/airborne foot, inconsistent baselines or insufficient distinct poses leave the measurement unverified. Manual contact is a user-supplied assumption: silhouette geometry alone cannot prove ground contact.
+
+`--facing left|right` is an annotation. It does not flip pixels, change measurement sign or set scene direction. Without `--out`, JSON goes to stdout. Analysis never removes or edits frames.
+
+Python API: `analyze_motion(sequence, *, contacts=None, foot_box=None, facing=None) -> dict` in `sprite_gen.qa.motion`.
+
+| Report field | Meaning |
+|---|---|
+| `frame_count`, `duration_seconds` | Full original sequence count and elapsed time, including repeated pose holds |
+| `duplicate_frames` | Exact image, adjacent exact, exact silhouette and near silhouette duplicate counts; near uses IoU >= 0.98 |
+| `frames`, `bbox_stats`, `anchor_px`, `edge_contact` | Per-frame timing, measured bounds/anchor offsets and canvas edge contact |
+| `motion` | Visible and silhouette changes; no walking-direction inference |
+| `contact_candidates`, `confidence`, `warnings`, `method` | Contact measurements, reasons for rejection and the measurement assumptions |
+| `stride_verified` | `true` only when the declared contact and isolated ROI pass the stance checks |
+| `stride_px_per_second` | Absolute stance speed in source pixels/second, otherwise `null` |
+| `foot_velocity_px_per_second` | Signed stance foot velocity, positive toward image right, otherwise `null` |
+| `source_fingerprints` | Source-path SHA-256 mapping bound to the loaded inputs, for stale-measurement rejection |
+| `sequence` | Selected source/state, fps override, frame count, size, anchor and effective per-frame durations; scene must match this as well as the source fingerprints |
+
+Repeated tracked poses retain their complete elapsed duration. Velocity uses distinct pose onset times; duplicate holds add time but do not add independent votes. The last hold remains part of the clip duration without inventing a later displacement endpoint. Confidence is a conditional heuristic, not a calibrated probability of contact.
+
+Scene consumes only verified measurements for the matching selected asset and requires an explicit direction relative to a declared plane or the world. Measurement does not automatically apply stride to any scene or sprite.
diff --git a/docs/assets/village-scene.gif b/docs/assets/village-scene.gif
new file mode 100644
index 0000000..27c896d
Binary files /dev/null and b/docs/assets/village-scene.gif differ
diff --git a/docs/scene.md b/docs/scene.md
new file mode 100644
index 0000000..88c552c
--- /dev/null
+++ b/docs/scene.md
@@ -0,0 +1,107 @@
+# Optional scene creation
+
+> Owns: Scene spec, planes, camera, lighting, measured stride application, render/inspection and output contracts · Index: [docs/README.md](README.md)
+
+`scene-render` places finished assets without generating or modifying them. `scene-inspect` measures the same composition without exporting a video. Both accept a versioned JSON spec. Sprite generation can end with an atlas or loop; this workflow is optional, and artwork from other tools can enter here directly.
+
+## A complete static scene
+
+Save this as `scene.json` beside any static `actor.png`. The default asset anchor is bottom centre; `at` places that anchor in world pixels.
+
+```json
+{
+ "kind": "sprite-gen-scene",
+ "version": 1,
+ "canvas": {"width": 640, "height": 360, "background": [235, 235, 240, 255]},
+ "fps": 20,
+ "duration": 2,
+ "assets": {"actor": {"source": "actor.png"}},
+ "planes": {"ground": {"velocity": [0, 0]}},
+ "camera": {"at": [0, 0], "velocity": [0, 0]},
+ "light": {"squash": 0.25, "shear": 0.8, "opacity": 0.4, "blur": 3, "color": [20, 15, 30]},
+ "layers": [
+ {"id": "actor", "asset": "actor", "at": [320, 310], "plane": "ground", "shadow": true}
+ ]
+}
+```
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir render/ --formats png,mp4 --export-layers
+sprite-gen scene-inspect --spec scene.json --out scene-check.json
+```
+
+For animations, replace the PNG reference with an [external frame descriptor, loop strip or runtime atlas](asset-tools.md#shared-asset-input). Add `"state": "walk"` to an atlas reference when it has several states. Paths resolve relative to the scene spec; frame/image paths within asset descriptors resolve relative to those descriptors. Asset timing and anchors stay in the asset metadata.
+
+## Spec ownership and units
+
+| Field | Contract |
+|---|---|
+| `kind`, `version` | `sprite-gen-scene`, `1`; unknown fields are rejected |
+| `canvas` | Integer `width`, `height`, RGB/RGBA byte `background`; at most 8192 per axis and 16 megapixels |
+| `fps`, `duration` | Output sampling rate and seconds; `duration * fps` must be an integer from 1 to 10000; fps <= 120 |
+| `assets` | Named `{source, state?}` references, or source strings; metadata is loaded once through the shared adapter |
+| `planes` | Named `{velocity: [x,y]}` in world pixels/second; a layer's own velocity is relative to its plane |
+| `camera` | `at`, `velocity`, in world pixels and pixels/second |
+| `light` | `squash`, `shear`, `opacity`, `blur`, `color`, passed to the [shared shadow projection](asset-tools.md#projected-shadows) |
+| `layers` | Nonempty ordered list, sorted stably by `z` before compositing |
+
+Canvas origin is top left; positive x is right, positive y is down. Each layer has a unique `id` (letters/digits/dash/underscore) and named `asset`. Optional fields:
+
+| Layer field | Default and meaning |
+|---|---|
+| `at` | `[0,0]`, world position of the asset anchor at scene time zero |
+| `velocity` | `[0,0]`, motion relative to the selected plane, or world if none |
+| `plane` | No plane; otherwise a declared plane name |
+| `scale`, `opacity`, `z` | `1`, `1`, `0`; positive raster scale, alpha multiplier 0..1, stacking order |
+| `parallax` | `1`, multiplier on camera displacement; 0 keeps a layer unaffected by the camera |
+| `repeat_x`, `period` | `false`, source width; integer horizontal repeat period in source pixels |
+| `shadow` | `false`; project the source silhouette using the scene light |
+| `playback_rate`, `offset` | `1`, `0`; asset time is `scene_time * playback_rate + offset`, with offset in seconds |
+| `loop` | Source loop flag, otherwise true; false holds the final frame after its end |
+| `stride` | Optional verified motion report plus explicit direction; mutually exclusive with `velocity` |
+
+Screen anchor equals `at + (plane_velocity + layer_velocity) * time - (camera.at + camera.velocity * time) * parallax`. Raster dimensions are rounded from source dimensions and scale; the anchor follows the actual resized dimensions. For repeated strips, use the tile's measured period and inspect two or more copies for recognisable joins.
+
+## Applying measured stride
+
+First run [`inspect-motion`](asset-tools.md#motion-and-contact-evidence) with genuine same-foot contact spans and an isolated ROI. Then replace the layer's `velocity` with:
+
+```json
+"stride": {"report": "stance.json", "direction": "right"}
+```
+
+Scene accepts only `stride_verified: true` with a positive `stride_px_per_second` and matching source/sequence identity. It rejects stale sources, another state or different measurement timing. Keep native asset durations consistent; a standalone `--fps` override is not automatically an instruction to change the scene's asset timing. Describe reusable timing in the asset metadata.
+
+Stride magnitude is converted from source pixels/second to the rendered horizontal scale and multiplied by `playback_rate`. Explicit `direction` supplies the sign; the named plane velocity is then added. `facing` in the QA report never chooses scene direction. A left-moving stance foot can support rightward travel, but scene does not guess that relationship. Unverified or airborne clips require an explicit placement velocity chosen by the scene author.
+
+## Outputs and failure behaviour
+
+`--formats` selects a comma-separated subset of `png,mp4,gif`. MP4 requires `ffmpeg`, even canvas dimensions and an opaque background. GIF also requires an opaque background; export transparent content as PNG frames or layer plates.
+
+The output directory is dedicated to one render and must be empty. Rendering and encoding stage before publication, protected by the shared run-directory writer lock. Invalid specs, changed sources, encoder errors or publication failures stop with a nonzero result. Sources and pre-existing outputs are preserved; the CLI does not regenerate assets or retry a failed encoder automatically.
+
+GIF defaults preserve the scene frame rate, use 256 colours without dithering (for flat pixel-art colours), and cap width at 640 pixels. `--gif-width`, `--gif-fps`, `--gif-colors` and `--gif-dither` make those choices explicit; `sierra2_4a` can preserve gradual tones in painted scenery. GIF fps cannot exceed scene fps; more samples require rendering the scene itself at a higher rate. `--gif-max-bytes` defaults to 8,000,000: an oversized result fails and asks for an explicit budget or quality change. The encoder never silently lowers frame rate, resolution or colours.
+
+```bash
+sprite-gen scene-render --spec scene.json --out-dir gif-render/ --formats gif \
+ --gif-width 600 --gif-fps 20 --gif-colors 256 --gif-dither sierra2_4a --gif-max-bytes 40000000
+```
+
+| Output | Meaning |
+|---|---|
+| `frames/frame-NNNNN.png` | All rendered frames when `png` is selected |
+| `scene.mp4`, `scene.gif` | Selected encoded formats |
+| `check-NNNNN.png` | Representative rendered frames for visual review |
+| `scene.report.json` | Source fingerprints, output list, encoding details and scene inspection |
+| `placement.json` | Resolved placement and source references, camera, light, fps and duration |
+| `layers/<id>.png` | Optional canvas-sized plates at time zero, with `--export-layers` |
+
+Layer plates are static; animated layers remain references in `placement.json`. This output is not a self-contained project archive: copy all referenced assets when moving it.
+
+## Inspection
+
+`scene-inspect` reports viewport clipping, including completely offscreen layers, repeat joins, timing and loop measurements. It compares the actual last rendered output frame with the first as well as ordinary adjacent transitions; phase closure is separate from visual seam quality. A clean numerical result still needs visual review, especially for locomotion and repeating architecture.
+
+`--require-loop` makes a failed loop check return nonzero. Without `--out`, the JSON is printed. An output report cannot overwrite a source, a source alias or the reserved writer lock. Inspection does not fix, reverse, flip or resample source frames.
+
+Python APIs: `load_scene(path)` in `sprite_gen.scene.model`, `render_scene(spec, out_dir, **options)` in `sprite_gen.scene.render`, and `inspect_scene(scene, **options)` in `sprite_gen.scene.inspect_scene`. Each command also supports `python -m` with its module name.
diff --git a/pyproject.toml b/pyproject.toml
index 0896fd8..027734b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -18,7 +18,7 @@ readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
dependencies = [
- "pillow>=12.0,<13",
+ "pillow>=12.3.0,<13",
# NumPy is a direct dependency, never a transitive ride-along: the chroma
# extraction path imports it directly and must not depend on some other
# package happening to pull it in.
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.py
index 23b633c..d0d7c21 100644
--- a/sprite_gen/_modules.py
+++ b/sprite_gen/_modules.py
@@ -9,6 +9,13 @@ MODULE_DOMAIN = {
'guide': 'workflow',
'preferences': 'workflow',
'runio': 'spec',
+ 'assets': 'spec',
+ 'tile': 'background',
+ 'shadow': 'effects',
+ 'motion': 'qa',
+ 'render': 'scene',
+ 'inspect_scene': 'scene',
+ 'model': 'scene',
'layout': 'spec',
'migrate_request': 'spec',
'migrate_breathe': 'spec',
@@ -61,27 +68,41 @@ DOMAINS: list[tuple[str, str]] = [
("frames", "Frames — chroma/white removal, row extraction, sheet slicing, atlas unpacking"),
("curate", "Curation — direction anchors and the curation sidecar"),
("compose", "Compose — runtime atlas, cycles, GIFs, layers, exports"),
- ("effects", "Post-processing — recolor, breathing, interpolation"),
- ("qa", "QA — inspect, score, preview, bounded correction loop"),
+ ("background", "Background — repeating painted strips and textures"),
+ ("effects", "Post-processing — recolor, breathing, interpolation, projected shadows"),
+ ("scene", "Scene — asset placement, camera, lighting, rendering and inspection"),
+ ("qa", "QA — motion/contact measurements, inspect, score, preview, bounded correction loop"),
("serve", "Webviews — curation and composition canvases"),
- ("spec", "Spec — request migrations and run I/O"),
+ ("spec", "Spec — read-only assets, request migrations and run I/O"),
("util", "Utilities"),
]
DOMAIN_ORDER = [d for d, _ in DOMAINS]
DOMAIN_TITLE = dict(DOMAINS)
-# The four pipelines — first-class objects. The CLI help, the docs index and the README
+# Ordered sprite pipelines. Standalone tool groups and scene workflow are separate.
+# The CLI help, the docs index and the README
# pipeline table are checked against THIS list; a verb named here must exist as a verb.
PIPELINES: list[dict[str, object]] = [
{"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],
"chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},
{"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-frames", "video-loop", "video-set"],
"chain": "video-canvas → video → video-frames → video-loop, or video-set", "doc": "docs/video-pipeline.md"},
+]
+
+TOOL_GROUPS: list[dict[str, object]] = [
{"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "unpack-atlas"],
"chain": "cutout · slice-sheet · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},
{"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "compose-layers", "export-pngs", "export-aseprite"],
"chain": "recolor · compose-layers · export-pngs · export-aseprite", "doc": "docs/recolor.md"},
+ {"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],
+ "chain": "background-tile · shadow · inspect-motion (independent; no generation required)", "doc": "docs/asset-tools.md"},
+]
+
+WORKFLOWS: list[dict[str, object]] = [
+ {"key": "S", "name": "scene", "verbs": ["scene-render", "scene-inspect"],
+ "chain": "existing assets + scene spec → scene-render; scene-inspect for measurements",
+ "doc": "docs/scene.md"},
]
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index dccf91c..45fcadc 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -8,16 +8,18 @@ from pathlib import Path
from typing import Callable
from sprite_gen import _modules, gen
+from sprite_gen.background import tile
from sprite_gen.curate import anchor
from sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, compose_layers, export_aseprite, export_pngs
-from sprite_gen.qa import correction_loop, inspect, preview, score
+from sprite_gen.qa import correction_loop, inspect, preview, score, motion
from sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas
from sprite_gen.gen import gen_set, prepare, video
from sprite_gen.video import batch as video_batch
from sprite_gen.video import canvas as video_canvas
from sprite_gen.video import frames as video_frames
from sprite_gen.video import loop as video_loop
-from sprite_gen.effects import recolor
+from sprite_gen.effects import recolor, shadow
+from sprite_gen.scene import render, inspect_scene
from sprite_gen.serve import serve_compose, serve_curation
from sprite_gen.spec import migrate_breathe, migrate_request
from sprite_gen.gen.prepare import STYLE_DEFAULT, _outline_config
@@ -228,6 +230,11 @@ def _add_correction_loop(p: argparse.ArgumentParser) -> None:
COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callable[..., int]]] = {
+ "background-tile": ("Quilt a repeating RGBA background and measure its join.", tile.add_arguments, tile.run),
+ "shadow": ("Project silhouette shadows from any supported asset.", shadow.add_arguments, shadow.run),
+ "inspect-motion": ("Measure asset timing and contact evidence without changing animation.", motion.add_arguments, motion.run),
+ "scene-render": ("Render referenced assets using scene placement, camera and lighting.", render.add_arguments, render.run),
+ "scene-inspect": ("Measure scene loops, viewport clipping and repeated joins.", inspect_scene.add_arguments, inspect_scene.run),
"workflow": ("Resolve image/sprite choices, check access and guide the next conversation step.", guide.add_arguments, guide.run),
"defaults": ("Show, explicitly save or clear the defaults for each user workflow.", preferences.add_arguments, preferences.run),
"prepare": ("Prepare a sprite-gen component-row run.", _add_prepare, prepare.run),
@@ -372,10 +379,14 @@ def command_domains() -> dict[str, list[str]]:
def _help_description() -> str:
- lines = ["sprite-gen — 2D sprite pipelines as one CLI. Every verb works alone or as a pipeline stage.", "", "pipelines:"]
- for pipe in _modules.PIPELINES: # the catalog, not a copy of it
- label = f"{pipe['key']} {pipe['name']}"
- lines.append(f" {label:<20} {pipe['chain']} ({pipe['doc']})")
+ lines = ["sprite-gen — assets and scenes in one CLI. Workflows compose independent commands."]
+ for title, entries in (("sprite pipelines", _modules.PIPELINES),
+ ("standalone tool groups", _modules.TOOL_GROUPS),
+ ("scene workflow", _modules.WORKFLOWS)):
+ lines += ["", f"{title}:"]
+ for item in entries:
+ label = f"{item['key']} {item['name']}"
+ lines.append(f" {label:<20} {item['chain']} ({item['doc']})")
lines += ["", "tools by domain:"]
width = max(len(v) for v in COMMANDS)
for domain, verbs in command_domains().items():
diff --git a/tests/packaging/test_cli_taxonomy.py b/tests/packaging/test_cli_taxonomy.py
index 1698ce2..f87906e 100644
--- a/tests/packaging/test_cli_taxonomy.py
+++ b/tests/packaging/test_cli_taxonomy.py
@@ -40,26 +40,26 @@ def test_help_lists_each_verb_once_under_its_domain() -> None:
assert f"[{domain}]" in out
for verb in verbs:
assert len(re.findall(rf"(?m)^\s+{re.escape(verb)}\s{{2,}}", out)) == 1, verb
- for pipe in _modules.PIPELINES:
+ for pipe in (*_modules.PIPELINES, *_modules.TOOL_GROUPS, *_modules.WORKFLOWS):
assert f"{pipe['key']} {pipe['name']}" in out and str(pipe["doc"]) in out
-def test_pipeline_catalog_names_real_verbs_and_docs() -> None:
- """Validator finding 2026-09-09: the pipeline list was a hand-written tuple in cli.py.
- It is now a catalog in _modules; every verb it names is a real verb, every doc exists,
- and both README pipeline tables mention each pipeline's doc."""
+def test_catalog_names_real_verbs_and_docs() -> None:
+ """Ordered pipelines, tool groups and optional workflows have distinct catalogs."""
from pathlib import Path
root = Path(cli.__file__).resolve().parents[1]
- keys = [p["key"] for p in _modules.PIPELINES]
- assert keys == ["A", "B", "C", "D"]
- for pipe in _modules.PIPELINES:
+ assert [p["key"] for p in _modules.PIPELINES] == ["A", "B"]
+ assert [p["key"] for p in _modules.TOOL_GROUPS] == ["C", "D", "E"]
+ assert [p["key"] for p in _modules.WORKFLOWS] == ["S"]
+ catalog = [*_modules.PIPELINES, *_modules.TOOL_GROUPS, *_modules.WORKFLOWS]
+ for pipe in catalog:
for verb in pipe["verbs"]:
assert verb in cli.COMMANDS, (pipe["key"], verb)
assert (root / str(pipe["doc"])).is_file(), pipe["doc"]
index = (root / "docs" / "README.md").read_text(encoding="utf-8")
readme = (root / "README.md").read_text(encoding="utf-8")
- for pipe in _modules.PIPELINES:
+ for pipe in catalog:
doc_name = str(pipe["doc"]).split("/")[-1]
row = next((l for l in index.splitlines() if l.startswith(f"| **{pipe['key']} ·")), None)
assert row is not None, f"docs/README.md has no pipeline row for {pipe['key']}"