Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test: pixel-draw's gates ask the engine's own judgments - G3 the transparent background classify_raw_alpha reads a raw by (alpha_verdict), G4 the tile join background-tile measures (inspect_tile, along x and y), G5 the lone pixels the YCbCr matte cleanup erases (isolated_dots: no opaque pixel among eight neighbours, so a diagonal stroke is joined); each gate calls its judgment and says what it answers, and the pick sheet shows transparency on the engine's preview checker
Soohong Kim0e3de373db6c
diff --git a/tests/background/test_tile.py b/tests/background/test_tile.pyindex 9d4b03d..8379e24 100644--- a/tests/background/test_tile.py+++ b/tests/background/test_tile.py@@ -1,5 +1,6 @@# SPDX-License-Identifier: Apache-2.0-"""Synthetic pixel oracles for periodic cropping and RGBA quilting."""+"""Synthetic pixel oracles for periodic cropping and RGBA quilting. The join measure, `inspect_tile`,+is also `pixel-draw`'s G4 tile seam (below)."""import json@@ -156,3 +157,54 @@ def test_inspection_handles_one_pixel_and_rejects_empty_or_bad_axis():(Image.new("RGBA", (2, 2)), "diagonal")]:with pytest.raises(ValueError):inspect_tile(image, axis)+++GRASS, INK = (78, 144, 56, 255), (40, 30, 46, 255)+++def tile_calls(monkeypatch):+ """Every call to the join measure: the image and axis it was asked about, and what it answered."""+ from sprite_gen.background import tile as tile_module++ real, seen = tile_module.inspect_tile, []++ def recording(image, axis="x"):+ seen.append((image.copy(), axis, real(image, axis)))+ return seen[-1][2]++ monkeypatch.setattr(tile_module, "inspect_tile", recording)+ return seen+++def test_pixel_draw_g4_asks_it_of_each_frame_along_both_axes(tile_calls):+ """`pixel-draw`'s G4 tile seam is this measure, asked of a tile frame along x and along y; what it+ says needs review warns, in its words, and nothing fails."""+ from sprite_gen.gen import pixel_grid as pg+ from sprite_gen.gen.pixel_gates import evaluate++ seam = [[GRASS if x < 7 else INK for x in range(8)] for _ in range(8)]+ gates = evaluate({"tile": seam}, kind="tile", rule=pg.palette_rule("free"), walk_cycle=False)+ assert [axis for _, axis, _ in tile_calls] == ["x", "y"]+ assert all(image.tobytes() == pg.image_of(seam).tobytes() for image, _, _ in tile_calls)+ x_report, y_report = (report for _, _, report in tile_calls)+ assert x_report["status"] == "needs-review" and y_report["status"] == "pass"+ assert gates["ok"] and gates["G4"]["warn"] and gates["G4"]["needs_review"] == ["tile x"]+ assert gates["G4"]["frames"] == {"tile": {"x": x_report, "y": y_report}}+ assert gates["warnings"] == ["G4 tile seam (look at tiled-3x3.png): tile x: "+ "Wrap edge color difference exceeds interior variation."]+++def test_pixel_draw_g4_says_what_it_answers(monkeypatch):+ """Answer that every join needs review: G4 warns of a tile that wraps cleanly, and still passes it."""+ from sprite_gen.background import tile as tile_module+ from sprite_gen.gen import pixel_grid as pg+ from sprite_gen.gen.pixel_gates import evaluate++ real = tile_module.inspect_tile+ monkeypatch.setattr(tile_module, "inspect_tile", lambda image, axis="x": {+ **real(image, axis), "status": "needs-review", "review_reasons": ["Said so."]})+ flat = [[GRASS] * 8 for _ in range(8)]+ gates = evaluate({"tile": flat}, kind="tile", rule=pg.palette_rule("free"), walk_cycle=False)+ assert gates["ok"] and gates["G4"]["needs_review"] == ["tile x", "tile y"]+ assert gates["warnings"] == ["G4 tile seam (look at tiled-3x3.png): tile x: Said so.; tile y: Said so."]diff --git a/tests/frames/test_isolated_dots.py b/tests/frames/test_isolated_dots.pynew file mode 100644index 0000000..1d794e2--- /dev/null+++ b/tests/frames/test_isolated_dots.py@@ -0,0 +1,95 @@+# SPDX-License-Identifier: Apache-2.0+"""A lone pixel is one judgment, `frames.extract.isolated_dots`: an opaque pixel with no opaque pixel+among its eight neighbours - one that touches another only at a corner is joined to it, as every+component the engine reads is. The YCbCr matte's cleanup erases a matte's dots by it+(`_cleanup_alpha_ycc`, byte for byte as before: tests/frames/test_extract_perf_equivalence.py), and+`pixel-draw`'s G5 counts a grid's stray pixels by it."""+from __future__ import annotations++from PIL import Image++import sprite_gen.frames.extract as extract_module+from sprite_gen.frames.extract import isolated_dots+from sprite_gen.gen import pixel_grid as pg+from sprite_gen.gen.pixel_gates import evaluate++INK, CLEAR = (40, 30, 46, 255), (0, 0, 0, 0)+FREE16 = pg.palette_rule("free")+++def mask(rows: list[str]) -> Image.Image:+ """An L mask, 1 where a row says `#`."""+ image = Image.new("L", (len(rows[0]), len(rows)))+ image.putdata([1 if c == "#" else 0 for row in rows for c in row])+ return image+++def marked(image: Image.Image) -> list[str]:+ values = list(image.getdata())+ return ["".join("#" if values[y * image.width + x] else "." for x in range(image.width)) for y in range(image.height)]+++def stroke_and_speck(size: int = 16):+ """A block (rows and columns 6..11), a one-pixel diagonal stroke off its top-left corner, and a speck."""+ frame = [[INK if 6 <= y <= 11 and 6 <= x <= 11 else CLEAR for x in range(size)] for y in range(size)]+ for step in (3, 4, 5):+ frame[step][step] = INK+ frame[2][12] = INK+ return frame+++def test_a_dot_has_no_opaque_neighbour_of_eight():+ dots = isolated_dots(mask(["#.....",+ ".#....",+ "......",+ "...#..",+ "......",+ ".....#"]))+ assert marked(dots) == ["......",+ "......",+ "......",+ "...#..",+ "......",+ ".....#"]+++def test_the_matte_cleanup_erases_exactly_the_dots():+ rows = ["..........",+ ".####.....",+ ".####..#..",+ ".####.....",+ "......#...",+ ".......#..",+ "..#.......",+ ".........."]+ image = Image.new("RGBA", (len(rows[0]), len(rows)))+ image.putdata([INK if c == "#" else CLEAR for row in rows for c in row])+ dots = marked(isolated_dots(image.getchannel("A").point(lambda a: 1 if a > 10 else 0)))+ extract_module._cleanup_alpha_ycc(image)+ after = marked(image.getchannel("A"))+ erased = [(x, y) for y, row in enumerate(rows) for x, c in enumerate(row) if c == "#" and after[y][x] == "."]+ assert erased == [(x, y) for y, row in enumerate(dots) for x, c in enumerate(row) if c == "#"] == [(7, 2), (2, 6)]+++def test_pixel_draw_g5_counts_them(monkeypatch):+ real, seen = extract_module.isolated_dots, []++ def recording(op):+ seen.append((op.copy(), real(op)))+ return seen[-1][1]++ monkeypatch.setattr(extract_module, "isolated_dots", recording)+ frame = stroke_and_speck()+ gates = evaluate({"f": frame}, kind="icon", rule=FREE16, walk_cycle=False)+ ((op, dots),) = seen+ assert list(op.getdata()) == [1 if p[3] >= 128 else 0 for row in frame for p in row]+ assert gates["G5"]["isolated_pixels"] == dots.histogram()[255] == 1+ assert gates["warnings"] == ["G5 1 stray pixel(s) with no opaque neighbour"]+++def test_pixel_draw_g5_says_what_it_answers(monkeypatch):+ """Answer that every opaque pixel is a dot: G5 counts every one, and still only warns."""+ monkeypatch.setattr(extract_module, "isolated_dots", lambda op: op.point(lambda v: 255 if v else 0))+ gates = evaluate({"f": stroke_and_speck()}, kind="icon", rule=FREE16, walk_cycle=False)+ assert gates["ok"] and gates["G5"]["isolated_pixels"] == 36 + 3 + 1+ assert gates["warnings"] == ["G5 40 stray pixel(s) with no opaque neighbour"]diff --git a/tests/gen/test_alpha_verdict.py b/tests/gen/test_alpha_verdict.pynew file mode 100644index 0000000..15a217e--- /dev/null+++ b/tests/gen/test_alpha_verdict.py@@ -0,0 +1,89 @@+# SPDX-License-Identifier: Apache-2.0+"""Whether a picture's background is really transparent is one judgment, `gen.chroma.alpha_verdict`+(docs/gen.md): `real-alpha` when at least 5 % of its pixels and half of its one-pixel border are+alpha 0, `no-alpha` when no pixel is, `ambiguous` between. `classify_raw_alpha` asks it of a generated+raw before a chroma key runs, and `pixel-draw`'s G3 of every frame it drew: a sprite or icon frame must+be `real-alpha`, with something drawn and its four corners clear; a tile frame `no-alpha`."""+from __future__ import annotations++import pytest+from PIL import Image++from sprite_gen.gen import chroma+from sprite_gen.gen import pixel_grid as pg+from sprite_gen.gen.pixel_gates import evaluate++INK, CLEAR = (40, 30, 46, 255), (0, 0, 0, 0)+FREE16 = pg.palette_rule("free")+++def icon(size: int = 16):+ """A block of ink rows 3..12, columns 4..11, on a clear canvas."""+ return [[INK if 3 <= y <= 12 and 4 <= x <= 11 else CLEAR for x in range(size)] for y in range(size)]+++def calls(monkeypatch):+ """Every call to the judgment: the alpha band it was asked about and what it answered."""+ real, seen = chroma.alpha_verdict, []++ def recording(alpha):+ seen.append((alpha.copy(), real(alpha)))+ return seen[-1][1]++ monkeypatch.setattr(chroma, "alpha_verdict", recording)+ return seen+++def test_a_generated_raw_is_read_by_it(tmp_path, calls):+ image = Image.new("RGBA", (20, 20), (255, 0, 255, 255))+ for y in range(4, 16):+ for x in range(4, 16):+ image.putpixel((x, y), (0, 0, 0, 0))+ path = tmp_path / "raw.png"+ image.save(path)+ stats = chroma.classify_raw_alpha(path)+ ((alpha, verdict),) = calls+ assert alpha.tobytes() == image.getchannel("A").tobytes()+ assert verdict == {"verdict": "ambiguous", "alpha_zero_pct": 36.0, "border_alpha_zero_pct": 0.0}+ assert stats == {"mode": "RGBA", "has_alpha_band": True, **verdict}+++def test_g3_asks_it_of_every_frame(calls):+ frame = icon()+ gates = evaluate({"f": frame}, kind="icon", rule=FREE16, walk_cycle=False)+ ((alpha, verdict),) = calls+ assert alpha.tobytes() == pg.image_of(frame).getchannel("A").tobytes()+ assert verdict["verdict"] == "real-alpha"+ assert gates["G3"]["ok"] and gates["G3"]["frames"]["f"] == {+ "opaque_pixels": 80, "opaque_fraction": 0.3125, "corners_transparent": True, **verdict}+++def test_g3_says_what_it_answers(monkeypatch):+ """Answer `ambiguous`: G3 fails a sprite on a clear canvas. Answer `real-alpha`: G3 fails a tile,+ which must be `no-alpha`, however opaque it is."""+ monkeypatch.setattr(chroma, "alpha_verdict",+ lambda alpha: {"verdict": "ambiguous", "alpha_zero_pct": 1.0, "border_alpha_zero_pct": 50.0})+ sprite = evaluate({"f": icon()}, kind="sprite", rule=FREE16, walk_cycle=False)+ assert not sprite["ok"] and sprite["failed"] == ["G3"]+ monkeypatch.setattr(chroma, "alpha_verdict",+ lambda alpha: {"verdict": "real-alpha", "alpha_zero_pct": 9.0, "border_alpha_zero_pct": 90.0})+ tile = evaluate({"tile": [[INK] * 8 for _ in range(8)]}, kind="tile", rule=FREE16, walk_cycle=False)+ assert not tile["ok"] and tile["failed"] == ["G3"]+++def test_a_canvas_filled_but_for_half_its_border_has_no_transparent_background():+ """48 px of ink with its top row, its left column and its four corners clear: half the border is+ alpha 0, but 96 pixels are not 5 % of 2,304 - `ambiguous`, and G3 fails it."""+ size = 48+ frame = [[INK] * size for _ in range(size)]+ for x in range(size):+ frame[0][x] = CLEAR+ for y in range(size):+ frame[y][0] = CLEAR+ frame[size - 1][size - 1] = CLEAR+ gates = evaluate({"f": frame}, kind="icon", rule=FREE16, walk_cycle=False)+ measured = gates["G3"]["frames"]["f"]+ assert measured["corners_transparent"] and measured["border_alpha_zero_pct"] == 51.06+ assert measured["verdict"] == "ambiguous" and measured["alpha_zero_pct"] == 4.17+ assert not gates["ok"] and gates["failed"] == ["G3"]diff --git a/tests/gen/test_pixel_draw.py b/tests/gen/test_pixel_draw.pyindex 9e337a8..010459a 100644--- a/tests/gen/test_pixel_draw.py+++ b/tests/gen/test_pixel_draw.py@@ -313,6 +313,21 @@ def test_the_vision_pick_chooses_between_two_that_passed(tmp_path, claude):assert [c["id"] for c in report["calls"]] == ["c1-gen1", "c2-gen1", "pick"]+def test_the_pick_sheet_shows_transparency_on_the_engines_preview_checker(tmp_path):+ """The candidates' transparent pixels show the checker the engine's contact sheets and GIF+ previews show (`qa.preview.checker`), eight sheet pixels a square."""+ from sprite_gen.qa.preview import checker++ by_label = {}+ for label, cid in (("A", "c1"), ("B", "c2")):+ (tmp_path / cid).mkdir()+ Image.new("RGBA", (64, 48), (0, 0, 0, 0)).save(tmp_path / cid / "preview.png")+ by_label[label] = pixel_draw.Candidate(cid, files={"preview": f"{cid}/preview.png"})+ sheet = Image.open(io.BytesIO(pixel_draw.pick_sheet(tmp_path, by_label, tile=False))).convert("RGB")+ left, top = 16 + 56, 16 # past the margin and the label column+ assert sheet.crop((left, top, left + 64, top + 48)).tobytes() == checker((64, 48), square=8).convert("RGB").tobytes()++def test_a_person_picks_when_asked(tmp_path, claude):fake = claude({"c1-gen1": reply(SPRITE16), "c2-gen1": reply(SPRITE16.replace("r #d03a34", "r #c03030"))})out = tmp_path / "run"diff --git a/tests/gen/test_pixel_gates.py b/tests/gen/test_pixel_gates.pyindex e48ba01..b101fe8 100644--- a/tests/gen/test_pixel_gates.py+++ b/tests/gen/test_pixel_gates.py@@ -1,11 +1,14 @@# SPDX-License-Identifier: Apache-2.0"""Gates G2..G6 and G8 of `pixel-draw` on recorded answers (tests/fixtures/pixel_draw) and on gridsmade to break exactly one rule. G2, G3 and G6 fail a candidate; G4, G5 and the walk check only warn.-G8 never fails: its judgment is the image path's, `frames.extract.safe_area_fit`-(tests/frames/test_safe_area_fit.py) - a frame past the physical cap warns, one past the safe area-within the cap is an info line - and a sprite whose feet are off the floor row warns. The-`*-safe-area-pass` answers were drawn under the safe-area prompt; the other recorded sprites when the-prompt asked to fill the canvas."""+G3, G4, G5 and G8 ask the engine's own judgments, each tested with its owner: G3 the transparent+background of `gen.chroma.alpha_verdict` (tests/gen/test_alpha_verdict.py), G4 the join measure of+`background.tile.inspect_tile` (tests/background/test_tile.py), G5 the lone pixels of+`frames.extract.isolated_dots` (tests/frames/test_isolated_dots.py), and G8 the safe area of+`frames.extract.safe_area_fit` (tests/frames/test_safe_area_fit.py) - a frame past the physical cap+warns, one past the safe area within the cap is an info line - and a sprite whose feet are off the+floor row warns. The `*-safe-area-pass` answers were drawn under the safe-area prompt; the other+recorded sprites when the prompt asked to fill the canvas."""from __future__ import annotationsfrom pathlib import Path@@ -14,7 +17,7 @@ import pytestfrom sprite_gen.gen import pixel_gates, preparefrom sprite_gen.gen import pixel_grid as pg-from sprite_gen.gen.pixel_gates import evaluate, g6_frames, seam_ratio+from sprite_gen.gen.pixel_gates import evaluate, g6_framesFIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "pixel_draw"WALK = ("walk1", "walk2", "walk3", "walk4")@@ -42,6 +45,7 @@ def test_recorded_sprite_passes_every_gate():assert gates["ok"] and gates["failed"] == [] and gates["warnings"] == [] and gates["info"] == []assert gates["G2"]["colors_used"] <= 16assert gates["G3"]["frames"]["sprite"]["corners_transparent"]+ assert gates["G3"]["frames"]["sprite"]["verdict"] == "real-alpha"assert gates["G5"]["isolated_pixels"] == 0 and "G6" not in gates and "G4" not in gatesassert gates["G8"]["frames"]["sprite"]["bbox"] == [3, 1, 12, 14] and gates["G8"]["floor_row"] == 14@@ -49,7 +53,9 @@ def test_recorded_sprite_passes_every_gate():def test_recorded_tile_is_opaque_and_repeats():gates = evaluate(frames_of("tile-16-pass.txt", 16, ("tile",)), kind="tile", rule=FREE16, walk_cycle=False)assert gates["ok"] and gates["G3"]["frames"]["tile"]["opaque_fraction"] == 1.0 and gates["info"] == []- assert gates["G4"]["seam_ratio"] <= 1.5 and not gates["G4"]["warn"]+ assert gates["G3"]["frames"]["tile"]["verdict"] == "no-alpha"+ assert gates["G4"]["needs_review"] == [] and not gates["G4"]["warn"]+ assert {axis: report["status"] for axis, report in gates["G4"]["frames"]["tile"].items()} == {"x": "pass", "y": "pass"}def test_g2_counts_colours_against_the_limit_and_the_fixed_set():@@ -78,9 +84,10 @@ def test_g3_alpha_failures(frame, kind):def test_g4_seam_only_warns():striped = [[GRASS if x < 2 or x >= 6 else MOSS for x in range(8)] for _ in range(8)] # wraps cleanlyseam = [[GRASS if x < 7 else INK for x in range(8)] for _ in range(8)]- assert seam_ratio(striped) <= 1.5+ clean = evaluate({"tile": striped}, kind="tile", rule=FREE16, walk_cycle=False)+ assert clean["ok"] and not clean["G4"]["warn"] and clean["warnings"] == []gates = evaluate({"tile": seam}, kind="tile", rule=FREE16, walk_cycle=False)- assert gates["G4"]["warn"] and gates["G4"]["seam_ratio"] > 1.5+ assert gates["G4"]["warn"] and gates["G4"]["needs_review"] == ["tile x"]assert gates["ok"] and any(w.startswith("G4 tile seam") for w in gates["warnings"])@@ -93,6 +100,18 @@ def test_g5_stray_pixels_only_warn():assert gates["warnings"] == ["G5 1 stray pixel(s) with no opaque neighbour"]+def test_g5_a_one_pixel_diagonal_stroke_is_not_stray():+ """Each pixel of a diagonal stroke touches the next at a corner: joined, as a staff or a blade drawn+ at 45 degrees is. Only the speck that touches nothing is stray."""+ frame = [[INK if 6 <= y <= 11 and 6 <= x <= 11 else CLEAR for x in range(16)] for y in range(16)]+ for step in (3, 4, 5):+ frame[step][step] = INK+ frame[2][12] = INK+ gates = evaluate({"f": frame}, kind="icon", rule=FREE16, walk_cycle=False)+ assert gates["G5"]["isolated_pixels"] == 1 and gates["G5"]["frames"] == {"f": 1}+ assert gates["warnings"] == ["G5 1 stray pixel(s) with no opaque neighbour"]++def test_recorded_four_directions_stand_on_one_line():gates = evaluate(frames_of("fourdir-16-pass.txt", 16, FOURDIR), kind="sprite", rule=FREE16, walk_cycle=False)assert gates["G6"]["ok"] and gates["G6"]["identical_pairs"] == []