Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): video-set-sheet lays a set's directions on one sheet — compass order, one cell, one ground line, every row as cut, an optional centre picture
Soohong Kimeffacc02c78d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ba1da4..d1e97a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased (v2.42.0)+- **New `sprite-gen video-set-sheet`: the directions of one set on one sheet, standing on one ground line.** Each direction is cut on its own and a strip is the union of its own cycle's bodies, so laid side by side the directions stand at different heights and cell sizes. `video-set-sheet --loop-dir <dir> --view <view> …` (the views as `video-cycle-align` takes them; a strip turned over to face the other way is a direction like any other) writes `<name>.sheet.png` and `<name>.sheet.json`: a row per direction in the compass order S, SW, W, NW, N, NE, E, SE whatever order the loops are given in, a frame a column; one cell that holds every pixel of every cell of every direction, centred on the pivot each strip declares (`anchor`) or else its bottom centre, so every cell's pivot is its bottom centre; one ground line, `baseline_y`, the lowest body pixel (alpha 8 and over, as `video-loop` reads a body) of any cell — a fainter pixel, a soft shadow, is kept in the cell below the line and is no body — (a direction whose strip leaves room under its feet stands that much above it, as cut: `body_bottom_y`); and every row as cut, pixel for pixel — nothing is scaled direction by direction, one size across a set is `video-loop --body-height`'s. `--center <still>` stands a transparent still (the set's base) with its body on the same line at the rows' standing height (the median of their `body_h`, against the still's own as `video-loop` reads one), centred, in `<name>.center.png`. Loops of different lengths, in frames or frame time, are laid all the same, the shorter rows' last cells empty, with `same_length: false` and a warning. The record carries `order`, `columns`, `cell_w`, `cell_h`, `baseline_y`, `anchor`, `same_length`, per row its `code`, `view`, `frames`, `delay_ms`, strip `name`, `input`, `strip_sha256`, `body_h` and `body_bottom_y`, and the centre's `png`, `input`, `sha256`, `standing_h`, `body_h`, `scale` and `box`. A direction given twice, a front or back view with a side, a `--view` count other than the loops', a loop directory without one strip and its sidecar, an opaque centre still and a centre beside rows without `body_h` are refused before anything is written. The loop directories are only read. Every other verb writes what 2.41.0 writes. [docs/video-pipeline.md](docs/video-pipeline.md#7-one-sheet-for-a-set--video-set-sheet).+- **`tests/video/test_set_sheet.py`** lays synthetic strips of different sizes, one standing above its strip's bottom and one with a declared pivot: the rows come out in compass order from any order given, every cell is its strip's cell pixel for pixel with no alpha lost, the lowest body pixel of any cell is the ground line and the floating direction stands its gap above it, a soft shadow under the feet is kept below the line with no alpha lost, the cell is the bodies' union about the pivot and touches it where they do, and a declared pivot lands on the cell's centre. A sheet laid by hand — every strip centred in one wide cell and stood on its bottom, the ground line the lowest pixel of any cell — is the engine's sheet cropped by one offset, cell for cell, its ground line the same line. A centre still drawn twice the rows' size and wider than them, with a faint shadow, stands its body on the line at the rows' median standing height, centred, the cell made to hold it and its shadow. Rows of 12 and 10 frames, or of one length at two frame times, are laid and said to differ; each refusal writes nothing.- **Fix: `video-cycle-align` refuses a loop whose strip as cut is missing, by name, before any loop of the set is touched.** Since 2.41.0 a loop's first alignment reads its strip as cut (`<name>.strip.png`, or `follow.source.png` where a follow-through moved it) to record `cycle_align.origin`. A loop directory holding `cycle/` and its `strip.json` without that PNG ended in a `FileNotFoundError` traceback, with no report and `cycle.source/` already copied into every loop of the set. It is now refused as a loop cut before `cell_height_cap` was recorded is: `video-cycle-align: <loop dir>: no <name>.strip.png — …`, exit 1, every loop of the set file for file as it was (under `video-set`, that state's alignment fails and its loops stay as cut). It is still not aligned without its origin, which `video-follow --read-on` carries regions by: put the strip back, or cut the loop again. A loop aligned before keeps the origin it recorded and is aligned again without its strip, as before. [docs/loop-repair.md](docs/loop-repair.md) section 4.- **`tests/video/test_cycle_align.py`** takes the strip out of one loop of a synthetic set: the refusal names it, and both loop directories are as they were, with no `cycle.source/` and no report. A loop aligned once is aligned again without its strip, its origin kept.diff --git a/SKILL.md b/SKILL.mdindex dcd39ea..a073099 100644--- a/SKILL.md+++ b/SKILL.md@@ -103,6 +103,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) || A soft part of a walk loop follows the body (a chest, a belly): an ellipse in the first cell, after `video-cycle-align` — `--read-on <sha256>` where it was read on the cut the loop was aligned from; `--stretch-floor D` to keep a least area | `video-follow` | [video-pipeline](docs/video-pipeline.md#6-follow-through--video-follow) || Where that ellipse is carried in every other cell, and what the move changes there (an arm crossing a chest moves with it; the stretch, the bend and the seam): a record and boards of every cell, nothing moved | `video-follow-inspect` | [video-pipeline](docs/video-pipeline.md#inspecting-a-follow-through--video-follow-inspect) |+| A set's directions on one sheet, standing on one ground line (a 3×3 board, an engine import): rows in compass order S SW W NW N NE E SE from each loop's `--view`, one cell size, every row as cut, an optional centre picture (`--center`) at the rows' standing height; loops of different lengths are laid and said to differ (`same_length` false) — align the set first | `video-set-sheet` | [video-pipeline](docs/video-pipeline.md#7-one-sheet-for-a-set--video-set-sheet) || Compare the currently displayed loop with a final candidate, including after follow-through | `video-loop-compare` | [loop-comparison](docs/loop-comparison.md) || Restore post-processing damage in the current cut from its exact source times, preserving normal cells and playback | `video-source-manifest` → `video-loop-repair` → `video-loop-compare` | [source restoration](docs/loop-comparison.md#restoring-the-active-cut-from-source) || Video sprites from a clip your agent makes with a connected video MCP (ZCRE, 지크) | `video-canvas`, `video-prompt --no-last-frame`, the agent's own MCP tools (quote, user approval, generate, save the mp4), then `video-frames` and `video-loop` (a walk or run with `--anchor motion-auto`, which holds its size), and for a walk or run cut in two or more directions `video-cycle-align --view …` over their loop directories (a set it stops on a loop that may hold two cycles: look at that loop, count its strides, and pass `--cycles <loop>=<k>`; a loop the report lists under `unnamed_feet` — its view could not tell the feet apart, or only by too small a margin (`low-margin`): look at its first candidate frame, say which own foot lands there, and align again with `--foot <loop>=left|right`). `video-set` is not run on this route, so the set stage it runs by default (`--align-cycles auto`) is yours to run. sprite-gen never calls the MCP. Walk, run and jump only: ZCRE's `grok-imagine-video-1.5` has no end frame, so idle, attack and diagonal walks are refused unless `--unpinned` | [video-pipeline](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) |diff --git a/docs/README.md b/docs/README.mdindex 592e600..e4c61de 100644--- a/docs/README.md+++ b/docs/README.md@@ -17,6 +17,8 @@ flowchart LRb1[video-canvas] --> b2[video] --> b3[video-frames] --> b4[video-loop]b5[video-set] -.runs all four.-> b1b4 --> b6[video-cycle-align] --> b7[video-follow]+ b6 --> b8[video-set-sheet]+ b7 --> b8endsubgraph C["C · utilities"]direction LR@@ -38,7 +40,7 @@ flowchart LR| 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` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-follow` (`video-follow-inspect` shows every cell of it and moves nothing); `handed-check` for an item on one side |+| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-follow` (`video-follow-inspect` shows every cell of it and moves nothing), `video-set-sheet` (a set's directions on one sheet, on one ground line); `handed-check` for an item on one side || **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` |@@ -78,7 +80,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, row usage || [prompt-assembly.md](prompt-assembly.md) | What the engine adds to a still or clip prompt and when: the pieces, the 2.22.0 freeze without `--handed`, what counts as already said, and the notes on the caller's own words || [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing) with the user's own credential |-| [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch |+| [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet || [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides || [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the jolt index and its gate, one cycle length per direction set || [frame-interpolation.md](frame-interpolation.md) | Generative in-betweens for sprite frames, recorded as a take |diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex a12cd56..ac9bc79 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -1,6 +1,6 @@# Video → sprite pipeline (engine SSoT)-> Owns: Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch · Index: [docs/README.md](README.md)+> Owns: Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's sheet · Index: [docs/README.md](README.md)One still becomes a whole motion set: the still is padded into the canvas a stateneeds, Grok Imagine animates it in place, the clip is keyed frame by frame, and one@@ -26,6 +26,7 @@ still ──video-canvas──▶ canvas.png ──video──▶ clip.mp4 ─| `sprite-gen video-cycle-align` | `sprite_gen/video/align.py` | the loop directories of one walk or run, one per direction → one cycle length, each loop turned to start on a foot strike, + report ([loop repair](loop-repair.md) section 4) || `sprite-gen video-follow` | `sprite_gen/video/follow.py` | a loop directory + an ellipse → the strip, GIF and WebP with that region following the body ([section 6](#6-follow-through--video-follow)) || `sprite-gen video-follow-inspect` | `sprite_gen/video/follow_inspect.py` | a loop directory + the ellipses `video-follow` takes → a record of where each is carried in every cell and what the move changes there, and two boards of every cell; the loop directory is only read ([section 6](#inspecting-a-follow-through--video-follow-inspect)) |+| `sprite-gen video-set-sheet` | `sprite_gen/video/set_sheet.py` | the loop directories of one set, each with its `--view` → one sheet: a row per direction in compass order, one cell size, one ground line, every row as cut, + a record and an optional centre picture; the loop directories are only read ([section 7](#7-one-sheet-for-a-set--video-set-sheet)) |Wrappers: `scripts/video_canvas.py`, `scripts/video_frames.py`, `scripts/video_loop.py`,`scripts/video_set.py`. Binaries: `ffmpeg`/`ffprobe` (frames), `img2webp` from libwebp@@ -1343,6 +1344,57 @@ sprite-gen video-follow-inspect --loop-dir set/front-run/loop --region 136,164,6They are two files so that whoever says what is inside an ellipse can be given the cells as cutalone, without the answer beside them.+## 7. One sheet for a set — `video-set-sheet`++Each direction of a set is cut on its own, and a strip is the union of its own cycle's bodies: a side+walk's cell is wider than a front one's, a direction with a long ear taller. Laid side by side as they+are — a 3×3 board, a sheet for a game engine — the directions stand at different heights and the board+shows it as it plays. `video-set-sheet` lays them on one sheet that a board or an engine can place as it+is:++```bash+sprite-gen video-set-sheet --loop-dir S/loop --view front --loop-dir W/loop --view side@left \+ --loop-dir N/loop --view back --loop-dir E/loop --view side@right --center base.png --out-dir walk-set --name walk+```++- **Rows.** One per direction given, in the compass order **S, SW, W, NW, N, NE, E, SE** — clockwise from+ the viewer, the order a character turns in — whatever order the loops are given in. `--view` names the+ row, as `video-cycle-align` takes it: `front` S, `back` N, `side@right` E, `side@left` W,+ `front_diagonal@right` SE, `front_diagonal@left` SW, `back_diagonal@right` NE, `back_diagonal@left` NW+ (`@left` faces the screen's left). A strip turned over to face the other way is a direction like any+ other. A direction given twice, a front or back view with a side (its picture turned over is not a+ compass direction) and a count of `--view` other than the loops' are refused before anything is written.+- **One cell.** Each strip is laid on its pivot — the one its sidecar declares (`anchor`: the foot line+ under `video-loop --anchor feet`), else its bottom centre, where `video-loop` stands the feet — and the+ cell is the union of every pixel of every cell of every direction (and of the centre picture), centred+ on that pivot: every cell's pivot is its bottom centre (`anchor` in the record), and no pixel is dropped.+- **One ground line.** `baseline_y` is the lowest body pixel of any cell of any direction — body as+ `video-loop` reads one, alpha 8 and over: that pixel is row `baseline_y − 1` of its cell. A fainter+ pixel (a soft shadow under the feet) is no body: it is kept, and the cell reaches below the line to hold+ it, so `cell_h` is `baseline_y` or more. A direction whose strip leaves room under its feet stands that+ much above the line, as cut: each row's `body_bottom_y` says where its lowest body pixel ends.+- **No row scaled.** Every cell of the sheet is the strip's own cell, pixel for pixel. One size across+ the set is `video-loop --body-height`'s; the sheet never sizes a direction on its own. A board that+ shows the sheet smaller scales it as one, and stands each cell's `baseline_y` on its ground.+- **The centre picture** (`--center`): a transparent still — the set's base, the picture a board shows in+ its middle. It is scaled to the rows' standing height (the median of their `body_h`, against the+ still's own standing height read as `video-loop` reads one: its box at alpha 8 and over), its body+ stood on the ground line and centred on the pivot, alone in a cell of the sheet's size+ (`<name>.center.png`); a fainter shadow under it is kept below the line. A+ still with no transparent background is refused (cut it off first: `sprite-gen cutout`), and so are+ rows without `body_h` beside one.+- **Lengths.** Loops of different lengths, in frames or in frame time, are laid all the same, one frame+ a column and the shorter rows' last cells empty; the record says `same_length: false` and a warning line+ names each direction's length. `video-cycle-align` gives a set one cycle length.++The record, `<name>.sheet.json` (kind `sprite-gen-video-set-sheet`, schema 1): `sheet`, `order` (the+rows' codes), `columns`, `cell_w`, `cell_h`, `baseline_y`, `anchor` (`[cell_w / 2, baseline_y]`),+`same_length`; `rows`, one per row with its `row`, `code`, `view`, `frames`, `delay_ms`, the strip's+`name`, the loop directory as `input`, the strip's `strip_sha256`, `body_h` and `body_bottom_y`; and+`center` — null, or the picture's `png`, `input`, `sha256`, its own `standing_h`, the rows' `body_h` it+was scaled to, the `scale` and its `box` in the cell. The loop directories are only read: no strip,+frame or frame time is changed.+## What the rules were measured onEvery threshold above (the 15 % period tolerance, the 2.0 seam gate, the 0.15diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 4f5c029..4d1d665 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -29,6 +29,7 @@ MODULE_DOMAIN = {'align': 'video','follow': 'video','follow_inspect': 'video',+ 'set_sheet': 'video','compare': 'video','restoration': 'video','source': 'video',@@ -95,8 +96,8 @@ DOMAIN_TITLE = dict(DOMAINS)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-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align", "video-follow", "video-follow-inspect", "handed-check"],- "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set; video-follow for a soft part's follow-through (video-follow-inspect shows every cell of it and moves nothing); handed-check for an item on one side", "doc": "docs/video-pipeline.md"},+ {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align", "video-follow", "video-follow-inspect", "video-set-sheet", "handed-check"],+ "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set; video-follow for a soft part's follow-through (video-follow-inspect shows every cell of it and moves nothing); video-set-sheet lays a set's directions on one sheet on one ground line; handed-check for an item on one side", "doc": "docs/video-pipeline.md"},]TOOL_GROUPS: list[dict[str, object]] = [diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 2f1af9a..698d37b 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -23,6 +23,7 @@ from sprite_gen.video import clip_prompt as video_promptfrom sprite_gen.video import align as video_alignfrom sprite_gen.video import follow as video_followfrom sprite_gen.video import follow_inspect as video_follow_inspect+from sprite_gen.video import set_sheet as video_set_sheetfrom sprite_gen.video import compare as video_comparefrom sprite_gen.video import restoration as video_restorationfrom sprite_gen.video import source as video_source@@ -400,6 +401,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_follow_inspect.add_arguments,video_follow_inspect.run,),+ "video-set-sheet": (+ "The directions of one set on one sheet: rows in compass order (S SW W NW N NE E SE), one cell holding every body box, one ground line under every cell, no row scaled; an optional centre picture stood on the same line at the rows' standing height.",+ video_set_sheet.add_arguments,+ video_set_sheet.run,+ ),"rife": ("install: download the pinned RIFE (rife-ncnn-vulkan, sha256-checked) into the user data directory, where the loop repair finds it.",rife_install.add_arguments,diff --git a/sprite_gen/video/set_sheet.py b/sprite_gen/video/set_sheet.pynew file mode 100644index 0000000..abd26e2--- /dev/null+++ b/sprite_gen/video/set_sheet.py@@ -0,0 +1,272 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video-set-sheet` — the directions of one set on one sheet, standing on one ground line.++A set's loops are cut one direction at a time, each strip its own cell size: a strip is the union of+its own cycle's bodies (`video-loop`), so a side walk is wider than a front one. Laid side by side as+they are, the directions stand at different heights and drift apart as a board plays. This lays them+on one sheet the way a board needs them:++- **Rows in the compass order** S, SW, W, NW, N, NE, E, SE — clockwise from the viewer, the order a+ character turns in — whatever order the loops are given in; a direction not given has no row. Each+ loop's `--view` says which it is, as `video-cycle-align` takes it: `front` is S, `back` N,+ `side|front_diagonal|back_diagonal@right|left` the rest (`@left` faces the screen's left: W, SW, NW).+ A strip turned over to face the other way is a direction like any other.+- **One cell** that holds every pixel of every cell of every direction (and of the centre picture),+ centred on the pivot, so every cell's pivot is its bottom centre. Each strip is laid on its own pivot+ — the one its sidecar declares (`anchor`, the foot line under `video-loop --anchor feet`), else its+ bottom centre — and on its own bottom, where `video-loop` stands the feet.+- **One ground line** (`baseline_y`): the lowest body pixel of any cell of any direction — body as+ `video-loop` reads one, alpha 8 and over (`ALPHA_SOLID`); a fainter pixel (a soft shadow) is kept in the cell+ and is no body. A direction whose strip leaves room under its feet stands that much above it, as cut+ (`body_bottom_y`).+- **No row scaled.** Every cell is the strip's own cell, pixel for pixel; one size across the set is+ `video-loop --body-height`'s, never made here direction by direction.+- **The centre picture** (`--center`, a transparent still such as the set's base): scaled to the rows'+ standing height (the median of their `body_h`, against the still's own height read as `video-loop`+ reads a standing pose), its body stood on the same ground line and centred on the pivot, in a cell of+ its own.++Loops of different lengths (frames or frame time) are laid all the same, the shorter rows' last cells+empty, and said to differ: `same_length` false and a warning. `video-cycle-align` gives a set one length.+The rows' pixels, frames and frame times are read, never changed; the loop directories are only read.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import statistics+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from PIL import Image++from sprite_gen.gen import handedness as handed_mod+from sprite_gen.spec.assets import load_asset+from sprite_gen.spec.runio import atomic_write_text+from sprite_gen.util.resample import resize_cell+from sprite_gen.video import loop as loop_mod+from sprite_gen.video.repair import ALPHA_SOLID++PROG = "video-set-sheet"+KIND = "sprite-gen-video-set-sheet"+SCHEMA = 1+# The compass code of each view, and the order of a sheet's rows: clockwise from the viewer.+ORDER = ("S", "SW", "W", "NW", "N", "NE", "E", "SE")+CODES = {"front": "S", "front_diagonal@left": "SW", "side@left": "W", "back_diagonal@left": "NW", "back": "N",+ "back_diagonal@right": "NE", "side@right": "E", "front_diagonal@right": "SE"}+++@dataclass(frozen=True)+class Row:+ """One direction of the set: its loop's strip cells as cut, the pivot it stands on and its timing."""++ code: str+ view: str+ dir: Path+ name: str+ frames: tuple[Image.Image, ...]+ anchor: tuple[float, float]+ delay_ms: float+ body_h: int | None+ sha256: str++ def origin(self) -> tuple[int, int]:+ """Where each cell's top-left corner goes with the set's pivot at (0, 0). A pivot between two pixels+ (an odd width's centre) is taken at the one right of it, so the cell lies half a pixel left of it."""+ return -math.ceil(self.anchor[0]), -math.ceil(self.anchor[1])+++def code_of(view: str) -> str:+ """The compass code of a `--view`, or a refusal: a front or back view turned over faces no side."""+ name, _, facing = view.partition("@")+ handed_mod.validate_view(name, facing or None)+ code = CODES.get(view)+ if code is None:+ raise SystemExit(f"{PROG}: --view {view}: a front or back view faces no side on a sheet — its picture turned over is "+ f"not a compass direction; give {name}")+ return code+++def read_row(loop_dir: Path, view: str) -> Row:+ """A loop directory's strip as one direction: the `<name>.strip.json` it holds and the strip beside it,+ read as the asset loader reads a loop strip (`spec.assets.load_asset`: its cells, frame time and pivot)."""+ code = code_of(view)+ d = loop_dir.expanduser().resolve()+ metas = sorted(d.glob("*.strip.json"))+ if len(metas) != 1:+ raise SystemExit(f"{PROG}: {d}: expected one <name>.strip.json (a video-loop output directory), found {len(metas)}")+ name = metas[0].name[: -len(".strip.json")]+ strip = d / f"{name}.strip.png"+ if not strip.is_file():+ raise SystemExit(f"{PROG}: {d}: no {strip.name} beside {metas[0].name}")+ try:+ seq = load_asset(metas[0])+ meta = json.loads(metas[0].read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise SystemExit(f"{PROG}: {d}: {exc}") from exc+ body_h = meta.get("body_h")+ return Row(code=code, view=view, dir=d, name=name, frames=tuple(seq.frames), anchor=(float(seq.anchor[0]), float(seq.anchor[1])),+ delay_ms=meta["delay_ms"], body_h=int(body_h) if body_h is not None else None,+ sha256=hashlib.sha256(strip.read_bytes()).hexdigest())+++def _box(im: Image.Image) -> tuple[int, int, int, int] | None:+ """Every pixel of a cell that is not fully transparent: nothing outside it is dropped from the sheet."""+ return im.getchannel("A").getbbox()+++def _body(im: Image.Image) -> tuple[int, int, int, int] | None:+ """The body's box: alpha ALPHA_SOLID and over, as video-loop reads a body (its crop, `body_h`)."""+ return im.getchannel("A").point(lambda v: 255 if v >= ALPHA_SOLID else 0).getbbox()+++def _centre(path: Path, rows: list[Row]) -> tuple[Image.Image, dict[str, Any]]:+ """The centre picture cropped to its pixels and scaled to the rows' standing height, with its record."""+ p = path.expanduser().resolve()+ try:+ still = Image.open(p).convert("RGBA")+ except OSError as exc:+ raise SystemExit(f"{PROG}: --center {p}: {exc}") from exc+ if still.getchannel("A").getextrema()[0] == 255:+ raise SystemExit(f"{PROG}: --center {p}: no transparent background — cut it off first (sprite-gen cutout)")+ missing = [str(r.dir) for r in rows if r.body_h is None]+ if missing:+ raise SystemExit(f"{PROG}: --center needs the rows' standing height, and {', '.join(missing)} has no body_h in its "+ "strip metadata — cut it with video-loop")+ target = round(statistics.median(r.body_h for r in rows)) # type: ignore[misc]+ try:+ standing = loop_mod.standing_height(p)+ except SystemExit as exc:+ raise SystemExit(f"{PROG}: --center {p}: no body in it to stand on the ground line "+ f"(every pixel under alpha {ALPHA_SOLID})") from exc+ scale = target / standing+ crop = still.crop(_box(still))+ scaled = resize_cell(crop, (max(1, round(crop.width * scale)), max(1, round(crop.height * scale))))+ scaled = scaled.crop(_box(scaled))+ if _body(scaled) is None:+ raise SystemExit(f"{PROG}: --center {p}: no body left at {scale:.4f} of its size to stand on the ground line")+ return scaled, {"input": str(p), "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "standing_h": standing,+ "body_h": target, "scale": round(scale, 4)}+++def lay(rows: list[Row], centre: Image.Image | None = None) -> tuple[Image.Image, Image.Image | None, dict[str, Any]]:+ """The sheet (rows in the given order, a frame a column), the centre picture's cell, and the geometry:+ `cell_w`, `cell_h`, `baseline_y`, `anchor`, `columns`, each row's `body_bottom_y`, the centre's `box`.+ Coordinates are the set's: its pivot at (0, 0), every row's own pivot laid on it."""+ boxes: list[tuple[int, int, int, int]] = []+ bottoms = []+ for row in rows:+ ox, oy = row.origin()+ bodies = [b[3] + oy for b in map(_body, row.frames) if b]+ if not bodies:+ raise SystemExit(f"{PROG}: {row.dir}: no cell of its strip holds a body (every pixel under alpha {ALPHA_SOLID})")+ boxes += [(b[0] + ox, b[1] + oy, b[2] + ox, b[3] + oy) for b in map(_box, row.frames) if b]+ bottoms.append(max(bodies))+ ground = max(bottoms)+ place = None+ if centre is not None:+ # its body's box centred on the pivot and its body's lowest pixel on the ground line+ body = _body(centre)+ place = (-math.ceil((body[0] + body[2]) / 2), ground - body[3]) # type: ignore[index]+ boxes.append((place[0], place[1], place[0] + centre.width, place[1] + centre.height))+ half = max(1, -min(b[0] for b in boxes), max(b[2] for b in boxes))+ left, top = -half, min(b[1] for b in boxes)+ cell_w, cell_h = 2 * half, max(b[3] for b in boxes) - top+ columns = max(len(row.frames) for row in rows)+ sheet = Image.new("RGBA", (cell_w * columns, cell_h * len(rows)), (0, 0, 0, 0))+ for r, row in enumerate(rows):+ ox, oy = row.origin()+ for k, frame in enumerate(row.frames):+ # cells never overlap, so each is copied as it is (a crop past the strip's edge is transparent)+ sheet.paste(frame.crop((left - ox, top - oy, left - ox + cell_w, top - oy + cell_h)), (k * cell_w, r * cell_h))+ geometry: dict[str, Any] = {"cell_w": cell_w, "cell_h": cell_h, "baseline_y": ground - top, "anchor": [half, ground - top],+ "columns": columns, "body_bottom_y": [b - top for b in bottoms]}+ cell = None+ if centre is not None and place is not None:+ cell = Image.new("RGBA", (cell_w, cell_h), (0, 0, 0, 0))+ x, y = place[0] - left, place[1] - top+ cell.paste(centre, (x, y))+ geometry["center_box"] = [x, y, x + centre.width, y + centre.height]+ return sheet, cell, geometry+++def make_sheet(loop_dirs: list[Path], views: list[str] | None, *, out_dir: Path, name: str = "set",+ center: Path | None = None) -> dict[str, Any]:+ """Lay the loops on one sheet and write `<name>.sheet.png`, `<name>.sheet.json` and, with a centre+ picture, `<name>.center.png` into `out_dir`. Everything is read and checked before anything is written."""+ views = list(views or [])+ if not loop_dirs:+ raise SystemExit(f"{PROG}: at least one --loop-dir")+ if len(views) != len(loop_dirs):+ raise SystemExit(f"{PROG}: {len(views)} --view for {len(loop_dirs)} --loop-dir; give one per loop, in the same order")+ read = [read_row(Path(d), v) for d, v in zip(loop_dirs, views)]+ seen: dict[str, Row] = {}+ for row in read:+ if row.code in seen:+ raise SystemExit(f"{PROG}: --view {row.view} is given twice ({seen[row.code].dir}, {row.dir}); one loop per direction")+ seen[row.code] = row+ rows = [seen[c] for c in ORDER if c in seen]+ centre, centre_record = _centre(Path(center), rows) if center is not None else (None, None)+ sheet, centre_cell, geometry = lay(rows, centre)+ same = len({(len(r.frames), r.delay_ms) for r in rows}) == 1+ record: dict[str, Any] = {+ "kind": KIND, "schema": SCHEMA, "sheet": f"{name}.sheet.png", "order": [r.code for r in rows],+ "columns": geometry["columns"], "cell_w": geometry["cell_w"], "cell_h": geometry["cell_h"],+ "baseline_y": geometry["baseline_y"], "anchor": geometry["anchor"], "same_length": same,+ "rows": [{"row": i, "code": r.code, "view": r.view, "frames": len(r.frames), "delay_ms": r.delay_ms, "name": r.name,+ "input": str(r.dir), "strip_sha256": r.sha256, "body_h": r.body_h, "body_bottom_y": bottom}+ for i, (r, bottom) in enumerate(zip(rows, geometry["body_bottom_y"]))],+ "center": ({"png": f"{name}.center.png", **centre_record, "box": geometry["center_box"]} if centre_record else None),+ }+ out = Path(out_dir).expanduser()+ out.mkdir(parents=True, exist_ok=True)+ sheet.save(out / record["sheet"])+ if centre_cell is not None:+ centre_cell.save(out / record["center"]["png"])+ atomic_write_text(out / f"{name}.sheet.json", json.dumps(record, indent=2) + "\n")+ if not same:+ print(f"{PROG}: warning: the directions differ in length — "+ + ", ".join(f"{r.code} {len(r.frames)} frames at {r.delay_ms:g} ms" for r in rows)+ + "; the sheet is laid all the same, the shorter rows' last cells empty (same_length false). "+ "video-cycle-align gives a set one cycle length", file=sys.stderr)+ return record+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--loop-dir", action="append", type=Path, required=True,+ help="a video-loop output directory (its <name>.strip.png and .strip.json), aligned or not, one per direction "+ "(repeat); a strip turned over to face the other way is a direction like any other")+ parser.add_argument("--view", action="append", required=True,+ help="the view of each --loop-dir, in the same order, as video-cycle-align takes it: front (S), back (N), or "+ "side|front_diagonal|back_diagonal@right|left (E W, SE SW, NE NW); it names the row")+ parser.add_argument("--center", type=Path,+ help="a transparent still for the middle of a board (the set's base): scaled to the rows' standing height "+ "(the median of their body_h) and stood on the same ground line, written as <name>.center.png")+ parser.add_argument("--out-dir", type=Path, required=True, help="where <name>.sheet.png, <name>.sheet.json (and <name>.center.png) go")+ parser.add_argument("--name", default="set", help="the files' stem (default set)")+++def run(**kwargs: object) -> int:+ record = make_sheet(list(kwargs["loop_dir"]), kwargs.get("view"), out_dir=Path(kwargs["out_dir"]), # type: ignore[arg-type]+ name=str(kwargs.get("name") or "set"), center=kwargs.get("center")) # type: ignore[arg-type]+ out = Path(kwargs["out_dir"]).expanduser() # type: ignore[arg-type]+ print(json.dumps({"sheet": str(out / record["sheet"]), **{k: record[k] for k in ("order", "columns", "cell_w", "cell_h",+ "baseline_y", "same_length")},+ "lengths": {r["code"]: r["frames"] for r in record["rows"]},+ "center": str(out / record["center"]["png"]) if record["center"] else None}, ensure_ascii=False, indent=2))+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog=f"sprite-gen {PROG}", description=__doc__)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())