Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(follow): --on-fold lower takes the largest gain that does not fold, never under 1; refuse stays the default
Soohong Kim577546919c98
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3b0e718..00c04c0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased - A follow-through that would fold its region can take the largest gain that does not++- **New `video-follow --on-fold lower`**: a move that would fold a region over itself is no longer only refused. The move is the gain times the move at gain 1, so the gain at which a region folds is known (2 · radius / (π · move at gain 1)); `lower` takes the largest gain under it, in steps of 0.01 and no more than `--gain`, one gain for the strip set by the region with the smallest radius, and names it on stderr. It never goes under 1, the mass as measured: a region too small for that is still refused, and the message names the largest gain that would not fold. The record says what was asked and what was used (`gain_requested`, `gain`, `on_fold`, and `fold`: lowered or not, the move asked for, the move at gain 1, per region the smaller radius, how near the used move is to folding it, and the gain at which it folds). The default stays `--on-fold refuse`: the same strip, GIF, WebP and refusal message as 2.24.0, byte for byte; the record only gains those keys. [docs/video-pipeline.md](docs/video-pipeline.md#6-follow-through--video-follow).+## v2.25.0 - Every view of an aligned walk starts as the same foot lands, read off the legs, and RIFE leaves no black between crossing legs- **Output change: every frame RIFE makes, and where every aligned loop starts.** Frames made by RIFE (`video-cycle-align`, `video-set --align-cycles auto`, `video-loop` jump repair) are drawn differently wherever the legs cross or the flow is unsure; frames taken as filmed are untouched. Every loop `video-cycle-align` turns may start on a different frame: on its legs instead of its top edge, and, with views, on one foot for the whole set. A loop already aligned starts where the new rule says the next time it is aligned (it is read from `cycle.source/`).diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex d9d4f56..42d87f1 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -810,7 +810,7 @@ bounce. `video-follow` puts that follow-through back on a cut loop:```bashsprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [--region …] \- [--gain 2.5] [--freq 2.4] [--zeta 0.6] [--board follow.png]+ [--gain 2.5] [--on-fold refuse|lower] [--freq 2.4] [--zeta 0.6] [--board follow.png]```- **The region** is an ellipse over the part in the strip's first cell, in cell pixels@@ -829,11 +829,23 @@ sprite-gen video-follow --loop-dir set/front-walk/loop --region 136,164,60,50 [-at the centre and 0 at the rim (cos²), sampled as premultiplied bilinear colour; outside it nopixel changes. A move so large that the weight's slope folds the picture over(offset × π / (2 · radius) ≥ 1) is refused: lower `--gain` or give the region larger radii.+- **`--on-fold lower`** lowers the gain for you instead of refusing. The move is the gain times+ the move at gain 1, so the gain at which a region folds is 2 · radius / (π · move at gain 1),+ and the strip takes the largest gain under it, in steps of 0.01 and no more than `--gain`. One+ gain for the strip, set by the region with the smallest radius: every part hangs on the same+ body and answers the same motion, and the recorded `gain` is then the `--gain` that gives this+ strip by itself. It does not go under 1, the mass as measured: a region too small for that is+ refused (the message names the largest gain that would not fold), so a follow-through is never+ quietly weaker than the motion it answers. The default stays `refuse`, with the same output and+ the same message as 2.24.0; a strip that does not fold is the same under either.- **What it writes**: the strip, GIF and WebP over the loop's own (both animations re-opened andchecked as `video-loop` checks them), and `follow` in `<name>.strip.json` (the regions, the- settings, the body's bob, `dx_px`/`dy_px` per cell, `reach_px`). `cycle/` is left as cut. The- strip as it was is kept as `follow.source.png`; running `video-follow` again reads from it, so a- second run never moves a moved strip. `--board` writes the cells before and after where the part+ settings, the body's bob, `dx_px`/`dy_px` per cell, `reach_px`; `gain` is the gain used and+ `gain_requested` the one asked for, and `fold` says whether it was lowered, the move asked for,+ the move at gain 1, and per region its smaller radius, how near the used move is to folding it+ (`ratio`, under 1) and the gain at which it folds). A lowered gain is also named on stderr.+ `cycle/` is left as cut. The strip as it was is kept as `follow.source.png`; running+ `video-follow` again reads from it, so a second run never moves a moved strip. `--board` writes the cells before and after where the partsits lowest and highest, on white.- **Order**: after `video-cycle-align`. An alignment rebuilds the strip from the cut, removes`follow.source.png` and the `follow` record, and says so (`follow_cleared` in its loop row); adiff --git a/sprite_gen/video/follow.py b/sprite_gen/video/follow.pyindex a0d3dd9..6f8f2e3 100644--- a/sprite_gen/video/follow.py+++ b/sprite_gen/video/follow.py@@ -19,7 +19,9 @@ the body's bob. Inside it every pixel is moved by the offset times a weight thatcentre and falls to 0 at the rim (cos²); outside it no pixel changes. The move is sampled aspremultiplied bilinear colour, so an edge never picks up the colour under a transparent pixel.A move so large that the weight's slope folds the picture over (offset × π / (2 · radius) ≥ 1)-is refused.+is refused. `--on-fold lower` takes the largest gain that does not fold instead (the offset+grows in a straight line with the gain, so that gain is known without a search), and never one+under 1, the mass as measured: a region too small for that is still refused.The strip as it was before is kept as `follow.source.png` beside it; running the command againreads from there, so a second follow-through never moves a moved strip. `video-loop` (a new@@ -33,6 +35,7 @@ import argparseimport jsonimport mathimport shutil+import sysfrom pathlib import Pathfrom typing import Any@@ -46,6 +49,9 @@ from sprite_gen.video import loop as loop_modFREQ_DEFAULT = 2.4 # Hz: a slow, soft partZETA_DEFAULT = 0.6 # damping ratio: it lags and settles, with no ringingGAIN_DEFAULT = 2.5 # times the physical answer+GAIN_MEASURED = 1.0 # the mass as measured: `--on-fold lower` does not go under it+GAIN_STEP = 0.01 # a lowered gain is a whole number of these, so the report's `gain` is the `--gain` to pass+ON_FOLD_MODES = ("refuse", "lower")HARMONICS = 6 # of the cycle, for the body's motion: a step's shape, not its noiseALPHA_SOLID = 128HEAD_SHARE = 0.07 # of the body's height under the crown: where the head's middle is read@@ -94,6 +100,30 @@ def follow_offsets(motion: np.ndarray, fps: float, *, freq: float, zeta: float,return gain * np.fft.irfft(spectrum * response, n)+def fold_ratio(reach: float, radius: float) -> float:+ """How near a move of `reach` px is to folding a region whose smaller radius is `radius`: at 1+ the steepest part of the weight (cos², slope π / (2 · radius)) stops the picture, past it the+ picture runs backwards."""+ return reach * math.pi / (2 * radius)+++def gain_limit(reach_per_gain: float, radius: float) -> float | None:+ """The gain at which a region of that radius folds; no gain folds it when the body is still."""+ return 2 * radius / (math.pi * reach_per_gain) if reach_per_gain > 0 else None+++def lowered_gain(gain: float, reach_per_gain: float, radius: float) -> float:+ """The largest gain, in steps of GAIN_STEP and no more than `gain`, that `fold_ratio` passes."""+ limit = gain_limit(reach_per_gain, radius)+ if limit is None:+ return gain+ steps = math.ceil(limit / GAIN_STEP) - 1 # under the limit, never on it+ # The step count is rounded from floats: the one test that decides is `fold_ratio` itself.+ while steps > 0 and fold_ratio(steps * GAIN_STEP * reach_per_gain, radius) >= 1:+ steps -= 1+ return min(gain, round(steps * GAIN_STEP, 2))++def _sample(premultiplied: np.ndarray, sx: np.ndarray, sy: np.ndarray) -> np.ndarray:h, w = premultiplied.shape[:2]x0 = np.clip(np.floor(sx).astype(int), 0, w - 2)@@ -131,7 +161,8 @@ def move_regions(cell: Image.Image, regions: list[tuple[float, float, float, flodef follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]], *, gain: float = GAIN_DEFAULT,- freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, board: Path | None = None) -> dict[str, Any]:+ freq: float = FREQ_DEFAULT, zeta: float = ZETA_DEFAULT, board: Path | None = None,+ on_fold: str = "refuse") -> dict[str, Any]:loop_dir = loop_dir.expanduser().resolve()metas = sorted(loop_dir.glob("*.strip.json"))if len(metas) != 1:@@ -145,6 +176,8 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]raise SystemExit("video-follow: at least one --region cx,cy,rx,ry")if gain < 0 or freq <= 0 or not 0 < zeta:raise SystemExit("video-follow: --gain must be 0 or more, --freq and --zeta above 0")+ if on_fold not in ON_FOLD_MODES:+ raise SystemExit(f"video-follow: unknown --on-fold {on_fold!r}; expected one of {', '.join(ON_FOLD_MODES)}")strip_path = loop_dir / f"{name}.strip.png"source = loop_dir / SOURCEif not source.exists():@@ -167,9 +200,24 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]dx = follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=gain)reach = float(np.max(np.hypot(dx, dy)))smallest = min(min(rx, ry) for _, _, rx, ry in regions)- if reach * math.pi / (2 * smallest) >= 1:- raise SystemExit(f"video-follow: a move of {reach:.1f} px folds a region of radius {smallest:g} px over itself; "- "lower --gain or give the region larger radii")+ requested, reach_requested = gain, reach+ # The offset is the gain times the answer at gain 1, so one move decides every gain.+ reach_per_gain = float(np.max(np.hypot(follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=1.0),+ follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=1.0))))+ if fold_ratio(reach, smallest) >= 1:+ if on_fold == "refuse":+ raise SystemExit(f"video-follow: a move of {reach:.1f} px folds a region of radius {smallest:g} px over itself; "+ "lower --gain or give the region larger radii")+ # One gain for the strip, set by the smallest region: every part hangs on the same body and+ # answers the same motion, and the report's `gain` is then the `--gain` that gives this strip.+ gain = lowered_gain(requested, reach_per_gain, smallest)+ if gain < GAIN_MEASURED:+ raise SystemExit(f"video-follow: a move of {reach:.1f} px folds a region of radius {smallest:g} px over itself, and "+ f"--on-fold lower would have to go under --gain {GAIN_MEASURED:g} (the mass as measured moves "+ f"{reach_per_gain:.1f} px; the largest gain that does not fold is {gain:g}); give the region larger radii")+ dy = follow_offsets(rows, fps, freq=freq, zeta=zeta, gain=gain)+ dx = follow_offsets(cols, fps, freq=freq, zeta=zeta, gain=gain)+ reach = float(np.max(np.hypot(dx, dy)))out = [move_regions(c, regions, (cols[k] - cols[0], rows[k] - rows[0]), (dx[k], dy[k])) for k, c in enumerate(cells)]joined = Image.new("RGBA", (w * n, h), (0, 0, 0, 0))for k, c in enumerate(out):@@ -186,6 +234,14 @@ def follow_loop(loop_dir: Path, regions: list[tuple[float, float, float, float]]"body_bob_px": [round(float(np.ptp(cols)), 2), round(float(np.ptp(rows)), 2)],"dx_px": np.round(dx, 2).tolist(), "dy_px": np.round(dy, 2).tolist(),"reach_px": round(reach, 2),+ "gain_requested": requested, "on_fold": on_fold,+ "fold": {+ "lowered": gain != requested, "ratio": round(fold_ratio(reach, smallest), 3),+ "reach_requested_px": round(reach_requested, 2), "reach_per_gain_px": round(reach_per_gain, 3),+ "regions": [{"radius_px": min(rx, ry), "ratio": round(fold_ratio(reach, min(rx, ry)), 3),+ "gain_limit": None if (limit := gain_limit(reach_per_gain, min(rx, ry))) is None else round(limit, 3)}+ for _, _, rx, ry in regions],+ },"gif": loop_mod.verify_animation(gif_path, expect_frames=n, check_stale=False),"webp": loop_mod.verify_animation(webp_path, expect_frames=n, check_stale=True),}@@ -217,6 +273,9 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--region", action="append", type=parse_region, required=True,help="cx,cy,rx,ry: an ellipse over the soft part in the strip's first cell, in cell pixels (repeatable)")parser.add_argument("--gain", type=float, default=GAIN_DEFAULT, help=f"times the physical answer (default {GAIN_DEFAULT:g}; 1 is the mass as measured, 0 leaves the strip as it was)")+ parser.add_argument("--on-fold", choices=ON_FOLD_MODES, default="refuse",+ help=f"a move that folds a region over itself: refuse (default), or lower — take the largest gain that does not fold "+ f"(one gain for the strip, set by the smallest region; never under {GAIN_MEASURED:g}, the mass as measured: that is still refused)")parser.add_argument("--freq", type=float, default=FREQ_DEFAULT, help=f"the part's own frequency in Hz (default {FREQ_DEFAULT:g})")parser.add_argument("--zeta", type=float, default=ZETA_DEFAULT, help=f"damping ratio (default {ZETA_DEFAULT:g}: lags and settles, no ringing)")parser.add_argument("--board", type=Path, help="write a before/after picture at the frames where the part sits lowest and highest")@@ -225,8 +284,12 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:def run(**kwargs: object) -> int:result = follow_loop(Path(str(kwargs["loop_dir"])), list(kwargs["region"]), # type: ignore[arg-type]gain=float(kwargs.get("gain", GAIN_DEFAULT)), freq=float(kwargs.get("freq", FREQ_DEFAULT)), # type: ignore[arg-type]- zeta=float(kwargs.get("zeta", ZETA_DEFAULT)), board=kwargs.get("board")) # type: ignore[arg-type]- print(json.dumps({k: result[k] for k in ("strip", "regions", "gain", "body_bob_px", "reach_px")}+ zeta=float(kwargs.get("zeta", ZETA_DEFAULT)), board=kwargs.get("board"), # type: ignore[arg-type]+ on_fold=str(kwargs.get("on_fold") or "refuse"))+ if result["fold"]["lowered"]:+ print(f"video-follow: --gain {result['gain_requested']:g} folds a region (a move of {result['fold']['reach_requested_px']:g} px); "+ f"lowered to --gain {result['gain']:g}", file=sys.stderr)+ print(json.dumps({k: result[k] for k in ("strip", "regions", "gain", "gain_requested", "on_fold", "body_bob_px", "reach_px")}| ({"board": result["board"]} if "board" in result else {}), ensure_ascii=False, indent=2))return 0diff --git a/tests/video/test_follow.py b/tests/video/test_follow.pyindex 3ae34d8..ac82fc3 100644--- a/tests/video/test_follow.py+++ b/tests/video/test_follow.py@@ -1,6 +1,7 @@"""`video-follow`: a region of a walk loop follows the body's bob, on a synthetic walker."""import jsonimport math+import reimport numpy as npimport pytest@@ -122,6 +123,118 @@ def test_a_move_that_would_fold_the_region_is_refused(loop_dir):follow.follow_loop(loop_dir, [(cx, cy, 2, 2)], gain=50)+def test_the_default_refusal_reads_as_it_did(loop_dir):+ cx, cy, _, _ = chest_region(loop_dir)+ as_cut = (loop_dir/'walk.strip.png').read_bytes()+ with pytest.raises(SystemExit) as refused:+ follow.follow_loop(loop_dir, [(cx, cy, 2, 2)], gain=50)+ assert re.fullmatch(r'video-follow: a move of \d+\.\d px folds a region of radius 2 px over itself; '+ r'lower --gain or give the region larger radii', str(refused.value))+ assert (loop_dir/'walk.strip.png').read_bytes() == as_cut+ assert 'follow' not in json.loads((loop_dir/'walk.strip.json').read_text())+++def small_region(loop_dir, share):+ """A region on the chest whose smaller radius folds at `share` of the default gain."""+ cx, cy, rx, _ = chest_region(loop_dir)+ reach = follow.follow_loop(loop_dir, [(cx, cy, 40, 40)])['reach_px']+ return (cx, cy, rx, share*reach*math.pi/2)+++def folds_nowhere(rec, meta):+ """Every cell's picture runs forwards: along the move, the sample point never turns back."""+ h, w = meta['h'], meta['w']+ yy, xx = np.mgrid[0:h, 0:w].astype(float)+ worst = 0.0+ for dx, dy in zip(rec['dx_px'], rec['dy_px']):+ weight = np.zeros((h, w))+ for cx, cy, rx, ry in rec['regions']:+ r = np.sqrt(((xx-cx)/rx)**2+((yy-cy)/ry)**2)+ weight = np.maximum(weight, np.where(r < 1, np.cos(r*math.pi/2)**2, 0))+ gy, gx = np.gradient(weight)+ worst = max(worst, float(np.max(dx*gx+dy*gy)))+ return worst < 1, worst+++def test_lower_takes_the_largest_gain_that_does_not_fold(loop_dir):+ region = small_region(loop_dir, 0.7) # folds at 0.7 of the default gain: 1.75+ with pytest.raises(SystemExit, match='folds a region'):+ follow.follow_loop(loop_dir, [region])+ result = follow.follow_loop(loop_dir, [region], on_fold='lower')+ meta = json.loads((loop_dir/'walk.strip.json').read_text())+ rec = meta['follow']+ assert rec['gain_requested'] == follow.GAIN_DEFAULT and rec['on_fold'] == 'lower' and rec['fold']['lowered'] is True+ assert result['gain'] == rec['gain']+ # Under the request, not under the mass as measured, and the largest that passes: the next step folds.+ limit = rec['fold']['regions'][0]['gain_limit']+ assert 1.70 < limit < 1.80 and follow.GAIN_MEASURED <= rec['gain'] < limit <= rec['gain']+follow.GAIN_STEP+1e-9+ assert 0.99 <= rec['fold']['ratio'] < 1+ assert rec['fold']['regions'][0]['radius_px'] == pytest.approx(region[3])+ assert rec['reach_px'] < rec['fold']['reach_requested_px']+ assert rec['reach_px'] == pytest.approx(rec['gain']*rec['fold']['reach_per_gain_px'], abs=0.02)+ ok, worst = folds_nowhere(rec, meta)+ assert ok, worst+ lowered = (loop_dir/'walk.strip.png').read_bytes()+ assert lowered != (loop_dir/follow.SOURCE).read_bytes()+ # The report's gain is the --gain that gives this strip; one step more is refused.+ follow.follow_loop(loop_dir, [region], gain=rec['gain'])+ assert (loop_dir/'walk.strip.png').read_bytes() == lowered+ assert json.loads((loop_dir/'walk.strip.json').read_text())['follow']['fold']['lowered'] is False+ with pytest.raises(SystemExit, match='folds a region'):+ follow.follow_loop(loop_dir, [region], gain=rec['gain']+follow.GAIN_STEP)+++def test_the_smallest_region_sets_the_one_gain(loop_dir):+ small = small_region(loop_dir, 0.7)+ cx, cy, rx, ry = chest_region(loop_dir)+ alone = follow.follow_loop(loop_dir, [small], on_fold='lower')+ both = follow.follow_loop(loop_dir, [(cx, cy+30, rx, ry), small], on_fold='lower')+ assert both['gain'] == alone['gain']+ large, little = both['fold']['regions']+ assert large['gain_limit'] > follow.GAIN_DEFAULT > little['gain_limit']+ assert large['ratio'] < little['ratio'] < 1+++def test_lower_does_not_go_under_the_mass_as_measured(loop_dir):+ region = small_region(loop_dir, 0.3) # folds at 0.75: under gain 1+ as_cut = (loop_dir/'walk.strip.png').read_bytes()+ meta = (loop_dir/'walk.strip.json').read_text()+ with pytest.raises(SystemExit) as refused:+ follow.follow_loop(loop_dir, [region], on_fold='lower')+ assert 'folds a region' in str(refused.value) and 'under --gain 1' in str(refused.value)+ assert (loop_dir/'walk.strip.png').read_bytes() == as_cut+ assert (loop_dir/'walk.strip.json').read_text() == meta+ # A request already under 1 that folds is refused too: lowering only goes down.+ with pytest.raises(SystemExit, match='under --gain 1'):+ follow.follow_loop(loop_dir, [small_region(loop_dir, 0.3)], gain=0.9, on_fold='lower')+++def test_lower_changes_nothing_when_nothing_folds(loop_dir):+ region = chest_region(loop_dir)+ refuse = follow.follow_loop(loop_dir, [region])+ strip = (loop_dir/'walk.strip.png').read_bytes()+ lower = follow.follow_loop(loop_dir, [region], on_fold='lower')+ assert (loop_dir/'walk.strip.png').read_bytes() == strip+ assert lower['gain'] == lower['gain_requested'] == refuse['gain'] == follow.GAIN_DEFAULT+ assert lower['fold']['lowered'] is False and lower['dy_px'] == refuse['dy_px']+ assert lower['fold']['ratio'] < 1 and lower['fold']['reach_requested_px'] == lower['reach_px']+++def test_the_command_takes_on_fold_and_says_what_it_lowered_to(loop_dir, capsys):+ region = small_region(loop_dir, 0.7)+ text = ','.join(f'{v:.3f}' for v in region)+ with pytest.raises(SystemExit, match='folds a region'):+ follow.main(['--loop-dir', str(loop_dir), '--region', text])+ capsys.readouterr()+ assert follow.main(['--loop-dir', str(loop_dir), '--region', text, '--on-fold', 'lower']) == 0+ out, err = capsys.readouterr()+ printed = json.loads(out)+ assert printed['gain_requested'] == 2.5 and printed['on_fold'] == 'lower' and 1 <= printed['gain'] < 2.5+ assert f"lowered to --gain {printed['gain']:g}" in err+ with pytest.raises(SystemExit, match='unknown --on-fold'):+ follow.follow_loop(loop_dir, [region], on_fold='quietly')++def test_bad_regions_are_refused(loop_dir):with pytest.raises(SystemExit, match='outside'):follow.follow_loop(loop_dir, [(9999, 10, 5, 5)])