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(slice-sheet): --scale sheet keeps a sheet's relative sizes, --fit contain keeps each cut whole, and a report states factor, size and anchor per cell

Soohong Kim435c9cf99508
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index b86cd32..cbb6c40 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -194,6 +194,8 @@ def _add_slice_sheet(p: argparse.ArgumentParser) -> None:
p.add_argument("--debris-fraction", type=float, default=slice_sheet.DEFAULT_DEBRIS_FRACTION)
p.add_argument("--alpha-floor", type=int, default=0, help=slice_sheet.ALPHA_FLOOR_HELP)
p.add_argument("--alpha-edge", type=int, default=2, help=slice_sheet.ALPHA_EDGE_HELP)
+ p.add_argument("--scale", choices=slice_sheet.SCALES, default="cell", help=slice_sheet.SCALE_HELP)
+ p.add_argument("--fit", choices=slice_sheet.FITS, default="none", help=slice_sheet.FIT_HELP)
def _add_inspect(p: argparse.ArgumentParser) -> None:
diff --git a/sprite_gen/frames/slice_sheet.py b/sprite_gen/frames/slice_sheet.py
index e408c5d..838af60 100644
--- a/sprite_gen/frames/slice_sheet.py
+++ b/sprite_gen/frames/slice_sheet.py
@@ -24,7 +24,13 @@ module owns only cell geometry:
they sit inside the cell;
- every cell's main figure is scaled so its height equals ``target_height``
(per-cell normalization — generators routinely draw rows at different
- sizes) and its feet rest on ``baseline_y`` of the output canvas.
+ sizes) and its feet rest on ``baseline_y`` of the output canvas;
+- ``scale="sheet"`` instead takes one factor for the whole sheet (the tallest
+ main subject reaches ``target_height``), so props drawn at different sizes
+ keep them; ``fit="contain"`` lowers the factor until every cut fits its
+ canvas, so a wide subject is never cut. The report
+ (``<prefix>slice-sheet.json``) states each cell's factor, size, box on the
+ canvas, the main subject's base point and the pixels the canvas cut.
Field lessons baked in here (a cut-in overhaul, 2026-07-09):
sheet-wide max-height scaling preserves the generator's size jitter, grid
@@ -41,6 +47,7 @@ from pathlib import Path
from PIL import Image
+from sprite_gen._deps import np
from sprite_gen.frames.alpha_floor import clear_haze
from sprite_gen.frames.extract import remove_chroma_background
from sprite_gen.spec.runio import atomic_write_text
@@ -62,6 +69,13 @@ CHROMA_KEY_HELP = "magenta, green, #RRGGBB, or none for a sheet that is already
ALPHA_FLOOR_HELP = ("clear faint alpha haze below this alpha (1..255) before cutting, and write "
"<prefix>alpha-cleanup.json; 0 (default) leaves the alpha as it is")
ALPHA_EDGE_HELP = "with --alpha-floor: faint pixels this close to a solid pixel are its edge and are kept"
+SCALES = ("cell", "sheet")
+FITS = ("none", "contain")
+SCALE_HELP = ("cell (default): each cell's main subject reaches --target-height; sheet: one factor for the whole "
+ "sheet, the tallest main subject reaching --target-height, so every subject keeps its drawn size")
+FIT_HELP = ("none (default): the canvas cuts whatever the factor puts past its edge; contain: the factor is lowered "
+ "until the whole cut fits the canvas, the main subject still centred with its base on --baseline-y")
+REPORT_KIND = "sprite-gen-slice-sheet"
def parse_chroma_key(value: str) -> tuple[int, int, int] | None:
@@ -130,6 +144,22 @@ def _relabel_within_cell(part: list[int], width: int) -> list[list[int]]:
return subs
+def _contain_factor(name: str, cut: dict, canvas: tuple[int, int], baseline_y: float) -> float:
+ """The largest factor at which the whole cut fits the canvas, placed as `slice_sheet` places it:
+ the main subject centred, its base on the baseline, every other part where it was drawn."""
+ mx0, mx1, _my0, my1 = cut["main"]
+ x0, x1, y0, y1 = cut["box"]
+ center = (mx0 + mx1) / 2
+ limits = [canvas[0] / 2 / max(center - x0, x1 + 1 - center), baseline_y / (my1 + 1 - y0)]
+ if y1 > my1:
+ room = canvas[1] - baseline_y
+ if room <= 0:
+ raise ValueError(f"{name}: a part below the main subject's base needs room under --baseline-y "
+ f"{baseline_y:g} on the {canvas[1]} px canvas")
+ limits.append(room / (y1 - my1))
+ return min(limits)
+
+
def slice_sheet(
sheet: Path,
out_dir: Path,
@@ -150,6 +180,8 @@ def slice_sheet(
debris_fraction: float = DEFAULT_DEBRIS_FRACTION,
alpha_floor: int = 0,
alpha_edge: int = 2,
+ scale: str = "cell",
+ fit: str = "none",
) -> list[Path]:
cols, rows = grid
cell_count = cols * rows
@@ -157,6 +189,13 @@ def slice_sheet(
raise ValueError(f"--names needs exactly {cell_count} entries for grid {cols}x{rows}")
if target_height > baseline_y:
raise ValueError("target height must fit above the feet baseline")
+ if scale not in SCALES:
+ raise ValueError(f"scale must be one of {', '.join(SCALES)}, not {scale!r}")
+ if fit not in FITS:
+ raise ValueError(f"fit must be one of {', '.join(FITS)}, not {fit!r}")
+ if fit == "contain" and not 0 < baseline_y <= canvas[1]:
+ raise ValueError(f"--fit contain needs --baseline-y inside the {canvas[1]} px canvas")
+ names = names or [f"cell-{cell}" for cell in range(cell_count)]
rgba = Image.open(sheet).convert("RGBA")
if chroma_key is not None:
@@ -236,44 +275,119 @@ def slice_sheet(
atomic_write_text(out_dir / f"{prefix}alpha-cleanup.json", json.dumps(cleanup, indent=2) + "\n")
print(f"{sheet.name} alpha haze {cleanup['haze_fraction_before']:.2%} -> "
f"{cleanup['haze_fraction_after']:.2%} (floor {alpha_floor}, cleared {cleanup['cleared_pixels']} px)")
- written: list[Path] = []
+ # Every cell is measured before any is written: the sheet factor needs them all, and an empty
+ # cell fails the sheet before a single cut lands.
+ cuts = []
for cell in range(cell_count):
comps_in = buckets[cell]
if not comps_in:
raise SystemExit(f"{sheet}: cell {cell} has no subject after extraction")
main = max(comps_in, key=len)
- main_ys = [i // width for i in main]
main_xs = [i % width for i in main]
- main_top, main_bottom = min(main_ys), max(main_ys)
- scale = target_height / (main_bottom - main_top + 1)
-
+ main_ys = [i // width for i in main]
all_pixels = {i for comp in comps_in for i in comp}
xs = [i % width for i in all_pixels]
ys = [i // width for i in all_pixels]
- x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
+ cuts.append({"name": names[cell], "parts": comps_in, "pixels": all_pixels,
+ "main": (min(main_xs), max(main_xs), min(main_ys), max(main_ys)),
+ "box": (min(xs), max(xs), min(ys), max(ys))})
+
+ # The factor: the height rule (each main subject reaches the target, or with `sheet` the tallest
+ # does and the rest keep their drawn size), lowered by `contain` until the cut fits its canvas.
+ def main_height(cut: dict) -> int:
+ return cut["main"][3] - cut["main"][2] + 1
+
+ for cut in cuts:
+ cut["factor"], cut["factor_from"] = target_height / main_height(cut), "target_height"
+ cut["fits"] = _contain_factor(cut["name"], cut, canvas, baseline_y) if fit == "contain" else None
+ sheet_factor = sheet_from = None
+ if scale == "sheet":
+ tallest = max(cuts, key=main_height)
+ sheet_factor, sheet_from = target_height / main_height(tallest), {"rule": "target_height", "cell": tallest["name"]}
+ for cut in cuts:
+ if cut["fits"] is not None and cut["fits"] < sheet_factor:
+ sheet_factor, sheet_from = cut["fits"], {"rule": "fit", "cell": cut["name"]}
+ for cut in cuts:
+ cut["factor"], cut["factor_from"] = sheet_factor, sheet_from["rule"]
+ else:
+ for cut in cuts:
+ if cut["fits"] is not None and cut["fits"] < cut["factor"]:
+ cut["factor"], cut["factor_from"] = cut["fits"], "fit"
+
+ written: list[Path] = []
+ records = []
+ for cell, cut in enumerate(cuts):
+ factor = cut["factor"]
+ mx0, mx1, main_top, main_bottom = cut["main"]
+ x0, x1, y0, y1 = cut["box"]
piece = Image.new("RGBA", (x1 - x0 + 1, y1 - y0 + 1), (0, 0, 0, 0))
piece_px = piece.load()
- for index in all_pixels:
+ for index in cut["pixels"]:
x, y = index % width, index // width
piece_px[x - x0, y - y0] = pixels[x, y]
- new_size = (max(1, round(piece.size[0] * scale)), max(1, round(piece.size[1] * scale)))
+ new_size = (max(1, round(piece.size[0] * factor)), max(1, round(piece.size[1] * factor)))
piece = resize_cell(piece, new_size)
- main_center_x = (min(main_xs) + max(main_xs)) / 2
+ main_center_x = (mx0 + mx1) / 2
out = Image.new("RGBA", canvas, (0, 0, 0, 0))
- offset_x = round(canvas[0] / 2 - (main_center_x - x0) * scale)
- offset_y = round(baseline_y - (main_bottom - y0 + 1) * scale)
- out.alpha_composite(piece, (max(0, offset_x), max(0, offset_y)))
-
- name = names[cell] if names else f"cell-{cell}"
- path = out_dir / f"{prefix}{name}.png"
+ offset_x = round(canvas[0] / 2 - (main_center_x - x0) * factor)
+ offset_y = round(baseline_y - (main_bottom - y0 + 1) * factor)
+ if fit == "contain":
+ # the factor fits the cut; rounding may leave it a pixel over an edge, so it moves back in
+ offset_x = min(max(offset_x, 0), canvas[0] - new_size[0])
+ offset_y = min(max(offset_y, 0), canvas[1] - new_size[1])
+ else:
+ offset_x, offset_y = max(0, offset_x), max(0, offset_y)
+ out.alpha_composite(piece, (offset_x, offset_y))
+ coverage = np.asarray(piece.getchannel("A"))
+ clipped = int(np.count_nonzero(coverage)) - int(np.count_nonzero(
+ coverage[:max(0, canvas[1] - offset_y), :max(0, canvas[0] - offset_x)]))
+
+ path = out_dir / f"{prefix}{cut['name']}.png"
out.save(path)
written.append(path)
+ main_w, main_h = mx1 - mx0 + 1, main_bottom - main_top + 1
print(
f"{sheet.name} cell{cell} -> {path.name} "
- f"main_h {main_bottom - main_top + 1} -> {round((main_bottom - main_top + 1) * scale)} "
- f"comps {len(comps_in)}"
+ f"main_h {main_h} -> {round(main_h * factor)} "
+ f"comps {len(cut['parts'])}"
)
+ if clipped:
+ print(f"{sheet.name} cell{cell}: the canvas cut {clipped} px of {path.name} (--fit contain keeps it whole)")
+ records.append({
+ "name": cut["name"],
+ "file": path.name,
+ "factor": factor,
+ "factor_from": cut["factor_from"],
+ "subject": {"sheet": {"w": main_w, "h": main_h},
+ "canvas": {"w": round(main_w * factor), "h": round(main_h * factor)}},
+ "box": {"x": offset_x, "y": offset_y, "w": new_size[0], "h": new_size[1]},
+ # the main subject's base centre where it landed: the point it stands on
+ "anchor": [round(offset_x + ((mx0 + mx1 + 1) / 2 - x0) * new_size[0] / (x1 - x0 + 1), 3),
+ round(offset_y + (main_bottom + 1 - y0) * new_size[1] / (y1 - y0 + 1), 3)],
+ "clipped_px": clipped,
+ "parts": len(cut["parts"]),
+ })
+
+ report = {
+ "kind": REPORT_KIND,
+ "version": 1,
+ "sheet": sheet.name,
+ "grid": [cols, rows],
+ "canvas": {"w": canvas[0], "h": canvas[1]},
+ "baseline_y": baseline_y,
+ "target_height": target_height,
+ "scale": scale,
+ "fit": fit,
+ "factor": sheet_factor,
+ "factor_from": sheet_from,
+ "alpha_cleanup": f"{prefix}alpha-cleanup.json" if cleanup is not None else None,
+ "cells": records,
+ }
+ report_path = out_dir / f"{prefix}slice-sheet.json"
+ atomic_write_text(report_path, json.dumps(report, indent=2, allow_nan=False) + "\n")
+ factor_text = f" factor {sheet_factor:.4f} ({sheet_from['rule']}, {sheet_from['cell']})" if sheet_factor else ""
+ print(f"{sheet.name}: scale {scale}, fit {fit}{factor_text}; report {report_path.name}")
return written
@@ -298,6 +412,8 @@ def run(
debris_fraction: float = DEFAULT_DEBRIS_FRACTION,
alpha_floor: int = 0,
alpha_edge: int = 2,
+ scale: str = "cell",
+ fit: str = "none",
) -> int:
name_list = [part.strip() for part in names.split(",") if part.strip()] if names else None
slice_sheet(
@@ -319,6 +435,8 @@ def run(
debris_fraction=debris_fraction,
alpha_floor=alpha_floor,
alpha_edge=alpha_edge,
+ scale=scale,
+ fit=fit,
)
return 0
@@ -349,6 +467,8 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--debris-fraction", type=float, default=DEFAULT_DEBRIS_FRACTION)
parser.add_argument("--alpha-floor", type=int, default=0, help=ALPHA_FLOOR_HELP)
parser.add_argument("--alpha-edge", type=int, default=2, help=ALPHA_EDGE_HELP)
+ parser.add_argument("--scale", choices=SCALES, default="cell", help=SCALE_HELP)
+ parser.add_argument("--fit", choices=FITS, default="none", help=FIT_HELP)
args = parser.parse_args(argv)
return run(**vars(args))