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(video-loop): a walk or run cut under its state's gait floor whose steps nothing counted is named a half step, kept as cut

Soohong Kim79c57b4ac1a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d0fa9e..f2da449 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -82,6 +82,10 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
- **Fixed: `video-loop --anchor motion-auto` no longer refuses a walk or run for its opening frames alone.** Where `auto_motion.discover` finds no two regions through the whole clip (`automatic motion anchor needs two separated regions trackable throughout the clip`, or `found no stable textured region`), the analysis is read again on the clip after the fewest frames it opens on, fewer than the window's shortest cut, with which the anchor finds its two regions through the rest (`auto_motion.analyse_after_opening`, new exception `auto_motion.RegionsUnfound`). A clip filmed from a still opens on that still and on the standing pose the body sets off from, and the regions the middle of the clip shows may be out of the anchor's reach there; the refusal came before the search, so the gait fallback never ran. Those frames are left out of the search as a lead-in is (`lead_in.search_from`, every frame number the clip's own), recorded in the report's new `untracked_opening` (`frames`, `first`, `shorter_than`, `refused`) and, once a cut is found, a warning line `video-loop: warning: the automatic motion anchor found its two regions from frame <k> on, not from the clip's first frames: ...` that does not repeat the refusal's words. Where no such opening leaves the clip tracked, it is refused in the same words as before, followed by ` — nor through the clip after any of its first 1 to <n> frames left out (an opening shorter than the shortest cut, <n + 1> frames)`; where the cut the search took holds no two regions when its frames are read again for the correction, the refusal now ends ` — on the cut the search took (frames <a>-<b>)`. Tests: `tests/video/test_auto_motion_opening.py` (a synthetic walker whose first three frames carry its head and torso 90 px forward: refused as filmed before, now cut after them with every frame number the clip's own; the same walker without them unchanged; the lean again mid-clip refused with the new words).
+**Upgrading from 3.5.0: a walk or run cut shorter than its state's gait floor, its steps not counted, now says so (`cycle.half_step` and a warning line); every cut and image is as before.**
+
+- **New: `video-loop` names a half-step cut.** A walk or run loops on an even number of steps (two, one cycle). The half-period guard reads the gait floor (`LoopProfile.min_seconds`) in whole frames, rounded, so a run cut 8 frames long at 24 fps (0.33 s, under the run's 0.35 s) is taken as two steps. Such a periodic cut whose steps nothing counted (no `cycle.steps`) is kept, recorded in `cycle.half_step` (`rule`, `state`, `seconds`, `gait_floor`, `why`, `two_steps`; in the stdout summary too) and named in a warning line that suggests `--steps 1`; the line repeats no refusal's words. Python callers: `loop.half_step`, `loop.half_step_verdict`, `loop.HALF_STEP_RULE`. Docs: [video-pipeline.md](docs/video-pipeline.md) section 4. **Tests**: `tests/video/test_loop_half_step.py`.
+
## v3.5.0 - Widened square canvas framing for side walk and run stride and trailing parts, measured background matte cutout for flat backgrounds of any colour, and failure when a cutout removes nothing
**Upgrading from 3.4.0: `video-set` now frames a walk or run filmed from the side on a square widened by the room its still lacks, and a background the chroma engine did not recognise, which used to come out with nothing removed, is now cut out.** A still that leaves less than `GAIT_ROOM` clear in front of its silhouette (0.15 of the silhouette's height) or behind it (0.25) gains the columns it lacks on that side; the square gains the same number of rows above the still. A still that leaves the room keeps its canvas to the byte. Every other state, a front, back or diagonal view, `--shape` and `--fit tight` are framed as before. Each side walk or run's `canvas.report.json`, and its item in `set.report.json`, gains `room`. `video-canvas` gains `--view` and reads the room only with `--view side`. Backgrounds the chroma engine already recognised key byte for byte as before. A pure or recognised magenta/green background still goes to the chroma engine and a bright achromatic one to the white matte, with the same bytes.
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index fa6913a..f7f0954 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -414,6 +414,18 @@ and a true cycle half a drawing late are **the same picture**. So
`video-loop` cuts the period it always cut, and only **records** what a half or a third of it shows
(`cycle.fundamental`, `sprite_gen/video/period.py`).
+**A cut under the gait floor is named a half step.** A walk or run loops on an even number of steps —
+two, one cycle; a loop of one step plays the same leg leading every time round. The gait floor
+(`LoopProfile.min_seconds`: walk 0.6 s, run 0.35 s) is the duration under which a period is one step,
+and the half-period guard reads it in whole frames, rounded, to choose among candidates: a run cut 8
+frames long at 24 fps (0.33 s) is taken. Such a periodic cut (`--cycle auto` or `periodic`) whose steps
+nothing counted — no `cycle.steps`: not the clip's crossings, `--steps` or the held side's two lengths —
+is kept as cut, recorded in `cycle.half_step` (`rule`, `state`, `seconds`, `gait_floor` in seconds and
+frames, `why` the steps were not counted, `two_steps`: twice the cut and whether the clip holds it) and
+named in a warning line (`loop.half_step`, `HALF_STEP_RULE`). Nothing is cut again on it: where the two
+legs are drawn alike the pixels cannot count the steps, and a clip that draws the same leg forward every
+step shows the same step twice in a cut two lengths long. `--steps 1` cuts it two lengths long.
+
**The size is held before the search or cut** (`--size-hold auto`, the default). A walk or run clip filmed from its first frame only often grows or shrinks as it plays, so the frame one cycle after the first is not the first's size and the loop pops at the wrap. Under `--size-hold auto`, a walk or run cut automatically with `--anchor motion-auto` (before the cycle search) or cut by hand with `--cycle fixed` under any anchor (before the cut is read, over the whole clip) is held at its first frame's size. When a clip's height changes by 1 % or more over the clip, read one cycle on, frames are scaled back to the first frame's size about their feet. Where the size is held and the feet climb or sink by 1 % of the first frame's height or more over the clip, frames are also shifted so their feet stand on the first frame's row. This stops a receding walk's jump at the wrap from moving into place: the motion anchor's fine search corrects a climb within 28 rows over the cut but leaves the cut uncorrected when feet climb further than that, and the body anchor moves frames sideways only.
The cut's seam and step count are measured on the held frames. A fixed cut is held only where the cut itself shows the change, comparing each frame of the cut with the frame one cycle of the cut's length later, or, where the clip ends before that frame, with the frame one cycle earlier, and feet are moved only where the cut shows them move. Where the cut does not show the change, it is cut as filmed, and the report says why. The report records `size_hold` with `padding_ltrb`, records `size_hold.feet` when size is held, and also records `size_hold.cut_frames` on a held fixed cut. Fixed cuts with `--anchor motion` record the shifted target boxes in `size_hold.anchor_regions`. Automatic searches under `--anchor body`, `feet`, or `none`, `--cycle pinned`, and cuts of states that are not a walk or run are not held. `video-loop-repair` restores a held fixed cut from its source frames by holding them again by those moves (a report without them, from 3.1.0, is not restored).
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 63e64d2..77cfefd 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -1831,6 +1831,48 @@ def coverage_verdict(cycle: dict[str, Any]) -> list[str]:
f"past it (under {COVERAGE_MIN:g}): its repeat is barely seen — the seam says whether it closes; a longer take shows it repeat"]
+# A walk or run loops on an even number of steps — two, one cycle: the left foot forward once and the right once. A loop
+# of one step plays the same leg leading every time round (a half step). The gait floor (`LoopProfile.min_seconds`) is
+# the duration under which a period is one step; the half-period guard reads it in whole frames, rounded, to choose among
+# the search's candidates (`detect_cycle`, `local_cycle.detect`), so a cut up to half a frame under it is taken. Such a
+# cut whose steps nothing counted (no `cycle.steps`: neither the clip's crossings, --steps nor the held side's two
+# lengths) is named — `cycle.half_step` and a warning line — and kept: pixels cannot count steps where the legs are
+# drawn alike, and a cut two of its lengths long is the count's to take (`--steps 1`).
+HALF_STEP_RULE = "a walk or run loops on an even number of steps — two, one cycle"
+
+
+def half_step(cycle: dict[str, Any], prof: LoopProfile, fps: float, *, state: str, clip_frames: int) -> dict[str, Any] | None:
+ """The record of a periodic walk or run cut shorter than its state's gait floor whose steps were not counted
+ (HALF_STEP_RULE); None for any other cut. `clip_frames` is what the clip holds after its lead-in."""
+ if not prof.gait or prof.min_seconds <= 0 or cycle.get("kind") != "periodic" or "steps" in cycle:
+ return None
+ seconds = cycle["length"] / fps
+ if seconds >= prof.min_seconds:
+ return None
+ counted = cycle.get("step_count")
+ if counted is None:
+ why = "the clip's crossings were not read"
+ elif not counted.get("readable"):
+ why = counted.get("why") or "the clip does not show its steps"
+ else:
+ why = (counted.get("cut") or {}).get("why") or "no count of two"
+ two = 2 * cycle["length"]
+ return {"rule": HALF_STEP_RULE, "state": state, "seconds": round(seconds, 4),
+ "gait_floor": {"seconds": prof.min_seconds, "frames": round(prof.min_seconds * fps)},
+ "steps": "not counted", "why": why, "two_steps": {"frames": two, "in_clip": two <= clip_frames}}
+
+
+def half_step_verdict(cycle: dict[str, Any]) -> list[str]:
+ """A cut recorded as one step (`cycle.half_step`), in words; empty otherwise."""
+ said = cycle.get("half_step")
+ if not said:
+ return []
+ return [f"the cut {cycle['start']}/{cycle['length']} plays {said['seconds']:.2f} s, under the {said['state']}'s gait floor of "
+ f"{said['gait_floor']['seconds']:g} s, and its steps were not counted ({said['why']}): {HALF_STEP_RULE}, and a cut "
+ "this short is one, the same leg leading every time round (a half step) — count the steps in the loop "
+ f"(video-loop --steps 1 cuts it two lengths long, {said['two_steps']['frames']} frames)"]
+
+
def _blend_wrap(frames: list[Image.Image], pin_file: Path, *, mode: str, anchor: str, cycle: dict[str, Any], fps: float,
seam_max: float) -> tuple[list[Image.Image], dict[str, Any]]:
"""`wrap_blend.apply` on a pinned cut, the pinned last frame cleaned as the cut's frames are (`_scrub`,
@@ -2259,6 +2301,8 @@ def _cut_loop(
if "steps" in cycle:
# A cut two steps long is one cycle: how much of a second the clip holds past it (after its lead-in).
cycle["coverage"] = round((n - skip - L) / L, 4)
+ if cycle_mode in ("auto", "periodic") and (said := half_step(cycle, prof, fps, state=state, clip_frames=n - skip)):
+ cycle["half_step"] = said
# The same, over the cut alone: a clip held for part of its length is held where the cut is.
report_base["cycle_drawings"] = held_mod.measure_cycle(clip_steps, start=i, length=L, fps=fps)
if gait_frames is not None:
@@ -2447,6 +2491,7 @@ def _cut_loop(
warnings += repair_mod.held_edge_verdict(cycle.get("seam_pop"))
warnings += coverage_verdict(cycle)
warnings += local_cycle.step_verdict(cycle)
+ warnings += half_step_verdict(cycle)
gated = repair != "off" and (jolt_max is not None or head_step_max is not None)
over = repair_mod.jolt_verdict(jolt, jolt_max=jolt_max, head_step_max=head_step_max) if gated else []
report_base["jolt"] = {**jolt, "reference": reference, "warnings": warnings,
@@ -2873,6 +2918,8 @@ def run(**kwargs: object) -> int:
summary["cycle"]["coverage"] = payload["cycle"]["coverage"]
if "step_screen" in payload["cycle"]:
summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]
+ if "half_step" in payload["cycle"]:
+ summary["cycle"]["half_step"] = payload["cycle"]["half_step"]
if "step_count" in payload["cycle"]:
counted = payload["cycle"]["step_count"]
summary["cycle"]["step_count"] = {k: counted[k] for k in ("mode", "readable", "chosen_by", "cut", "why") if k in counted}
diff --git a/tests/video/test_loop_half_step.py b/tests/video/test_loop_half_step.py
new file mode 100644
index 0000000..538b06a
--- /dev/null
+++ b/tests/video/test_loop_half_step.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A walk or run cut shorter than its state's gait floor, its steps not counted, is named a half step.
+
+A walk or run loops on two steps. The half-period guard reads the gait floor in whole frames, rounded, so a run cut 8
+frames long at 24 fps (0.33 s, under the run's 0.35 s) is taken as a cycle; the cut stays as it was, and the report and
+a warning line say it is one step (`cycle.half_step`, docs/video-pipeline.md section 4)."""
+from __future__ import annotations
+
+import pytest
+
+from sprite_gen.video import loop
+from tests.video import test_gait_fallback as walks
+
+# The lines a caller matches on the loop's stderr to read a refusal (spritegen-app modal/pipeline.py): a warning that
+# keeps the loop carries none of them.
+REFUSALS = ("no periodic cycle found", "loop seam ratio", "loop step ratio", "loop step count refutes", "loop seam pop")
+
+
+def _cut(length, **more):
+ return {"kind": "periodic", "start": 2, "length": length,
+ "step_count": {"readable": False, "why": "0 crossings in the clip: under two steps, no step range"}, **more}
+
+
+def test_a_run_cut_under_the_floor_in_seconds_is_one_step():
+ run = loop.profile_for("run")
+ assert round(run.min_seconds * 24) == 8 # the guard's floor in frames: an 8-frame cut passes it
+ said = loop.half_step(_cut(8), run, 24.0, state="run", clip_frames=73)
+ assert said == {"rule": loop.HALF_STEP_RULE, "state": "run", "seconds": 0.3333,
+ "gait_floor": {"seconds": 0.35, "frames": 8}, "steps": "not counted",
+ "why": "0 crossings in the clip: under two steps, no step range",
+ "two_steps": {"frames": 16, "in_clip": True}}
+ line, = loop.half_step_verdict({**_cut(8), "half_step": said})
+ assert line.startswith("the cut 2/8 plays 0.33 s, under the run's gait floor of 0.35 s")
+ assert "(a half step)" in line and "--steps 1" in line
+ assert not any(words in line for words in REFUSALS)
+
+
[email protected]("cycle, state, fps", [
+ (_cut(9), "run", 24.0), # 0.375 s: over the floor
+ (_cut(12), "run", 24.0),
+ (_cut(8, steps={"count": 2, "by": "crossings"}), "run", 24.0), # counted two steps
+ (_cut(8, steps={"count": 2, "by": "given", "given": 2}), "run", 24.0), # --steps 2
+ ({**_cut(8), "kind": "fixed"}, "run", 24.0), # a cut the caller named
+ (_cut(8), "idle", 24.0), # not a gait
+ (_cut(5), "run", 12.0), # 0.42 s at 12 fps
+])
+def test_a_cut_at_or_over_the_floor_or_counted_is_not_named(cycle, state, fps):
+ assert loop.half_step(cycle, loop.profile_for(state), fps, state=state, clip_frames=73) is None
+ assert loop.half_step_verdict(cycle) == []
+
+
+def test_the_floor_is_read_in_seconds_at_any_rate_and_a_short_clip_says_two_steps_do_not_fit():
+ # 4 frames at 12 fps is 0.33 s, and the guard's floor rounds to 4 frames there too.
+ said = loop.half_step(_cut(4), loop.profile_for("run"), 12.0, state="run", clip_frames=36)
+ assert said["seconds"] == 0.3333 and said["gait_floor"] == {"seconds": 0.35, "frames": 4}
+ # A walk a frame under its floor at 24 fps (0.58 s, the guard's floor 14 frames), in a clip too short for two lengths.
+ said = loop.half_step(_cut(14), loop.profile_for("walk"), 24.0, state="walk", clip_frames=20)
+ assert said["seconds"] == 0.5833 and said["gait_floor"] == {"seconds": 0.6, "frames": 14}
+ assert said["two_steps"] == {"frames": 28, "in_clip": False}
+
+
+def test_a_run_cut_one_step_long_is_kept_and_named(tmp_path, capsys):
+ (tmp_path / "eight").mkdir()
+ code, report, _ = walks.run(tmp_path / "eight", [walks.walker(k, period=8) for k in range(73)], "--size-hold", "off",
+ state="run")
+ assert code == 0 and report["status"] == "passed"
+ cycle = report["cycle"]
+ assert cycle["length"] == 8 and "steps" not in cycle and not cycle["step_count"]["readable"]
+ assert cycle["half_step"]["seconds"] == 0.3333 and cycle["half_step"]["two_steps"] == {"frames": 16, "in_clip": True}
+ err = capsys.readouterr().err
+ warned = [line for line in err.splitlines() if "(a half step)" in line]
+ assert len(warned) == 1 and warned[0].startswith(f"video-loop: warning: the cut {cycle['start']}/8 plays 0.33 s")
+ assert not any(words in err for words in REFUSALS)
+ assert any("(a half step)" in line for line in report["jolt"]["warnings"])
+
+ # Counted, it is not named: --steps 2 keeps the cut, --steps 1 cuts it two lengths long.
+ for steps, length in (("2", 8), ("1", 16)):
+ (tmp_path / steps).mkdir()
+ code, counted, _ = walks.run(tmp_path / steps, [walks.walker(k, period=8) for k in range(73)], "--size-hold", "off",
+ "--steps", steps, state="run")
+ assert code == 0 and abs(counted["cycle"]["length"] - length) <= 1
+ assert "half_step" not in counted["cycle"]
+ assert "(a half step)" not in capsys.readouterr().err
+
+
+def test_a_run_cut_two_steps_long_says_nothing(tmp_path, capsys):
+ code, report, _ = walks.run(tmp_path, [walks.walker(k, period=12) for k in range(73)], "--size-hold", "off", state="run")
+ assert code == 0 and report["cycle"]["length"] == 12 and "half_step" not in report["cycle"]
+ assert "(a half step)" not in capsys.readouterr().err