Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(ui-kit): the report names each element PNG from its own directory
Soohong Kim9e70fa411e15
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80d9b31..cafef3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,9 +6,9 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).-- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json`: its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.+- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.- **New: `game-pack` request and manifest version 2 with `images`, `tiles` and `ui`.** Single images (props) are atlas frames with an anchor and an optional footprint (`"base"` measures where the image meets the ground); tiles are their own PNG and WebP files with their stored and on-screen sizes; `ui.kit` reads a `ui-kit` report into nine-slice entries (frame, size, stretch, insets, padding) and `ui.icons` adds fixed icons. Every number is in pixels of the stored image. A version 1 request is packed byte for byte as before, and a version 1 request naming the new sections is refused ([game-pack](docs/game-pack.md#version-2-images-tiles-and-ui)).-- **Tests** — `tests/background/test_tile_xy.py` (an exact doubly periodic crop, a join that stays visible on one axis names that axis, the cyclic seam), `tests/frames/test_alpha_floor.py` (a haze ring cleared, thin strokes and their anti-aliased edges kept), `tests/frames/test_ui_kit.py` (a synthetic sheet on the layout: insets to the pixel over corner ornaments, a long flourish, a bar's end gem and cap; badge padding inside its ring; a packed kit at four scales keeps ornament fringes out of the stretched middle), `tests/frames/test_slice_sheet_transparent.py`, `tests/compose/test_game_pack_v2.py` (the manifest field by field, refusals, and a version 1 manifest and page pixels frozen from 2.44.0), `tests/compose/test_game_pack_audio.py` (a version 1 pack with sound keeps its file list, manifest bytes and page pixels from 2.44.0; a version 2 pack with sound adds only its tile files) and the `--layout-guide ui-kit` cases in `tests/gen/test_layout_guide.py`.+- **Tests** — `tests/background/test_tile_xy.py` (an exact doubly periodic crop, a join that stays visible on one axis names that axis, the cyclic seam), `tests/frames/test_alpha_floor.py` (a haze ring cleared, thin strokes and their anti-aliased edges kept), `tests/frames/test_ui_kit.py` (a synthetic sheet on the layout: insets to the pixel over corner ornaments, a long flourish, a bar's end gem and cap; badge padding inside its ring; a packed kit at four scales keeps ornament fringes out of the stretched middle; a report in, beside, below or above `--out-dir` names the PNGs from its own directory and packs the same bytes), `tests/frames/test_slice_sheet_transparent.py`, `tests/compose/test_game_pack_v2.py` (the manifest field by field, refusals, and a version 1 manifest and page pixels frozen from 2.44.0), `tests/compose/test_game_pack_audio.py` (a version 1 pack with sound keeps its file list, manifest bytes and page pixels from 2.44.0; a version 2 pack with sound adds only its tile files) and the `--layout-guide ui-kit` cases in `tests/gen/test_layout_guide.py`.- Bump audio processing recipe to version 4, measure BS.1770-4 loudness over normalized PCM frames and gated blocks, support a peak-limited loudness goal, normalize loudnorm-unanalysable short clips via limiter passes instead of refusing them, encode AAC using `-aac_coder fast`, record `normalization.pcm_lufs` and `pcm_true_peak_dbtp` required to load version 4 bundles, keep recipe version 3 bundles loadable in game packs by their own rule (target loudness, decoded files re-measured with loudnorm), reject recipe version 1-2 bundles, and reject recipe version 1-3 output directories in `sprite-gen sound` while reusing cached provider audio.- Bump audio processing recipe to version 3, require `ffprobe` on `PATH`, export M4A with `-movie_timescale 48000`, and validate AAC stream duration with `ffprobe`.diff --git a/docs/ui-kit.md b/docs/ui-kit.mdindex 209fe7c..57d6fcd 100644--- a/docs/ui-kit.md+++ b/docs/ui-kit.md@@ -38,7 +38,7 @@ sprite-gen ui-kit --sheet uikit.png --out-dir ui/The command writes `ui/<element>.png` for every element of the layout and `ui/ui-kit.json`. It never changes the sheet and refuses an output directory that holds the sheet. Options:* `--alpha-floor N` (default `64`, `0` turns it off) and `--alpha-edge N` (default `2`): the [alpha cleanup](#alpha-cleanup) that runs before anything is cut.-* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`).+* `--report PATH`: write the JSON report elsewhere (default `<out-dir>/ui-kit.json`); it must end in `.json`. Each element's `file` in it then leads from the report's directory to the PNG in `--out-dir`.1. **Alpha cleanup.** Faint haze between elements would join them, so it is cleared first (below).2. **Parts.** Pixels with alpha above zero form 8-connected parts. A part smaller than 16 pixels is dropped and counted.@@ -111,13 +111,14 @@ Solid pixels and edge pixels are never changed, so a stroke stays whole as long}```-`box` is the layout box scaled to this sheet and `rect` the element's bounding box, both in sheet pixels. `file` is relative to the report. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.+`box` is the layout box scaled to this sheet and `rect` the element's bounding box, both in sheet pixels. `file` is the element PNG's path from the report's own directory, with `/` separators: `panel.png` when the report is in `--out-dir` (the default), `../elements/panel.png` for `--out-dir elements --report reports/kit.json`. A reader joins it to the report's directory, as [`game-pack`](game-pack.md#version-2-request) does, so a report and its elements move together. `size`, `insets` and `padding` are in pixels of the element PNG. Elements appear in layout order. `status` is `needs-review` when any `review_reasons` apply; the PNGs are written either way, so the elements can be inspected.Like every measurement here, `pass` means the numbers found nothing to flag. Look at the elements stretched to a few sizes before shipping them.## Python API-* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written without `sheet`.+* `sprite_gen.frames.ui_kit.split_ui_kit(image, *, alpha_floor=64, alpha_edge=2) -> (elements, report)`: the elements as images by name, and the report as written to its default place, `<out-dir>/ui-kit.json` (each `file` is `<element>.png`), without `sheet`.+* `sprite_gen.frames.ui_kit.report_file(report, png) -> str` and `element_path(report, file) -> Path`: the `file` a report at `report` gives an element PNG, and the PNG a report's `file` names.* `sprite_gen.frames.ui_kit.measure_insets(image, stretch) -> (insets, notes)` and `measure_padding(image) -> (padding, notes)`: the measures above on one element image, with the review notes they raise.* `sprite_gen.frames.ui_kit.boxes(size)`, `draw_guide(path, size)` and `guide_text()`: the layout, the guide image and its prompt paragraph.* `sprite_gen.frames.alpha_floor.clear_haze(image, *, floor=64, edge=2) -> (image, report)`.diff --git a/sprite_gen/compose/game_pack.py b/sprite_gen/compose/game_pack.pyindex 5e3f889..fae54dd 100644--- a/sprite_gen/compose/game_pack.py+++ b/sprite_gen/compose/game_pack.py@@ -21,7 +21,7 @@ from PIL import Imagefrom sprite_gen.audio.manifest import load as load_soundfrom sprite_gen.audio.playback import player as audio_player-from sprite_gen.frames.ui_kit import REPORT_KIND as UI_KIT_KIND, STRETCHES, measure_insets+from sprite_gen.frames.ui_kit import REPORT_KIND as UI_KIT_KIND, STRETCHES, element_path, measure_insetsfrom sprite_gen._deps import npfrom sprite_gen.spec.assets import finite, load_asset, load_asset_statesfrom sprite_gen.util.resample import resize_cell@@ -241,7 +241,7 @@ def _ui_kit(path, scale, page_size):raise ValueError(f"{key}: stretch {stretch} needs {', '.join(fixed)} insets of 0")if not isinstance(record.get("file"), str) or not record["file"]:raise ValueError(f"{key}: the report names no file")- sequence = _still(path.parent / record["file"], key)+ sequence = _still(element_path(path, record["file"]), key)image = sequence.frames[0]if record.get("size") != {"w": image.width, "h": image.height}:raise ValueError(f"{key}: the report's size does not match {record['file']}")diff --git a/sprite_gen/frames/ui_kit.py b/sprite_gen/frames/ui_kit.pyindex 6c979ab..9e4166e 100644--- a/sprite_gen/frames/ui_kit.py+++ b/sprite_gen/frames/ui_kit.py@@ -4,7 +4,8 @@docs/ui-kit.md is the contract. One table (`LAYOUT`) is the layout: `gen --layout-guide ui-kit`draws it (`draw_guide`) and says it (`guide_text`), and the splitter cuts along it. The sheet'salpha haze is cleared first (`alpha_floor.clear_haze`), parts are assigned to boxes by centroid,-and each element's insets and content padding are measured on its own pixels.+and each element's insets and content padding are measured on its own pixels. The report names each+element PNG by its path from the report's own directory (`report_file`, `element_path`)."""from __future__ import annotations@@ -12,6 +13,7 @@ from __future__ import annotationsimport argparseimport ioimport json+import osfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -251,7 +253,8 @@ def _parts(mask: Any) -> list[dict[str, Any]]:def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,alpha_edge: int = 2) -> tuple[dict[str, Image.Image], dict[str, Any]]:- """Cut ``image`` along the layout: element images by name, and the report (without the sheet path)."""+ """Cut ``image`` along the layout: element images by name, and the report as written to its default+ place, ``<out-dir>/ui-kit.json`` (each ``file`` is ``<element>.png``), without the sheet path."""rgba = image.convert("RGBA")width, height = rgba.sizeif abs(width - height) > 0.01 * max(width, height):@@ -320,6 +323,16 @@ def split_ui_kit(image: Image.Image, *, alpha_floor: int = 64,return elements, report+def report_file(report: Path, png: Path) -> str:+ """The ``file`` a report at ``report`` gives ``png``: its path from the report's directory, ``/``-separated."""+ return Path(os.path.relpath(png, Path(report).parent)).as_posix()+++def element_path(report: Path, file: str) -> Path:+ """The element PNG that the ``file`` of a report at ``report`` names."""+ return Path(report).parent / file++def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: int = 2,report: Path | None = None) -> int:sheet = Path(sheet).expanduser().resolve()@@ -329,12 +342,17 @@ def _publish(*, sheet: Path, out_dir: Path, alpha_floor: int = 64, alpha_edge: iraise ValueError(f"sheet is not a file: {sheet}")if out_dir == sheet.parent or out_dir in sheet.parents or report_path == sheet:raise ValueError("the output directory must not hold the sheet; choose a new directory")+ if report_path.suffix.lower() != ".json":+ raise ValueError("--report must be a .json path")with Image.open(sheet) as image:if image.format != "PNG" or getattr(image, "n_frames", 1) != 1:raise ValueError("--sheet must be a single-frame PNG")elements, measured = split_ui_kit(image, alpha_floor=alpha_floor, alpha_edge=alpha_edge)written = {"kind": measured["kind"], "version": measured["version"], "sheet": str(sheet)}written.update((key, value) for key, value in measured.items() if key not in written)+ # wherever --report puts the report, each `file` leads from it to the PNG written in out_dir+ written["elements"] = {name: {**record, "file": report_file(report_path, out_dir / record["file"])}+ for name, record in measured["elements"].items()}payloads: dict[Path, bytes | str] = {}for name, element in elements.items():png = io.BytesIO()@@ -364,7 +382,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:help="alpha haze cleanup floor, 1..255 (0 turns the cleanup off)")parser.add_argument("--alpha-edge", type=int, default=2,help="faint pixels this close to a solid pixel are its edge and are kept")- parser.add_argument("--report", type=Path, help="JSON report (default: <out-dir>/ui-kit.json)")+ parser.add_argument("--report", type=Path,+ help="JSON report (default: <out-dir>/ui-kit.json); its element paths are relative to it")def run(**kwargs: Any) -> int:diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.pyindex 73d1405..919f0e3 100644--- a/tests/frames/test_ui_kit.py+++ b/tests/frames/test_ui_kit.py@@ -15,6 +15,7 @@ import numpy as npimport pytestfrom PIL import Image+from sprite_gen import clifrom sprite_gen.compose import game_packfrom sprite_gen.frames import ui_kit@@ -265,6 +266,51 @@ def test_cli_refuses_to_write_into_the_sheets_directory_over_the_sheet(tmp_path)ui_kit.main(["--sheet", str(sheet), "--out-dir", str(tmp_path)])+# --out-dir, --report (None: the default <out-dir>/ui-kit.json) and the `file` the report gives the+# panel: the PNG's path from the report's own directory, with "/" separators+REPORT_PLACES = [+ ("ui", None, "panel.png"),+ ("elements", "reports/kit.json", "../elements/panel.png"),+ ("ui", "ui/reports/kit.json", "../panel.png"),+ ("reports/elements", "reports/kit.json", "elements/panel.png"),+]+++def test_a_report_anywhere_names_the_written_pngs_and_packs_the_same(tmp_path):+ image, _ = synthetic_sheet()+ sheet = tmp_path / "uikit.png"+ image.save(sheet)+ packs = []+ for index, (out_dir, report, panel) in enumerate(REPORT_PLACES):+ root = tmp_path / f"place-{index}"+ args = ["ui-kit", "--sheet", str(sheet), "--out-dir", str(root / out_dir)]+ if report is not None:+ args += ["--report", str(root / report)]+ assert cli.main(args) == 0+ report_path = root / (report or f"{out_dir}/ui-kit.json")+ written = json.loads(report_path.read_text())+ assert written["elements"]["panel"]["file"] == panel+ for name, entry in written["elements"].items():+ assert (report_path.parent / entry["file"]).resolve() == (root / out_dir / f"{name}.png").resolve()+ request = root / "game.json"+ request.write_text(json.dumps({"version": 2, "ui": {"kit": report_path.relative_to(root).as_posix()}}))+ assert cli.main(["game-pack", "--request", str(request), "--out-dir", str(root / "pack")]) == 0+ packs.append({path.name: path.read_bytes() for path in (root / "pack").iterdir()})+ assert len(json.loads(packs[0]["game-pack.json"])["ui"]["nine_slice"]) == len(ui_kit.LAYOUT)+ assert packs == [packs[0]] * len(REPORT_PLACES)+++def test_a_report_path_that_is_not_json_is_refused_before_anything_is_written(tmp_path):+ image, _ = synthetic_sheet()+ sheet = tmp_path / "uikit.png"+ image.save(sheet)+ out = tmp_path / "ui"+ # the report would replace an element PNG of the same name+ with pytest.raises(SystemExit, match=r"--report must be a \.json path"):+ ui_kit.main(["--sheet", str(sheet), "--out-dir", str(out), "--report", str(out / "panel.png")])+ assert not out.exists()++def test_guide_draws_every_box_and_the_text_names_every_element(tmp_path):path = tmp_path / "guide.png"cell = ui_kit.draw_guide(path, (1024, 1024))