Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(extract): a row's one scale keeps every pose on its anchor
Soohong Kimaa185a9497a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 449b243..d69a0be 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- **Fix: the poses of one image row keep one size and stay on their anchor.** Each pose of a row was shrunk into its cell on its own, so a raised or extended weapon shrank that pose's body (PR #107 gave the row one shrink ratio). That ratio fitted the widest pose by its own width, and `fit_to_cell` then placed it with its `align_x` anchor (the legs, by default) on the cell's centre line: a weapon held far out crossed the cell and the pose was pushed back in, body and all, so the body jumped back in that frame alone (a greatsword thrust: 39 px in a 256 cell). The ratio is now one function, `fit_scale`, which keeps every pose inside the safe area where its anchor puts it; `fit_to_cell` takes it for a frame alone, the row takes it over every pose, and `qa/inspect` fits a row the same way instead of pose by pose. With `bbox-center` nothing changes. A weapon held far to one side now costs size in a square cell: give such a row a wider cell ([pixel-unfake](docs/pixel-unfake.md)). Test: `tests/frames/test_row_scale.py`.- **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` (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.diff --git a/docs/pixel-unfake.md b/docs/pixel-unfake.mdindex 91b1a16..51c2595 100644--- a/docs/pixel-unfake.md+++ b/docs/pixel-unfake.md@@ -27,12 +27,17 @@ Optional `fit` object (opt-in; absent means legacy behavior). For pixel-art targ`prepare_sprite_run.py` exposes these as `--fit-resample`, `--fit-align-x`, `--fit-align-y`, and `--fit-ground-frames` / `--no-fit-ground-frames`, plus the `pixel_unfake` family below as `--fit-pixel-unfake`, `--fit-logical-height`, `--fit-palette-size`, `--fit-detail-bias`, `--fit-outline {on,off,STRENGTH}`, `--fit-pitch-hint`. CLI flags override the same keys in `--request` JSON, one stderr line naming them ([run contract](run-contract.md#1-pipeline-stages)); either way the merged result is recorded in the run's `sprite-request.json` `fit` object (SSoT).With `fit.pixel_unfake: false`, extracted poses in each state row share one shrink-ratio, chosen to fit the widest and tallest poses inside the cell's safe area.-A raised or extended weapon therefore does not shrink only that pose's body.-This preserves scale already present in the generated row; it does not repair-size drift drawn by the image model. Alignment still follows `align_x`/`align_y`,-and separate state rows can have different shrink ratios. The pixel-unfake path-and standalone `fit_to_cell` calls keep their existing behavior.+ratio (`fit_scale`), chosen so that every pose, placed with its `align_x` anchor on+the cell's centre line, stays inside the cell's safe area: the reach on either side+of the anchor within half the safe width, the height within the safe height. A+raised or extended weapon therefore neither shrinks only that pose's body nor+pushes that pose off its anchor (a pose crossing the cell used to be pushed back+in, body and all). With `bbox-center` the reach is half the width, so the ratio+fits the widest pose by its width. This preserves scale already present in the+generated row; it does not repair size drift drawn by the image model. A weapon+held far to one side costs size in a square cell: give such a row a wider cell.+Separate state rows can have different shrink ratios, and a single frame is a row+of one. The pixel-unfake path keeps its own placement.## `pixel_unfake` modediff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex 9b3ba14..f0aaa99 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -1259,6 +1259,32 @@ def _alpha_centroid_x(sprite: Image.Image, bottom_fraction: float = 1.0, min_alpreturn (weighted / total) if total else width / 2.0+def _anchor_x(sprite: Image.Image, align_x: str) -> float:+ """The x of `sprite` (cropped to its bbox) that `fit_to_cell` puts on the cell's centre line."""+ if align_x == "foot-centroid":+ return _alpha_centroid_x(sprite, 0.2)+ if align_x == "centroid":+ return _alpha_centroid_x(sprite)+ if align_x == "alpha-centroid":+ return _alpha_centroid_x(sprite, 1.0, ALPHA_CENTROID_MIN_ALPHA)+ return sprite.width / 2.0+++def fit_scale(sprites: list[Image.Image], cell_width: int, cell_height: int, safe_margin_x: int,+ safe_margin_y: int, align_x: str) -> float:+ """The one scale (at most 1) at which every sprite, cropped to its bbox and placed with its anchor+ (`_anchor_x`) on the cell's centre line, stays inside the safe area: the reach on either side of the+ anchor within half the safe width, the height within the safe height. A frame alone is a row of one.+ With `bbox-center` the reach is half the width, so this is the safe width over the widest frame."""+ half = max(0.5, cell_width / 2.0 - safe_margin_x)+ max_height = max(1, cell_height - safe_margin_y * 2)+ scale = 1.0+ for sprite in sprites:+ anchor = _anchor_x(sprite, align_x)+ scale = min(scale, half / max(anchor, sprite.width - anchor, 0.5), max_height / sprite.height)+ return scale++def _alpha_centroid_row_left(frame: Image.Image, cell_width: int, scale: int) -> int:# 픽셀 언페이크 행 경로의 프레임별 가로 배치 (align_x: alpha-centroid 전용).# 행 union 공동 left 는 register_row_frames 의 정합 잔차가 그대로 지터로@@ -1332,10 +1358,8 @@ def fit_to_cell(if bbox is None:return targetsprite = image.crop(bbox)- max_width = max(1, cell_width - safe_margin_x * 2)- max_height = max(1, cell_height - safe_margin_y * 2)if scale is None:- scale = min(max_width / sprite.width, max_height / sprite.height, 1.0)+ scale = fit_scale([sprite], cell_width, cell_height, safe_margin_x, safe_margin_y, align_x)if scale != 1.0:new_size = (max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale)))if resample_name == "kcentroid":@@ -1350,14 +1374,8 @@ def fit_to_cell(cropped = sprite.getbbox()if cropped is not None:sprite = sprite.crop(cropped)- if align_x == "foot-centroid":- left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 0.2))- left = max(0, min(cell_width - sprite.width, left))- elif align_x == "centroid":- left = round(cell_width / 2.0 - _alpha_centroid_x(sprite))- left = max(0, min(cell_width - sprite.width, left))- elif align_x == "alpha-centroid":- left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 1.0, ALPHA_CENTROID_MIN_ALPHA))+ if align_x in ("foot-centroid", "centroid", "alpha-centroid"):+ left = round(cell_width / 2.0 - _anchor_x(sprite, align_x))left = max(0, min(cell_width - sprite.width, left))else:left = (cell_width - sprite.width) // 2@@ -2611,15 +2629,12 @@ def extract_component_images(strip: Image.Image, frame_count: int) -> list[Imagedef fit_row_to_cells(images: list[Image.Image], cell_width: int, cell_height: int,safe_margin_x: int, safe_margin_y: int,fit: dict[str, Any] | None = None) -> list[Image.Image]:- # The prop's reach changes a pose's bounds, not the character's physical size.- # One scale for the complete row fits even its widest/tallest pose.- bounds = [bbox for image in images if (bbox := image.getbbox()) is not None]- scale = 1.0- if bounds:- max_width = max(bbox[2] - bbox[0] for bbox in bounds)- max_height = max(bbox[3] - bbox[1] for bbox in bounds)- scale = min(max(1, cell_width - 2 * safe_margin_x) / max_width,- max(1, cell_height - 2 * safe_margin_y) / max_height, 1.0)+ # The prop's reach changes a pose's bounds, not the character's physical size. One scale for the+ # complete row (fit_scale) keeps every pose inside the safe area where its anchor puts it, so a+ # weapon held far out neither shrinks its pose alone nor pushes that pose off its anchor.+ align_x = str((fit or {}).get("align_x", "foot-centroid")).lower()+ sprites = [image.crop(bbox) for image in images if (bbox := image.getbbox()) is not None]+ scale = fit_scale(sprites, cell_width, cell_height, safe_margin_x, safe_margin_y, align_x) if sprites else 1.0return [fit_to_cell(image, cell_width, cell_height, safe_margin_x, safe_margin_y,fit, scale=scale) for image in images]diff --git a/sprite_gen/qa/inspect.py b/sprite_gen/qa/inspect.pyindex 5e9ed2f..00ccd4e 100644--- a/sprite_gen/qa/inspect.py+++ b/sprite_gen/qa/inspect.py@@ -120,18 +120,15 @@ def _strip_for_state(run_dir: Path, request: dict[str, Any], state: str, args: adef _frames_from_raw(strip: Image.Image, expected: int, request: dict[str, Any]) -> tuple[list[Image.Image], int]:cell_width, cell_height, safe_margin_x, safe_margin_y = extract.cell_geometry(request["cell"])segments, natural = segment_strip(strip, expected)- frames: list[Image.Image] = []- for left, right in segments:- frames.append(- extract.fit_to_cell(- strip.crop((left, 0, right, strip.height)),- cell_width,- cell_height,- safe_margin_x,- safe_margin_y,- request.get("fit") or {},- )- )+ # A row is fitted the way extract fits it: one scale for every pose (extract.fit_row_to_cells).+ frames = extract.fit_row_to_cells(+ [strip.crop((left, 0, right, strip.height)) for left, right in segments],+ cell_width,+ cell_height,+ safe_margin_x,+ safe_margin_y,+ request.get("fit") or {},+ )return frames, naturaldiff --git a/tests/frames/test_row_scale.py b/tests/frames/test_row_scale.pyindex 0b06790..399fa27 100644--- a/tests/frames/test_row_scale.py+++ b/tests/frames/test_row_scale.py@@ -66,3 +66,29 @@ def test_cli_extract_preserves_body_scale(tmp_path):assert len(sizes) == 3for axis in (0, 1):assert max(size[axis] for size in sizes) - min(size[axis] for size in sizes) <= 1+++def red_body_centre_x(frame):+ mask = Image.new('L', frame.size)+ mask.putdata([255 if r > 180 and g < 80 and b < 80 and a > 128 else 0+ for r, g, b, a in frame.get_flattened_data()])+ box = mask.getbbox()+ assert box is not None+ return (box[0] + box[2]) / 2++[email protected]('route', ['components', 'slots'])[email protected]('align_x', ['foot-centroid', 'centroid', 'alpha-centroid', 'bbox-center'])+def test_a_reaching_weapon_does_not_push_its_pose_off_its_anchor(route, align_x):+ """The row scale used to fit the widest pose by its own width; placed at its anchor (the legs, by+ default) that pose crossed the cell and was pushed back in, body and all, so the body jumped back+ in that frame alone. The scale now keeps every pose inside the safe area where its anchor puts it."""+ fn = extract.extract_component_frames if route == 'components' else extract.extract_slot_frames+ frames = fn(attack_strip(), 3, 128, 128, 12, 12, {'align_x': align_x})+ assert frames is not None and len(frames) == 3+ for frame in frames: # inside the safe area, give or take the pixel the shrink rounds+ x0, y0, x1, y1 = frame.getbbox()+ assert x0 >= 12 - 1 and x1 <= 128 - 12 + 1+ if align_x == 'foot-centroid': # the legs are the body here, so the body stays put+ centres = [red_body_centre_x(frame) for frame in frames]+ assert max(centres) - min(centres) <= 1